Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Puppet Warp: pins that stretch the content too far are refused (#1019) (#1492)

kayrockscreenprinting3f7d8afc7886
diff --git a/crates/algo/src/puppet.rs b/crates/algo/src/puppet.rs
index abb9b56b8..3defc001b 100644
--- a/crates/algo/src/puppet.rs
+++ b/crates/algo/src/puppet.rs
@@ -766,15 +766,29 @@ pub fn render(src: &Surface, bounds: Rect, mesh: &PuppetMesh, deformed: &[[f64;
crate::warp::warp_triangles(src, bounds, &verts, &tris, interp)
}
-/// Applies a puppet warp to `src` (content inside `bounds`).
-pub fn puppet_warp(src: &Surface, bounds: Rect, w: &PuppetWarp, interp: Interp) -> Surface {
+/// The largest area (px) a puppet warp's result may span: 2³⁰, about 16000 tiles. A pin dragged
+/// absurdly far stretches the mesh over far more, and the renderer allocates bookkeeping for
+/// every tile of it before drawing (#1019).
+pub const MAX_WARP_PIXELS: f64 = (1u64 << 30) as f64;
+
+/// Applies a puppet warp to `src` (content inside `bounds`). `None` when the deformed mesh would
+/// span more than [`MAX_WARP_PIXELS`].
+pub fn puppet_warp(src: &Surface, bounds: Rect, w: &PuppetWarp, interp: Interp) -> Option<Surface> {
let (solver, v, order) = deform(src, bounds, w, ITERATIONS);
// No triangles (an expansion that shrinks every pixel away): nothing to warp. Rendering the
// empty mesh would drop every pixel of the layer.
if solver.mesh.tris.is_empty() {
- return src.clone();
+ return Some(src.clone());
}
- render(src, bounds, &solver.mesh, &v, &order, interp)
+ let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ for p in &v {
+ (x0, y0, x1, y1) = (x0.min(p[0]), y0.min(p[1]), x1.max(p[0]), y1.max(p[1]));
+ }
+ let area = (x1 - x0 + 1.0) * (y1 - y0 + 1.0);
+ if area.is_nan() || area > MAX_WARP_PIXELS {
+ return None;
+ }
+ Some(render(src, bounds, &solver.mesh, &v, &order, interp))
}
#[cfg(test)]
@@ -832,7 +846,7 @@ mod tests {
],
] {
let w = PuppetWarp { pins, mode: PuppetMode::Normal, density: PuppetDensity::Normal, expansion: 2.0 };
- let out = puppet_warp(&s, b, &w, Interp::Bicubic);
+ let out = puppet_warp(&s, b, &w, Interp::Bicubic).unwrap();
let worst = s.read_region(b).iter().zip(out.read_region(b)).map(|(a, c)| (a - c).abs()).fold(0.0f32, f32::max);
assert!(worst <= 1.0 / 255.0 + 1e-6, "{st:?}: {worst}");
}
@@ -855,10 +869,31 @@ mod tests {
};
assert!(build_mesh(&s, b, w.density, w.expansion).tris.is_empty());
// Nothing to warp: the pixels stay, rather than being dropped outside an empty mesh.
- let out = puppet_warp(&s, b, &w, Interp::Bilinear);
+ let out = puppet_warp(&s, b, &w, Interp::Bilinear).unwrap();
assert_eq!(out.read_region(b), s.read_region(b));
}
+ #[test]
+ fn a_pin_dragged_absurdly_far_is_refused_before_rendering() {
+ // #1019: the renderer sized its tile bookkeeping by the deformed mesh, so one far pin
+ // allocated hundreds of MB before drawing a pixel.
+ let s = blob(SampleType::U8);
+ let b = s.content_bounds();
+ let pin = |dst: [f64; 2]| PuppetWarp {
+ pins: vec![
+ PuppetPin { src: [28.0, 20.0], dst: [28.0, 20.0], rotate: None, depth: 0 },
+ PuppetPin { src: [60.0, 62.0], dst, rotate: None, depth: 0 },
+ ],
+ mode: PuppetMode::Normal,
+ density: PuppetDensity::Normal,
+ expansion: 2.0,
+ };
+ assert!(puppet_warp(&s, b, &pin([1048576.0, 1048576.0]), Interp::Bilinear).is_none());
+ assert!(puppet_warp(&s, b, &pin([-1e7, 62.0]), Interp::Bilinear).is_none());
+ let near = puppet_warp(&s, b, &pin([70.0, 66.0]), Interp::Bilinear).expect("a near pin warps");
+ assert!(!near.content_bounds().is_empty());
+ }
+
#[test]
fn a_single_pin_translates_rigidly() {
let s = blob(SampleType::U8);
@@ -873,7 +908,7 @@ mod tests {
for (d, x) in v.iter().zip(&solver.mesh.verts) {
assert!((d[0] - x[0] - 10.0).abs() < 1e-3 && (d[1] - x[1] + 5.0).abs() < 1e-3, "{d:?} {x:?}");
}
- let out = puppet_warp(&s, b, &w, Interp::Bilinear);
+ let out = puppet_warp(&s, b, &w, Interp::Bilinear).unwrap();
assert_eq!(out.content_bounds(), b.translate(10, -5));
assert_eq!(out.pixel(30, 20), s.pixel(20, 25));
// A fixed rotation turns the whole mesh about the pin.
diff --git a/crates/engine/src/distort_cmds.rs b/crates/engine/src/distort_cmds.rs
index 8ead161cf..786702cbb 100644
--- a/crates/engine/src/distort_cmds.rs
+++ b/crates/engine/src/distort_cmds.rs
@@ -151,11 +151,12 @@ pub fn liquify_surface(surf: &Surface, strokes: &[LiquifyStroke], cell: f64, can
apply_liquify(surf, &field)
}
-/// Puppet-warps a surface's content.
-pub fn puppet_surface(surf: &Surface, w: &PuppetWarp, interp: Interp) -> Surface {
+/// Puppet-warps a surface's content; `None` when the result would span more than
+/// [`photocraft_algo::puppet::MAX_WARP_PIXELS`].
+pub fn puppet_surface(surf: &Surface, w: &PuppetWarp, interp: Interp) -> Option<Surface> {
let b = surf.content_bounds();
if w.is_identity() || b.is_empty() {
- return surf.clone();
+ return Some(surf.clone());
}
puppet_warp(surf, b, w, interp)
}
@@ -178,7 +179,8 @@ pub fn apply_to_surface(id: &str, params: &Value, surf: &Surface, canvas: Rect)
let (strokes, cell) = liquify_params(id, params, canvas).ok()?;
Some(liquify_surface(surf, &strokes, cell, canvas))
}
- PUPPET | PUPPET_SMART => Some(puppet_surface(surf, &puppet_params(id, params).ok()?, interp(params))),
+ // A stored warp too far to render leaves the smart object as it is (#1019).
+ PUPPET | PUPPET_SMART => Some(puppet_surface(surf, &puppet_params(id, params).ok()?, interp(params)).unwrap_or_else(|| surf.clone())),
PERSPECTIVE | PERSPECTIVE_SMART => Some(perspective_surface(surf, &perspective_params(id, params).ok()?, interp(params))),
_ => None,
}
@@ -231,16 +233,10 @@ fn check_locks(l: &Layer, group: Locks, position: bool) -> Result<()> {
/// Shared driver: a smart object records `cmd` as a smart filter; a pixel layer is edited in
/// place by `f(surface, selection)`.
type MaskFn<'a> = Option<&'a dyn Fn(&Surface) -> Surface>;
+/// Deforms a layer's pixels (with the selection and canvas); an `Err` leaves the layer as it was.
+type LayerFn<'a> = &'a dyn Fn(&Surface, Option<&Surface>, Rect) -> Result<Surface>;
-fn run_on_layer(
- s: &mut Session,
- cmd: &str,
- label: &str,
- p: &Value,
- moves: bool,
- f: &dyn Fn(&Surface, Option<&Surface>, Rect) -> Surface,
- mask: MaskFn,
-) -> Result<Value> {
+fn run_on_layer(s: &mut Session, cmd: &str, label: &str, p: &Value, moves: bool, f: LayerFn, mask: MaskFn) -> Result<Value> {
let id = target(s, p)?;
let mut params = p.clone();
if let Value::Object(m) = &mut params {
@@ -262,7 +258,7 @@ fn run_on_layer(
let LayerContent::Raster(surf) = &mut l.content else {
return Err(EngineError::Other(format!("{label} needs a pixel layer (rasterize it first)")));
};
- *surf = f(surf, selection.as_ref(), canvas);
+ *surf = f(surf, selection.as_ref(), canvas)?;
// A linked layer mask follows a geometric warp.
if let (Some(mf), Some(m)) = (mask, l.mask.as_mut())
&& m.linked
@@ -295,10 +291,10 @@ fn liquify(s: &mut Session, p: &Value) -> Result<Value> {
false,
&|surf, sel, _| {
let out = apply_liquify(surf, &field);
- match sel {
+ Ok(match sel {
Some(sel) => mix_by_selection(surf, &out, sel),
None => out,
- }
+ })
},
None,
)?;
@@ -310,14 +306,14 @@ fn liquify(s: &mut Session, p: &Value) -> Result<Value> {
/// Lifts the selected pixels (when there is a selection), deforms them with `f` and puts them
/// back over the rest; without a selection deforms the whole surface.
-fn deform_selected(surf: &Surface, sel: Option<&Surface>, f: &dyn Fn(&Surface) -> Surface) -> Surface {
+fn deform_selected(surf: &Surface, sel: Option<&Surface>, f: &dyn Fn(&Surface) -> Result<Surface>) -> Result<Surface> {
match sel {
Some(sel) => {
let (lifted, mut rest) = crate::transform_cmds::split_selected(surf, sel);
- let moved = f(&lifted);
+ let moved = f(&lifted)?;
crate::transform_cmds::composite_over(&mut rest, &moved);
rest.prune();
- rest
+ Ok(rest)
}
None => {
let fmt = surf.format();
@@ -335,7 +331,8 @@ fn puppet(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
return Ok(json!({"layer": id.0, "changed": false}));
}
let it = interp(p);
- run_on_layer(s, cmd, "Puppet Warp", p, true, &|surf, sel, _| deform_selected(surf, sel, &|x| puppet_surface(x, &w, it)), None)
+ let too_far = || bad(cmd, "the pins stretch the content too far: the result would cover more than 2^30 pixels");
+ run_on_layer(s, cmd, "Puppet Warp", p, true, &|surf, sel, _| deform_selected(surf, sel, &|x| puppet_surface(x, &w, it).ok_or_else(too_far)), None)
}
fn perspective(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
@@ -357,7 +354,7 @@ fn perspective(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
"Perspective Warp",
p,
true,
- &|surf, sel, _| deform_selected(surf, sel, &|x| perspective_surface(x, &planes, it)),
+ &|surf, sel, _| deform_selected(surf, sel, &|x| Ok(perspective_surface(x, &planes, it))),
Some(&mask_fn),
)?;
r["planes"] = json!(planes);
diff --git a/crates/engine/src/distort_cmds/tests.rs b/crates/engine/src/distort_cmds/tests.rs
index bdf786390..f3b6fe174 100644
--- a/crates/engine/src/distort_cmds/tests.rs
+++ b/crates/engine/src/distort_cmds/tests.rs
@@ -134,6 +134,42 @@ fn puppet_with_an_expansion_that_empties_the_mesh_keeps_the_layer() {
assert_eq!(active_surface(&s).read_region(Rect::new(0, 0, 80, 60)), before.read_region(Rect::new(0, 0, 80, 60)));
}
+#[test]
+fn puppet_refuses_pins_that_stretch_the_content_too_far() {
+ // #1019: a pin dragged to (2^20, 2^20) stretched the mesh over ~17.6 million tiles, and the
+ // renderer allocated bookkeeping for every one before drawing anything.
+ let far = json!({"pins": [{"src": [20, 20], "dst": [20, 20]}, {"src": [50, 30], "dst": [1048576, 1048576]}]});
+ let full = Rect::new(0, 0, 80, 60);
+ for depth in [8u64, 16, 32] {
+ for selected in [false, true] {
+ let mut s = session(depth);
+ if selected {
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
+ }
+ let (before, past) = (active_surface(&s), s.active().unwrap().history.past_len());
+ let err = s.execute(PUPPET, far.clone()).unwrap_err();
+ assert!(err.to_string().contains("too far"), "{depth} {selected}: {err}");
+ assert_eq!(active_surface(&s).read_region(full), before.read_region(full), "{depth} {selected}: layer unchanged");
+ assert_eq!(s.active().unwrap().history.past_len(), past, "{depth} {selected}: no history step");
+ }
+ // Controls: a rigid move still moves the content, and a pin 4000 px out (well inside the
+ // budget) still warps.
+ let mut s = session(depth);
+ s.execute(PUPPET, json!({"pins": [{"src": [20, 20], "dst": [30, 25]}, {"src": [50, 30], "dst": [60, 35]}], "mode": "rigid"})).unwrap();
+ assert_eq!(active_surface(&s).content_bounds(), Rect::new(20, 15, 70, 45), "{depth}");
+ let mut s = session(depth);
+ s.execute(PUPPET, json!({"pins": [{"src": [20, 20], "dst": [20, 20]}, {"src": [50, 30], "dst": [4050, 4030]}]})).unwrap();
+ assert!(active_surface(&s).content_bounds().x1 > 1000, "{depth}");
+ }
+ // A smart object stores the filter; a warp too far to render leaves its pixels as they were.
+ let mut s = session(8);
+ s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
+ let before = active_surface(&s);
+ s.execute(PUPPET_SMART, far).unwrap();
+ assert_eq!(smart(&s).smart_filters.len(), 1);
+ assert_eq!(active_surface(&s), before);
+}
+
#[test]
fn puppet_two_pins_bend_the_block() {
let mut s = session(8);