PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Make magnetic lasso edge direction polarity-independent (#3415)
imSlicedBread28f3c18c0d11
diff --git a/crates/algo/src/magnetic.rs b/crates/algo/src/magnetic.rsindex f2dab0881..54759237c 100644--- a/crates/algo/src/magnetic.rs+++ b/crates/algo/src/magnetic.rs@@ -512,12 +512,11 @@ fn direction_cost(tp: [f32; 2], tq: [f32; 2], dx: i32, dy: i32, len: f32) -> f32if tp == [0.0; 2] || tq == [0.0; 2] {return NEUTRAL_DIRECTION;}- let mut l = [dx as f32 / len, dy as f32 / len];- if tp[0] * l[0] + tp[1] * l[1] < 0.0 {- l = [-l[0], -l[1]];- }- let dp = (tp[0] * l[0] + tp[1] * l[1]).clamp(-1.0, 1.0);- let dq = (l[0] * tq[0] + l[1] * tq[1]).clamp(-1.0, 1.0);+ // An edge tangent is an axis, not a directed vector: reversing the strongest channel's+ // gradient must not make an otherwise straight edge expensive to follow.+ let l = [dx as f32 / len, dy as f32 / len];+ let dp = (tp[0] * l[0] + tp[1] * l[1]).abs().clamp(0.0, 1.0);+ let dq = (l[0] * tq[0] + l[1] * tq[1]).abs().clamp(0.0, 1.0);2.0 / (3.0 * PI) * (dp.acos() + dq.acos())}diff --git a/crates/algo/src/magnetic/tests.rs b/crates/algo/src/magnetic/tests.rsindex ccfc73bc0..ee187bc78 100644--- a/crates/algo/src/magnetic/tests.rs+++ b/crates/algo/src/magnetic/tests.rs@@ -55,6 +55,39 @@ fn snaps_to_the_most_prominent_edge() {assert!((p[0] - 18.0).abs() < 0.01, "{p:?}");}+#[test]+fn gradient_polarity_does_not_make_a_straight_edge_look_like_a_turn() {+ // A gradient can reverse across adjacent pixels when another colour channel becomes the+ // strongest one. The edge tangent is an axis, so its sign must not change the path cost.+ let forward = direction_cost([1.0, 0.0], [1.0, 0.0], 1, 0, 1.0);+ let reversed = direction_cost([1.0, 0.0], [-1.0, 0.0], 1, 0, 1.0);+ assert!(forward < 1e-6, "aligned edge: {forward}");+ assert!(reversed < 1e-6, "same edge with reversed gradient polarity: {reversed}");+}++#[test]+fn traces_a_straight_edge_through_a_gradient_polarity_change() {+ let read = Cell::new(0);+ // The contrast stays high, but the edge changes from dark-to-light to light-to-dark halfway+ // down. The horizontal seam intersects it; the guide stays on the vertical contour.+ let mut f = image(+ |x, y| {+ let left = x < 32;+ let top = y < 32;+ let white = left != top;+ grey(if white { 255 } else { 0 })+ },+ &read,+ );+ let mut t = Tracer::new(Rect::new(0, 0, 64, 64));+ let path = t.trace(&mut f, [32.0, 5.0], [32.0, 59.0], &[[32.0, 32.0]], Settings::default());+ assert_eq!(path.first(), Some(&[32.0, 5.0]));+ assert_eq!(path.last(), Some(&[32.0, 59.0]));+ for p in &path {+ assert!((p[0] - 32.0).abs() < 1.0, "left the high-contrast edge: {p:?}; {path:?}");+ }+}+#[test]fn trace_follows_a_curved_edge() {let read = Cell::new(0);