From b7994e8f60623529e1962837ce38b51e4eeabb0e Mon Sep 17 00:00:00 2001 From: OneSlips Date: Thu, 22 Oct 2026 13:14:08 +1000 Subject: [PATCH 01/15] LR-EDIT-GEOM-UPRIGHT: posts among people are corrected; Upright says why it found nothing - A vertical (or horizontal) family is accepted when most of it agrees, or when it holds at least 30 % of the family and twice the support of any rival vanishing point the disagreeing lines form: people, dresses and foliage point every which way, mirrored tree flanks form a rival. - Analysis records why a family gave no vanishing point (too few / too short lines, one object, disagreeing lines, meeting inside the photo); geometry.upright returns it as `note` ("No vertical correction: ...") and the panel shows it over the photo, suggesting Guided. - Synthetic regression: converging posts clipped by the frame flanking six tilted figures, tree texture and a hedge line (failed before: Disagree). - LR-EDIT-GEOM-UPRIGHT downgraded to partial until checked on real shots. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 8d87086175f617f8b40d4215e7cce00f36e4e848) --- crates/engine/src/cmd/develop.rs | 21 ++++-- crates/engine/src/tests.rs | 22 ++++++ crates/pipeline/src/tests_geometry.rs | 94 ++++++++++++++++++++++++ crates/pipeline/src/upright.rs | 100 +++++++++++++++++++++++--- crates/ui-egui/src/panels/right.rs | 13 +++- docs/parity-checklist.md | 5 +- 6 files changed, 235 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index fbc3d4041a..916b253c8f 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -758,19 +758,20 @@ pub fn specs() -> Vec { "Upright", [], None, - "{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes", + "{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes → {mode, transform, note (why the mode found nothing to correct, when it didn't)}", has_active, |s, p| { let mode: Upright = serde_json::from_value(p.get("mode").cloned().unwrap_or(json!("auto"))).map_err(|e| bad("geometry.upright", e.to_string()))?; let id = active(s, "geometry.upright")?; let d = s.develop_of(id).unwrap_or_default(); - let transform = match mode { - Upright::Off | Upright::Guided => None, + let (transform, note) = match mode { + Upright::Off | Upright::Guided => (None, None), m => { let src = s.source_now(id, SourceLevel::Preview).map_err(|e| bad("geometry.upright", e))?; let info = s.source_info(id); - Some(lightcraft_pipeline::upright::auto_transform(&src, &info, &d, m)) + let a = lightcraft_pipeline::upright::analyze_source(&src, &info, &d); + (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a)) } }; edit(s, "geometry.upright", "Upright", |d| { @@ -778,7 +779,17 @@ pub fn specs() -> Vec { d.geometry.upright_transform = transform; Ok(()) })?; - Ok(json!({"mode": mode, "transform": transform})) + // say why when the mode can't do what it says, instead of nothing happening + let note = note.map(|why| { + let what = match mode { + Upright::Level => "No level correction", + Upright::Vertical => "No vertical correction", + Upright::Full => "No full correction", + _ => "No Upright correction", + }; + format!("{what}: {why}. Try Guided: draw lines along what should be vertical.") + }); + Ok(json!({"mode": mode, "transform": transform, "note": note})) } ), cmd!( diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 93f4e6adcf..183ae4eeb4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1924,3 +1924,25 @@ fn auto_sync_hdr_enabled_preserves_per_photo_tuning() { assert!(s.auto_sync, "Auto Sync must remain enabled"); } } + +/// Upright that finds nothing to correct says why instead of silently doing nothing. +#[test] +fn upright_says_why_it_found_nothing_to_correct() { + let mut s = demo(); + let mut noted = 0; + for id in s.visible().iter().copied().take(4).collect::>() { + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + let r = s.execute("geometry.upright", &json!({"mode": "vertical"})).unwrap(); + let identity = r["transform"] == serde_json::to_value(lightcraft_geom::Homography::IDENTITY).unwrap(); + match r["note"].as_str() { + Some(note) => { + noted += 1; + assert!(note.starts_with("No vertical correction: "), "{note}"); + } + None => assert!(!identity, "a vertical correction was found: {r}"), + } + } + assert!(noted > 0, "the demo's natural scenes have no verticals to correct"); + let r = s.execute("geometry.upright", &json!({"mode": "off"})).unwrap(); + assert!(r["note"].is_null()); +} diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index ac244cb0dc..6e37132702 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -524,3 +524,97 @@ fn auto_straighten_leaves_steep_lines_alone() { let deg = level(&tilted_scene(8.0, 30.0)).expect("8° is"); assert!((deg + 8.0).abs() < 0.5, "{deg}"); } + +/// A ceremony aisle under a pavilion, shot from below and slightly rolled. Two thick white posts, +/// left and right, clipped by the frame's top and bottom, converge; a level hedge line; in the middle, people and +/// a dress whose edges are near-vertical but point nowhere in common; tree texture behind. Upright Vertical / Auto +/// did nothing on such a photo. +fn pavilion(w: usize, h: usize, fwd: lightcraft_geom::Homography) -> Rgb32f { + let l = w.max(h) as f64 / 2.0; + let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0); + // cheap deterministic noise + let noise = |x: f64, y: f64| { + let n = ((x * 12.9898 + y * 78.233).sin() * 43758.5453).fract().abs(); + n as f32 + }; + synth( + w, + h, + move |p| { + let q = fwd.apply(Point::new((p.x - cx) / l, (p.y - cy) / l)); + Point::new(q.x, q.y) + }, + move |q| { + let (x, y) = (q.x, q.y); + // posts: thick, bright, the whole height + for px in [-0.78, 0.8] { + if (x - px).abs() < 0.045 { + return [0.95; 3]; + } + } + // people in the middle: tilted shapes (a dress, suits), near-vertical edges in every direction + let people: [(f64, f64, f64, f64, f32); 6] = [ + (-0.32, 0.25, 0.09, 9.0, 0.08), + (-0.12, 0.2, 0.13, -11.0, 0.92), + (0.05, 0.22, 0.08, 14.0, 0.1), + (0.22, 0.28, 0.07, -7.0, 0.85), + (0.38, 0.3, 0.06, 18.0, 0.15), + (-0.5, 0.33, 0.05, -16.0, 0.12), + ]; + for (px, py, half_w, tilt, v) in people { + let (s, c) = tilt.to_radians().sin_cos(); + let (dx, dy) = (x - px, y - py); + let (u, t) = (dx * c - dy * s, dx * s + dy * c); + // a body from py − 0.35 (head) to py + 0.35, wider at the bottom (a dress) + if t.abs() < 0.35 && u.abs() < half_w * (1.0 + 0.8 * (t + 0.35)) { + return [v; 3]; + } + } + if y < -0.12 { + // sky (bright, but not as bright as the white posts) + [0.62 - 0.05 * y.abs() as f32; 3] + } else if y < 0.08 { + // trees: dark, textured + [0.18 + 0.12 * noise((x * 90.0).floor(), (y * 90.0).floor()); 3] + } else { + // lawn, below a level hedge line + [0.42 + 0.06 * noise((x * 140.0).floor(), (y * 140.0).floor()); 3] + } + }, + ) +} + +#[test] +fn upright_corrects_converging_posts_among_people() { + let (w, h) = (900usize, 600usize); + let shot = lightcraft_develop::Geometry { vertical: 30.0, rotate: -1.5, ..Default::default() }; + let src = pavilion(w, h, crate::transform::manual(&shot)); + let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default()); + assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why); + // the middle of the bright post in a quarter of the frame, on a row (centroid of the white pixels) + let post_x = |img: &Rgba8, y: usize, right: bool| { + let (a, b) = if right { (img.width * 3 / 4, img.width) } else { (0, img.width / 4) }; + let (mut s, mut n) = (0.0f64, 0.0f64); + for x in a..b { + if img.get(x, y)[1] > 225 { + s += x as f64; + n += 1.0; + } + } + s / n.max(1.0) + }; + let lean = |img: &Rgba8, right: bool| post_x(img, img.height / 6, right) - post_x(img, img.height * 5 / 6, right); + let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image; + assert!(lean(&raw, false).abs() > 8.0 && lean(&raw, true).abs() > 8.0, "the posts lean in the photo: {} {}", lean(&raw, false), lean(&raw, true)); + for mode in [Upright::Vertical, Upright::Auto] { + let img = upright_render(&src, mode); + for right in [false, true] { + assert!( + lean(&img, right).abs() < 2.5, + "{mode:?}: the {} post still leans {} px", + if right { "right" } else { "left" }, + lean(&img, right) + ); + } + } +} diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 58a61adbe2..f656311160 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -429,26 +429,90 @@ pub struct Analysis { pub horizontal: Vec, pub vertical_vp: Option<[f64; 3]>, pub horizontal_vp: Option<[f64; 3]>, + /// Why there is no vertical vanishing point (when there is none). + pub vertical_why: Option, + /// Why there is no horizontal vanishing point (when there is none). + pub horizontal_why: Option, +} + +/// Why a family of lines gives no perspective to correct. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reject { + /// Fewer than two long lines of the family. + TooFew, + /// Too little of them: short lines only. + TooShort, + /// All on one object: not spread across the photo. + OneObject, + /// They point in different directions (trees, people, folds), not at one vanishing point. + Disagree, + /// They meet inside or near the photo: a scene feature (a road, rays), not a tilted camera. + MeetInside, +} + +impl Reject { + /// In words for the user: "No vertical correction: …". + pub fn message(self) -> &'static str { + match self { + Reject::TooFew => "it found too few straight lines", + Reject::TooShort => "the straight lines it found are too short", + Reject::OneObject => "the straight lines are all on one object", + Reject::Disagree => "the straight lines point in different directions (people, trees or folds rather than buildings)", + Reject::MeetInside => "the straight lines meet inside the photo (a scene feature rather than a tilted camera)", + } + } } /// Whether a family's vanishing point is backed by real structure rather than one object: at least three /// inlier segments, a total inlier length of a quarter of the long edge, and inliers spread across at least a -/// fifth of the long edge perpendicular to the family, and at least 60 % of the family's length agreeing (the -/// mirrored flanks of conical trees or peaks converge somewhere but say nothing about the camera). -fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> bool { +/// fifth of the long edge perpendicular to the family, and most of the family's long lines agreeing (the +/// mirrored flanks of conical trees or peaks converge somewhere but say nothing about the camera), or at least +/// the lines that disagree not gathering at a rival point (two posts flanking a crowd). +fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> Result<(), Reject> { let thr = 3f64.to_radians(); let inl: Vec<&Segment> = segs.iter().filter(|s| vp_error(s, v) < thr).collect(); let total: f64 = inl.iter().map(|s| s.len()).sum(); let across = |s: &&Segment| if vertical { s.mid().x } else { s.mid().y }; let (lo, hi) = inl.iter().map(across).fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x))); - // consensus: real structure agrees; mirrored flanks (trees, peaks) split the family roughly in half - let family: f64 = segs.iter().map(Segment::len).sum(); // a camera-tilt vanishing point lies far outside the frame; one inside or near it is a scene feature // (sun rays, a road to the horizon), not perspective to correct if v[2].abs() > 1e-9 && (v[0] / v[2]).hypot(v[1] / v[2]) < 2.0 { - return false; + return Err(Reject::MeetInside); + } + if inl.len() < 3 { + return Err(Reject::TooFew); + } + if total < 0.5 { + return Err(Reject::TooShort); + } + if hi - lo < 0.4 { + return Err(Reject::OneObject); + } + // consensus: real structure agrees; mirrored flanks (trees, peaks) split the family in two halves that each + // converge somewhere. Most of the family agreeing settles it; else the lines that disagree must not gather at + // a rival point of their own nearly as strongly (people, folds and foliage point every which way, so a few + // long posts among them still decide) + let family: f64 = segs.iter().map(Segment::len).sum(); + if total >= 0.6 * family { + return Ok(()); + } + let rest: Vec = segs.iter().copied().filter(|s| vp_error(s, v) >= thr).collect(); + let rival = vanishing_point(&rest).map_or(0.0, |(_, support)| support); + if total >= 0.3 * family && total >= 2.0 * rival { + return Ok(()); + } + Err(Reject::Disagree) +} + +/// One family's vanishing point, if [`reliable`], else why not. +fn family_vp(segs: &[Segment], vertical: bool) -> (Option<[f64; 3]>, Option) { + match vanishing_point(segs) { + None => (None, Some(Reject::TooFew)), + Some((v, _)) => match reliable(segs, v, vertical) { + Ok(()) => (Some(v), None), + Err(why) => (None, Some(why)), + }, } - inl.len() >= 3 && total >= 0.5 && hi - lo >= 0.4 && total >= 0.6 * family } /// Group segments into near-vertical / near-horizontal families and find their vanishing points (only reliable @@ -456,9 +520,23 @@ fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> bool { pub fn analyze(segs: &[Segment]) -> Analysis { let vertical: Vec = segs.iter().copied().filter(|s| s.tilt_from_vertical() < 30.0).collect(); let horizontal: Vec = segs.iter().copied().filter(|s| s.tilt_from_vertical() > 60.0).collect(); - let vertical_vp = vanishing_point(&vertical).map(|v| v.0).filter(|v| reliable(&vertical, *v, true)); - let horizontal_vp = vanishing_point(&horizontal).map(|v| v.0).filter(|v| reliable(&horizontal, *v, false)); - Analysis { vertical, horizontal, vertical_vp, horizontal_vp } + let (vertical_vp, vertical_why) = family_vp(&vertical, true); + let (horizontal_vp, horizontal_why) = family_vp(&horizontal, false); + Analysis { vertical, horizontal, vertical_vp, horizontal_vp, vertical_why, horizontal_why } +} + +/// Why `mode` corrects less than it asks for on this analysis: `None` when it does what it says (or it is Off, +/// Guided or Auto with nothing to fix). In words for the user, after "No vertical correction: ". +pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { + match mode { + Upright::Vertical | Upright::Full if a.vertical_vp.is_none() => Some(a.vertical_why.unwrap_or(Reject::TooFew).message()), + Upright::Full if a.horizontal_vp.is_none() => Some(a.horizontal_why.unwrap_or(Reject::TooFew).message()), + Upright::Level if level_angle(&a.vertical, &a.horizontal).is_none() => Some(Reject::Disagree.message()), + Upright::Auto if a.vertical_vp.is_none() && level_angle(&a.vertical, &a.horizontal).is_none() => { + Some(a.vertical_why.unwrap_or(Reject::TooFew).message()) + } + _ => None, + } } /// The Upright correction for `mode` from an analysis (lens-corrected → transformed, centred coordinates). @@ -486,7 +564,7 @@ pub fn solve(mode: Upright, a: &Analysis) -> Homography { let roll = x.atan2(y).to_degrees(); let confirmed = roll.abs() <= 3.0 || level_angle(&[], &a.horizontal).is_some_and(|h| (h - roll).abs() <= 3.0); if !confirmed { - let weaker = Analysis { vertical_vp: None, horizontal_vp: None, ..a.clone() }; + let weaker = Analysis { vertical_vp: None, horizontal_vp: None, vertical_why: Some(Reject::Disagree), ..a.clone() }; return solve(Upright::Auto, &weaker); } } diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index feb2019181..5b4b0f293e 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -366,7 +366,8 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let active = modes.iter().position(|(_, m, _)| *m == d.geometry.upright); if let Some(i) = crate::widgets::segmented(ui, "upright", &items, active, 3) { let (_, mode, key) = modes[i]; - let _ = app.run("geometry.upright", json!({"mode": key})); + let r = app.run("geometry.upright", json!({"mode": key})); + upright_note(app, ui.ctx(), r.as_ref().ok()); app.ui.tool = if mode == Upright::Guided { "guidedUpright".into() } else { String::new() }; } } @@ -377,7 +378,8 @@ fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { && text_button(ui, "uprightUpdate", crate::i18n::tr("Update"), false).clicked() { let mode = serde_json::to_value(d.geometry.upright).unwrap_or_default(); - let _ = app.run("geometry.upright", json!({"mode": mode})); + let r = app.run("geometry.upright", json!({"mode": mode})); + upright_note(app, ui.ctx(), r.as_ref().ok()); } if guided { let drawing = app.ui.tool == "guidedUpright"; @@ -1537,6 +1539,13 @@ enum HistoryRow { Undone, } +/// Upright that found nothing to correct says why, as a note over the photo. +fn upright_note(app: &mut LightcraftApp, ctx: &egui::Context, result: Option<&serde_json::Value>) { + if let Some(note) = result.and_then(|r| r.get("note")).and_then(serde_json::Value::as_str) { + app.toast_for(ctx, note.to_string(), 8.0); + } +} + fn history_row(i: usize, cursor: Option) -> HistoryRow { match cursor { Some(c) if i == c => HistoryRow::Current, diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 080680b9ff..422bbf583f 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-EDIT-GEOM-UPRIGHT: ✅ → 🟡, long posts among people are corrected, Upright says why it found nothing; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -216,7 +216,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). ) | LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper | | LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | | -| LR-EDIT-GEOM-UPRIGHT | Upright | P1 | ✅ | `cmd:geometry.upright`, `cmd:geometry.guides` | | +| LR-EDIT-GEOM-UPRIGHT | Upright | P1 | 🟡 | `cmd:geometry.upright`, `cmd:geometry.guides`, `crates/pipeline/src/upright.rs` | a vertical family is accepted when most of it agrees, or when the lines that disagree (people, folds, foliage) gather at no rival point half as strong, so two long posts flanking a crowd decide (`upright_corrects_converging_posts_among_people`); a mode that finds nothing to correct says why (`note`, shown over the photo: too few / too short lines, one object, lines that disagree, lines meeting inside the photo) and suggests Guided. Downgraded from ✅: a user's real pavilion shots (thick posts, thin poles) were not corrected and the tuning is so far proven on synthetic scenes only; thin poles below a pixel at the 1024 px analysis size are still lost | | LR-EDIT-GEOM-MANUAL | Manual transform | P1 | ✅ | `ctl:geometry.*` | | | LR-EDIT-GEOM-CONSTRAIN | Constrain crop | P1 | ✅ | `crates/ui-egui/src/panels/right.rs` (checkbox → `cmd:develop.merge`), `crates/engine/src/lib.rs` (`fit_constrained_crop`) | Ticking it, or changing Geometry, Upright or lens corrections while it is ticked, shrinks the stored crop about its centre until no blank corner is left, so the Crop tool shows it (it used to apply at render time only, outside the Crop tool: issue #1927; tests in `crates/engine/src/tests_constrain_crop.rs`). A crop drawn by hand is kept as drawn; unticking keeps the tighter crop | | LR-EDIT-GEOM-GRID | Grid while transforming | P2 | ✅ | `crates/ui-egui/src/panels/detail.rs` | a fine grid over the photo while a geometry slider is dragged | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-25 | minor | LR-EDIT-GEOM-UPRIGHT: ✅ → 🟡 (real shots of posts among people were not corrected; tuned on synthetic scenes only): a vertical family wins over a crowd of disagreeing lines unless they gather at a rival point, Vertical follows long posts rather than decks, drapes or gown folds; a mode that finds nothing says why | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | patch | LR-LIB-RATING, LR-LIB-DELETE: a slider drag still open when a rating, flag or label takes the photo out of the view, or when the photo is deleted, ends as its own undo step before the selection moves on, as moving to the next photo does; LR-BEHAV-LOCALIZE lists all 18 languages; status unchanged | From 73488c1d430d672d082c41ffb3e5da09dedb2997 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 25 Oct 2026 04:13:23 +1000 Subject: [PATCH 02/15] LR-EDIT-GEOM-UPRIGHT: Vertical follows long posts, not decks, drapes or gown folds Measured on the photographer's own Upright corrections (190 frames, ground truth = Upright + the rotation added by hand; local eval, never committed): lines that meet inside the photo (a deck running to the horizon, a drape's apex) no longer outvote the posts or form a rival; collinear pieces of one edge are joined; a vanishing point needs two long lines apart, and a big camera turn needs most of the long lines. Edges against foliage are kept (lower gradient threshold). Messages say briefly what was seen. Dev tools: engine example upright_eval (decode, product path, analysis planes) and pipeline example upright_planes (detector on saved planes). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 8322daf0a933a5355b8627299e3dfc8f5b6102c7) --- crates/engine/examples/upright_eval.rs | 81 ++++++++ crates/pipeline/examples/upright_planes.rs | 47 +++++ crates/pipeline/src/tests_geometry.rs | 114 +++++++++++ crates/pipeline/src/upright.rs | 217 ++++++++++++++++++--- 4 files changed, 434 insertions(+), 25 deletions(-) create mode 100644 crates/engine/examples/upright_eval.rs create mode 100644 crates/pipeline/examples/upright_planes.rs diff --git a/crates/engine/examples/upright_eval.rs b/crates/engine/examples/upright_eval.rs new file mode 100644 index 0000000000..6c2ae565aa --- /dev/null +++ b/crates/engine/examples/upright_eval.rs @@ -0,0 +1,81 @@ +//! Upright on real photos (a developer tool, not part of the app): imports each photo of a manifest into an +//! in-memory library, applies its lens settings, runs Upright the way the app does and writes one JSON line per +//! photo (the transform each mode finds and why a mode found nothing). With `--planes DIR` it also saves the +//! analysis plane of each photo at 2048 px (`.lum`: u32 width, u32 height, f32 samples, little endian), so +//! the detector can be tuned on them without decoding raws again (`lightcraft-pipeline` example +//! `upright_planes`). +//! +//! `cargo run --release -p lightcraft-engine --example upright_eval -- [--planes DIR]` +//! +//! The manifest is a JSON array of `{key, local, optics?, orientation?}` (`local`: a copy of the photo; nothing +//! is written next to it). Ground truth and scoring live outside the repository. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::Write; + +use lightcraft_engine::Session; +use lightcraft_engine::catalog::PhotoId; +use lightcraft_engine::media::SourceLevel; +use serde_json::{Value, json}; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let manifest: Vec = serde_json::from_str(&std::fs::read_to_string(&args[0]).unwrap()).unwrap(); + let mut out = std::fs::File::create(&args[1]).unwrap(); + let planes = args.iter().position(|a| a == "--planes").map(|i| std::path::PathBuf::from(&args[i + 1])); + if let Some(p) = &planes { + std::fs::create_dir_all(p).unwrap(); + } + for m in &manifest { + // a fresh in-memory library per photo, so a few hundred raws fit + let mut s = Session::new().with_fs(); + let key = m["key"].as_str().unwrap().to_string(); + let local = m["local"].as_str().unwrap(); + let r = match s.execute("library.import", &json!({"paths": [local]})) { + Ok(r) => r, + Err(e) => { + eprintln!("{key}: {e}"); + continue; + } + }; + let Some(id) = r["imported"][0].as_u64() else { + eprintln!("{key}: not imported"); + continue; + }; + s.execute("library.select", &json!({"ids": [id], "active": id})).unwrap(); + let mut partial = serde_json::Map::new(); + for k in ["optics", "orientation"] { + if let Some(v) = m.get(k).filter(|v| !v.is_null()) { + partial.insert(k.into(), v.clone()); + } + } + if !partial.is_empty() + && let Err(e) = s.execute("develop.merge", &json!({"settings": partial})) + { + eprintln!("{key}: lens settings: {e}"); + } + let mut line = json!({"key": key}); + for mode in ["vertical", "auto", "full", "level"] { + match s.execute("geometry.upright", &json!({"mode": mode})) { + Ok(r) => line[mode] = json!({"transform": r["transform"], "note": r["note"]}), + Err(e) => line[mode] = json!({"error": e.to_string()}), + } + } + if let Some(dir) = &planes { + let d = s.develop_of(PhotoId(id)).unwrap_or_default(); + let src = s.source_now(PhotoId(id), SourceLevel::Preview).unwrap(); + let info = s.source_info(PhotoId(id)); + let lum = lightcraft_pipeline::upright::analysis_luminance(&src, &info, &d, 2048); + let mut bytes = Vec::with_capacity(8 + lum.data.len() * 4); + bytes.extend_from_slice(&(lum.width as u32).to_le_bytes()); + bytes.extend_from_slice(&(lum.height as u32).to_le_bytes()); + for v in &lum.data { + bytes.extend_from_slice(&v.to_le_bytes()); + } + std::fs::write(dir.join(format!("{key}.lum")), bytes).unwrap(); + line["source"] = json!([src.width, src.height]); + } + writeln!(out, "{line}").unwrap(); + eprintln!("{key} done"); + } +} diff --git a/crates/pipeline/examples/upright_planes.rs b/crates/pipeline/examples/upright_planes.rs new file mode 100644 index 0000000000..b1ba8c226d --- /dev/null +++ b/crates/pipeline/examples/upright_planes.rs @@ -0,0 +1,47 @@ +//! Upright detector on saved analysis planes (a developer tool, not part of the app): reads the `.lum` planes +//! that `lightcraft-engine`'s `upright_eval` example saves, runs the line finder and the solver at the app's +//! analysis size and writes one JSON line per plane (the Vertical / Auto / Full transforms and why a mode found +//! nothing), so a change to the detector can be scored against the photographer's own corrections quickly. +//! +//! `cargo run --release -p lightcraft-pipeline --example upright_planes -- ` +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::io::Write; + +use lightcraft_develop::Upright; +use lightcraft_pipeline::upright; +use lightcraft_raster::Plane; + +fn read_plane(path: &std::path::Path) -> Plane { + let b = std::fs::read(path).unwrap(); + let w = u32::from_le_bytes(b[0..4].try_into().unwrap()) as usize; + let h = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize; + let data = b[8..].as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(); + Plane { width: w, height: h, data } +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let mut out = std::fs::File::create(&args[1]).unwrap(); + let mut paths: Vec<_> = std::fs::read_dir(&args[0]).unwrap().filter_map(|e| e.ok().map(|e| e.path())).collect(); + paths.retain(|p| p.extension().is_some_and(|e| e == "lum")); + paths.sort(); + for p in paths { + let key = p.file_stem().unwrap().to_string_lossy().to_string(); + let plane = read_plane(&p); + let size = std::env::var("UPRIGHT_SIZE").ok().and_then(|v| v.parse().ok()).unwrap_or(1024); + let a = upright::analyze_plane_at(&plane, size); + let mut line = serde_json::json!({"key": key}); + for (name, mode) in [("vertical", Upright::Vertical), ("auto", Upright::Auto), ("full", Upright::Full)] { + line[name] = serde_json::json!({"transform": upright::solve(mode, &a), "note": upright::shortfall(mode, &a)}); + } + writeln!(out, "{line}").unwrap(); + // UPRIGHT_DUMP=dir: the near-vertical lines and the vanishing point, to draw over the photo + if let Ok(dir) = std::env::var("UPRIGHT_DUMP") { + let segs: Vec<[f64; 4]> = a.vertical.iter().map(|s| [s.a.x, s.a.y, s.b.x, s.b.y]).collect(); + let h: Vec<[f64; 4]> = a.horizontal.iter().map(|s| [s.a.x, s.a.y, s.b.x, s.b.y]).collect(); + let d = serde_json::json!({"vertical": segs, "horizontal": h, "vp": a.vertical_vp.or(upright::vanishing_point(&a.vertical).map(|x| x.0)), "why": a.vertical_why.map(|w| w.message())}); + std::fs::write(std::path::Path::new(&dir).join(format!("{key}.json")), d.to_string()).unwrap(); + } + } +} diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index 6e37132702..401b0893a7 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -618,3 +618,117 @@ fn upright_corrects_converging_posts_among_people() { } } } + +/// A ceremony under a white gazebo, shot level with a long lens but rolled 1.6° +/// (portrait). Two white posts stand up the whole frame; the deck's boards run away to the horizon (they meet +/// inside the photo); two drapes hang diagonally from the roof; a couple stands between the posts. Upright +/// Vertical said "the straight lines point in different directions" and did nothing. +fn gazebo(w: usize, h: usize, fwd: lightcraft_geom::Homography) -> 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| fwd.apply(Point::new((p.x - cx) / l, (p.y - cy) / l)), + move |q| { + let (x, y) = (q.x, q.y); + for px in [-0.47, 0.47] { + if (x - px).abs() < 0.035 { + return [0.95; 3]; + } + } + // drapes from the roof's middle out and down, thin bright bands + for (x0, x1) in [(-0.05, -0.3), (0.05, 0.3)] { + let (y0, y1) = (-1.0, 0.25); + if y > y0 && y < y1 { + let t = (y - y0) / (y1 - y0); + if (x - (x0 + (x1 - x0) * t)).abs() < 0.02 { + return [0.7; 3]; + } + } + } + // the couple: a dark suit and a white gown, a little tilted + for (px, half_w, tilt, v) in [(-0.1, 0.07, 6.0f64, 0.85f32), (0.1, 0.06, -5.0, 0.08)] { + let (s, c) = tilt.to_radians().sin_cos(); + let (dx, dy) = (x - px, y - 0.25); + let (u, t) = (dx * c - dy * s, dx * s + dy * c); + if t.abs() < 0.4 && u.abs() < half_w * (1.0 + 0.8 * (t + 0.4)) { + return [v; 3]; + } + } + if y > 0.3 { + // deck boards running to a point on the horizon (inside the photo) + let a = x.atan2(y + 0.1); + if (a * 14.0).rem_euclid(1.0) < 0.12 { + return [0.15; 3]; + } + return [0.55; 3]; + } + // sky, a railing line + if (y - 0.05).abs() < 0.01 { [0.3; 3] } else { [0.62; 3] } + }, + ) +} + +#[test] +fn upright_vertical_follows_the_posts_not_the_deck_or_the_drapes() { + let (w, h) = (600usize, 900usize); + let shot = lightcraft_develop::Geometry { rotate: 1.6, ..Default::default() }; + let src = gazebo(w, h, crate::transform::manual(&shot)); + let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default()); + assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why); + let post_x = |img: &Rgba8, y: usize, right: bool| { + let (a, b) = if right { (img.width * 3 / 4, img.width) } else { (0, img.width / 4) }; + let (mut s, mut n) = (0.0f64, 0.0f64); + for x in a..b { + if img.get(x, y)[1] > 235 { + s += x as f64; + n += 1.0; + } + } + s / n.max(1.0) + }; + let lean = |img: &Rgba8, right: bool| post_x(img, img.height / 8, right) - post_x(img, img.height * 5 / 8, right); + let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image; + assert!(lean(&raw, false).abs() > 6.0 && lean(&raw, true).abs() > 6.0, "the posts lean: {} {}", lean(&raw, false), lean(&raw, true)); + for mode in [Upright::Vertical, Upright::Auto] { + let img = upright_render(&src, mode); + for right in [false, true] { + assert!( + lean(&img, right).abs() < 2.0, + "{mode:?}: the {} post still leans {} px", + if right { "right" } else { "left" }, + lean(&img, right) + ); + } + } +} + +/// Do no harm: a gown's folds spreading to the floor point at a far point too, but they are short and there is +/// no post, wall or door among them: Upright Vertical leaves such a photo alone. +#[test] +fn upright_vertical_leaves_a_gown_without_structure_alone() { + let (w, h) = (600usize, 900usize); + let l = 450.0; + let src = synth( + w, + h, + |p| Point::new((p.x - 300.0) / l, (p.y - 450.0) / l), + |q| { + let (x, y) = (q.x, q.y); + // the gown: from the waist (y = −0.1) to the floor (y = 0.9), widening + if y > -0.1 && y < 0.9 && x.abs() < 0.08 + 0.45 * (y + 0.1) { + // folds: soft, wavy dark lines that all aim at a point far below (y = 3) + let a = x.atan2(3.0 - y) + 0.012 * (y * 23.0).sin(); + let band = (a * 40.0).rem_euclid(1.0) < 0.15; + let piece = ((y * 9.0).floor() as i64 + (a * 40.0).floor() as i64).rem_euclid(3) == 0; + return if band && piece { [0.55; 3] } else { [0.92; 3] }; + } + // a plain, soft background + [0.35 + 0.05 * (x as f32); 3] + }, + ); + let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default()); + assert!(a.vertical_vp.is_none(), "folds are not structure: {:?}", a.vertical_vp); + assert!(crate::upright::shortfall(Upright::Vertical, &a).is_some(), "and it says why"); +} diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index f656311160..4dbf4a9af3 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -99,7 +99,8 @@ pub fn detect_segments(lum: &Plane) -> Vec { } sorted.sort_by(f32::total_cmp); let p90 = sorted[sorted.len() * 9 / 10]; - let thr = (p90 * 0.35).max(0.008); + // a quarter of the 90th percentile: a post's edge against foliage stays in + let thr = (p90 * 0.25).max(0.008); let mut order: Vec = (0..n as u32).filter(|&i| mag[i as usize] > thr).collect(); order.sort_by(|&a, &b| mag[b as usize].total_cmp(&mag[a as usize])); let mut used = vec![false; n]; @@ -273,6 +274,11 @@ fn refine_vp(segs: &[&Segment]) -> [f64; 3] { /// The dominant vanishing point of a segment family: RANSAC over pairs, then least squares on the inliers. /// Returns the point and the total inlier length, or None with fewer than two consistent segments. pub fn vanishing_point(segs: &[Segment]) -> Option<([f64; 3], f64)> { + vanishing_point_where(segs, |_| true) +} + +/// [`vanishing_point`] among the candidate points `ok` accepts. +fn vanishing_point_where(segs: &[Segment], ok: impl Fn([f64; 3]) -> bool) -> Option<([f64; 3], f64)> { if segs.len() < 2 { return None; } @@ -290,6 +296,9 @@ pub fn vanishing_point(segs: &[Segment]) -> Option<([f64; 3], f64)> { continue; } let v = norm(v); + if !ok(v) { + continue; + } let sc = score(v); if best.is_none_or(|b| sc > b.1) { best = Some((v, sc)); @@ -454,15 +463,36 @@ impl Reject { /// In words for the user: "No vertical correction: …". pub fn message(self) -> &'static str { match self { - Reject::TooFew => "it found too few straight lines", - Reject::TooShort => "the straight lines it found are too short", + Reject::TooFew => "too few straight lines", + Reject::TooShort => "the straight lines are too short", Reject::OneObject => "the straight lines are all on one object", - Reject::Disagree => "the straight lines point in different directions (people, trees or folds rather than buildings)", - Reject::MeetInside => "the straight lines meet inside the photo (a scene feature rather than a tilted camera)", + Reject::Disagree => "the long lines lean different ways", + Reject::MeetInside => "the lines meet inside the photo (a floor or a road, not a tilted camera)", } } } +/// How far (degrees) the camera turns to send the vertical vanishing point `v` to the image's y axis. +fn tilt_degrees(v: [f64; 3]) -> f64 { + let d = direction(v, DEFAULT_FOCAL); + d[1].abs().clamp(0.0, 1.0).acos().to_degrees() +} + +/// Whether a (homogeneous) vanishing point lies inside or near the photo (within twice the half long edge of +/// its centre): a scene feature rather than a camera tilt. +fn inside(v: [f64; 3]) -> bool { + v[2].abs() > 1e-9 && (v[0] / v[2]).hypot(v[1] / v[2]) < 2.0 +} + +/// A long line (in half long edges: 7.5 % of the long edge), and how far apart (across the family) two of them +/// must be to vouch for a vanishing point. Tuned on a photographer's own Upright corrections. +const LONG_LINE: f64 = 0.15; +const LONG_APART: f64 = 0.25; +/// Camera turns (degrees) above which a vertical correction needs three long lines and half the long lines' +/// length agreeing, and above which it needs most of it. +const BIG_TILT: f64 = 10.0; +const HUGE_TILT: f64 = 20.0; + /// Whether a family's vanishing point is backed by real structure rather than one object: at least three /// inlier segments, a total inlier length of a quarter of the long edge, and inliers spread across at least a /// fifth of the long edge perpendicular to the family, and most of the family's long lines agreeing (the @@ -476,7 +506,7 @@ fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> Result<(), Reject> let (lo, hi) = inl.iter().map(across).fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x))); // a camera-tilt vanishing point lies far outside the frame; one inside or near it is a scene feature // (sun rays, a road to the horizon), not perspective to correct - if v[2].abs() > 1e-9 && (v[0] / v[2]).hypot(v[1] / v[2]) < 2.0 { + if inside(v) { return Err(Reject::MeetInside); } if inl.len() < 3 { @@ -488,25 +518,143 @@ fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> Result<(), Reject> if hi - lo < 0.4 { return Err(Reject::OneObject); } + // real structure has long straight edges: at least two long lines, apart, agree (folds of a dress, hair + // and foliage are short pieces that agree by chance) + let long: Vec = inl.iter().filter(|s| s.len() >= LONG_LINE).map(across).collect(); + let spread = long.iter().fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + if long.len() < 2 || spread.1 - spread.0 < LONG_APART { + return Err(Reject::TooShort); + } + // a big correction needs more than a few lines: three long lines and half the long lines' + // length agreeing (the folds of a gown spreading to the floor point at a far point too) + let tilt = if vertical { tilt_degrees(v) } else { 0.0 }; // consensus: real structure agrees; mirrored flanks (trees, peaks) split the family in two halves that each // converge somewhere. Most of the family agreeing settles it; else the lines that disagree must not gather at // a rival point of their own nearly as strongly (people, folds and foliage point every which way, so a few // long posts among them still decide) - let family: f64 = segs.iter().map(Segment::len).sum(); + let mut family: f64 = segs.iter().map(Segment::len).sum(); + // (judged on the long lines: a gown's many short folds don't outvote the posts around it) + let long_family: f64 = segs.iter().filter(|s| s.len() >= LONG_LINE).map(Segment::len).sum(); + let long_total: f64 = inl.iter().filter(|s| s.len() >= LONG_LINE).map(|s| s.len()).sum(); + let share = if tilt > HUGE_TILT { 0.6 } else { 0.5 }; + if tilt > BIG_TILT && (long.len() < 3 || long_total < share * long_family) { + return Err(Reject::Disagree); + } + if total >= 0.6 * family { + return Ok(()); + } + // Lines that meet inside or near the photo are scene features (floorboards running to the horizon, the + // apex of a drape, rays), never a camera tilt: they neither vote against the posts nor make a rival + // (the posts of a gazebo were outvoted by its deck and its curtains). + let mut rest: Vec = segs.iter().copied().filter(|s| vp_error(s, v) >= thr).collect(); + let mut rival = 0.0; + for _ in 0..4 { + let Some((r, support)) = vanishing_point(&rest) else { break }; + if !inside(r) { + rival = support; + break; + } + let (scene, other): (Vec, Vec) = rest.iter().partition(|s| vp_error(s, r) < thr); + if scene.is_empty() { + break; + } + family -= scene.iter().map(Segment::len).sum::(); + rest = other; + } if total >= 0.6 * family { return Ok(()); } - let rest: Vec = segs.iter().copied().filter(|s| vp_error(s, v) >= thr).collect(); - let rival = vanishing_point(&rest).map_or(0.0, |(_, support)| support); if total >= 0.3 * family && total >= 2.0 * rival { return Ok(()); } + // most of the long lines agreeing settles it too (posts round a gown and its folds) + if long_total >= 0.6 * long_family { + return Ok(()); + } Err(Reject::Disagree) } +/// Join the pieces of one straight edge (a post's side broken by a person in front of it, a branch, a +/// highlight) into one line, so a long structural edge counts as long: pieces on the same line (within 1.5° +/// and about 3 px at the analysis size) with a gap of at most a quarter of the half long edge between them. +fn merge_collinear(mut segs: Vec) -> Vec { + segs.sort_by(|a, b| b.len().total_cmp(&a.len())); + // each line: its first (longest) piece as the reference, and every piece joined to it + let mut lines: Vec<(Segment, Vec)> = Vec::with_capacity(segs.len()); + for s in segs { + let joined = lines.iter_mut().find(|(l, _)| collinear(l, &s)); + match joined { + Some((l, pieces)) => { + pieces.push(s); + *l = fit_line(pieces).unwrap_or(*l); + } + None => lines.push((s, vec![s])), + } + } + lines.into_iter().map(|(l, _)| l).collect() +} + +/// Whether piece `s` lies on line `l` (within 1.5° and about 3 px at the analysis size) with a gap of at most a +/// quarter of the half long edge between them. +fn collinear(l: &Segment, s: &Segment) -> bool { + let (dx, dy) = (l.b.x - l.a.x, l.b.y - l.a.y); + let n = dx.hypot(dy); + if n < 1e-9 { + return false; + } + let (ux, uy) = (dx / n, dy / n); + let (sx, sy) = (s.b.x - s.a.x, s.b.y - s.a.y); + let sn = sx.hypot(sy).max(1e-12); + if ((ux * sx + uy * sy) / sn).abs() < 1.5f64.to_radians().cos() { + return false; + } + let off = |p: Point| (p.x - l.a.x) * -uy + (p.y - l.a.y) * ux; + if off(s.a).abs() > 0.006 || off(s.b).abs() > 0.006 { + return false; + } + let t = |p: Point| (p.x - l.a.x) * ux + (p.y - l.a.y) * uy; + let (t0, t1) = (t(s.a).min(t(s.b)), t(s.a).max(t(s.b))); + (t0 - n).max(-t1).max(0.0) <= 0.25 +} + +/// The line through pieces (their endpoints weighted by the piece's length, principal axis), from end to end. +fn fit_line(pieces: &[Segment]) -> Option { + let (mut sw, mut mx, mut my) = (0.0, 0.0, 0.0); + for s in pieces { + let w = s.len(); + for p in [s.a, s.b] { + sw += w; + mx += w * p.x; + my += w * p.y; + } + } + if sw <= 0.0 { + return None; + } + let (mx, my) = (mx / sw, my / sw); + let (mut sxx, mut syy, mut sxy) = (0.0, 0.0, 0.0); + for s in pieces { + let w = s.len(); + for p in [s.a, s.b] { + let (dx, dy) = (p.x - mx, p.y - my); + sxx += w * dx * dx; + syy += w * dy * dy; + sxy += w * dx * dy; + } + } + let th = 0.5 * (2.0 * sxy).atan2(sxx - syy); + let (ux, uy) = (th.cos(), th.sin()); + let t = |p: Point| (p.x - mx) * ux + (p.y - my) * uy; + let (lo, hi) = pieces.iter().flat_map(|s| [t(s.a), t(s.b)]).fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(v), hi.max(v))); + Some(Segment { a: Point::new(mx + ux * lo, my + uy * lo), b: Point::new(mx + ux * hi, my + uy * hi) }) +} + /// One family's vanishing point, if [`reliable`], else why not. fn family_vp(segs: &[Segment], vertical: bool) -> (Option<[f64; 3]>, Option) { - match vanishing_point(segs) { + // a camera tilt puts the point outside the photo: look there first, so lines meeting inside it (a deck + // running to the horizon) can't take the place of the posts + let found = vanishing_point_where(segs, |v| !inside(v)).or_else(|| vanishing_point(segs)); + match found { None => (None, Some(Reject::TooFew)), Some((v, _)) => match reliable(segs, v, vertical) { Ok(()) => (Some(v), None), @@ -518,8 +666,8 @@ fn family_vp(segs: &[Segment], vertical: bool) -> (Option<[f64; 3]>, Option Analysis { - let vertical: Vec = segs.iter().copied().filter(|s| s.tilt_from_vertical() < 30.0).collect(); - let horizontal: Vec = segs.iter().copied().filter(|s| s.tilt_from_vertical() > 60.0).collect(); + let vertical = merge_collinear(segs.iter().copied().filter(|s| s.tilt_from_vertical() < 30.0).collect()); + let horizontal = merge_collinear(segs.iter().copied().filter(|s| s.tilt_from_vertical() > 60.0).collect()); let (vertical_vp, vertical_why) = family_vp(&vertical, true); let (horizontal_vp, horizontal_why) = family_vp(&horizontal, false); Analysis { vertical, horizontal, vertical_vp, horizontal_vp, vertical_why, horizontal_why } @@ -625,9 +773,6 @@ const ANALYSIS_LONG: usize = 1024; /// segment detection and vanishing points. Cached per source + optics settings. pub fn analyze_source(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Analysis { static CACHE: Mutex> = Mutex::new(Vec::new()); - let mut base = s.clone(); - base.geometry = Geometry::default(); - base.crop = Crop::default(); let key = crate::optics::fingerprint(src) ^ lightcraft_develop::DevelopSettings { optics: s.optics, orientation: s.orientation, ..Default::default() }.hash64().rotate_left(17); if let Ok(c) = CACHE.lock() @@ -635,16 +780,7 @@ pub fn analyze_source(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> A { return a.clone(); } - let frame = crate::frame_for(src, info, &base, false); - let (w, h) = frame.fit(ANALYSIS_LONG, ANALYSIS_LONG); - let img = frame.sample(src, w, h); - // perceptual lightness, normalized to the image's bright end - let lum = img.luminance(); - let mut v: Vec = lum.data.iter().copied().filter(|x| x.is_finite()).collect(); - v.sort_by(f32::total_cmp); - let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4); - let lum = lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4)); - let a = analyze(&detect_segments(&lum)); + let a = analyze(&detect_segments(&analysis_luminance(src, info, s, ANALYSIS_LONG))); if let Ok(mut c) = CACHE.lock() { c.push((key, a.clone())); if c.len() > 8 { @@ -664,6 +800,37 @@ pub const STRAIGHTEN_MAX_DEGREES: f64 = 10.0; /// nothing about the horizon in that measurement. pub const STRAIGHTEN_MIN_LINES: usize = 3; +/// The plane Upright looks for lines in: the lens-corrected photo (optics and orientation applied, no +/// perspective or crop) at `long` px on its long edge, as perceptual lightness normalized to its bright end. +pub fn analysis_luminance(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, long: usize) -> Plane { + let mut base = s.clone(); + base.geometry = Geometry::default(); + base.crop = Crop::default(); + let frame = crate::frame_for(src, info, &base, false); + let (w, h) = frame.fit(long, long); + let img = frame.sample(src, w, h); + let lum = img.luminance(); + let mut v: Vec = lum.data.iter().copied().filter(|x| x.is_finite()).collect(); + v.sort_by(f32::total_cmp); + let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4); + lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4)) +} + +/// Analyse an [`analysis_luminance`] plane of any size (brought to the analysis size first). +pub fn analyze_plane(lum: &Plane) -> Analysis { + analyze_plane_at(lum, ANALYSIS_LONG) +} + +/// [`analyze_plane`] at `size` px on the long edge (at most the plane's own). +pub fn analyze_plane_at(lum: &Plane, size: usize) -> Analysis { + let long = lum.width.max(lum.height); + if long > size { + let fit = lightcraft_raster::resample::fit(lum, size, size, lightcraft_raster::resample::Filter::Box); + return analyze(&detect_segments(&fit)); + } + analyze(&detect_segments(lum)) +} + /// The rotation (degrees, clockwise +) that levels `src`'s dominant horizon/plumb lines, if they agree /// (the consensus rule of Upright Level), within [`STRAIGHTEN_MAX_DEGREES`] and backed by at least /// [`STRAIGHTEN_MIN_LINES`] lines. Used by the crop panel's Auto straighten. From c60c9c01a4ef96523485e1f7130083d3bf055979 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 26 Oct 2026 07:17:22 +1000 Subject: [PATCH 03/15] LR-EDIT-GEOM-UPRIGHT: Auto says why whenever it leaves a photo alone; review fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto's correction and its note now come from one decision, so a tilt it won't fix (over 5°) or a vertical correction too steep for it say why; a level horizon it accepts says nothing. Level with no lines says there are too few. Parity summary refreshed. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/tests_geometry.rs | 27 +++++++++++ crates/pipeline/src/upright.rs | 65 +++++++++++++++++---------- docs/parity-checklist.md | 6 +-- 3 files changed, 71 insertions(+), 27 deletions(-) diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index 401b0893a7..73b35b2536 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -732,3 +732,30 @@ fn upright_vertical_leaves_a_gown_without_structure_alone() { assert!(a.vertical_vp.is_none(), "folds are not structure: {:?}", a.vertical_vp); assert!(crate::upright::shortfall(Upright::Vertical, &a).is_some(), "and it says why"); } + +/// Auto's note follows what Auto did: a tilted horizon it won't fix (over 5°) and a vertical correction too steep +/// to make both say why, while a level horizon it accepts says nothing. +#[test] +fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() { + use crate::upright::{Analysis, Reject, Segment, shortfall, solve}; + use lightcraft_develop::Upright; + use lightcraft_geom::Homography; + let line = |deg: f64, y: f64| { + let (s, c) = deg.to_radians().sin_cos(); + Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) } + }; + // a level horizon: Auto accepts a zero-degree correction, so it has nothing to explain + let level = Analysis { horizontal: vec![line(0.0, -0.2), line(0.0, 0.2)], ..Analysis::default() }; + assert_eq!(shortfall(Upright::Auto, &level), None); + // a horizon 10° off: Auto leaves it alone, and says so + let tilted = Analysis { horizontal: vec![line(10.0, -0.2), line(10.0, 0.2)], ..Analysis::default() }; + assert_eq!(solve(Upright::Auto, &tilted), Homography::IDENTITY); + assert_eq!(shortfall(Upright::Auto, &tilted), Some(Reject::TooFew.message())); + // lines meeting just below the photo: too steep for Auto, which says so; Vertical still corrects them + let steep = Analysis { vertical_vp: Some([0.0, 0.3, 1.0]), ..Analysis::default() }; + assert_eq!(solve(Upright::Auto, &steep), Homography::IDENTITY); + assert_eq!(shortfall(Upright::Auto, &steep), Some(Reject::TooSteep.message())); + assert_ne!(solve(Upright::Vertical, &steep), Homography::IDENTITY); + // Level with no lines at all says there are too few, not that they disagree + assert_eq!(shortfall(Upright::Level, &Analysis::default()), Some(Reject::TooFew.message())); +} diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 4dbf4a9af3..14beafa52f 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -457,6 +457,8 @@ pub enum Reject { Disagree, /// They meet inside or near the photo: a scene feature (a road, rays), not a tilted camera. MeetInside, + /// Correcting them would turn the camera too far to be a tilt (Auto leaves it to Vertical). + TooSteep, } impl Reject { @@ -468,6 +470,7 @@ impl Reject { Reject::OneObject => "the straight lines are all on one object", Reject::Disagree => "the long lines lean different ways", Reject::MeetInside => "the lines meet inside the photo (a floor or a road, not a tilted camera)", + Reject::TooSteep => "the lines lean too far to be a tilted camera (Vertical corrects them anyway)", } } } @@ -679,10 +682,11 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { match mode { Upright::Vertical | Upright::Full if a.vertical_vp.is_none() => Some(a.vertical_why.unwrap_or(Reject::TooFew).message()), Upright::Full if a.horizontal_vp.is_none() => Some(a.horizontal_why.unwrap_or(Reject::TooFew).message()), - Upright::Level if level_angle(&a.vertical, &a.horizontal).is_none() => Some(Reject::Disagree.message()), - Upright::Auto if a.vertical_vp.is_none() && level_angle(&a.vertical, &a.horizontal).is_none() => { - Some(a.vertical_why.unwrap_or(Reject::TooFew).message()) + Upright::Level if level_angle(&a.vertical, &a.horizontal).is_none() => { + let why = if a.vertical.is_empty() && a.horizontal.is_empty() { Reject::TooFew } else { Reject::Disagree }; + Some(why.message()) } + Upright::Auto => auto(a).err().map(Reject::message), _ => None, } } @@ -704,29 +708,42 @@ pub fn solve(mode: Upright, a: &Analysis) -> Homography { Some((r, f)) => recentre(&rotation_homography(&r, f)), None => vertical().map(|r| recentre(&rotation_homography(&r, DEFAULT_FOCAL))).unwrap_or_else(level), }, - Upright::Auto => { - // A vertical family that implies a camera roll must be confirmed by the horizontals (a real roll tilts - // both); otherwise it is scene structure (e.g. the same-side flanks of many conical trees). - if let Some(v) = a.vertical_vp { - let (x, y) = if v[1] < 0.0 { (-v[0], -v[1]) } else { (v[0], v[1]) }; - let roll = x.atan2(y).to_degrees(); - let confirmed = roll.abs() <= 3.0 || level_angle(&[], &a.horizontal).is_some_and(|h| (h - roll).abs() <= 3.0); - if !confirmed { - let weaker = Analysis { vertical_vp: None, horizontal_vp: None, vertical_why: Some(Reject::Disagree), ..a.clone() }; - return solve(Upright::Auto, &weaker); - } - } - // balanced: full correction only when it is moderate, else vertical, else level - if let Some((r, f)) = full().filter(|(r, _)| rotation_angle(r) < 20f64.to_radians()) { - return recentre(&rotation_homography(&r, f)); - } - match vertical().filter(|r| rotation_angle(r) < 25f64.to_radians()) { - Some(r) => recentre(&rotation_homography(&r, DEFAULT_FOCAL)), - // conservative: only small horizon fixes; bigger tilts are usually intentional or scene lines - None => level_angle(&a.vertical, &a.horizontal).filter(|d| d.abs() <= 5.0).map(rot_z_h).unwrap_or(Homography::IDENTITY), - } + Upright::Auto => auto(a).unwrap_or(Homography::IDENTITY), + } +} + +/// What Auto does with an analysis: the correction it applies, or why it applies none. [`solve`] and +/// [`shortfall`] both ask it, so the note always matches the correction. +fn auto(a: &Analysis) -> Result { + // A vertical family that implies a camera roll must be confirmed by the horizontals (a real roll tilts + // both); otherwise it is scene structure (e.g. the same-side flanks of many conical trees). + if let Some(v) = a.vertical_vp { + let (x, y) = if v[1] < 0.0 { (-v[0], -v[1]) } else { (v[0], v[1]) }; + let roll = x.atan2(y).to_degrees(); + let confirmed = roll.abs() <= 3.0 || level_angle(&[], &a.horizontal).is_some_and(|h| (h - roll).abs() <= 3.0); + if !confirmed { + let weaker = Analysis { vertical_vp: None, horizontal_vp: None, vertical_why: Some(Reject::Disagree), ..a.clone() }; + return auto(&weaker); } } + // balanced: full correction only when it is moderate, else vertical, else level + if let Some((v, h)) = a.vertical_vp.zip(a.horizontal_vp) { + let f = focal_from_vps(v, h).unwrap_or(DEFAULT_FOCAL); + let r = solve_full(v, h, f); + if rotation_angle(&r) < 20f64.to_radians() { + return Ok(recentre(&rotation_homography(&r, f))); + } + } + let vertical = a.vertical_vp.map(|v| solve_vertical(v, DEFAULT_FOCAL)); + if let Some(r) = vertical.filter(|r| rotation_angle(r) < 25f64.to_radians()) { + return Ok(recentre(&rotation_homography(&r, DEFAULT_FOCAL))); + } + // conservative: only small horizon fixes; bigger tilts are usually intentional or scene lines + match level_angle(&a.vertical, &a.horizontal) { + Some(d) if d.abs() <= 5.0 => Ok(rot_z_h(d)), + _ if vertical.is_some() => Err(Reject::TooSteep), + _ => Err(a.vertical_why.unwrap_or(Reject::TooFew)), + } } /// Guided Upright from user guides (centred coordinates of the lens-corrected image). Guides closer to vertical diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 422bbf583f..cebf08b6a9 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -31,7 +31,7 @@ cited here still exists. Formerly docs/parity.md. | C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) | | D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) | | E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) | -| F. Edit panel — global adjustments (EDIT) | 44 | 2 | 3 | 1 | 28/28 (100%) | 13/14 (93%) | +| F. Edit panel — global adjustments (EDIT) | 43 | 3 | 3 | 1 | 28/28 (100%) | 12/14 (86%) | | G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) | | H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) | | I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) | @@ -53,9 +53,9 @@ cited here still exists. Formerly docs/parity.md. | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | | Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 421 | 65 | 57 | 35 | 196/203 (97%) | 146/161 (91%) | +| **Total** | 420 | 66 | 57 | 35 | 196/203 (97%) | 145/161 (90%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.5%** of 543 in-scope rows — P0 98.3% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.4%** of 543 in-scope rows — P0 98.3% of 203 · P1 94.1% of 161 · P2 56.7% of 178. ## Top gaps and shortcut notes From d595e955e2de0b4fd932d96f4166ce471c53c156 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Tue, 27 Oct 2026 00:43:13 +1000 Subject: [PATCH 04/15] LR-EDIT-GEOM-UPRIGHT: a refined vanishing point must pass the same test; the example refuses size 0 The least-squares point refined from a candidate's lines is now held to the `ok` test the candidates passed; when it fails, the candidate itself stands. Test: a_refined_vanishing_point_the_test_refuses_falls_back_to_its_candidate. The upright_planes example ignores UPRIGHT_SIZE=0 and uses its default. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/examples/upright_planes.rs | 2 +- crates/pipeline/src/upright.rs | 28 +++++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/pipeline/examples/upright_planes.rs b/crates/pipeline/examples/upright_planes.rs index b1ba8c226d..fa87f837ed 100644 --- a/crates/pipeline/examples/upright_planes.rs +++ b/crates/pipeline/examples/upright_planes.rs @@ -29,7 +29,7 @@ fn main() { for p in paths { let key = p.file_stem().unwrap().to_string_lossy().to_string(); let plane = read_plane(&p); - let size = std::env::var("UPRIGHT_SIZE").ok().and_then(|v| v.parse().ok()).unwrap_or(1024); + let size = std::env::var("UPRIGHT_SIZE").ok().and_then(|v| v.parse::().ok()).filter(|&n| n > 0).unwrap_or(1024); let a = upright::analyze_plane_at(&plane, size); let mut line = serde_json::json!({"key": key}); for (name, mode) in [("vertical", Upright::Vertical), ("auto", Upright::Auto), ("full", Upright::Full)] { diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 14beafa52f..7fbe3f2fe3 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -310,7 +310,8 @@ fn vanishing_point_where(segs: &[Segment], ok: impl Fn([f64; 3]) -> bool) -> Opt if inl.len() < 2 { return None; } - let v = refine_vp(&inl); + // refined, the point must still be one `ok` accepts (else the candidate it came from stands) + let v = Some(refine_vp(&inl)).filter(|r| ok(*r)).unwrap_or(v); let total: f64 = segs.iter().filter(|s| vp_error(s, v) < thr * 2.0).map(|s| s.len()).sum(); let count = segs.iter().filter(|s| vp_error(s, v) < thr * 2.0).count(); (count >= 2).then_some((v, total)) @@ -894,3 +895,28 @@ pub fn homography(g: &Geometry, ow: f64, oh: f64) -> Homography { _ => g.upright_transform.unwrap_or(Homography::IDENTITY), } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The point refined from a candidate's lines is still held to the same test as the candidate: one that test + /// turns down leaves the candidate itself (CodeRabbit on #2966). + #[test] + fn a_refined_vanishing_point_the_test_refuses_falls_back_to_its_candidate() { + // three near-vertical lines that nearly, not exactly, meet far above the photo + let segs = [ + Segment { a: Point::new(-0.5, -0.8), b: Point::new(-0.45, 0.8) }, + Segment { a: Point::new(0.5, -0.8), b: Point::new(0.45, 0.8) }, + Segment { a: Point::new(0.0, -0.8), b: Point::new(0.0003, 0.8) }, + ]; + // only the candidates made from two of the lines pass; the least-squares point of all three does not + let candidates: Vec<[f64; 3]> = (0..3) + .flat_map(|i| (i + 1..3).map(move |j| (i, j))) + .flat_map(|(i, j)| [norm(cross(segs[i].line(), segs[j].line())), norm(cross(segs[j].line(), segs[i].line()))]) + .collect(); + let ok = |v: [f64; 3]| candidates.contains(&v); + let (v, _) = vanishing_point_where(&segs, ok).expect("a point"); + assert!(ok(v), "{v:?} is not one of the candidates"); + } +} From a9f8c9a2dcfa764af5f0e127dc541135f53fb43d Mon Sep 17 00:00:00 2001 From: OneSlips Date: Tue, 27 Oct 2026 17:07:32 +1000 Subject: [PATCH 05/15] LR-EDIT-GEOM-UPRIGHT: a note implies an identity transform in the upright test (CodeRabbit, #2966) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 862cb1dd55..e54223bce7 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2023,6 +2023,7 @@ fn upright_says_why_it_found_nothing_to_correct() { match r["note"].as_str() { Some(note) => { noted += 1; + assert!(identity, "a note was returned with a correction: {r}"); assert!(note.starts_with("No vertical correction: "), "{note}"); } None => assert!(!identity, "a vertical correction was found: {r}"), From 97a9344fcec2ae4560f83f109ca27176a471b7fb Mon Sep 17 00:00:00 2001 From: OneSlips Date: Tue, 27 Oct 2026 19:24:36 +1000 Subject: [PATCH 06/15] LR-EDIT-GEOM-UPRIGHT: scene lines inside the photo don't count in either long-line check (CodeRabbit, #2966) Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/upright.rs | 62 +++++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 20 deletions(-) diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 7fbe3f2fe3..d29be4d61c 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -538,32 +538,34 @@ fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> Result<(), Reject> // long posts among them still decide) let mut family: f64 = segs.iter().map(Segment::len).sum(); // (judged on the long lines: a gown's many short folds don't outvote the posts around it) - let long_family: f64 = segs.iter().filter(|s| s.len() >= LONG_LINE).map(Segment::len).sum(); + let mut long_family: f64 = segs.iter().filter(|s| s.len() >= LONG_LINE).map(Segment::len).sum(); let long_total: f64 = inl.iter().filter(|s| s.len() >= LONG_LINE).map(|s| s.len()).sum(); let share = if tilt > HUGE_TILT { 0.6 } else { 0.5 }; - if tilt > BIG_TILT && (long.len() < 3 || long_total < share * long_family) { - return Err(Reject::Disagree); - } - if total >= 0.6 * family { - return Ok(()); - } + let big = tilt > BIG_TILT; // Lines that meet inside or near the photo are scene features (floorboards running to the horizon, the // apex of a drape, rays), never a camera tilt: they neither vote against the posts nor make a rival - // (the posts of a gazebo were outvoted by its deck and its curtains). - let mut rest: Vec = segs.iter().copied().filter(|s| vp_error(s, v) >= thr).collect(); + // (the posts of a gazebo were outvoted by its deck and its curtains), and the big-tilt test below + // doesn't count them either. let mut rival = 0.0; - for _ in 0..4 { - let Some((r, support)) = vanishing_point(&rest) else { break }; - if !inside(r) { - rival = support; - break; + if big || total < 0.6 * family { + let mut rest: Vec = segs.iter().copied().filter(|s| vp_error(s, v) >= thr).collect(); + for _ in 0..4 { + let Some((r, support)) = vanishing_point(&rest) else { break }; + if !inside(r) { + rival = support; + break; + } + let (scene, other): (Vec, Vec) = rest.iter().partition(|s| vp_error(s, r) < thr); + if scene.is_empty() { + break; + } + family -= scene.iter().map(Segment::len).sum::(); + long_family -= scene.iter().filter(|s| s.len() >= LONG_LINE).map(Segment::len).sum::(); + rest = other; } - let (scene, other): (Vec, Vec) = rest.iter().partition(|s| vp_error(s, r) < thr); - if scene.is_empty() { - break; - } - family -= scene.iter().map(Segment::len).sum::(); - rest = other; + } + if big && (long.len() < 3 || long_total < share * long_family) { + return Err(Reject::Disagree); } if total >= 0.6 * family { return Ok(()); @@ -919,4 +921,24 @@ mod tests { let (v, _) = vanishing_point_where(&segs, ok).expect("a point"); assert!(ok(v), "{v:?} is not one of the candidates"); } + + /// Long lines meeting inside the photo (floorboards, a drape) are scene features: they don't make a big + /// tilt's posts look outvoted (CodeRabbit on #2966). + #[test] + fn scene_lines_inside_the_photo_do_not_outvote_a_big_tilts_posts() { + // three posts leaning to a point far above the photo: a camera tilt of about 15 degrees + let v = norm([0.0, 5.6, 1.0]); + assert!(tilt_degrees(v) > BIG_TILT && tilt_degrees(v) < HUGE_TILT, "{}", tilt_degrees(v)); + let toward = |x: f64, (px, py): (f64, f64), y1: f64| { + let t = (y1 + 0.8) / (py + 0.8); + Segment { a: Point::new(x, -0.8), b: Point::new(x + (px - x) * t, y1) } + }; + let mut segs: Vec = [-0.8, 0.0, 0.8].iter().map(|&x| toward(x, (0.0, 5.6), 0.8)).collect(); + // six longer floor lines running to a point inside the photo, more length than the posts + segs.extend([-0.5, -0.35, -0.2, 0.2, 0.35, 0.5].iter().map(|&x| toward(x, (0.0, 0.9), 0.6))); + let posts: f64 = segs[..3].iter().map(Segment::len).sum(); + let floor: f64 = segs[3..].iter().map(Segment::len).sum(); + assert!(posts < 0.5 * (posts + floor), "the floor lines must outweigh the posts: {posts} vs {floor}"); + assert_eq!(reliable(&segs, v, true), Ok(())); + } } From 347d2bd62cf1fa90ce7d8d941f967d1d80c3d344 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 1 Nov 2026 07:58:21 +1000 Subject: [PATCH 07/15] LR-EDIT-GEOM-UPRIGHT: Auto says a horizon is too tilted to level; Full's hint names the missing lines (CodeRabbit, #2966) Auto declining a horizon more than 5 degrees off now says so (the new TooTilted reason) instead of 'too few straight lines'. When Full finds the verticals but not the horizontals, its note asks for horizontal guides. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/develop.rs | 9 +++++---- crates/pipeline/src/tests_geometry.rs | 17 ++++++++++++++++- crates/pipeline/src/upright.rs | 10 ++++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 797798fa62..87946dca30 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -841,13 +841,14 @@ pub fn specs() -> Vec { serde_json::from_value(p.get("mode").cloned().unwrap_or(json!("auto"))).map_err(|e| bad("geometry.upright", e.to_string()))?; let id = active(s, "geometry.upright")?; let d = s.develop_of(id).unwrap_or_default(); - let (transform, note) = match mode { - Upright::Off | Upright::Guided => (None, None), + let (transform, note, family) = match mode { + Upright::Off | Upright::Guided => (None, None, "vertical"), m => { let src = s.source_now(id, SourceLevel::Preview).map_err(|e| bad("geometry.upright", e))?; let info = s.source_info(id); let a = lightcraft_pipeline::upright::analyze_source(&src, &info, &d); - (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a)) + let family = lightcraft_pipeline::upright::missing_family(m, &a); + (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a), family) } }; edit(s, "geometry.upright", "Upright", |d| { @@ -863,7 +864,7 @@ pub fn specs() -> Vec { Upright::Full => "No full correction", _ => "No Upright correction", }; - format!("{what}: {why}. Try Guided: draw lines along what should be vertical.") + format!("{what}: {why}. Try Guided: draw lines along what should be {family}.") }); Ok(json!({"mode": mode, "transform": transform, "note": note})) } diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index ab059e9773..19cef45bc1 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -842,7 +842,8 @@ fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() { // a horizon 10° off: Auto leaves it alone, and says so let tilted = Analysis { horizontal: vec![line(10.0, -0.2), line(10.0, 0.2)], ..Analysis::default() }; assert_eq!(solve(Upright::Auto, &tilted), Homography::IDENTITY); - assert_eq!(shortfall(Upright::Auto, &tilted), Some(Reject::TooFew.message())); + assert_eq!(shortfall(Upright::Auto, &tilted), Some(Reject::TooTilted.message()), "too tilted, not too few lines"); + assert_ne!(solve(Upright::Level, &tilted), Homography::IDENTITY, "Level still fixes it"); // lines meeting just below the photo: too steep for Auto, which says so; Vertical still corrects them let steep = Analysis { vertical_vp: Some([0.0, 0.3, 1.0]), ..Analysis::default() }; assert_eq!(solve(Upright::Auto, &steep), Homography::IDENTITY); @@ -851,3 +852,17 @@ fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() { // Level with no lines at all says there are too few, not that they disagree assert_eq!(shortfall(Upright::Level, &Analysis::default()), Some(Reject::TooFew.message())); } + +/// The Guided hint names the lines the mode is missing: Full with verticals but no horizontals asks for horizontal +/// guides, and with no verticals (or in Vertical) for vertical ones. +#[test] +fn upright_hint_asks_for_the_missing_line_family() { + use crate::upright::{Analysis, missing_family}; + use lightcraft_develop::Upright; + let verticals_only = Analysis { vertical_vp: Some([0.0, 8.0, 1.0]), ..Analysis::default() }; + assert_eq!(missing_family(Upright::Full, &verticals_only), "horizontal"); + assert_eq!(missing_family(Upright::Full, &Analysis::default()), "vertical"); + assert_eq!(missing_family(Upright::Vertical, &Analysis::default()), "vertical"); + let horizontals_only = Analysis { horizontal_vp: Some([8.0, 0.0, 1.0]), ..Analysis::default() }; + assert_eq!(missing_family(Upright::Full, &horizontals_only), "vertical"); +} diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index dae667b809..b1b71c212f 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -460,6 +460,8 @@ pub enum Reject { MeetInside, /// Correcting them would turn the camera too far to be a tilt (Auto leaves it to Vertical). TooSteep, + /// The horizon is tilted more than Auto levels (5°): usually intentional, or scene lines (Level fixes it anyway). + TooTilted, } impl Reject { @@ -472,6 +474,7 @@ impl Reject { Reject::Disagree => "the long lines lean different ways", Reject::MeetInside => "the lines meet inside the photo (a floor or a road, not a tilted camera)", Reject::TooSteep => "the lines lean too far to be a tilted camera (Vertical corrects them anyway)", + Reject::TooTilted => "the horizon is tilted too far to be a levelling fix (Level corrects it anyway)", } } } @@ -694,6 +697,12 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { } } +/// The line family Guided needs drawn when `mode` falls short ("vertical" or "horizontal"): Full that found its +/// verticals but not its horizontals needs horizontal guides; everything else needs vertical ones. +pub fn missing_family(mode: Upright, a: &Analysis) -> &'static str { + if mode == Upright::Full && a.vertical_vp.is_some() && a.horizontal_vp.is_none() { "horizontal" } else { "vertical" } +} + /// The Upright correction for `mode` from an analysis (lens-corrected → transformed, centred coordinates). pub fn solve(mode: Upright, a: &Analysis) -> Homography { let level = || level_angle(&a.vertical, &a.horizontal).map(rot_z_h).unwrap_or(Homography::IDENTITY); @@ -745,6 +754,7 @@ fn auto(a: &Analysis) -> Result { match level_angle(&a.vertical, &a.horizontal) { Some(d) if d.abs() <= 5.0 => Ok(rot_z_h(d)), _ if vertical.is_some() => Err(Reject::TooSteep), + Some(_) => Err(Reject::TooTilted), _ => Err(a.vertical_why.unwrap_or(Reject::TooFew)), } } From 59ddd490f15538de07d422d52ce0b72cec5f761c Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 1 Nov 2026 11:29:06 +1000 Subject: [PATCH 08/15] LR-EDIT-GEOM-UPRIGHT: Full's hint asks for both guide families; the too-tilted reason names lines, not the horizon (CodeRabbit, #2966) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/develop.rs | 2 +- crates/pipeline/src/tests_geometry.rs | 17 +++++++---------- crates/pipeline/src/upright.rs | 13 +++++++------ 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 87946dca30..6a9cf9de48 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -847,7 +847,7 @@ pub fn specs() -> Vec { let src = s.source_now(id, SourceLevel::Preview).map_err(|e| bad("geometry.upright", e))?; let info = s.source_info(id); let a = lightcraft_pipeline::upright::analyze_source(&src, &info, &d); - let family = lightcraft_pipeline::upright::missing_family(m, &a); + let family = lightcraft_pipeline::upright::missing_family(m); (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a), family) } }; diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index 19cef45bc1..f4e00b3321 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -853,16 +853,13 @@ fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() { assert_eq!(shortfall(Upright::Level, &Analysis::default()), Some(Reject::TooFew.message())); } -/// The Guided hint names the lines the mode is missing: Full with verticals but no horizontals asks for horizontal -/// guides, and with no verticals (or in Vertical) for vertical ones. +/// The Guided hint names the lines to draw: Full needs both families (Guided uses only the guides drawn), the +/// other modes vertical ones. #[test] -fn upright_hint_asks_for_the_missing_line_family() { - use crate::upright::{Analysis, missing_family}; +fn upright_hint_asks_for_the_lines_guided_needs() { + use crate::upright::missing_family; use lightcraft_develop::Upright; - let verticals_only = Analysis { vertical_vp: Some([0.0, 8.0, 1.0]), ..Analysis::default() }; - assert_eq!(missing_family(Upright::Full, &verticals_only), "horizontal"); - assert_eq!(missing_family(Upright::Full, &Analysis::default()), "vertical"); - assert_eq!(missing_family(Upright::Vertical, &Analysis::default()), "vertical"); - let horizontals_only = Analysis { horizontal_vp: Some([8.0, 0.0, 1.0]), ..Analysis::default() }; - assert_eq!(missing_family(Upright::Full, &horizontals_only), "vertical"); + assert_eq!(missing_family(Upright::Full), "vertical and what should be horizontal"); + assert_eq!(missing_family(Upright::Vertical), "vertical"); + assert_eq!(missing_family(Upright::Level), "vertical"); } diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index b1b71c212f..94ca8ac661 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -460,7 +460,8 @@ pub enum Reject { MeetInside, /// Correcting them would turn the camera too far to be a tilt (Auto leaves it to Vertical). TooSteep, - /// The horizon is tilted more than Auto levels (5°): usually intentional, or scene lines (Level fixes it anyway). + /// The lines it would level by (horizontal, else vertical) are tilted more than Auto levels (5°): usually + /// intentional, or scene lines (Level fixes it anyway). TooTilted, } @@ -474,7 +475,7 @@ impl Reject { Reject::Disagree => "the long lines lean different ways", Reject::MeetInside => "the lines meet inside the photo (a floor or a road, not a tilted camera)", Reject::TooSteep => "the lines lean too far to be a tilted camera (Vertical corrects them anyway)", - Reject::TooTilted => "the horizon is tilted too far to be a levelling fix (Level corrects it anyway)", + Reject::TooTilted => "the lines are tilted too far to be a levelling fix (Level corrects them anyway)", } } } @@ -697,10 +698,10 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { } } -/// The line family Guided needs drawn when `mode` falls short ("vertical" or "horizontal"): Full that found its -/// verticals but not its horizontals needs horizontal guides; everything else needs vertical ones. -pub fn missing_family(mode: Upright, a: &Analysis) -> &'static str { - if mode == Upright::Full && a.vertical_vp.is_some() && a.horizontal_vp.is_none() { "horizontal" } else { "vertical" } +/// The lines Guided needs drawn when `mode` falls short: Full needs both families drawn (Guided works from the +/// guides alone, not from lines Full found), the others vertical ones. +pub fn missing_family(mode: Upright) -> &'static str { + if mode == Upright::Full { "vertical and what should be horizontal" } else { "vertical" } } /// The Upright correction for `mode` from an analysis (lens-corrected → transformed, centred coordinates). From f1c1f8a308f27ee2506c8386202303d6156a0cba Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 1 Nov 2026 15:30:43 +1000 Subject: [PATCH 09/15] LR-EDIT-GEOM-UPRIGHT: the Guided hint says how many lines to draw (CodeRabbit, #2966) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/develop.rs | 6 +++--- crates/pipeline/src/tests_geometry.rs | 13 +++++++------ crates/pipeline/src/upright.rs | 13 +++++++++---- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 6a9cf9de48..e14347c9b1 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -842,12 +842,12 @@ pub fn specs() -> Vec { let id = active(s, "geometry.upright")?; let d = s.develop_of(id).unwrap_or_default(); let (transform, note, family) = match mode { - Upright::Off | Upright::Guided => (None, None, "vertical"), + Upright::Off | Upright::Guided => (None, None, ""), m => { let src = s.source_now(id, SourceLevel::Preview).map_err(|e| bad("geometry.upright", e))?; let info = s.source_info(id); let a = lightcraft_pipeline::upright::analyze_source(&src, &info, &d); - let family = lightcraft_pipeline::upright::missing_family(m); + let family = lightcraft_pipeline::upright::guided_hint(m); (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a), family) } }; @@ -864,7 +864,7 @@ pub fn specs() -> Vec { Upright::Full => "No full correction", _ => "No Upright correction", }; - format!("{what}: {why}. Try Guided: draw lines along what should be {family}.") + format!("{what}: {why}. Try Guided: draw {family}.") }); Ok(json!({"mode": mode, "transform": transform, "note": note})) } diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index f4e00b3321..1f304f0dc9 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -853,13 +853,14 @@ fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() { assert_eq!(shortfall(Upright::Level, &Analysis::default()), Some(Reject::TooFew.message())); } -/// The Guided hint names the lines to draw: Full needs both families (Guided uses only the guides drawn), the -/// other modes vertical ones. +/// The Guided hint says what to draw: Full needs two guides of each family (Guided uses only the guides drawn, and +/// one of a kind only levels), Vertical two vertical ones, and Level a single line. #[test] fn upright_hint_asks_for_the_lines_guided_needs() { - use crate::upright::missing_family; + use crate::upright::guided_hint; use lightcraft_develop::Upright; - assert_eq!(missing_family(Upright::Full), "vertical and what should be horizontal"); - assert_eq!(missing_family(Upright::Vertical), "vertical"); - assert_eq!(missing_family(Upright::Level), "vertical"); + assert_eq!(guided_hint(Upright::Full), "two lines along what should be vertical and two along what should be horizontal"); + assert_eq!(guided_hint(Upright::Vertical), "two lines along what should be vertical"); + assert_eq!(guided_hint(Upright::Level), "a line along what should be level or upright"); + assert_eq!(guided_hint(Upright::Auto), "two lines along what should be vertical"); } diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 94ca8ac661..c212ff51f7 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -698,10 +698,15 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { } } -/// The lines Guided needs drawn when `mode` falls short: Full needs both families drawn (Guided works from the -/// guides alone, not from lines Full found), the others vertical ones. -pub fn missing_family(mode: Upright) -> &'static str { - if mode == Upright::Full { "vertical and what should be horizontal" } else { "vertical" } +/// What to draw in Guided when `mode` falls short ("Try Guided: draw …"). Guided works from the guides alone, not +/// from lines the mode found, and one guide of a kind only levels ([`solve_guided`]): Full needs two of each +/// family, Vertical two vertical ones, and levelling one line. +pub fn guided_hint(mode: Upright) -> &'static str { + match mode { + Upright::Full => "two lines along what should be vertical and two along what should be horizontal", + Upright::Level => "a line along what should be level or upright", + _ => "two lines along what should be vertical", + } } /// The Upright correction for `mode` from an analysis (lens-corrected → transformed, centred coordinates). From bb9e1746861d7ae094ea07a9d1bbd73fe16ab932 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Sun, 1 Nov 2026 22:21:02 +1000 Subject: [PATCH 10/15] LR-EDIT-GEOM-UPRIGHT: Auto's Guided hint also offers one level line, and one guide of each family only levels (CodeRabbit, #2966) Auto falls short for its verticals or for a horizon tilted past the 5 degrees it levels; one level guide fixes the second in Guided, so its hint names both. A test checks that one vertical and one horizontal guide only level, and that the one line Auto's hint offers levels a horizon 10 degrees off. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/tests_geometry.rs | 29 ++++++++++++++++++++++++++- crates/pipeline/src/upright.rs | 5 ++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index 1f304f0dc9..ed5991d9df 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -862,5 +862,32 @@ fn upright_hint_asks_for_the_lines_guided_needs() { assert_eq!(guided_hint(Upright::Full), "two lines along what should be vertical and two along what should be horizontal"); assert_eq!(guided_hint(Upright::Vertical), "two lines along what should be vertical"); assert_eq!(guided_hint(Upright::Level), "a line along what should be level or upright"); - assert_eq!(guided_hint(Upright::Auto), "two lines along what should be vertical"); + assert_eq!(guided_hint(Upright::Auto), "two lines along what should be vertical, or one line along what should be level"); +} + +/// What the hints promise is what Guided does: one vertical and one horizontal guide only level (the horizontal one +/// becomes level, the vertical one keeps its lean, so Full's hint asks for two of each), and the single level line +/// Auto's hint offers fixes the horizon Auto leaves alone for being more than 5° off. +#[test] +fn solve_guided_levels_one_guide_of_each_family_only() { + use crate::upright::{Analysis, Reject, Segment, shortfall, solve_guided}; + use lightcraft_develop::Upright; + let vertical = Segment { a: Point::new(0.1, -0.5), b: Point::new(0.19, 0.5) }; + let horizontal = Segment { a: Point::new(-0.5, 0.1), b: Point::new(0.5, 0.12) }; + let h = solve_guided(&[vertical, horizontal]); + let (p, q) = (h.apply(horizontal.a), h.apply(horizontal.b)); + assert!((p.y - q.y).abs() < 1e-9, "the horizontal guide is levelled: {p:?} {q:?}"); + let (p, q) = (h.apply(vertical.a), h.apply(vertical.b)); + assert!((p.x - q.x).abs() > 0.03, "the vertical guide keeps its lean (no full correction): {p:?} {q:?}"); + // a horizon 10° off: too tilted for Auto, levelled by the one line its hint asks for + let (s, c) = 10f64.to_radians().sin_cos(); + let horizon = Segment { a: Point::new(-0.4 * c, -0.4 * s), b: Point::new(0.4 * c, 0.4 * s) }; + let tilted = Analysis { + horizontal: vec![horizon, Segment { a: Point::new(horizon.a.x, 0.2 + horizon.a.y), b: Point::new(horizon.b.x, 0.2 + horizon.b.y) }], + ..Analysis::default() + }; + assert_eq!(shortfall(Upright::Auto, &tilted), Some(Reject::TooTilted.message())); + let h = solve_guided(&[horizon]); + let (p, q) = (h.apply(horizon.a), h.apply(horizon.b)); + assert!((p.y - q.y).abs() < 1e-9, "one level guide fixes it: {p:?} {q:?}"); } diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index c212ff51f7..edebc5bed0 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -700,11 +700,14 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { /// What to draw in Guided when `mode` falls short ("Try Guided: draw …"). Guided works from the guides alone, not /// from lines the mode found, and one guide of a kind only levels ([`solve_guided`]): Full needs two of each -/// family, Vertical two vertical ones, and levelling one line. +/// family, Vertical two vertical ones, and levelling one line. Auto falls short either for its verticals (two +/// vertical guides) or for a horizon tilted more than it levels ([`Reject::TooTilted`]: one level guide), so it names +/// both. pub fn guided_hint(mode: Upright) -> &'static str { match mode { Upright::Full => "two lines along what should be vertical and two along what should be horizontal", Upright::Level => "a line along what should be level or upright", + Upright::Auto => "two lines along what should be vertical, or one line along what should be level", _ => "two lines along what should be vertical", } } From 0e4cdb47760d2b04574bc20d354e6223ff02a765 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 2 Nov 2026 02:00:15 +1000 Subject: [PATCH 11/15] LR-EDIT-GEOM-UPRIGHT: Auto's Guided hint follows why Auto stopped: one level line for a tilted horizon, vertical lines for steep posts (CodeRabbit, #2966) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit guided_hint takes the analysis. When Auto refuses a horizon over 5° it offers one level line; when it refuses converging posts as too steep it asks for two vertical lines only, since one level guide only levels and can't straighten them. With too few or unusable lines it still names both. Test: upright_hint_asks_for_the_lines_guided_needs covers the tilted and steep cases. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/develop.rs | 2 +- crates/pipeline/src/tests_geometry.rs | 22 +++++++++++++++++----- crates/pipeline/src/upright.rs | 22 ++++++++++++++-------- 3 files changed, 32 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index e14347c9b1..0e978bcd59 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -847,7 +847,7 @@ pub fn specs() -> Vec { let src = s.source_now(id, SourceLevel::Preview).map_err(|e| bad("geometry.upright", e))?; let info = s.source_info(id); let a = lightcraft_pipeline::upright::analyze_source(&src, &info, &d); - let family = lightcraft_pipeline::upright::guided_hint(m); + let family = lightcraft_pipeline::upright::guided_hint(m, &a); (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a), family) } }; diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index ed5991d9df..7a716ee17e 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -857,12 +857,24 @@ fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() { /// one of a kind only levels), Vertical two vertical ones, and Level a single line. #[test] fn upright_hint_asks_for_the_lines_guided_needs() { - use crate::upright::guided_hint; + use crate::upright::{Analysis, Segment, guided_hint}; use lightcraft_develop::Upright; - assert_eq!(guided_hint(Upright::Full), "two lines along what should be vertical and two along what should be horizontal"); - assert_eq!(guided_hint(Upright::Vertical), "two lines along what should be vertical"); - assert_eq!(guided_hint(Upright::Level), "a line along what should be level or upright"); - assert_eq!(guided_hint(Upright::Auto), "two lines along what should be vertical, or one line along what should be level"); + let none = Analysis::default(); + assert_eq!(guided_hint(Upright::Full, &none), "two lines along what should be vertical and two along what should be horizontal"); + assert_eq!(guided_hint(Upright::Vertical, &none), "two lines along what should be vertical"); + assert_eq!(guided_hint(Upright::Level, &none), "a line along what should be level or upright"); + // Auto with no usable lines: either kind of guide can help + assert_eq!(guided_hint(Upright::Auto, &none), "two lines along what should be vertical, or one line along what should be level"); + // Auto stopped by a horizon over 5°: one level line fixes it (solve_guided_levels_one_guide_of_each_family_only) + let line = |deg: f64, y: f64| { + let (s, c) = deg.to_radians().sin_cos(); + Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) } + }; + let tilted = Analysis { horizontal: vec![line(10.0, -0.2), line(10.0, 0.2)], ..Analysis::default() }; + assert_eq!(guided_hint(Upright::Auto, &tilted), "one line along what should be level"); + // Auto stopped by converging posts too steep for it: a level line can't straighten them (CodeRabbit, #2966) + let steep = Analysis { vertical_vp: Some([0.0, 0.3, 1.0]), ..Analysis::default() }; + assert_eq!(guided_hint(Upright::Auto, &steep), "two lines along what should be vertical"); } /// What the hints promise is what Guided does: one vertical and one horizontal guide only level (the horizontal one diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index edebc5bed0..6454f5bc54 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -698,17 +698,23 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { } } -/// What to draw in Guided when `mode` falls short ("Try Guided: draw …"). Guided works from the guides alone, not -/// from lines the mode found, and one guide of a kind only levels ([`solve_guided`]): Full needs two of each -/// family, Vertical two vertical ones, and levelling one line. Auto falls short either for its verticals (two -/// vertical guides) or for a horizon tilted more than it levels ([`Reject::TooTilted`]: one level guide), so it names -/// both. -pub fn guided_hint(mode: Upright) -> &'static str { +/// What to draw in Guided when `mode` falls short on `a` ("Try Guided: draw …"). Guided works from the guides +/// alone, not from lines the mode found, and one guide of a kind only levels ([`solve_guided`]): Full needs two of +/// each family, Vertical two vertical ones, and levelling one line. Auto follows why it stopped: a horizon tilted +/// more than it levels ([`Reject::TooTilted`]) takes one level guide; a vertical correction too steep for it +/// ([`Reject::TooSteep`]) needs two vertical guides, as one level line can't straighten converging posts; with too +/// few or unusable lines either can help, so it names both. +pub fn guided_hint(mode: Upright, a: &Analysis) -> &'static str { + const VERTICAL: &str = "two lines along what should be vertical"; match mode { Upright::Full => "two lines along what should be vertical and two along what should be horizontal", Upright::Level => "a line along what should be level or upright", - Upright::Auto => "two lines along what should be vertical, or one line along what should be level", - _ => "two lines along what should be vertical", + Upright::Auto => match auto(a) { + Err(Reject::TooTilted) => "one line along what should be level", + Err(Reject::TooSteep) => VERTICAL, + _ => "two lines along what should be vertical, or one line along what should be level", + }, + _ => VERTICAL, } } From edc649014bb019c1350f6b919f303c44aad5014a Mon Sep 17 00:00:00 2001 From: OneSlips Date: Mon, 2 Nov 2026 04:46:51 +1000 Subject: [PATCH 12/15] LR-EDIT-GEOM-UPRIGHT: a photo levelled by its upright lines asks for an upright line when it leans too far When Guided levels a photo by its vertical lines (few or no horizontal ones), a lean past the limit now asks for one line along what should be upright, not a level line it would not use. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/tests_geometry.rs | 4 ++++ crates/pipeline/src/upright.rs | 19 ++++++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index 7a716ee17e..8bd44e6f12 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -872,6 +872,10 @@ fn upright_hint_asks_for_the_lines_guided_needs() { }; let tilted = Analysis { horizontal: vec![line(10.0, -0.2), line(10.0, 0.2)], ..Analysis::default() }; assert_eq!(guided_hint(Upright::Auto, &tilted), "one line along what should be level"); + // the same tilt found from vertical lines only (posts 10° off, no horizon): one upright line, as + // one vertical guide levels too (CodeRabbit, #2966) + let leaning = Analysis { vertical: vec![line(100.0, -0.2), line(100.0, 0.2)], ..Analysis::default() }; + assert_eq!(guided_hint(Upright::Auto, &leaning), "one line along what should be upright"); // Auto stopped by converging posts too steep for it: a level line can't straighten them (CodeRabbit, #2966) let steep = Analysis { vertical_vp: Some([0.0, 0.3, 1.0]), ..Analysis::default() }; assert_eq!(guided_hint(Upright::Auto, &steep), "two lines along what should be vertical"); diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 6454f5bc54..ac23037dc9 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -390,6 +390,14 @@ fn level_angle(vert: &[Segment], horiz: &[Segment]) -> Option { /// [`level_angle`] that only answers for at most `max` degrees, backed by at least `min_lines` /// agreeing segments. +/// Whether levelling goes by the vertical lines: the horizontal ones lead unless there are none or +/// their length is under half the verticals'. +fn levels_by_vertical(vert: &[Segment], horiz: &[Segment]) -> bool { + let lh: f64 = horiz.iter().map(Segment::len).sum(); + let lv: f64 = vert.iter().map(Segment::len).sum(); + !(lh >= lv * 0.5 && lh > 0.0) +} + pub(crate) fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64, min_lines: usize) -> Option { let dev = |s: &Segment, vertical: bool| { let (dx, dy) = (s.b.x - s.a.x, s.b.y - s.a.y); @@ -405,9 +413,8 @@ pub(crate) fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64, }; if vertical { -a } else { a } }; - let lh: f64 = horiz.iter().map(Segment::len).sum(); - let lv: f64 = vert.iter().map(Segment::len).sum(); - let (set, vertical) = if lh >= lv * 0.5 && lh > 0.0 { (horiz, false) } else { (vert, true) }; + let vertical = levels_by_vertical(vert, horiz); + let set = if vertical { vert } else { horiz }; if set.is_empty() { return None; } @@ -700,8 +707,9 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { /// What to draw in Guided when `mode` falls short on `a` ("Try Guided: draw …"). Guided works from the guides /// alone, not from lines the mode found, and one guide of a kind only levels ([`solve_guided`]): Full needs two of -/// each family, Vertical two vertical ones, and levelling one line. Auto follows why it stopped: a horizon tilted -/// more than it levels ([`Reject::TooTilted`]) takes one level guide; a vertical correction too steep for it +/// each family, Vertical two vertical ones, and levelling one line. Auto follows why it stopped: a tilt more than +/// it levels ([`Reject::TooTilted`]) takes one guide of the family it levelled by (a level line for a horizon, an +/// upright one when only vertical lines were found); a vertical correction too steep for it /// ([`Reject::TooSteep`]) needs two vertical guides, as one level line can't straighten converging posts; with too /// few or unusable lines either can help, so it names both. pub fn guided_hint(mode: Upright, a: &Analysis) -> &'static str { @@ -710,6 +718,7 @@ pub fn guided_hint(mode: Upright, a: &Analysis) -> &'static str { Upright::Full => "two lines along what should be vertical and two along what should be horizontal", Upright::Level => "a line along what should be level or upright", Upright::Auto => match auto(a) { + Err(Reject::TooTilted) if levels_by_vertical(&a.vertical, &a.horizontal) => "one line along what should be upright", Err(Reject::TooTilted) => "one line along what should be level", Err(Reject::TooSteep) => VERTICAL, _ => "two lines along what should be vertical, or one line along what should be level", From f8469d3d5c494256d29a443519f1769ac29a8918 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:27:20 +0700 Subject: [PATCH 13/15] upright: long lines get their say when short pieces win; level failures say Disagree; post-lean tests require visible posts (CodeRabbit on #2966) --- crates/pipeline/src/tests_geometry.rs | 6 ++- crates/pipeline/src/upright.rs | 56 ++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index 56c6d8be52..3c8150aa6b 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -764,7 +764,8 @@ fn upright_corrects_converging_posts_among_people() { n += 1.0; } } - s / n.max(1.0) + assert!(n > 0.0, "a post is visible on row {y}"); + s / n }; let lean = |img: &Rgba8, right: bool| post_x(img, img.height / 6, right) - post_x(img, img.height * 5 / 6, right); let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image; @@ -849,7 +850,8 @@ fn upright_vertical_follows_the_posts_not_the_deck_or_the_drapes() { n += 1.0; } } - s / n.max(1.0) + assert!(n > 0.0, "a post is visible on row {y}"); + s / n }; let lean = |img: &Rgba8, right: bool| post_x(img, img.height / 8, right) - post_x(img, img.height * 5 / 8, right); let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image; diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index c6c578bc28..39d46bf0df 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -675,6 +675,19 @@ fn family_vp(segs: &[Segment], vertical: bool) -> (Option<[f64; 3]>, Option (None, Some(Reject::TooFew)), Some((v, _)) => match reliable(segs, v, vertical) { Ok(()) => (Some(v), None), + // the strongest point may be one of many short pieces (foliage, folds) outweighing a few long posts: + // the long lines alone get their say, judged against the whole family (a short-only family stays out) + Err(Reject::TooShort) => { + let long: Vec = segs.iter().copied().filter(|s| s.len() >= LONG_LINE).collect(); + let again = (long.len() >= 2 && long.len() < segs.len()) + .then(|| vanishing_point_where(&long, |v| !inside(v)).or_else(|| vanishing_point(&long))) + .flatten() + .filter(|(v, _)| reliable(segs, *v, vertical).is_ok()); + match again { + Some((v, _)) => (Some(v), None), + None => (None, Some(Reject::TooShort)), + } + } Err(why) => (None, Some(why)), }, } @@ -779,7 +792,13 @@ fn auto(a: &Analysis) -> Result { Some(d) if d.abs() <= 5.0 => Ok(rot_z_h(d)), _ if vertical.is_some() => Err(Reject::TooSteep), Some(_) => Err(Reject::TooTilted), - _ => Err(a.vertical_why.unwrap_or(Reject::TooFew)), + // nothing to level by: a vertical family's own reason when it has one beyond a lack of lines, else lines + // that are there but don't agree, else too few lines + _ => Err(match a.vertical_why { + Some(why) if why != Reject::TooFew => why, + _ if a.vertical.is_empty() && a.horizontal.is_empty() => Reject::TooFew, + _ => Reject::Disagree, + }), } } @@ -948,6 +967,41 @@ pub fn homography(g: &Geometry, ow: f64, oh: f64) -> Homography { mod tests { use super::*; + /// Many short parallel pieces outweighing three long posts don't hide the posts' vanishing point: the long + /// lines are tried on their own when the strongest point has only short lines (CodeRabbit on #2966). + #[test] + fn short_pieces_outweighing_the_posts_do_not_hide_their_vanishing_point() { + let mut segs: Vec = [-0.7, 0.0, 0.7].iter().map(|&x| Segment { a: Point::new(x, -0.8), b: Point::new(0.75 * x, 0.8) }).collect(); + let (dx, dy) = (0.06 * 20f64.to_radians().sin(), 0.06 * 20f64.to_radians().cos()); + for i in 0..60 { + let cx = -0.59 + 0.02 * i as f64; + segs.push(Segment { a: Point::new(cx - dx, -dy), b: Point::new(cx + dx, dy) }); + } + let a = analyze(&segs); + assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why); + // short pieces alone still give none + let a = analyze(&segs[3..]); + assert!(a.vertical_vp.is_none()); + } + + /// Lines that are there but don't agree on a level say so, rather than that there are too few lines + /// (CodeRabbit on #2966). + #[test] + fn horizontals_that_disagree_are_reported_as_disagreeing() { + let segs: Vec = [-4f64, 0.0, 4.0] + .iter() + .enumerate() + .map(|(i, d)| { + let (c, s) = (0.4 * d.to_radians().cos(), 0.4 * d.to_radians().sin()); + let y = -0.5 + 0.5 * i as f64; + Segment { a: Point::new(-c, y - s), b: Point::new(c, y + s) } + }) + .collect(); + let a = analyze(&segs); + assert!(a.vertical.is_empty()); + assert_eq!(auto(&a).err(), Some(Reject::Disagree)); + } + /// The point refined from a candidate's lines is still held to the same test as the candidate: one that test /// turns down leaves the candidate itself (CodeRabbit on #2966). #[test] From 8ed9e2a70d34ad9132eaad83e05aa2e1d57d0923 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:46:36 +0700 Subject: [PATCH 14/15] Upright: name the fallback correction in the note, keep 'no correction' for none (CodeRabbit on #2966) --- crates/engine/src/cmd/develop.rs | 13 ++++++----- crates/engine/src/tests.rs | 2 +- crates/pipeline/src/tests_geometry.rs | 31 +++++++++++++++++++++++++++ crates/pipeline/src/upright.rs | 12 +++++++++++ 4 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/develop.rs b/crates/engine/src/cmd/develop.rs index 152065857a..bebe8b1935 100644 --- a/crates/engine/src/cmd/develop.rs +++ b/crates/engine/src/cmd/develop.rs @@ -1072,21 +1072,22 @@ pub fn specs() -> Vec { "Perspective Correction", [], None, - "{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes → {mode, transform, note (why the mode found nothing to correct, when it didn't)}", + "{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes → {mode, transform, note (why the mode corrects less than it says, and what it did instead, when it does)}", has_active, |s, p| { let mode: Upright = serde_json::from_value(p.get("mode").cloned().unwrap_or(json!("auto"))).map_err(|e| bad("geometry.upright", e.to_string()))?; let id = active(s, "geometry.upright")?; let d = s.develop_of(id).unwrap_or_default(); - let (transform, note, family) = match mode { - Upright::Off | Upright::Guided => (None, None, ""), + let (transform, note, family, instead) = match mode { + Upright::Off | Upright::Guided => (None, None, "", None), m => { let src = s.source_now(id, SourceLevel::Preview).map_err(|e| bad("geometry.upright", e))?; let info = s.source_info(id); let a = lightcraft_pipeline::upright::analyze_source(&src, &info, &d); let family = lightcraft_pipeline::upright::guided_hint(m, &a); - (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a), family) + let instead = lightcraft_pipeline::upright::fallback(m, &a); + (Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a), family, instead) } }; edit(s, "geometry.upright", "Perspective Correction", |d| { @@ -1102,7 +1103,9 @@ pub fn specs() -> Vec { Upright::Full => "No full correction", _ => "No Upright correction", }; - format!("{what}: {why}. Try Guided: draw {family}.") + // (and what it did instead, when it fell back to a lesser correction: "nothing" is only said of none) + let instead = instead.map(|i| format!(" {i}.")).unwrap_or_default(); + format!("{what}: {why}.{instead} Try Guided: draw {family}.") }); Ok(json!({"mode": mode, "transform": transform, "note": note})) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d1a7d0d89b..2d296a5894 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2205,7 +2205,7 @@ fn upright_says_why_it_found_nothing_to_correct() { match r["note"].as_str() { Some(note) => { noted += 1; - assert!(identity, "a note was returned with a correction: {r}"); + assert!(identity || note.contains(" instead."), "a correction was applied but the note doesn't say which: {r}"); assert!(note.starts_with("No vertical correction: "), "{note}"); } None => assert!(!identity, "a vertical correction was found: {r}"), diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index 3c8150aa6b..b8f7a4f0ad 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -926,6 +926,37 @@ fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() { assert_eq!(shortfall(Upright::Level, &Analysis::default()), Some(Reject::TooFew.message())); } +/// A mode that falls back to a lesser correction says which one it applied, and "no correction" is kept for no +/// correction at all (CodeRabbit on #2966). +#[test] +fn upright_note_names_the_fallback_it_applied() { + use crate::upright::{Analysis, Segment, fallback, shortfall, solve}; + use lightcraft_develop::Upright; + use lightcraft_geom::Homography; + let line = |deg: f64, y: f64| { + let (s, c) = deg.to_radians().sin_cos(); + Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) } + }; + // no verticals, a tilted horizon: Vertical and Full both level it, and say so + let tilted = Analysis { horizontal: vec![line(4.0, -0.2), line(4.0, 0.2)], ..Analysis::default() }; + for m in [Upright::Vertical, Upright::Full] { + assert!(shortfall(m, &tilted).is_some()); + assert_ne!(solve(m, &tilted), Homography::IDENTITY); + assert_eq!(fallback(m, &tilted), Some("Levelled the photo instead"), "{m:?}"); + } + // a vertical vanishing point but no horizontal one: Full straightens the verticals + let vertical = Analysis { vertical_vp: Some([0.0, 3.0, 1.0]), ..Analysis::default() }; + assert!(shortfall(Upright::Full, &vertical).is_some()); + assert_ne!(solve(Upright::Full, &vertical), Homography::IDENTITY); + assert_eq!(fallback(Upright::Full, &vertical), Some("Straightened the vertical lines instead")); + assert_eq!(fallback(Upright::Vertical, &vertical), None, "Vertical did what it says"); + // nothing at all to go by: no fallback, the note says there was no correction + for m in [Upright::Vertical, Upright::Full, Upright::Level] { + assert_eq!(fallback(m, &Analysis::default()), None); + assert_eq!(solve(m, &Analysis::default()), Homography::IDENTITY); + } +} + /// The Guided hint says what to draw: Full needs two guides of each family (Guided uses only the guides drawn, and /// one of a kind only levels), Vertical two vertical ones, and Level a single line. #[test] diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 39d46bf0df..776ba9ab5e 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -718,6 +718,18 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { } } +/// What [`solve`] applies instead when `mode` falls short ([`shortfall`]) but corrects something all the same: Full +/// without a horizontal vanishing point straightens the verticals, and Vertical or Full without a vertical one levels. +/// In words for the user, after "No full correction: …. " (`None` when the result is no correction at all). +pub fn fallback(mode: Upright, a: &Analysis) -> Option<&'static str> { + let levels = || level_angle(&a.vertical, &a.horizontal).is_some_and(|d| d != 0.0); + match mode { + Upright::Full if a.vertical_vp.is_some() && a.horizontal_vp.is_none() => Some("Straightened the vertical lines instead"), + Upright::Vertical | Upright::Full if a.vertical_vp.is_none() && levels() => Some("Levelled the photo instead"), + _ => None, + } +} + /// What to draw in Guided when `mode` falls short on `a` ("Try Guided: draw …"). Guided works from the guides /// alone, not from lines the mode found, and one guide of a kind only levels ([`solve_guided`]): Full needs two of /// each family, Vertical two vertical ones, and levelling one line. Auto follows why it stopped: a tilt more than From 2b4c86c8c067ed95b86d50118cc43a26811f8405 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:59:35 +0100 Subject: [PATCH 15/15] upright: Full names no fallback when the verticals need no correction (CodeRabbit) --- crates/pipeline/src/tests_geometry.rs | 5 +++++ crates/pipeline/src/upright.rs | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/pipeline/src/tests_geometry.rs b/crates/pipeline/src/tests_geometry.rs index b8f7a4f0ad..0f8b284aa0 100644 --- a/crates/pipeline/src/tests_geometry.rs +++ b/crates/pipeline/src/tests_geometry.rs @@ -950,6 +950,11 @@ fn upright_note_names_the_fallback_it_applied() { assert_ne!(solve(Upright::Full, &vertical), Homography::IDENTITY); assert_eq!(fallback(Upright::Full, &vertical), Some("Straightened the vertical lines instead")); assert_eq!(fallback(Upright::Vertical, &vertical), None, "Vertical did what it says"); + // verticals already along the image's y axis: Full stores no correction, so it names no fallback + let straight = Analysis { vertical_vp: Some([0.0, 1.0, 0.0]), ..Analysis::default() }; + assert!(shortfall(Upright::Full, &straight).is_some()); + assert_eq!(solve(Upright::Full, &straight), Homography::IDENTITY); + assert_eq!(fallback(Upright::Full, &straight), None); // nothing at all to go by: no fallback, the note says there was no correction for m in [Upright::Vertical, Upright::Full, Upright::Level] { assert_eq!(fallback(m, &Analysis::default()), None); diff --git a/crates/pipeline/src/upright.rs b/crates/pipeline/src/upright.rs index 776ba9ab5e..c449067a5d 100644 --- a/crates/pipeline/src/upright.rs +++ b/crates/pipeline/src/upright.rs @@ -724,7 +724,10 @@ pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> { pub fn fallback(mode: Upright, a: &Analysis) -> Option<&'static str> { let levels = || level_angle(&a.vertical, &a.horizontal).is_some_and(|d| d != 0.0); match mode { - Upright::Full if a.vertical_vp.is_some() && a.horizontal_vp.is_none() => Some("Straightened the vertical lines instead"), + // verticals that already stand straight leave no correction to name + Upright::Full if a.vertical_vp.is_some() && a.horizontal_vp.is_none() => { + (solve(Upright::Full, a) != Homography::IDENTITY).then_some("Straightened the vertical lines instead") + } Upright::Vertical | Upright::Full if a.vertical_vp.is_none() && levels() => Some("Levelled the photo instead"), _ => None, }