Merge #11855 into the merge queue batch

fix(engine): a rectangular Perspective Crop keeps shape and fill layers (#11800)
This commit is contained in:
David Mann committed 2026-11-30 03:20:10 +01:00
commit 006a02e496
3 files changed
+247 -10

No files matched your search

+2
View File
@@ -102,6 +102,8 @@ pub mod pattern_fill_cmds;
pub mod perspective_crop_cmds;
#[cfg(test)]
mod perspective_crop_refuse_tests;
#[cfg(test)]
mod perspective_crop_vector_layers_tests;
pub mod photo_cmds;
pub mod plugin_cmds;
pub mod preset_import_cmds;
@@ -10,14 +10,19 @@
//!
//! A document holding a type layer or a smart object anywhere, and a Bitmap mode document, are
//! refused with the tool's alerts ([`UNSUPPORTED_LAYERS_ERROR`] and [`BITMAP_MODE_ERROR`], #11799)
//! before anything is rasterized or warped, so the document stays exactly as it was. Shape and fill
//! layers are rasterized first: a projective map has no editable equivalent for them (keeping them
//! live is #11800). Vector masks, paths, notes, slices and guides follow the affine map closest to
//! the homography (exact when the quad is a parallelogram).
//! before anything is rasterized or warped, so the document stays exactly as it was. When the quad
//! is a rectangle at any angle, whose map is affine, rectangle shape layers and Color Fill layers
//! stay shape and fill layers (#11800); a kept shape's stroke width scales with the mean of the
//! two axis scales, as in Image Size. Other shape and fill layers (other shapes, Gradient and
//! Pattern Fill) are rasterized then, their vector masks included. Any other quad holding a shape
//! or fill layer rasterizes every layer's vector data first, vector masks included, as Rasterize
//! All Layers does. Vector masks that are left (all of them when nothing is rasterized), paths,
//! notes, slices and guides follow the affine map closest to the homography (exact when the quad
//! is a parallelogram).
use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped};
use photocraft_color::{ColorMode, PixelFormat};
use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size};
use photocraft_doc::{Document, Fill, Layer, LayerContent, LayerId, LiveShape, Size};
use photocraft_geom::{Affine, Rect};
use photocraft_raster::Surface;
use serde_json::{Value, json};
@@ -141,6 +146,46 @@ fn interpolation(p: &Value) -> Result<Interp> {
}
}
/// Whether the quad (TL, TR, BR, BL) is a rectangle, at any angle: its map is then affine, so
/// shape and fill layers can follow it as they are. The right-angle test allows for the rounding
/// of the corners to f64, which far from the origin is larger than the angle of a short side.
fn is_rectangle(q: &[[f64; 2]; 4]) -> bool {
let [tl, tr, br, bl] = *q;
let (u, v) = ([tr[0] - tl[0], tr[1] - tl[1]], [bl[0] - tl[0], bl[1] - tl[1]]);
let (lu, lv) = (u[0].hypot(u[1]).max(1e-9), v[0].hypot(v[1]).max(1e-9));
// Each corner is off by up to half an ulp of the largest coordinate.
let ulp = q.iter().flatten().fold(1.0_f64, |m, c| m.max(c.abs())) * f64::EPSILON;
// The corners must close up relative to the short side: the output stretches that side most,
// so an absolute slack would move the far corner by many output pixels on a thin quad.
let closure = (tl[0] + br[0] - tr[0] - bl[0]).hypot(tl[1] + br[1] - tr[1] - bl[1]);
let parallelogram = closure <= 1e-9 * lu.min(lv) + 16.0 * ulp;
let tolerance = 1e-9 + 4.0 * ulp * (1.0 / lu + 1.0 / lv);
parallelogram && ((u[0] * v[0] + u[1] * v[1]) / (lu * lv)).abs() < tolerance
}
/// The mean of a rectangle crop's two axis scales: what a kept shape's stroke width is multiplied
/// by, as Image Size does with its mean scale (#8341).
fn stroke_scale(q: &[[f64; 2]; 4], w: f64, h: f64) -> f64 {
let [tl, tr, _, bl] = *q;
let (lu, lv) = ((tr[0] - tl[0]).hypot(tr[1] - tl[1]), (bl[0] - tl[0]).hypot(bl[1] - tl[1]));
if lu > 0.0 && lv > 0.0 { (w / lu + h / lv) / 2.0 } else { 1.0 }
}
/// Multiplies the stroke width of every shape layer (in groups too) by `k`.
fn scale_strokes(layers: &mut [Layer], k: f64) {
for l in layers {
match &mut l.content {
LayerContent::Group(g) => scale_strokes(&mut g.children, k),
LayerContent::Shape(sh) => {
if let Some(st) = &mut sh.stroke {
st.width = (f64::from(st.width) * k).clamp(0.0, f64::from(f32::MAX)) as f32;
}
}
_ => {}
}
}
}
/// The affine map closest to the crop for geometry that can't take a homography (vector masks,
/// paths, notes, guides): the quad's centroid goes to the output's centre and its mean horizontal
/// and vertical edges to the output's sides. Exact when the quad is a parallelogram.
@@ -231,6 +276,8 @@ fn apply(doc: &mut Document, q: &[[f64; 2]; 4], h: &Homography, size: (u32, u32)
}
doc.selection = None;
crate::canvas_geom::transform_geometry(doc, &nearest_affine(q, f64::from(w), f64::from(ht)));
// Only a rectangle crop keeps shape layers (#11800); every other quad rasterized them.
scale_strokes(&mut doc.layers, stroke_scale(q, f64::from(w), f64::from(ht)));
doc.size = Size::new(w, ht);
crate::canvas_geom::refresh(doc, crate::canvas_geom::Refresh::Shapes);
Ok(())
@@ -261,9 +308,22 @@ fn perspective_crop(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other(msg.into()));
}
crate::image_cmds::check_resample_budget(CMD, &d.doc, w, h, "")?;
// A type layer or a smart object can't get here (they are refused above), so only shape and
// fill layers are ever rasterized (#11800 is about keeping those live).
let rasterize = d.doc.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Shape(_) | LayerContent::Fill(_)));
// #11800: a rectangle's map is affine, so rectangle shapes and Color Fills follow it as they
// are, and only the other shape and fill layers are rasterized. Any other quad keeps Rasterize
// All Layers, which also turns the vector masks into pixel masks, so they follow the homography
// too. (Type layers and smart objects can't get here: they are refused above.)
let keeps_vectors = is_rectangle(&q);
let rasterize: Vec<LayerId> = d
.doc
.walk()
.iter()
.filter(|(_, _, l)| match &l.content {
LayerContent::Shape(sh) => !keeps_vectors || !matches!(sh.live, Some(LiveShape::Rect { .. })),
LayerContent::Fill(f) => !keeps_vectors || !matches!(f, Fill::Solid(_)),
_ => false,
})
.map(|(_, _, l)| l.id)
.collect();
let map = quad_to_rect(&q, f64::from(w), f64::from(h)).ok_or_else(|| bad("the corners don't define a perspective"))?;
let bg = s.tools.background;
// The Color Sampler points follow their pixels through the homography, which the edit's
@@ -271,8 +331,14 @@ fn perspective_crop(s: &mut Session, p: &Value) -> Result<Value> {
let samplers = s.active().map(|d| d.color_samplers.clone()).unwrap_or_default();
let removed = s.samplers_removed;
crate::analysis_cmds::compound(s, "Perspective Crop", |s| {
if rasterize {
if !rasterize.is_empty() && !keeps_vectors {
crate::extra_cmds::rasterize_all(s)?;
} else if !rasterize.is_empty() {
// One history entry for every layer, as Rasterize All Layers makes.
let key = crate::extra_cmds::step_key(s, "rasterizeAll");
for id in rasterize {
crate::extra_cmds::rasterize_one(s, id, None, &key)?;
}
}
s.edit("Perspective Crop", |doc, _| {
apply(doc, &q, &map, (w, h), interp, bg)?;
@@ -297,7 +363,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Perspective Crop",
menu: &[],
shortcut: None,
params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; shape and fill layers are rasterized; refused with the tool's alert, and nothing changes: a document holding a type layer or a smart object anywhere, hidden or inside a group included, answers "Could not use the perspective crop tool because the image contains unsupported layers types.", a Bitmap mode document "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).")"##,
params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; when the quad is a rectangle at any angle, rectangle shape layers and Color Fill layers are kept, their stroke widths scaled by the mean axis scale, and other shape and fill layers are rasterized; any other quad holding a shape or fill layer rasterizes every layer's vector data, vector masks included, and without one vector masks follow the closest affine map; refused with the tool's alert, and nothing changes: a document holding a type layer or a smart object anywhere, hidden or inside a group included, answers "Could not use the perspective crop tool because the image contains unsupported layers types.", a Bitmap mode document "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).")"##,
enabled: has_doc,
run: perspective_crop,
journal: true,
@@ -0,0 +1,169 @@
//! #11800: a Perspective Crop with a rectangular quad keeps shape and Color Fill layers as they
//! are (a shape moves with the content), in one undo step; any other quad still rasterizes them.
use photocraft_doc::{LayerContent, LayerId};
use serde_json::json;
use crate::Session;
/// 800 × 500 with a Levels adjustment, a Color Fill and a rectangle shape at 200,300–350,400.
fn doc() -> (Session, LayerId, LayerId) {
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 500})).unwrap();
s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
s.execute("layer.newFillLayer.solidColor", json!({"color": "#3366cc"})).unwrap();
let fill = s.active().unwrap().active_layer.unwrap();
s.execute("shape.create", json!({"kind": "rect", "rect": [200, 300, 150, 100], "fill": "#cc3333"})).unwrap();
let shape = s.active().unwrap().active_layer.unwrap();
(s, fill, shape)
}
fn crop(s: &mut Session, corners: serde_json::Value) {
s.execute("image.perspectiveCrop", json!({"corners": corners, "width": 602, "height": 402})).unwrap();
}
fn crop_to(s: &mut Session, corners: serde_json::Value, w: u32, h: u32) {
s.execute("image.perspectiveCrop", json!({"corners": corners, "width": w, "height": h})).unwrap();
}
fn past(s: &Session) -> usize {
s.active().unwrap().history.past_len()
}
fn content(s: &Session, id: LayerId) -> LayerContent {
s.active().unwrap().doc.layer(id).unwrap().content.clone()
}
fn shape_bounds(s: &Session, id: LayerId) -> (f64, f64, f64, f64) {
match content(s, id) {
LayerContent::Shape(sh) => sh.path.control_bounds().expect("a path"),
other => panic!("not a shape: {other:?}"),
}
}
#[test]
fn a_rectangular_crop_keeps_shape_and_fill_layers() {
let (mut s, fill, shape) = doc();
let before = s.active().unwrap().history.past_len();
crop(&mut s, json!([[99, 49], [701, 49], [701, 451], [99, 451]]));
assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one step");
assert!(matches!(content(&s, fill), LayerContent::Fill(_)), "still a fill layer");
let (x0, y0, x1, y1) = shape_bounds(&s, shape);
for (got, want) in [(x0, 101.0), (y0, 251.0), (x1, 251.0), (y1, 351.0)] {
assert!((got - want).abs() <= 1.0, "shape bounds {:?}", (x0, y0, x1, y1));
}
// The Color Fill still covers the new canvas, to its corners.
let d = &s.active().unwrap().doc;
assert_eq!((d.size.width, d.size.height), (602, 402));
for (x, y) in [(0, 0), (601, 0), (0, 401), (601, 401), (5, 5), (300, 20)] {
let px = photocraft_compose::render(d, photocraft_geom::Rect::new(x, y, x + 1, y + 1)).into_px();
assert!((px[0][2] - 0.8).abs() < 0.02, "the fill's colour at ({x}, {y}): {:?}", px[0]);
}
// One undo restores the layers as they were.
s.undo();
assert!(matches!(content(&s, fill), LayerContent::Fill(_)));
assert_eq!(shape_bounds(&s, shape), (200.0, 300.0, 350.0, 400.0));
}
#[test]
fn a_skewed_crop_still_rasterizes_them() {
let (mut s, fill, shape) = doc();
let before = past(&s);
crop(&mut s, json!([[120, 49], [701, 60], [680, 451], [99, 430]]));
assert!(matches!(content(&s, fill), LayerContent::Raster(_)));
assert!(matches!(content(&s, shape), LayerContent::Raster(_)));
assert_eq!(past(&s), before + 1, "one step");
s.undo();
assert!(matches!(content(&s, fill), LayerContent::Fill(_)));
assert_eq!(shape_bounds(&s, shape), (200.0, 300.0, 350.0, 400.0));
}
/// A rectangle at an angle maps affinely too: the shape stays a shape, its corners taken where the
/// rotated frame's axes take them.
#[test]
fn a_rotated_rectangle_keeps_shape_and_fill_layers() {
let (mut s, fill, shape) = doc();
// u = (400, 200), v = (-100, 200): perpendicular, |u| = 447.2, |v| = 223.6.
let (tl, u, v) = ([200.0, 50.0], [400.0, 200.0], [-100.0, 200.0]);
crop_to(&mut s, json!([tl, [600, 250], [500, 450], [100, 250]]), 447, 224);
assert!(matches!(content(&s, fill), LayerContent::Fill(_)), "still a fill layer");
let (lu, lv) = (f64::hypot(u[0], u[1]), f64::hypot(v[0], v[1]));
let map = |p: [f64; 2]| {
let d = [p[0] - tl[0], p[1] - tl[1]];
((d[0] * u[0] + d[1] * u[1]) / lu * 447.0 / lu, (d[0] * v[0] + d[1] * v[1]) / lv * 224.0 / lv)
};
let pts = [[200.0, 300.0], [350.0, 300.0], [350.0, 400.0], [200.0, 400.0]].map(map);
let want = pts.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
let got = shape_bounds(&s, shape);
for (g, w) in [(got.0, want.0), (got.1, want.1), (got.2, want.2), (got.3, want.3)] {
assert!((g - w).abs() <= 1.0, "shape bounds {got:?}, expected {want:?}");
}
}
/// A small rectangle far from the origin still counts as one: the corners' rounding to f64 is
/// larger there than its sides' right angle allows without a scale-aware tolerance.
#[test]
fn a_rectangle_far_from_the_origin_keeps_the_fill_layer() {
let (mut s, fill, _) = doc();
let q = json!([[9999980.266, 9999980.347], [9999980.826, 9999980.787], [9999979.066, 9999983.027], [9999978.506, 9999982.587]]);
s.execute("image.perspectiveCrop", json!({"corners": q})).unwrap();
assert!(matches!(content(&s, fill), LayerContent::Fill(_)), "still a fill layer");
}
/// A rectangle crop keeps only rectangle shapes and Color Fills: an ellipse and a Gradient Fill
/// keep the rasterizing they had before #11800 (not measured in the reference), in the same step.
#[test]
fn a_rectangular_crop_rasterizes_other_shapes_and_fills() {
let (mut s, fill, shape) = doc();
let ellipse =
LayerId(s.execute("shape.create", json!({"kind": "ellipse", "rect": [400, 100, 120, 80], "fill": "#33cc33"})).unwrap()["layer"].as_u64().unwrap());
s.execute("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#ffffff"})).unwrap();
let gradient = s.active().unwrap().active_layer.unwrap();
let before = past(&s);
crop(&mut s, json!([[99, 49], [701, 49], [701, 451], [99, 451]]));
assert!(matches!(content(&s, ellipse), LayerContent::Raster(_)), "ellipse rasterized");
assert!(matches!(content(&s, gradient), LayerContent::Raster(_)), "gradient fill rasterized");
assert!(matches!(content(&s, fill), LayerContent::Fill(_)), "still a fill layer");
assert!(matches!(content(&s, shape), LayerContent::Shape(_)), "still a shape layer");
assert_eq!(past(&s), before + 1, "one step");
s.undo();
assert!(matches!(content(&s, ellipse), LayerContent::Shape(_)));
assert!(matches!(content(&s, gradient), LayerContent::Fill(_)));
}
/// A thin quad whose corners miss a parallelogram by less than a micron is still no rectangle:
/// stretched across the output, that gap is many pixels, so the fill can't follow an affine map.
#[test]
fn a_thin_sheared_quad_is_not_a_rectangle() {
let (mut s, fill, _) = doc();
crop_to(&mut s, json!([[0, 0], [0.00001, 0], [0.0000109, 120000], [0, 120000]]), 1000, 1000);
assert!(matches!(content(&s, fill), LayerContent::Raster(_)), "fill rasterized");
}
/// A kept shape's stroke scales with the crop, as in Image Size: by the mean of the axis scales.
#[test]
fn a_scaled_rectangular_crop_scales_the_stroke_width() {
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 500})).unwrap();
let id = LayerId(s.execute("shape.create", json!({"rect": [200, 300, 150, 100], "stroke": {"width": 4}})).unwrap()["layer"].as_u64().unwrap());
// 602 x 402 onto 1204 x 402: x2 across, x1 down, mean 1.5.
crop_to(&mut s, json!([[99, 49], [701, 49], [701, 451], [99, 451]]), 1204, 402);
let LayerContent::Shape(sh) = content(&s, id) else { panic!("not a shape") };
let w = sh.stroke.expect("a stroke").width;
assert!((w - 6.0).abs() < 1e-3, "stroke width {w}");
}
/// A skewed crop with a shape layer rasterizes every layer's vector data, as Rasterize All Layers
/// does: a raster layer's vector mask becomes a pixel mask, so it follows the homography with the
/// pixels instead of an affine approximation.
#[test]
fn a_skewed_crop_rasterizes_vector_masks_too() {
let (mut s, _, _) = doc();
s.execute("layer.new.layer", json!({})).unwrap();
let raster = s.active().unwrap().active_layer.unwrap();
s.execute("layer.vectorMask.revealAll", json!({})).unwrap();
assert!(s.active().unwrap().doc.layer(raster).unwrap().vector_mask.is_some());
crop(&mut s, json!([[120, 49], [701, 60], [680, 451], [99, 430]]));
let l = s.active().unwrap().doc.layer(raster).unwrap();
assert!(l.vector_mask.is_none() && l.mask.is_some(), "the vector mask became a pixel mask");
}