PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Free Transform: solid pixel stretch (edge-repeat sampling, selected-pixel bounds) (#3867)
Fabio Lussi45f8921ae84e
diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rsindex 7d1dd0fe6..3b157b56a 100644--- a/crates/algo/src/transform.rs+++ b/crates/algo/src/transform.rs@@ -392,6 +392,15 @@ fn warp(px[((y - foot.y0) as usize * fw + (x - foot.x0) as usize) * n + c] as f64}};+ // Samples past the source rect repeat its edge, so a stretched edge row or column keeps its+ // colour and opacity (the "pixel stretch", #3773); the outline is antialiased by coverage+ // instead. `foot_u`/`foot_v` are a destination pixel's extent in source pixels.+ let clamped = |x: i32, y: i32, c: usize| at(x.clamp(src_rect.x0, src_rect.x1 - 1), y.clamp(src_rect.y0, src_rect.y1 - 1), c);+ let (mx, my) = ((t.x0 + t.x1) as f64 / 2.0, (t.y0 + t.y1) as f64 / 2.0);+ let (o, dx, dy) = (inv.apply(mx, my), inv.apply(mx + 1.0, my), inv.apply(mx, my + 1.0));+ let extent = |e: f64| if e.is_finite() && e > 1e-12 { e } else { 1.0 };+ let foot_u = extent((dx.0 - o.0).abs() + (dy.0 - o.0).abs());+ let foot_v = extent((dx.1 - o.1).abs() + (dy.1 - o.1).abs());let w = t.width() as usize;let len = w.checked_mul(t.height() as usize).and_then(|v| v.checked_mul(n)).ok_or(photocraft_raster::AllocationError::SizeOverflow)?;let bytes = len.checked_mul(std::mem::size_of::<f32>()).ok_or(photocraft_raster::AllocationError::SizeOverflow)?;@@ -424,7 +433,7 @@ fn warp(for (dy, wy) in [(0, 1.0 - fy), (1, fy)] {for (dx, wx) in [(0, 1.0 - fx), (1, fx)] {for (c, s) in acc.iter_mut().enumerate().take(n) {- *s += at(ix + dx, iy + dy, c) * wx * wy;+ *s += clamped(ix + dx, iy + dy, c) * wx * wy;}}}@@ -436,12 +445,21 @@ fn warp(for (i, wxi) in wx.iter().enumerate() {let k = wxi * wyj;for (c, s) in acc.iter_mut().enumerate().take(n) {- *s += at(ix - 1 + i as i32, iy - 1 + j as i32, c) * k;+ *s += clamped(ix - 1 + i as i32, iy - 1 + j as i32, c) * k;}}}}}+ if interp != Interp::Nearest {+ // How much of this pixel the warped source rect covers, per axis.+ let (uc, vc) = (u + 0.5, v + 0.5);+ let cu = ((uc - src_rect.x0 as f64).min(src_rect.x1 as f64 - uc) / foot_u + 0.5).clamp(0.0, 1.0);+ let cv = ((vc - src_rect.y0 as f64).min(src_rect.y1 as f64 - vc) / foot_v + 0.5).clamp(0.0, 1.0);+ for s in acc.iter_mut().take(n) {+ *s *= cu * cv;+ }+ }let al = acc[a].clamp(0.0, 1.0);if al <= 0.0 {continue;@@ -539,6 +557,24 @@ mod tests {Surface::new(PixelFormat::RGBA8)}+ /// The "pixel stretch" (#3773): a 1 px column scaled 100x stays solid across the stretch, as in+ /// Photoshop. Samples past the source edge repeat the edge, and only the outline is antialiased.+ #[test]+ fn stretched_single_column_stays_opaque() {+ let mut s = rgba();+ s.fill_rect(Rect::new(0, 0, 1, 4), &[0.0, 1.0, 0.0, 1.0]);+ for interp in [Interp::Bicubic, Interp::Bilinear] {+ let h = Homography::rect_to_quad([0.0, 0.0, 1.0, 4.0], [[0.0, 0.0], [100.0, 0.0], [100.0, 4.0], [0.0, 4.0]]).unwrap();+ let w = warp_surface(&s, Rect::new(0, 0, 1, 4), &h, interp).unwrap();+ assert_eq!(w.content_bounds(), Rect::new(0, 0, 100, 4), "{interp:?}");+ for x in [0, 1, 25, 50, 75, 99] {+ for y in 0..4 {+ assert!((w.sample_channel(x, y, 3) - 1.0).abs() < 1e-6, "{interp:?} alpha at ({x}, {y}) = {}", w.sample_channel(x, y, 3));+ }+ }+ }+ }+/// Photoshop 27.11's Free Transform, Bicubic, 200 % about the centre of a 64 px image whose left/// half is grey 64 and right half grey 192: the row across the edge, columns 26..36.#[test]diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rsindex bcf97126c..dfc3375d0 100644--- a/crates/engine/src/transform_cmds.rs+++ b/crates/engine/src/transform_cmds.rs@@ -282,7 +282,12 @@ fn check_layer_budget(doc_sel: Option<&Surface>, l: &Layer, h: &Homography) -> R}_ => {if let Some(surf) = l.surface() {- check_budget(surf.content_bounds(), h, &format!("layer \"{}\"", l.name))?;+ // With a selection only the lifted pixels are warped (`split_selected`).+ let src = match sel {+ Some(sel) => surf.content_bounds().intersect(&sel.content_bounds()),+ None => surf.content_bounds(),+ };+ check_budget(src, h, &format!("layer \"{}\"", l.name))?;}}}@@ -383,17 +388,20 @@ fn apply_transform(}_ => {if let Some(surf) = l.surface_mut() {- let src = surf.content_bounds();*surf = match doc_sel {- // Only the selected pixels move: lift them, clear them, warp and paste back.+ // Only the selected pixels move: lift them, clear them, warp and paste back. The+ // lifted pixels' own bounds are the edge a stretch repeats (#3773).Some(sel) => {let (lifted, mut rest) = split_selected(surf, sel)?;- let moved = warp_surface_with(&lifted, src, h, interp, ctl)?.ok_or(EngineError::Cancelled)?;+ let moved = warp_surface_with(&lifted, lifted.content_bounds(), h, interp, ctl)?.ok_or(EngineError::Cancelled)?;composite_over(&mut rest, &moved);rest.prune();rest}- None => warp_surface_with(surf, src, h, interp, ctl)?.ok_or(EngineError::Cancelled)?,+ None => {+ let src = surf.content_bounds();+ warp_surface_with(surf, src, h, interp, ctl)?.ok_or(EngineError::Cancelled)?+ }};}}@@ -445,6 +453,11 @@ pub fn split_selected(surf: &Surface, sel: &Surface) -> Result<(Surface, Surfacelet k = sel.sample_channel(x, y, 0);l[n - 1] *= k;r[n - 1] *= 1.0 - k;+ // Likewise an unselected pixel leaves nothing in the lifted surface, so its bounds are the+ // selected pixels' (what a stretch repeats at the edge, #3773).+ if l[n - 1] <= 0.0 {+ l.fill(0.0);+ }if r[n - 1] <= 0.0 {r.iter_mut().zip(&rest_clear).for_each(|(d, c)| *d = *c);}@@ -1249,6 +1262,93 @@ mod tests {assert!(s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0]})).is_err(), "locked layer refuses identity transform");}+ /// A 1 x 8 px column on a 256 x 256 canvas (#3773).+ fn column_session() -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 256, "height": 256})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.edit("paint", |doc, active| {+ let l = doc.layer_mut(active.unwrap()).unwrap();+ l.surface_mut().unwrap().fill_rect(Rect::new(100, 100, 101, 108), &[0.0, 1.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ s+ }++ fn opaque_green(s: &Session, x: i32, y: i32) -> bool {+ let st = s.active().unwrap();+ let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();+ (surf.sample_channel(x, y, 1) - 1.0).abs() < 1e-3 && (surf.sample_channel(x, y, 3) - 1.0).abs() < 1e-3+ }++ /// The "pixel stretch" (#3773): scales far past 1000% are taken, and the stretched column stays+ /// solid along its whole length.+ #[test]+ fn a_one_pixel_column_stretches_5000_percent() {+ let mut s = column_session();+ s.execute("edit.transform", json!({"quad": [[100, 100], [150, 100], [150, 108], [100, 108]]})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(100, 100, 150, 108));+ for x in [100, 101, 125, 149] {+ for y in 100..108 {+ assert!(opaque_green(&s, x, y), "({x}, {y})");+ }+ }+ }++ /// The technique as done in Photoshop: select a 1 px column of an image and stretch it across.+ #[test]+ fn a_selected_column_stretches_solid_over_the_image() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 256, "height": 256})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.edit("paint", |doc, active| {+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ surf.fill_rect(Rect::new(0, 0, 256, 256), &[1.0, 0.0, 0.0, 1.0]);+ surf.fill_rect(Rect::new(10, 0, 11, 256), &[0.0, 1.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ s.execute("select.rect", json!({"x": 10, "y": 0, "width": 1, "height": 256})).unwrap();+ s.execute("edit.transform", json!({"quad": [[10, 0], [250, 0], [250, 256], [10, 256]]})).unwrap();+ for x in [10, 11, 100, 200, 249] {+ assert!(opaque_green(&s, x, 128), "x = {x}");+ }+ let st = s.active().unwrap();+ let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();+ assert!(surf.sample_channel(250, 128, 0) > 0.999 && surf.sample_channel(9, 128, 0) > 0.999, "the image either side is untouched");+ }++ /// Free Transform keeps pixels moved off the canvas, as Photoshop does: an 8 x 8 layer moved+ /// three canvas widths right and back comes back whole.+ #[test]+ fn a_layer_moved_far_off_the_canvas_and_back_keeps_its_pixels() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.edit("paint", |doc, active| {+ let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ for y in 0..8 {+ for x in 0..8 {+ surf.fill_rect(Rect::new(20 + x, 20 + y, 21 + x, 21 + y), &[x as f32 / 8.0, y as f32 / 8.0, 0.5, 1.0]);+ }+ }+ Ok(())+ })+ .unwrap();+ let pixels = |s: &Session| {+ let st = s.active().unwrap();+ let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();+ (0..8 * 8 * 4).map(|i| surf.sample_channel(20 + i / 4 % 8, 20 + i / 32, (i % 4) as usize)).collect::<Vec<_>>()+ };+ let before = pixels(&s);+ s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 192, 0]})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(212, 20, 220, 28));+ s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -192, 0]})).unwrap();+ assert_eq!(active_bounds(&s), Rect::new(20, 20, 28, 28));+ assert_eq!(pixels(&s), before);+ }+#[test]fn relative_params_scale_and_rotate_about_the_frame_centre() {let mut s = Session::new();