Skip to content

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

Painting symmetry: canvas edits move the axis with the pixels (#7732)

David Mannc7c2c31416af
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index cd7f5d606..2d80e90a5 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -120,7 +120,7 @@ fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result<Val
// Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point
// lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`).
let half = photocraft_geom::Affine::translate(0.5, 0.5);
- s.set_sampler_map(half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5)));
+ s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5)));
}
s.edit(label, |doc, _| {
crate::canvas_geom::turn_canvas(doc, t);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index ba7556901..a4ef53dce 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -497,6 +497,9 @@ pub struct Session {
/// The canvas-geometry map the next [`Session::edit`] applies to the Color Sampler points (crop,
/// Canvas Size, Image Size, rotation set it just before their edit). Consumed by the edit.
sampler_map: Option<photocraft_geom::Affine>,
+ /// The same edit's map in edge coordinates, for the painting symmetry (Image Rotation maps the
+ /// samplers' pixel centres instead). Consumed by the edit.
+ symmetry_map: Option<photocraft_geom::Affine>,
/// Each open document's linked smart objects' files: size and modification time when last
/// seen ([`link_watch`]).
pub link_stamps: std::collections::HashMap<(u64, String), link_watch::Stamp>,
@@ -565,8 +568,16 @@ impl Session {
/// Move the Color Sampler points through `a` in the next [`Session::edit`] (crop, Canvas Size,
/// Image Size, rotation), dropping the ones that land outside the new canvas. View state: the
/// points stay pinned to their pixels, no history step. Cleared by the edit it is set for.
+ /// The painting symmetry moves through `a` too.
pub(crate) fn set_sampler_map(&mut self, a: photocraft_geom::Affine) {
- self.sampler_map = Some(a);
+ self.set_canvas_map(a, a);
+ }
+
+ /// [`set_sampler_map`](Self::set_sampler_map) for an edit whose sampler map differs from its
+ /// geometry map (a flip or rotation maps pixel centres): `geometry` moves the painting symmetry.
+ pub(crate) fn set_canvas_map(&mut self, geometry: photocraft_geom::Affine, samplers: photocraft_geom::Affine) {
+ self.sampler_map = Some(samplers);
+ self.symmetry_map = Some(geometry);
}
pub fn sync_tools_mask_target(&mut self) {
@@ -794,6 +805,7 @@ impl Session {
let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new));
let restrict = self.color_restrict;
let sampler_map = self.sampler_map.take();
+ let symmetry_map = self.symmetry_map.take();
let st = self.active_mut().ok_or(EngineError::NoDocument)?;
let before = st.doc.clone();
// Selecting layers is not a step, so the state this edit leaves behind targets what was
@@ -829,6 +841,10 @@ impl Session {
st.color_samplers.retain(|p| bounds.contains(p[0].floor() as i32, p[1].floor() as i32));
samplers_removed = n - st.color_samplers.len();
}
+ // The painting symmetry stays on its pixels too (Photoshop keeps it as a path).
+ if let Some(a) = symmetry_map {
+ st.symmetry = st.symmetry.take().and_then(|sym| sym.transform(&a));
+ }
// The pixels the edit can have changed, as its undo would report them: nothing for a
// selection, guides or a layer's name (a new lasso selection used to recomposite a large
// document, seconds on the CPU path, #1773), a new or deleted layer's bounds (a
diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rs
index 41b4ddde1..998c85f11 100644
--- a/crates/engine/src/mode_cmds.rs
+++ b/crates/engine/src/mode_cmds.rs
@@ -87,7 +87,7 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
let (cx, cy) = (f64::from(old.width) / 2.0, f64::from(old.height) / 2.0);
let (nx, ny) = (f64::from(new.width) / 2.0, f64::from(new.height) / 2.0);
let a = Affine { m: [cs, sn, -sn, cs, nx - (cs * cx - sn * cy), ny - (sn * cx + cs * cy)] };
- s.set_sampler_map(Affine::translate(0.5, 0.5).then(&a).then(&Affine::translate(-0.5, -0.5)));
+ s.set_canvas_map(a, Affine::translate(0.5, 0.5).then(&a).then(&Affine::translate(-0.5, -0.5)));
}
let size = s.edit("Rotate Canvas", |doc, _| {
let old = doc.size;
diff --git a/crates/engine/src/symmetry_cmds.rs b/crates/engine/src/symmetry_cmds.rs
index 2339568a0..7946b847f 100644
--- a/crates/engine/src/symmetry_cmds.rs
+++ b/crates/engine/src/symmetry_cmds.rs
@@ -4,7 +4,7 @@
use photocraft_doc::{LayerContent, vector::Path};
use photocraft_paint::{
StrokePoint,
- symmetry::{PresetSymmetry, SymmetryMode},
+ symmetry::{MAX_COORDINATE, PresetSymmetry, SymmetryMode},
};
use serde_json::{Value, json};
@@ -58,6 +58,33 @@ impl PaintingSymmetry {
Self::Preset(p) => json!({"mode":p.mode.id(), "center":p.center, "rotation":p.rotation}),
}
}
+ /// The symmetry after a canvas edit (crop, Canvas Size, Image Size, rotation) moved the pixels
+ /// through `a`, so the axis stays on the same image content. `None` when it lands beyond the
+ /// coordinate limits.
+ pub fn transform(&self, a: &photocraft_geom::Affine) -> Option<Self> {
+ let map = |[x, y]: [f64; 2]| {
+ let q = a.apply(photocraft_geom::Point::new(x, y));
+ [q.x, q.y].into_iter().all(|v| v.is_finite() && v.abs() <= MAX_COORDINATE).then_some([q.x, q.y])
+ };
+ match self {
+ Self::Path(axis) => {
+ let segments = axis.segments.iter().map(|&[p, q]| Some([map(p)?, map(q)?])).collect::<Option<_>>()?;
+ Some(Self::Path(SymmetryAxis { source: axis.source.clone(), segments }))
+ }
+ Self::Preset(p) => {
+ // The first axis' direction through the map's linear part gives the new angle; a
+ // flip mirrors it.
+ let [dx, dy] = *p.directions().first()?;
+ let [m0, m1, m2, m3, _, _] = a.m;
+ let turn = (m1 * dx + m3 * dy).atan2(m0 * dx + m2 * dy) - dy.atan2(dx);
+ let rotation = (p.rotation + turn.to_degrees()).rem_euclid(360.0);
+ if !rotation.is_finite() {
+ return None;
+ }
+ Some(Self::Preset(PresetSymmetry { center: map(p.center)?, rotation, ..*p }))
+ }
+ }
+ }
}
fn set_preset(s: &mut Session, p: &Value) -> Result<Value> {
@@ -246,6 +273,33 @@ mod tests {
assert!(SymmetryAxis::from_path("long".into(), &Path::new(vec![long])).is_err(), "path complexity remains bounded");
}
+ #[test]
+ fn canvas_edits_move_the_symmetry_with_the_pixels() {
+ let preset = |s: &Session| s.active().unwrap().symmetry.as_ref().unwrap().preset().unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
+ s.execute("paint.setSymmetry", json!({"mode": "vertical"})).unwrap();
+ s.execute("image.crop", json!({"x": 40, "y": 0, "width": 60, "height": 100})).unwrap();
+ assert_eq!(preset(&s).center, [10.0, 50.0], "the axis stays on the pixels it was on");
+ s.execute("image.imageSize", json!({"width": 120, "height": 200})).unwrap();
+ assert_eq!(preset(&s).center, [20.0, 100.0]);
+ s.execute("paint.setSymmetry", json!({"mode": "diagonal", "center": [30, 40]})).unwrap();
+ s.execute("image.imageRotation.flipCanvasHorizontal", json!({})).unwrap();
+ let p = preset(&s);
+ assert_eq!(p.center, [90.0, 40.0], "edge coordinates mirror about the canvas width, not the last pixel");
+ assert!((p.rotation - 90.0).abs() < 1e-9, "the 45° axis mirrors to 135°: {}", p.rotation);
+
+ // A path axis keeps lying on its (moved) source path.
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
+ s.execute("path.set", json!({"name": "work", "path": {"subpaths": [{"closed": false, "knots": [[40, 0], [60, 100]]}]}})).unwrap();
+ s.execute("paint.symmetryFromPath", json!({"name": "work"})).unwrap();
+ s.execute("image.crop", json!({"x": 30, "y": 10, "width": 50, "height": 80})).unwrap();
+ let st = s.active().unwrap();
+ let moved = SymmetryAxis::from_path("work".into(), st.doc.work_path.as_ref().unwrap()).unwrap();
+ assert_eq!(st.symmetry, Some(PaintingSymmetry::Path(moved)));
+ }
+
#[test]
fn symmetry_paints_mirrored_pixels_and_disable_stops_it() {
let mut s = Session::new();