From fc48f21f0fa7ba5090f7dc3ee7767d8828ed413d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 11 Oct 2026 04:34:27 +0200 Subject: [PATCH 01/15] Vanishing Point: on-canvas plane editor with Create/Edit Plane, grid and paste (#3122) Filter > Vanishing Point now opens a dialog mode on the canvas instead of the generic parameter dialog: - Create Plane (C): four clicks, in any order, make a plane (corners are normalised clockwise from the top-left, the order paste expects). - Edit Plane (V): drag corner nodes, or edge nodes to slide an edge along the plane's own perspective; click a plane to select it, Delete removes it. - The plane grid is drawn at the Grid Size, in the accent colour when the plane is valid, warning yellow when its perspective is doubtful and red (outline only) when the quad isn't convex (VpPlane::check). - With an image on the clipboard the selected plane previews it pasted in perspective; drag to move it, Width sets its size, New Layer renders it on a new layer. OK / Enter runs filter.vanishingPoint with the planes and the paste as one history step; the control channel drives the same session through {"ui": {...}}. The engine now rejects a drawn plane whose corners don't form a convex quad (bow-tie, dented) instead of warping along it. Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/vanishing.rs | 86 ++++ crates/engine/src/vp_cmds.rs | 33 +- crates/ui-egui/src/distort_ui.rs | 36 +- crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/vp_ui.rs | 611 ++++++++++++++++++++++++++++ docs/scorecard.md | 2 +- scorecard/tools.toml | 2 +- 23 files changed, 864 insertions(+), 11 deletions(-) create mode 100644 crates/ui-egui/src/vp_ui.rs diff --git a/crates/algo/src/vanishing.rs b/crates/algo/src/vanishing.rs index 5661d66c9d..77b7bb107c 100644 --- a/crates/algo/src/vanishing.rs +++ b/crates/algo/src/vanishing.rs @@ -114,6 +114,73 @@ impl VpPlane { }); Lifted { focal: f, center: c, pts } } + + /// Turn of each corner (`sin` of the angle between consecutive edges, positive when the + /// corners run clockwise on screen); `None` when an edge is shorter than a pixel or a corner + /// is not finite. + fn turns(&self) -> Option<[f64; 4]> { + let q = &self.corners; + if q.iter().flatten().any(|v| !v.is_finite() || v.abs() > 1e9) { + return None; + } + let e = |i: usize| [q[(i + 1) % 4][0] - q[i][0], q[(i + 1) % 4][1] - q[i][1]]; + let mut out = [0.0; 4]; + for (i, t) in out.iter_mut().enumerate() { + let (a, b) = (e(i), e((i + 1) % 4)); + let (la, lb) = (a[0].hypot(a[1]), b[0].hypot(b[1])); + if la < 1.0 || lb < 1.0 { + return None; + } + *t = (a[0] * b[1] - a[1] * b[0]) / (la * lb); + } + Some(out) + } + + /// How usable the plane is, the way Photoshop colours its grid: [`PlaneCheck::Invalid`] for + /// a quad that isn't convex (self-intersecting, a corner pushed inside, a near-straight or + /// near-zero corner), [`PlaneCheck::Questionable`] for a convex quad whose perspective can't + /// come from a camera centred at `center` (or with a corner sharper than 10°), else + /// [`PlaneCheck::Valid`]. + pub fn check(&self, center: [f64; 2]) -> PlaneCheck { + let Some(t) = self.turns() else { return PlaneCheck::Invalid }; + let same_sign = t.iter().all(|v| *v > 0.0) || t.iter().all(|v| *v < 0.0); + let min = t.iter().fold(f64::MAX, |m, v| m.min(v.abs())); + if !same_sign || min < 1f64.to_radians().sin() || self.homography().is_none() { + return PlaneCheck::Invalid; + } + if min < 10f64.to_radians().sin() { + return PlaneCheck::Questionable; + } + // Both vanishing points finite but no real focal length fits them. + let q = &self.corners; + let (v1, v2) = (meet(q[0], q[1], q[3], q[2]), meet(q[0], q[3], q[1], q[2])); + let finite = |v: V3| v[2].abs() > 1e-9 * (v[0].abs() + v[1].abs()).max(1.0); + if finite(v1) && finite(v2) && self.focal(center).is_none() { + return PlaneCheck::Questionable; + } + PlaneCheck::Valid + } + + /// The same quad with its corners clockwise on screen, starting at the top-left one + /// (the order [`paste`] and [`Scene::tear_off`] expect), however they were clicked. + pub fn normalized(&self) -> VpPlane { + let mut q = self.corners; + if self.turns().is_some_and(|t| t.iter().sum::() < 0.0) { + q = [q[0], q[3], q[2], q[1]]; + } + let first = (0..4).min_by(|&a, &b| (q[a][0] + q[a][1]).total_cmp(&(q[b][0] + q[b][1]))).unwrap_or(0); + VpPlane { corners: [q[first], q[(first + 1) % 4], q[(first + 2) % 4], q[(first + 3) % 4]] } + } +} + +/// Plane validity ([`VpPlane::check`]): Photoshop draws a valid plane's grid blue, a doubtful +/// one yellow and an invalid one red. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PlaneCheck { + Valid, + Questionable, + Invalid, } impl Lifted { @@ -363,6 +430,25 @@ mod tests { assert!((lu / lv - 2.0).abs() < 0.01, "aspect {}", lu / lv); } + #[test] + fn plane_check_and_corner_order() { + let c = [400.0, 300.0]; + assert_eq!(floor_quad(500.0, c).check(c), PlaneCheck::Valid); + let square = VpPlane { corners: [[10.0, 10.0], [110.0, 10.0], [110.0, 110.0], [10.0, 110.0]] }; + assert_eq!(square.check(c), PlaneCheck::Valid, "fronto-parallel"); + let bowtie = VpPlane { corners: [[10.0, 10.0], [110.0, 110.0], [110.0, 10.0], [10.0, 110.0]] }; + assert_eq!(bowtie.check(c), PlaneCheck::Invalid); + let dent = VpPlane { corners: [[10.0, 10.0], [110.0, 10.0], [40.0, 40.0], [10.0, 110.0]] }; + assert_eq!(dent.check(c), PlaneCheck::Invalid, "concave"); + let sliver = VpPlane { corners: [[10.0, 10.0], [300.0, 10.0], [300.0, 40.0], [200.0, 40.0]] }; + assert_eq!(sliver.check(c), PlaneCheck::Questionable, "a corner sharper than 10°"); + let nan = VpPlane { corners: [[f64::NAN, 10.0], [110.0, 10.0], [110.0, 110.0], [10.0, 110.0]] }; + assert_eq!(nan.check(c), PlaneCheck::Invalid); + // Clicked counter-clockwise from the bottom-right: clockwise from the top-left. + let ccw = VpPlane { corners: [[110.0, 110.0], [110.0, 10.0], [10.0, 10.0], [10.0, 110.0]] }; + assert_eq!(ccw.normalized(), square); + } + #[test] fn tear_off_is_perpendicular_and_shares_the_edge() { let c = [400.0, 300.0]; diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/vp_cmds.rs index 4d386d60d7..185930298a 100644 --- a/crates/engine/src/vp_cmds.rs +++ b/crates/engine/src/vp_cmds.rs @@ -3,7 +3,7 @@ //! ([`photocraft_algo::vanishing`]). The edit lands on the active pixel layer, or on a new layer //! with `"newLayer": true` (Photoshop's advice for non-destructive Vanishing Point work). -use photocraft_algo::vanishing::{Edge, Scene, VpPlane, clone_stroke, paste}; +use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_stroke, paste}; use photocraft_doc::{Document, Layer, LayerContent, LayerId}; use photocraft_geom::Rect; use photocraft_raster::Surface; @@ -34,12 +34,22 @@ pub fn scene(p: &Value, canvas: Rect) -> Result { let a = v.get("corners")?.as_array()?; Some([pt(a.first()?)?, pt(a.get(1)?)?, pt(a.get(2)?)?, pt(a.get(3)?)?]) }; - let first = corners(&planes[0]).ok_or_else(|| bad("the first plane needs four `corners`"))?; + // A drawn quad must be convex (Photoshop's red plane): a bow-tie or dented quad has no + // perspective to paste or clone along. + let drawn = |i: usize, c: [[f64; 2]; 4]| -> Result { + let pl = VpPlane { corners: c }; + if pl.check(center) == PlaneCheck::Invalid { + return Err(bad(format!("plane {i}: the four corners must form a convex quad"))); + } + Ok(pl) + }; + let first = planes.first().and_then(corners).ok_or_else(|| bad("the first plane needs four `corners`"))?; + let first = drawn(0, first)?; let focal = p.get("focalLength").and_then(Value::as_f64).filter(|f| *f > 0.0); - let mut sc = Scene::new(VpPlane { corners: first }, center, focal, canvas.width().max(canvas.height()) as f64); + let mut sc = Scene::new(first, center, focal, canvas.width().max(canvas.height()) as f64); for (i, pl) in planes.iter().enumerate().skip(1) { if let Some(c) = corners(pl) { - sc.planes.push(VpPlane { corners: c }); + sc.planes.push(drawn(i, c)?); continue; } let from = pl @@ -257,4 +267,19 @@ mod tests { let r = s.execute(VP, json!({"planes": planes, "newLayer": true})).unwrap(); assert_ne!(r["layer"].as_u64().unwrap(), floor.0); } + + #[test] + fn rejects_planes_that_are_not_convex() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200, "depth": 16})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let bowtie = json!([[20, 20], [180, 180], [180, 20], [20, 180]]); + let dent = json!([[20, 20], [180, 20], [60, 60], [20, 180]]); + let square = json!([[20, 20], [180, 20], [180, 180], [20, 180]]); + for planes in [json!([{"corners": bowtie}]), json!([{"corners": square}, {"corners": dent}])] { + let e = s.execute(VP, json!({"planes": planes})).unwrap_err().to_string(); + assert!(e.contains("convex"), "{e}"); + } + assert!(s.execute(VP, json!({"planes": [{"corners": square}]})).is_ok()); + } } diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rs index b3bda3a7f5..0a0d7914b0 100644 --- a/crates/ui-egui/src/distort_ui.rs +++ b/crates/ui-egui/src/distort_ui.rs @@ -1,10 +1,11 @@ -//! Interactive Liquify (full-window dialog), Puppet Warp and Perspective Warp (on-canvas modes). +//! Interactive Liquify (full-window dialog), Puppet Warp, Perspective Warp and Vanishing Point +//! (on-canvas modes). //! //! All three are previews over plain data (strokes, pins, planes); committing runs the engine -//! command with that data (`filter.liquify`, `edit.puppetWarp`, `edit.perspectiveWarp`, or the -//! smart-object twins), so the result is one history step and exactly replayable. This module +//! command with that data (`filter.liquify`, `edit.puppetWarp`, `edit.perspectiveWarp`, +//! `filter.vanishingPoint`, or the smart-object twins), so the result is one history step and exactly replayable. This module //! holds the shared runtime state and the hooks the shell calls (menus, pointer, keys, overlay, -//! options bar); the modes live in `liquify_ui`, `puppet_ui` and `perspective_ui`. +//! options bar); the modes live in `liquify_ui`, `puppet_ui`, `perspective_ui` and `vp_ui`. use std::sync::Arc; @@ -23,13 +24,14 @@ pub struct Distort { pub liquify: Option, pub puppet: Option, pub perspective: Option, + pub vanishing: Option, /// Filter Gallery dialog (gallery_ui). pub gallery: Option, } impl Distort { pub fn active(&self) -> bool { - self.liquify.is_some() || self.puppet.is_some() || self.perspective.is_some() + self.liquify.is_some() || self.puppet.is_some() || self.perspective.is_some() || self.vanishing.is_some() } /// Short description for `ui.inspect`. @@ -38,6 +40,7 @@ impl Distort { "liquify": self.liquify.as_ref().map(|d| d.describe()), "puppet": self.puppet.as_ref().map(|p| p.describe()), "perspective": self.perspective.as_ref().map(|p| p.describe()), + "vanishingPoint": self.vanishing.as_ref().map(|v| v.describe()), "gallery": self.gallery.as_ref().map(|g| g.describe()), }) } @@ -118,6 +121,8 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val "edit.perspectiveWarp" | "layer.smartObjects.perspectiveWarp" if ui.is_some() && app.distort.perspective.is_some() => { Some(crate::perspective_ui::control(app, ui.unwrap_or(&Value::Null))) } + "filter.vanishingPoint" if empty => Some(crate::vp_ui::begin(app, ctx).map(|_| json!({"vanishingPoint": app.distort.describe()["vanishingPoint"]}))), + "filter.vanishingPoint" if ui.is_some() && app.distort.vanishing.is_some() => Some(crate::vp_ui::control(app, ui.unwrap_or(&Value::Null))), _ => None, } } @@ -136,6 +141,10 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> crate::perspective_ui::pointer(app, ev, mods); return true; } + if app.distort.vanishing.is_some() { + crate::vp_ui::pointer(app, ev, mods); + return true; + } false } @@ -179,6 +188,16 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } return true; } + if app.distort.vanishing.is_some() { + if enter(ctx) { + let _ = crate::vp_ui::commit(app); + } else if esc(ctx) { + crate::vp_ui::escape(app); + } else { + crate::vp_ui::keys(app, ctx); + } + return true; + } false } @@ -190,6 +209,9 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some(p) = &app.distort.perspective { crate::perspective_ui::draw(p, painter, xf); } + if let Some(v) = &app.distort.vanishing { + crate::vp_ui::draw(v, painter, xf); + } } /// Options bar for the on-canvas modes. True when drawn. @@ -202,6 +224,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool { crate::perspective_ui::options_bar(app, ui); return true; } + if app.distort.vanishing.is_some() { + crate::vp_ui::options_bar(app, ui); + return true; + } false } diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 23339c72f5..b39e9381a8 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2441,3 +2441,11 @@ fontWeight Italic Kurzíva Front Image Přední obraz Search settings… Hledat nastavení… No matching settings Žádná odpovídající nastavení + Edit Plane Upravit rovinu + Create Plane Vytvořit rovinu + Grid Size: Velikost mřížky: + New Layer Nová vrstva + Vanishing Point: click four corners to create a plane Úběžník: klepnutím na čtyři rohy vytvoříte rovinu + Vanishing Point is not active Úběžník není aktivní + Apply Vanishing Point ({key}) Použít úběžník ({key}) + Fix the red plane first: its corners must form a convex quad Nejprve opravte červenou rovinu: její rohy musí tvořit konvexní čtyřúhelník diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index fa9bd5bf0f..b5eee5bed2 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2479,3 +2479,11 @@ fontWeight Italic Kursiv Front Image Vorderes Bild Search settings… Einstellungen durchsuchen… No matching settings Keine passenden Einstellungen + Edit Plane Ebene bearbeiten + Create Plane Ebene erstellen + Grid Size: Rastergröße: + New Layer Neue Ebene + Vanishing Point: click four corners to create a plane Fluchtpunkt: Klicken Sie auf vier Ecken, um eine Ebene zu erstellen + Vanishing Point is not active Fluchtpunkt ist nicht aktiv + Apply Vanishing Point ({key}) Fluchtpunkt anwenden ({key}) + Fix the red plane first: its corners must form a convex quad Korrigieren Sie zuerst die rote Ebene: Ihre Ecken müssen ein konvexes Viereck bilden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4c79317146..f01045950d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3548,3 +3548,8 @@ fontWeight Thin Πολύ λεπτά Front Image Μπροστινή εικόνα Search settings… Αναζήτηση ρυθμίσεων… No matching settings Δεν βρέθηκαν ρυθμίσεις + Grid Size: Μέγεθος πλέγματος: + Vanishing Point: click four corners to create a plane Σημείο φυγής: κάντε κλικ σε τέσσερις γωνίες για να δημιουργήσετε ένα επίπεδο + Vanishing Point is not active Το Σημείο φυγής δεν είναι ενεργό + Apply Vanishing Point ({key}) Εφαρμογή σημείου φυγής ({key}) + Fix the red plane first: its corners must form a convex quad Διορθώστε πρώτα το κόκκινο επίπεδο: οι γωνίες του πρέπει να σχηματίζουν κυρτό τετράπλευρο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a8be679f29..5517d8dadf 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2520,3 +2520,11 @@ fontWeight Italic Cursiva Front Image Imagen frontal Search settings… Buscar ajustes… No matching settings No hay ajustes que coincidan + Edit Plane Editar plano + Create Plane Crear plano + Grid Size: Tamaño de rejilla: + New Layer Capa nueva + Vanishing Point: click four corners to create a plane Punto de fuga: haga clic en cuatro esquinas para crear un plano + Vanishing Point is not active Punto de fuga no está activo + Apply Vanishing Point ({key}) Aplicar punto de fuga ({key}) + Fix the red plane first: its corners must form a convex quad Corrija primero el plano rojo: sus esquinas deben formar un cuadrilátero convexo diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 25c8e0f377..8d3121dd79 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2858,3 +2858,9 @@ fontWeight Italic Italique Front Image Image de premier plan Search settings… Rechercher des réglages… No matching settings Aucun réglage correspondant + Grid Size: Taille de la grille : + New Layer Nouveau calque + Vanishing Point: click four corners to create a plane Point de fuite : cliquez sur quatre coins pour créer un plan + Vanishing Point is not active Point de fuite n’est pas actif + Apply Vanishing Point ({key}) Appliquer le point de fuite ({key}) + Fix the red plane first: its corners must form a convex quad Corrigez d’abord le plan rouge : ses coins doivent former un quadrilatère convexe diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 9030e72525..910342b185 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2845,3 +2845,9 @@ fontWeight Italic Miring Front Image Gambar Depan Search settings… Cari pengaturan… No matching settings Tidak ada pengaturan yang cocok + Grid Size: Ukuran Grid: + New Layer Layer Baru + Vanishing Point: click four corners to create a plane Vanishing Point: klik empat sudut untuk membuat bidang + Vanishing Point is not active Vanishing Point tidak aktif + Apply Vanishing Point ({key}) Terapkan Vanishing Point ({key}) + Fix the red plane first: its corners must form a convex quad Perbaiki bidang merah dulu: sudut-sudutnya harus membentuk segi empat cembung diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9993449c5a..81c3145854 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2510,3 +2510,11 @@ fontWeight Italic Corsivo Front Image Immagine in primo piano Search settings… Cerca impostazioni… No matching settings Nessuna impostazione corrispondente + Edit Plane Modifica piano + Create Plane Crea piano + Grid Size: Dimensione griglia: + New Layer Nuovo livello + Vanishing Point: click four corners to create a plane Punto di fuga: fai clic su quattro angoli per creare un piano + Vanishing Point is not active Punto di fuga non è attivo + Apply Vanishing Point ({key}) Applica punto di fuga ({key}) + Fix the red plane first: its corners must form a convex quad Correggi prima il piano rosso: i suoi angoli devono formare un quadrilatero convesso diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 310650e1dc..08f56447ed 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3459,3 +3459,8 @@ fontWeight Italic 斜体 Front Image 前面の画像 Search settings… 設定を検索… No matching settings 一致する設定はありません + Grid Size: グリッドサイズ: + Vanishing Point: click four corners to create a plane 消点:4 つの角をクリックして面を作成します + Vanishing Point is not active 消点はアクティブではありません + Apply Vanishing Point ({key}) 消点を適用({key}) + Fix the red plane first: its corners must form a convex quad 先に赤い面を修正してください:角が凸四角形になる必要があります diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 21cf014d52..81b10fb7ce 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3019,3 +3019,10 @@ fontWeight Italic 기울임 Front Image 전면 이미지 Search settings… 설정 검색… No matching settings 일치하는 설정 없음 + Edit Plane 평면 편집 + Create Plane 평면 만들기 + Grid Size: 격자 크기: + Vanishing Point: click four corners to create a plane 소실점: 네 모서리를 클릭하여 평면을 만드십시오 + Vanishing Point is not active 소실점이 활성화되어 있지 않습니다 + Apply Vanishing Point ({key}) 소실점 적용 ({key}) + Fix the red plane first: its corners must form a convex quad 먼저 빨간색 평면을 수정하십시오: 모서리가 볼록 사각형을 이루어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 20370b4326..456b8c3f44 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3618,3 +3618,8 @@ cameraRaw Whites Witten Search settings… Instellingen zoeken… No matching settings Geen overeenkomende instellingen PhotoCraft — Screen Color Picker PhotoCraft — Schermkleurkiezer + Grid Size: Rastergrootte: + Vanishing Point: click four corners to create a plane Verdwijnpunt: klik op vier hoeken om een vlak te maken + Vanishing Point is not active Verdwijnpunt is niet actief + Apply Vanishing Point ({key}) Verdwijnpunt toepassen ({key}) + Fix the red plane first: its corners must form a convex quad Herstel eerst het rode vlak: de hoeken moeten een convexe vierhoek vormen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ac086df7a4..8acdcd1c62 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3459,3 +3459,8 @@ cameraRaw Roughness Chropowatość Front Image Obraz na wierzchu Search settings… Szukaj ustawień… No matching settings Brak pasujących ustawień + Grid Size: Rozmiar siatki: + Vanishing Point: click four corners to create a plane Punkt zbieżności: kliknij cztery narożniki, aby utworzyć płaszczyznę + Vanishing Point is not active Punkt zbieżności nie jest aktywny + Apply Vanishing Point ({key}) Zastosuj punkt zbieżności ({key}) + Fix the red plane first: its corners must form a convex quad Najpierw popraw czerwoną płaszczyznę: jej narożniki muszą tworzyć czworokąt wypukły diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a664352cc2..1b58102b86 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2866,3 +2866,9 @@ fontWeight Italic Itálico Front Image Imagem frontal Search settings… Pesquisar configurações… No matching settings Nenhuma configuração encontrada + Grid Size: Tamanho da grade: + New Layer Nova camada + Vanishing Point: click four corners to create a plane Ponto de fuga: clique em quatro cantos para criar um plano + Vanishing Point is not active Ponto de fuga não está ativo + Apply Vanishing Point ({key}) Aplicar ponto de fuga ({key}) + Fix the red plane first: its corners must form a convex quad Corrija primeiro o plano vermelho: seus cantos devem formar um quadrilátero convexo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f7d3cee401..22eda77f08 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2725,3 +2725,9 @@ fontWeight Italic Курсив Rasterize Layer Style Растрировать стиль слоя Search settings… Поиск настроек… No matching settings Нет подходящих настроек + Grid Size: Размер сетки: + New Layer Новый слой + Vanishing Point: click four corners to create a plane Точка схода: щелкните четыре угла, чтобы создать плоскость + Vanishing Point is not active Точка схода не активна + Apply Vanishing Point ({key}) Применить точку схода ({key}) + Fix the red plane first: its corners must form a convex quad Сначала исправьте красную плоскость: ее углы должны образовывать выпуклый четырехугольник diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1f9a076d8d..3fd50ffaf1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3546,3 +3546,8 @@ cameraRaw Masking Маскування Search settings… Пошук налаштувань… No matching settings Немає відповідних налаштувань PhotoCraft — Screen Color Picker PhotoCraft — Піпетка кольору екрана + Grid Size: Розмір сітки: + Vanishing Point: click four corners to create a plane Точка сходження: клацніть чотири кути, щоб створити площину + Vanishing Point is not active Точка сходження не активна + Apply Vanishing Point ({key}) Застосувати точку сходження ({key}) + Fix the red plane first: its corners must form a convex quad Спершу виправте червону площину: її кути мають утворювати опуклий чотирикутник diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index de1d2dcac2..644eb96e9c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2448,3 +2448,11 @@ fontWeight Italic 斜体 Front Image 前面的图像 Search settings… 搜索设置… No matching settings 没有匹配的设置 + Edit Plane 编辑平面 + Create Plane 创建平面 + Grid Size: 网格大小: + New Layer 新建图层 + Vanishing Point: click four corners to create a plane 消失点:单击四个角以创建平面 + Vanishing Point is not active 消失点未处于活动状态 + Apply Vanishing Point ({key}) 应用消失点({key}) + Fix the red plane first: its corners must form a convex quad 请先修正红色平面:其四个角必须构成凸四边形 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 697e5312ca..2150018ee0 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2418,3 +2418,11 @@ fontWeight Italic 斜體 Front Image 前面的影像 Search settings… 搜尋設定… No matching settings 沒有符合的設定 + Edit Plane 編輯平面 + Create Plane 建立平面 + Grid Size: 格點大小: + New Layer 新增圖層 + Vanishing Point: click four corners to create a plane 消失點:按一下四個角以建立平面 + Vanishing Point is not active 消失點未啟用 + Apply Vanishing Point ({key}) 套用消失點 ({key}) + Fix the red plane first: its corners must form a convex quad 請先修正紅色平面:其四個角必須構成凸四邊形 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0adf31b0f2..cbc2913acb 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -170,6 +170,7 @@ mod type_transform; mod variables_ui; pub mod vector_ui; pub mod view_cmds; +pub mod vp_ui; pub mod warp_preview; pub mod wheel_nav; pub mod wide_angle_ui; diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rs new file mode 100644 index 0000000000..bdaad601c6 --- /dev/null +++ b/crates/ui-egui/src/vp_ui.rs @@ -0,0 +1,611 @@ +//! Filter › Vanishing Point on the canvas (dialog mode). +//! +//! **Create Plane** (C): four clicks set a plane's corners, in any order. **Edit Plane** (V): +//! drag a corner node, or an edge node to slide that edge along the plane's own perspective; +//! click a plane to select it, Delete removes it. The plane's grid is drawn at the Grid Size and, +//! like Photoshop's, in the accent colour when the plane is valid, yellow when its perspective is +//! doubtful and red when it is invalid ([`VpPlane::check`]). With an image on the clipboard the +//! selected plane shows it pasted in perspective; drag it to move it on the plane. ↩ / OK runs +//! `filter.vanishingPoint` with the planes and the paste, so it is one history step and an +//! action or agent can replay it exactly. + +use egui::{Color32, Pos2, Stroke, TextureHandle, pos2}; +use photocraft_algo::transform::Homography; +use photocraft_algo::vanishing::{PlaneCheck, Scene, VpPlane}; +use photocraft_doc::{LayerContent, LayerId}; +use photocraft_engine::vp_cmds::VP; +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, ViewXform}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub enum VpTool { + EditPlane, + CreatePlane, +} + +enum Drag { + /// A corner node, and the pointer offset from it. + Corner { plane: usize, corner: usize, offset: [f64; 2] }, + /// An edge node (0 top, 1 right, 2 bottom, 3 left): the edge slides along the plane's + /// perspective as it was at the press. + Edge { plane: usize, edge: usize, h: Homography, inv: Homography }, + /// The pasted image, and the pointer offset from its top-left in plane coordinates. + Paste { offset: [f64; 2] }, +} + +/// The clipboard image shown pasted onto the plane. +struct Clip { + texture: TextureHandle, + width: f64, + height: f64, +} + +pub struct VpSession { + pub layer: LayerId, + canvas: Rect, + pub planes: Vec, + pub tool: VpTool, + /// Corners clicked so far with Create Plane. + pending: Vec<[f64; 2]>, + pub selected: Option, + /// Grid cell size in px at the plane's nearest edge. + pub grid_size: f64, + /// Paste the clipboard onto the selected plane on OK. + pub paste: bool, + /// Top-left of the pasted image in plane coordinates (0..1). + pub paste_at: [f64; 2], + /// Width of the pasted image as a fraction of the plane's width. + pub paste_width: f64, + pub new_layer: bool, + clip: Option, + drag: Option, +} + +/// Most planes a session holds (the control channel can't make it allocate without bound). +const MAX_PLANES: usize = 64; +/// Most grid lines drawn per direction. +const MAX_LINES: usize = 200; + +impl VpSession { + pub fn describe(&self) -> Value { + let center = self.center(); + let planes: Vec = self.planes.iter().map(|p| json!({"corners": p.corners, "check": p.check(center)})).collect(); + json!({ + "layer": self.layer.0, + "tool": self.tool, + "planes": planes, + "pending": self.pending, + "selected": self.selected, + "gridSize": self.grid_size, + "paste": self.paste && self.clip.is_some(), + "pasteAt": self.paste_at, + "pasteWidth": self.paste_width, + "newLayer": self.new_layer, + }) + } + + fn center(&self) -> [f64; 2] { + let c = self.canvas; + [f64::from(c.x0 + c.x1) / 2.0, f64::from(c.y0 + c.y1) / 2.0] + } + + /// The planes with the shared camera the engine derives from the first one. + fn scene(&self) -> Option { + let first = self.planes.first()?.clone(); + let fallback = f64::from(self.canvas.width().max(self.canvas.height())); + let mut sc = Scene::new(first, self.center(), None, fallback); + sc.planes.extend(self.planes.iter().skip(1).cloned()); + Some(sc) + } + + /// Plane `i`'s unit square → image map and metric side lengths. + fn frame(&self, i: usize) -> Option<(Homography, f64, f64)> { + if i >= self.planes.len() { + return None; + } + let (h, lu, lv) = self.scene()?.frame(i)?; + (lu.is_finite() && lv.is_finite() && lu > 1e-12 && lv > 1e-12).then_some((h, lu, lv)) + } + + /// The plane the paste lands on. + fn paste_plane(&self) -> Option { + if !self.paste || self.clip.is_none() { + return None; + } + self.selected.filter(|i| *i < self.planes.len()).or_else(|| (!self.planes.is_empty()).then_some(0)) + } + + /// Size of the pasted image in plane coordinates (the engine keeps its metric aspect). + fn paste_extent(&self, lu: f64, lv: f64) -> Option<[f64; 2]> { + let c = self.clip.as_ref()?; + Some([self.paste_width, self.paste_width * lu / lv * c.height / c.width.max(1.0)]) + } + + /// The command's params: the planes, and the paste when there is one. + pub fn params(&self) -> Value { + let planes: Vec = self.planes.iter().map(|p| json!({"corners": p.corners})).collect(); + let mut p = json!({"planes": planes}); + if let Some(i) = self.paste_plane() { + p["paste"] = json!([{"plane": i, "at": self.paste_at, "width": self.paste_width}]); + } + if self.new_layer { + p["newLayer"] = json!(true); + } + p + } + + fn add_corner(&mut self, p: [f64; 2]) { + if self.planes.len() >= MAX_PLANES { + return; + } + self.pending.push(p); + if let Ok(corners) = <[[f64; 2]; 4]>::try_from(self.pending.as_slice()) { + self.pending.clear(); + self.planes.push(VpPlane { corners }.normalized()); + self.selected = Some(self.planes.len() - 1); + // Photoshop hands over to Edit Plane once a plane is closed. + self.tool = VpTool::EditPlane; + } + } + + fn delete_selected(&mut self) { + if let Some(i) = self.selected.take().filter(|i| *i < self.planes.len()) { + self.planes.remove(i); + self.drag = None; + } + } + + /// Image positions of the edge nodes of plane `i`. + fn edge_nodes(&self, i: usize) -> Option<[[f64; 2]; 4]> { + let h = self.planes.get(i)?.homography()?; + let at = |u: f64, v: f64| { + let (x, y) = h.apply(u, v); + [x, y] + }; + Some([at(0.5, 0.0), at(1.0, 0.5), at(0.5, 1.0), at(0.0, 0.5)]) + } + + fn press(&mut self, p: [f64; 2], tol: f64) { + if self.tool == VpTool::CreatePlane { + self.add_corner(p); + return; + } + let near = |c: [f64; 2]| (c[0] - p[0]).hypot(c[1] - p[1]) <= tol; + // The selected plane's nodes win over the others'. + let order: Vec = self.selected.into_iter().chain((0..self.planes.len()).rev()).filter(|i| *i < self.planes.len()).collect(); + for &i in &order { + if let Some(ci) = self.planes[i].corners.iter().position(|c| near(*c)) { + let c = self.planes[i].corners[ci]; + self.selected = Some(i); + self.drag = Some(Drag::Corner { plane: i, corner: ci, offset: [c[0] - p[0], c[1] - p[1]] }); + return; + } + if let Some(e) = self.edge_nodes(i).and_then(|n| n.iter().position(|c| near(*c))) + && let Some(h) = self.planes[i].homography() + && let Some(inv) = h.inverse() + { + self.selected = Some(i); + self.drag = Some(Drag::Edge { plane: i, edge: e, h, inv }); + return; + } + } + if let Some(i) = self.paste_plane() + && let Some((h, lu, lv)) = self.frame(i) + && let Some(ext) = self.paste_extent(lu, lv) + && let Some(inv) = h.inverse() + { + let (u, v) = inv.apply(p[0], p[1]); + let (a, b) = (self.paste_at, [self.paste_at[0] + ext[0], self.paste_at[1] + ext[1]]); + if (a[0]..=b[0]).contains(&u) && (a[1]..=b[1]).contains(&v) { + self.drag = Some(Drag::Paste { offset: [a[0] - u, a[1] - v] }); + return; + } + } + self.selected = self.scene().and_then(|sc| sc.plane_at(p)); + } + + fn drag_to(&mut self, p: [f64; 2]) { + match &self.drag { + Some(Drag::Corner { plane, corner, offset }) => { + if let Some(c) = self.planes.get_mut(*plane).and_then(|pl| pl.corners.get_mut(*corner)) { + *c = [p[0] + offset[0], p[1] + offset[1]]; + } + } + Some(Drag::Edge { plane, edge, h, inv }) => { + let (u, v) = inv.apply(p[0], p[1]); + // The plane's (u, v) rectangle after the move. + let (u0, v0, u1, v1) = match edge { + 0 => (0.0, v.min(0.99), 1.0, 1.0), + 1 => (0.0, 0.0, u.max(0.01), 1.0), + 2 => (0.0, 0.0, 1.0, v.max(0.01)), + _ => (u.min(0.99), 0.0, 1.0, 1.0), + }; + if let Some(q) = slid_quad(h, u0, v0, u1, v1) + && let Some(pl) = self.planes.get_mut(*plane) + { + pl.corners = q; + } + } + Some(Drag::Paste { offset }) => { + let offset = *offset; + if let Some(i) = self.paste_plane() + && let Some(inv) = self.planes.get(i).and_then(VpPlane::homography).and_then(|h| h.inverse()) + { + let (u, v) = inv.apply(p[0], p[1]); + let at = [(u + offset[0]).clamp(-1.0, 2.0), (v + offset[1]).clamp(-1.0, 2.0)]; + if at.iter().all(|x| x.is_finite()) { + self.paste_at = at; + } + } + } + None => {} + } + } +} + +/// Corners of the image of `[u0, u1] × [v0, v1]` under `h`, or `None` when part of it would lie +/// on or beyond the plane's horizon (where the edge can't follow the perspective). +fn slid_quad(h: &Homography, u0: f64, v0: f64, u1: f64, v1: f64) -> Option<[[f64; 2]; 4]> { + let m = &h.0; + let w = |u: f64, v: f64| m[6] * u + m[7] * v + m[8]; + let side = w(0.5, 0.5).signum(); + let uv = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]]; + if uv.iter().any(|c| w(c[0], c[1]) * side <= 1e-9 * w(0.5, 0.5).abs()) { + return None; + } + let q = uv.map(|c| { + let (x, y) = h.apply(c[0], c[1]); + [x, y] + }); + (VpPlane { corners: q }.check([0.0, 0.0]) != PlaneCheck::Invalid).then_some(q) +} + +/// Starts Vanishing Point on the active pixel layer. +pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> { + if app.ui.transform.is_some() { + return Err("finish Free Transform first".into()); + } + let st = app.session.active().ok_or("no document")?; + let layer = st.active_layer.ok_or("no active layer")?; + match st.doc.layer(layer).map(|l| &l.content) { + Some(LayerContent::Raster(_)) => {} + Some(other) => return Err(format!("Vanishing Point needs a pixel layer (active layer is {} {} layer)", other.article(), other.kind_name())), + None => return Err("no active layer".into()), + } + let canvas = st.doc.bounds(); + let key = app.ui.alloc_id(); + let clip = app.session.clipboard.as_ref().and_then(|c| { + let r = c.surface.content_bounds(); + (!r.is_empty()).then(|| Clip { + texture: ctx.load_texture(format!("vp-paste-{key}"), crate::distort_ui::surface_image(&c.surface, r, 1024), egui::TextureOptions::LINEAR), + width: f64::from(r.width()), + height: f64::from(r.height()), + }) + }); + app.distort.vanishing = Some(VpSession { + layer, + canvas, + planes: Vec::new(), + tool: VpTool::CreatePlane, + pending: Vec::new(), + selected: None, + grid_size: 100.0, + paste: clip.is_some(), + paste_at: [0.25, 0.25], + paste_width: 0.5, + new_layer: false, + clip, + drag: None, + }); + app.ui.status = tl!("Vanishing Point: click four corners to create a plane").into(); + Ok(()) +} + +/// OK: runs `filter.vanishingPoint` with the planes (and the paste). An invalid plane keeps the +/// mode open; with nothing to paste the mode just closes. +pub fn commit(app: &mut PhotocraftApp) -> Result { + let Some(s) = app.distort.vanishing.as_ref() else { return Ok(Value::Null) }; + let center = s.center(); + if s.planes.iter().any(|p| p.check(center) == PlaneCheck::Invalid) { + let msg = tl!("Fix the red plane first: its corners must form a convex quad"); + app.ui.status = msg.into(); + return Err(msg.into()); + } + let params = s.params(); + app.distort.vanishing = None; + if params.get("paste").is_none() { + return Ok(json!({"committed": false})); + } + app.run(VP, params).map(|r| json!({"committed": true, "result": r})) +} + +/// Control channel: `filter.vanishingPoint {"ui": {...}}` while the mode is active. +pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { + if ui.get("commit").and_then(Value::as_bool) == Some(true) { + return commit(app); + } + if ui.get("cancel").and_then(Value::as_bool) == Some(true) { + app.distort.vanishing = None; + return Ok(json!({"cancelled": true})); + } + let s = app.distort.vanishing.as_mut().ok_or(tl!("Vanishing Point is not active"))?; + if let Some(t) = ui.get("tool").and_then(Value::as_str) { + s.tool = match t { + "edit" | "editPlane" => VpTool::EditPlane, + "create" | "createPlane" => VpTool::CreatePlane, + other => return Err(format!("tool: edit|create, not `{other}`")), + }; + s.pending.clear(); + } + if let Some(p) = ui.get("planes") { + let planes: Vec = serde_json::from_value(p.clone()).map_err(|e| format!("bad planes: {e}"))?; + if planes.len() > MAX_PLANES { + return Err(format!("at most {MAX_PLANES} planes")); + } + s.planes = planes; + // A drag holds indices into the old list. + s.drag = None; + s.selected = (!s.planes.is_empty()).then(|| s.planes.len() - 1); + } + if let Some(i) = ui.get("select").and_then(Value::as_u64) { + s.selected = usize::try_from(i).ok().filter(|i| *i < s.planes.len()); + } + if let Some(g) = ui.get("gridSize").and_then(Value::as_f64).filter(|g| g.is_finite()) { + s.grid_size = g.clamp(2.0, 2000.0); + } + if let Some(b) = ui.get("paste").and_then(Value::as_bool) { + s.paste = b; + } + if let Some(at) = ui.get("pasteAt").and_then(|v| Some([v.get(0)?.as_f64()?, v.get(1)?.as_f64()?])) { + s.paste_at = at.map(|x| if x.is_finite() { x.clamp(-1.0, 2.0) } else { 0.25 }); + } + if let Some(w) = ui.get("pasteWidth").and_then(Value::as_f64).filter(|w| w.is_finite()) { + s.paste_width = w.clamp(0.01, 10.0); + } + if let Some(b) = ui.get("newLayer").and_then(Value::as_bool) { + s.new_layer = b; + } + Ok(s.describe()) +} + +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) { + let tol = crate::distort_ui::tolerance(app); + let Some(s) = app.distort.vanishing.as_mut() else { return }; + match ev { + ToolEvent::Down { x, y, .. } => s.press([x, y], tol), + ToolEvent::Move { x, y, .. } => s.drag_to([x, y]), + ToolEvent::Up { x, y } => { + s.drag_to([x, y]); + s.drag = None; + } + } +} + +/// Keys while the mode is active (↩ and Esc are handled by `distort_ui::keys`). +pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { + use egui::{Key, Modifiers}; + if ctx.memory(|m| m.focused().is_some()) { + return; + } + let Some(s) = app.distort.vanishing.as_mut() else { return }; + let key = |k: Key| ctx.input_mut(|i| i.consume_key(Modifiers::NONE, k)); + if key(Key::V) { + s.tool = VpTool::EditPlane; + s.pending.clear(); + } else if key(Key::C) { + s.tool = VpTool::CreatePlane; + } else if key(Key::Delete) || key(Key::Backspace) { + s.delete_selected(); + } +} + +/// Esc: drops a half-clicked plane first, then leaves the mode. +pub fn escape(app: &mut PhotocraftApp) { + match app.distort.vanishing.as_mut() { + Some(s) if !s.pending.is_empty() => s.pending.clear(), + _ => app.distort.vanishing = None, + } +} + +pub fn draw(s: &VpSession, painter: &egui::Painter, xf: &ViewXform) { + let scr = |p: [f64; 2]| xf.to_screen(p[0] as f32, p[1] as f32); + let tokens = crate::theme::Tokens::get(painter.ctx()); + let center = s.center(); + // The paste first, under the grids. + if let Some(i) = s.paste_plane() + && s.planes.get(i).is_some_and(|p| p.check(center) != PlaneCheck::Invalid) + && let (Some((h, lu, lv)), Some(c)) = (s.frame(i), s.clip.as_ref()) + && let Some(ext) = s.paste_extent(lu, lv) + { + draw_paste(painter, &scr, &h, s.paste_at, ext, &c.texture); + } + for (i, p) in s.planes.iter().enumerate() { + let check = p.check(center); + let colour = match check { + PlaneCheck::Valid => tokens.accent, + PlaneCheck::Questionable => tokens.warning, + PlaneCheck::Invalid => tokens.danger, + }; + let selected = s.selected == Some(i); + // An invalid plane has no perspective to grid: just its red outline, as in Photoshop. + if check != PlaneCheck::Invalid + && let Some((h, lu, lv)) = s.frame(i) + { + let thin = Stroke::new(0.75, colour.gamma_multiply(0.6)); + let at = |u: f64, v: f64| { + let (x, y) = h.apply(u, v); + scr([x, y]) + }; + for u in grid_steps(p, lu, lv, s.grid_size, true) { + painter.line_segment([at(u, 0.0), at(u, 1.0)], thin); + } + for v in grid_steps(p, lu, lv, s.grid_size, false) { + painter.line_segment([at(0.0, v), at(1.0, v)], thin); + } + } + let pts: Vec = p.corners.iter().map(|c| scr(*c)).collect(); + painter.add(egui::Shape::closed_line(pts.clone(), Stroke::new(if selected { 2.0 } else { 1.25 }, colour))); + if selected { + let nodes = pts.into_iter().chain(s.edge_nodes(i).into_iter().flatten().map(scr)); + for c in nodes { + let r = egui::Rect::from_center_size(c, egui::vec2(7.0, 7.0)); + painter.rect_filled(r, 0.0, Color32::WHITE); + painter.rect_stroke(r, 0.0, Stroke::new(1.25, colour), egui::StrokeKind::Inside); + } + } + } + // Create Plane: the corners so far and a rubber band to the pointer. + if !s.pending.is_empty() { + let mut pts: Vec = s.pending.iter().map(|c| scr(*c)).collect(); + if let Some(hover) = painter.ctx().pointer_hover_pos() { + pts.push(hover); + } + painter.add(egui::Shape::line(pts.clone(), Stroke::new(1.25, tokens.accent))); + for c in pts.iter().take(s.pending.len()) { + painter.rect_filled(egui::Rect::from_center_size(*c, egui::vec2(6.0, 6.0)), 0.0, tokens.accent); + } + } +} + +/// Plane coordinates (0..1, exclusive) of the grid lines across `u` (or `v`) for cells of +/// `size` px at the plane's nearest edge, square in the plane's metric. +fn grid_steps(p: &VpPlane, lu: f64, lv: f64, size: f64, along_u: bool) -> Vec { + let q = &p.corners; + let d = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).hypot(a[1] - b[1]); + // Image px per metric unit at the nearest (longest-looking) edge. + let k = [d(q[0], q[1]) / lu, d(q[3], q[2]) / lu, d(q[0], q[3]) / lv, d(q[1], q[2]) / lv].into_iter().fold(0.0, f64::max); + let cell = size.max(1.0) / k; + let len = if along_u { lu } else { lv }; + if !cell.is_finite() || cell <= 0.0 || !len.is_finite() { + return Vec::new(); + } + let step = cell / len; + (1..MAX_LINES).map(|j| j as f64 * step).take_while(|t| *t < 1.0 - 1e-9).collect() +} + +/// The clipboard image on the plane: a mesh through the plane's homography, cells outside the +/// plane left out (the engine clips the paste to the plane). +fn draw_paste(painter: &egui::Painter, scr: &dyn Fn([f64; 2]) -> Pos2, h: &Homography, at: [f64; 2], ext: [f64; 2], tex: &TextureHandle) { + const N: usize = 24; + let mut mesh = egui::Mesh::with_texture(tex.id()); + let tint = Color32::from_white_alpha(230); + for j in 0..=N { + for i in 0..=N { + let (s, t) = (i as f64 / N as f64, j as f64 / N as f64); + let (x, y) = h.apply(at[0] + s * ext[0], at[1] + t * ext[1]); + mesh.vertices.push(egui::epaint::Vertex { pos: scr([x, y]), uv: pos2(s as f32, t as f32), color: tint }); + } + } + for j in 0..N { + for i in 0..N { + let (u, v) = (at[0] + (i as f64 + 0.5) / N as f64 * ext[0], at[1] + (j as f64 + 0.5) / N as f64 * ext[1]); + if !(0.0..=1.0).contains(&u) || !(0.0..=1.0).contains(&v) { + continue; + } + let a = (j * (N + 1) + i) as u32; + mesh.add_triangle(a, a + 1, a + N as u32 + 2); + mesh.add_triangle(a, a + N as u32 + 2, a + N as u32 + 1); + } + } + painter.add(mesh); +} + +pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let Some(s) = app.distort.vanishing.as_mut() else { return }; + if crate::widgets::pill_tab(ui, tl!("Edit Plane"), s.tool == VpTool::EditPlane).on_hover_text("V").clicked() { + s.tool = VpTool::EditPlane; + s.pending.clear(); + } + if crate::widgets::pill_tab(ui, tl!("Create Plane"), s.tool == VpTool::CreatePlane).on_hover_text("C").clicked() { + s.tool = VpTool::CreatePlane; + } + crate::widgets::vline(ui, 22.0); + ui.label(tl!("Grid Size:")); + let mut g = s.grid_size as f32; + if crate::widgets::value_field(ui, &mut g, 2.0..=2000.0, "px", 56.0).changed() { + s.grid_size = f64::from(g); + } + if s.clip.is_some() { + crate::widgets::vline(ui, 22.0); + crate::widgets::checkbox(ui, &mut s.paste, tl!("Paste")); + if s.paste { + ui.label(tl!("Width:")); + let mut w = (s.paste_width * 100.0) as f32; + if crate::widgets::value_field(ui, &mut w, 1.0..=1000.0, "%", 56.0).changed() { + s.paste_width = f64::from(w) / 100.0; + } + } + crate::widgets::checkbox(ui, &mut s.new_layer, tl!("New Layer")); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if crate::widgets::primary_button(ui, "✓", 32.0) + .on_hover_text(crate::i18n::fmt(tl!("Apply Vanishing Point ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))])) + .clicked() + { + let _ = commit(app); + } else if crate::widgets::secondary_button(ui, "⊘", 32.0).on_hover_text(tl!("Cancel (Esc)")).clicked() { + app.distort.vanishing = None; + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn app_with_layer() -> (egui::Context, PhotocraftApp) { + let ctx = egui::Context::default(); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", json!({"width": 240, "height": 160, "depth": 16})).unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#4080c0"})).unwrap(); + app.sync_views(); + (ctx, app) + } + + #[test] + fn four_clicks_make_a_plane_and_ok_pastes_in_one_step() { + let (ctx, mut app) = app_with_layer(); + // Something to paste: a red square on the clipboard. + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("edit.copy", json!({})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + let click = |app: &mut PhotocraftApp, x: f64, y: f64| { + crate::distort_ui::pointer(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(app, ToolEvent::Up { x, y }, egui::Modifiers::NONE); + }; + // A floor receding to the top, clicked counter-clockwise from the bottom-left. + for (x, y) in [(20.0, 150.0), (220.0, 150.0), (170.0, 60.0), (70.0, 60.0)] { + click(&mut app, x, y); + } + let s = app.distort.vanishing.as_ref().unwrap(); + assert_eq!(s.planes.len(), 1); + assert_eq!(s.planes[0].corners, [[70.0, 60.0], [170.0, 60.0], [220.0, 150.0], [20.0, 150.0]], "clockwise from the top-left"); + assert_eq!(s.tool, VpTool::EditPlane); + assert_eq!(s.describe()["planes"][0]["check"], "valid"); + // Edit Plane: drag the top edge node up; the edge slides along the perspective. + let top = s.edge_nodes(0).unwrap()[0]; + crate::distort_ui::pointer(&mut app, ToolEvent::Down { x: top[0], y: top[1], pressure: 1.0 }, egui::Modifiers::NONE); + crate::distort_ui::pointer(&mut app, ToolEvent::Up { x: top[0], y: top[1] - 15.0 }, egui::Modifiers::NONE); + let c = app.distort.vanishing.as_ref().unwrap().planes[0].corners; + assert!(c[0][1] < 60.0 && c[1][1] < 60.0 && c[1][0] - c[0][0] < 100.0, "taller and narrower at the far edge: {c:?}"); + assert_eq!(c[2], [220.0, 150.0]); + let before = app.session.active().unwrap().history.past_len(); + commit(&mut app).unwrap(); + assert!(app.distort.vanishing.is_none()); + assert_eq!(app.session.active().unwrap().history.past_len(), before + 1); + // The paste landed on the plane: red at its middle, blue outside it. + let st = app.session.active().unwrap(); + let l = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let h = VpPlane { corners: c }.homography().unwrap(); + let (x, y) = h.apply(0.5, 0.35); + assert!(l.rgba(x as i32, y as i32)[0] > 0.9, "{:?}", l.rgba(x as i32, y as i32)); + assert!(l.rgba(230, 20)[0] < 0.5, "outside the plane"); + } +} diff --git a/docs/scorecard.md b/docs/scorecard.md index 6c7f540004..aad562e6c8 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -158,7 +158,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | partial | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke brush, pencil, eraser (vector_cmds.rs:1170); brush-only button, no dialog | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | select.convertToShape with tolerance (vector_cmds.rs:1256); radius as a field only | | TOOL-214-13 | Mask Properties: Density and Feather controls | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Vector-mask density/feather in the engine (vector_cmds.rs:948); no UI controls | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15) behind a parameter dialog | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index c5190643a4..cefb18e599 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -206,7 +206,7 @@ id = "TOOL-214-14" target = "Vanishing Point window: draw and edit planes, paste, clone in perspective" status = "partial" issue = 214 -note = "filter.vanishingPoint (vp_cmds.rs:15) behind a parameter dialog" +note = "filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing" [[item]] id = "TOOL-214-15" From 914bb89a606722c7a902065438f80641831eeef5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 11 Oct 2026 08:57:16 +0200 Subject: [PATCH 02/15] Vanishing Point: tear off planes and clone in perspective (#3280) Tear-off planes in the Vanishing Point window: - Ctrl/Cmd-drag an edge node (Create or Edit Plane) tears off a plane at 90 degrees. Dragging its far edge node sets the depth, and Alt-dragging it sets the angle. - A torn plane is stored in its torn-off form (from/edge/angle/depth). Its corners are recomputed from its parent after every edit, the same way the engine builds the scene. It is drawn and validated like any other plane and sent to filter.vanishingPoint in that form. - Deleting a parent keeps its torn planes as drawn planes. Stamp tool (S): - Alt-click a plane to set the source, then drag to clone in perspective. - Options: Diameter, Hardness, Opacity and Aligned (later strokes keep the first stroke's offset). Cmd/Ctrl+Z removes the last stroke. - The canvas shows the strokes as they are painted. The preview paints them in pieces with the same frame the engine uses, and only the painted area recomposites. - The overlay shows the source crosshair and the foreshortened brush. - OK sends the strokes as the command's "clone" param, so the session is one history step. Algo: clone_stroke is split into clone_dabs (anchored stroke pieces, which return the changed area) and clone_source. sample() is safe for non-finite or edge coordinates. Engine: "clone" is parsed and validated up front. The engine caps clone strokes (4096), clone points (200k) and planes (64), checks numbers are finite, and checks the tear-off angle and depth ranges. It returns Err instead of silently dropping bad points. Clone strokes copy back only the area they changed, not the whole layer on every stroke. Scorecard TOOL-214-14 is now done. Still missing: the Marquee tool in the window and the Stamp's Heal modes. Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/vanishing.rs | 114 ++++- crates/engine/src/vp_cmds.rs | 169 +++++-- crates/ui-egui/src/canvas.rs | 7 + crates/ui-egui/src/distort_ui.rs | 6 +- crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/vp_ui.rs | 679 ++++++++++++++++++++++++++-- docs/scorecard.md | 4 +- scorecard/tools.toml | 4 +- 23 files changed, 925 insertions(+), 93 deletions(-) diff --git a/crates/algo/src/vanishing.rs b/crates/algo/src/vanishing.rs index 77b7bb107c..2ac85badb4 100644 --- a/crates/algo/src/vanishing.rs +++ b/crates/algo/src/vanishing.rs @@ -324,38 +324,97 @@ pub fn paste(scene: &Scene, i: usize, src: &Surface, src_rect: Rect, at: [f64; 2 Ok(Some(out)) } +/// The fixed frame of one clone stroke: the source and destination planes, the source offset in +/// plane-metric units and the brush radius, all set at the stroke's anchor (its first dab). +struct CloneFrame { + hs: Homography, + ls: (f64, f64), + hd: Homography, + hd_inv: Homography, + ld: (f64, f64), + offset: [f64; 2], + r_m: f64, +} + +impl CloneFrame { + fn new(scene: &Scene, source: [f64; 2], anchor: [f64; 2], size: f64) -> Option { + let (ps, pd) = (scene.plane_at(source)?, scene.plane_at(anchor)?); + let ((hs, lus, lvs), (hd, lud, lvd)) = (scene.frame(ps)?, scene.frame(pd)?); + let (hs_inv, hd_inv) = (hs.inverse()?, hd.inverse()?); + let ms = metric(&hs_inv, (lus, lvs), source); + let md0 = metric(&hd_inv, (lud, lvd), anchor); + // Brush radius in metric units (from the image size at the anchor). + let probe = metric(&hd_inv, (lud, lvd), [anchor[0] + size / 2.0, anchor[1]]); + let r_m = ((probe[0] - md0[0]).hypot(probe[1] - md0[1])).max(1e-9); + let offset = [ms[0] - md0[0], ms[1] - md0[1]]; + (offset.iter().all(|v| v.is_finite()) && r_m.is_finite()).then_some(CloneFrame { hs, ls: (lus, lvs), hd, hd_inv, ld: (lud, lvd), offset, r_m }) + } + + /// The source point (image px) that destination `p` copies from. + fn source_of(&self, p: [f64; 2]) -> [f64; 2] { + let m = metric(&self.hd_inv, self.ld, p); + let (x, y) = self.hs.apply((m[0] + self.offset[0]) / self.ls.0, (m[1] + self.offset[1]) / self.ls.1); + [x, y] + } +} + +/// Image point → plane-metric coordinates through the plane's inverse homography. +fn metric(inv: &Homography, l: (f64, f64), p: [f64; 2]) -> [f64; 2] { + let (u, v) = inv.apply(p[0], p[1]); + [u * l.0, v * l.1] +} + /// Perspective clone stamp: one stroke of dabs at image points `points` on the destination /// plane, copying from `source` (image px) with the offset fixed in plane-metric units at the /// first dab. `size` is the brush diameter in px at the first dab; `hardness` 0..=1. pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: &[[f64; 2]], size: f64, hardness: f64, opacity: f32) -> usize { let Some(first) = points.first() else { return 0 }; - let (Some(ps), Some(pd)) = (scene.plane_at(source), scene.plane_at(*first)) else { return 0 }; - let (Some((hs, lus, lvs)), Some((hd, lud, lvd))) = (scene.frame(ps), scene.frame(pd)) else { return 0 }; - let (Some(hs_inv), Some(hd_inv)) = (hs.inverse(), hd.inverse()) else { return 0 }; - let metric = |inv: &Homography, lu: f64, lv: f64, p: [f64; 2]| { - let (u, v) = inv.apply(p[0], p[1]); - [u * lu, v * lv] - }; - let ms = metric(&hs_inv, lus, lvs, source); - let md0 = metric(&hd_inv, lud, lvd, *first); - let offset = [ms[0] - md0[0], ms[1] - md0[1]]; - // Brush radius in metric units (from the image size at the first dab). - let probe = metric(&hd_inv, lud, lvd, [first[0] + size / 2.0, first[1]]); - let r_m = ((probe[0] - md0[0]).hypot(probe[1] - md0[1])).max(1e-9); + clone_dabs(scene, surf, source, *first, points, size, hardness, opacity).0 +} + +/// Where a clone stroke that starts at `anchor` copying from `source` samples for destination +/// `p`: the same plane-metric offset. A live preview paints a stroke in pieces with it, and +/// Aligned strokes keep the first stroke's offset. `None` when `source` or `anchor` is off the +/// planes. +pub fn clone_source(scene: &Scene, source: [f64; 2], anchor: [f64; 2], p: [f64; 2]) -> Option<[f64; 2]> { + let s = CloneFrame::new(scene, source, anchor, 1.0)?.source_of(p); + s.iter().all(|v| v.is_finite()).then_some(s) +} + +/// [`clone_stroke`]'s dabs at `points` for a stroke anchored at `anchor` (its first dab, which +/// fixes the offset and the brush's metric size), so a stroke can be painted in pieces exactly +/// as one. Returns the dabs painted and the area they changed. +#[allow(clippy::too_many_arguments)] +pub fn clone_dabs( + scene: &Scene, + surf: &mut Surface, + source: [f64; 2], + anchor: [f64; 2], + points: &[[f64; 2]], + size: f64, + hardness: f64, + opacity: f32, +) -> (usize, Rect) { + let Some(f) = CloneFrame::new(scene, source, anchor, size) else { return (0, Rect::EMPTY) }; + let (lud, lvd) = f.ld; let src_copy = surf.clone(); let fmt = surf.format(); let n = fmt.channels(); let mut dabs = 0; + let mut changed_area = Rect::EMPTY; for p in points { - let mc = metric(&hd_inv, lud, lvd, *p); + let mc = metric(&f.hd_inv, f.ld, *p); // Image-space footprint: map a metric circle's bounding points. let mut bb = [f64::MAX, f64::MAX, f64::MIN, f64::MIN]; for k in 0..16 { let a = k as f64 / 16.0 * std::f64::consts::TAU; - let (u, v) = ((mc[0] + r_m * a.cos()) / lud, (mc[1] + r_m * a.sin()) / lvd); - let (x, y) = hd.apply(u, v); + let (u, v) = ((mc[0] + f.r_m * a.cos()) / lud, (mc[1] + f.r_m * a.sin()) / lvd); + let (x, y) = f.hd.apply(u, v); bb = [bb[0].min(x), bb[1].min(y), bb[2].max(x), bb[3].max(y)]; } + if bb.iter().any(|v| !v.is_finite()) { + continue; + } let area = Rect::new(bb[0].floor() as i32, bb[1].floor() as i32, (bb[2].ceil() as i32).saturating_add(1), (bb[3].ceil() as i32).saturating_add(1)); if area.is_empty() || area.width() > 4096 || area.height() > 4096 { continue; @@ -365,17 +424,16 @@ pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: let mut changed = false; for (i, px) in data.chunks_exact_mut(n).enumerate() { let (x, y) = (area.x0 as f64 + (i % w) as f64 + 0.5, area.y0 as f64 + (i / w) as f64 + 0.5); - let m = metric(&hd_inv, lud, lvd, [x, y]); - let d = (m[0] - mc[0]).hypot(m[1] - mc[1]) / r_m; - if d >= 1.0 { + let m = metric(&f.hd_inv, f.ld, [x, y]); + let d = (m[0] - mc[0]).hypot(m[1] - mc[1]) / f.r_m; + if d >= 1.0 || d.is_nan() { continue; } let hard = hardness.clamp(0.0, 0.99); let fall = if d <= hard { 1.0 } else { 1.0 - (d - hard) / (1.0 - hard) }; let k = (fall * fall * (3.0 - 2.0 * fall)) as f32 * opacity; // Source pixel at the same metric offset. - let sm = [m[0] + offset[0], m[1] + offset[1]]; - let (sx, sy) = hs.apply(sm[0] / lus, sm[1] / lvs); + let (sx, sy) = f.hs.apply((m[0] + f.offset[0]) / f.ls.0, (m[1] + f.offset[1]) / f.ls.1); let s = sample(&src_copy, sx - 0.5, sy - 0.5, n); for c in 0..n { px[c] += (s[c] - px[c]) * k; @@ -385,15 +443,22 @@ pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: if changed { surf.write_region(area, &data); dabs += 1; + changed_area = if changed_area.is_empty() { area } else { changed_area.union(&area) }; } } - dabs + (dabs, changed_area) } fn sample(s: &Surface, x: f64, y: f64, n: usize) -> Vec { + if !x.is_finite() || !y.is_finite() { + return vec![0.0; n]; + } let (x0, y0) = (x.floor() as i32, y.floor() as i32); let (tx, ty) = ((x - x0 as f64) as f32, (y - y0 as f64) as f32); - let r = s.read_region(Rect::new(x0, y0, x0 + 2, y0 + 2)); + let r = s.read_region(Rect::new(x0, y0, x0.saturating_add(2), y0.saturating_add(2))); + if r.len() < 4 * n { + return vec![0.0; n]; + } (0..n).map(|c| (r[c] * (1.0 - tx) + r[n + c] * tx) * (1.0 - ty) + (r[2 * n + c] * (1.0 - tx) + r[3 * n + c] * tx) * ty).collect() } @@ -486,5 +551,8 @@ mod tests { let n = clone_stroke(&sc, &mut s, [sx, sy], &[[dx, dy]], 10.0, 0.8, 1.0); assert_eq!(n, 1); assert!(s.rgba(dx as i32, dy as i32)[0] > 0.8, "{:?}", s.rgba(dx as i32, dy as i32)); + // The stroke's anchor copies from the source itself. + let back = clone_source(&sc, [sx, sy], [dx, dy], [dx, dy]).unwrap(); + assert!((back[0] - sx).abs() < 1e-6 && (back[1] - sy).abs() < 1e-6, "{back:?}"); } } diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/vp_cmds.rs index 185930298a..e1e342a10a 100644 --- a/crates/engine/src/vp_cmds.rs +++ b/crates/engine/src/vp_cmds.rs @@ -3,7 +3,7 @@ //! ([`photocraft_algo::vanishing`]). The edit lands on the active pixel layer, or on a new layer //! with `"newLayer": true` (Photoshop's advice for non-destructive Vanishing Point work). -use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_stroke, paste}; +use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_dabs, paste}; use photocraft_doc::{Document, Layer, LayerContent, LayerId}; use photocraft_geom::Rect; use photocraft_raster::Surface; @@ -13,6 +13,11 @@ use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; pub const VP: &str = "filter.vanishingPoint"; +/// Most planes a scene holds. +pub const MAX_PLANES: usize = 64; +/// Most clone strokes, and dabs over all of them, one run paints. +pub const MAX_CLONE_STROKES: usize = 4096; +pub const MAX_CLONE_DABS: usize = 200_000; fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: VP.into(), msg: msg.into() } @@ -29,6 +34,9 @@ pub fn scene(p: &Value, canvas: Rect) -> Result { .and_then(Value::as_array) .filter(|a| !a.is_empty()) .ok_or_else(|| bad("pass `planes`: [{\"corners\":[[x,y]×4]}, {\"from\":0,\"edge\":\"top\",\"angle\":90}]"))?; + if planes.len() > MAX_PLANES { + return Err(bad(format!("at most {MAX_PLANES} planes"))); + } let center = [(canvas.x0 + canvas.x1) as f64 / 2.0, (canvas.y0 + canvas.y1) as f64 / 2.0]; let corners = |v: &Value| -> Option<[[f64; 2]; 4]> { let a = v.get("corners")?.as_array()?; @@ -67,6 +75,12 @@ pub fn scene(p: &Value, canvas: Rect) -> Result { }; let angle = pl.get("angle").and_then(Value::as_f64).unwrap_or(90.0); let depth = pl.get("depth").and_then(Value::as_f64).unwrap_or(1.0); + if !angle.is_finite() || !(0.0..=360.0).contains(&angle) { + return Err(bad(format!("plane {i}: `angle` must be 0..360 degrees"))); + } + if !depth.is_finite() || depth <= 0.0 || depth > 1000.0 { + return Err(bad(format!("plane {i}: `depth` must be above 0 and at most 1000"))); + } sc.tear_off(from, edge, angle, depth).ok_or_else(|| bad(format!("plane {i} would lie behind the camera")))?; } if sc.planes.iter().any(|p| p.homography().is_none()) { @@ -75,6 +89,86 @@ pub fn scene(p: &Value, canvas: Rect) -> Result { Ok(sc) } +/// One stroke of `"clone"`. +#[derive(Clone, Debug, PartialEq)] +pub struct CloneSpec { + pub source: [f64; 2], + pub points: Vec<[f64; 2]>, + pub size: f64, + pub hardness: f64, + pub opacity: f64, +} + +/// Reads `"clone"`: finite points, at most [`MAX_CLONE_STROKES`] strokes and +/// [`MAX_CLONE_DABS`] dabs in all. +pub fn clone_specs(p: &Value) -> Result> { + let Some(v) = p.get("clone").filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + let strokes = v.as_array().ok_or_else(|| bad("`clone` is a list of strokes"))?; + if strokes.len() > MAX_CLONE_STROKES { + return Err(bad(format!("at most {MAX_CLONE_STROKES} clone strokes"))); + } + let finite = |q: [f64; 2]| q.iter().all(|v| v.is_finite() && v.abs() < 1e7); + let num = |c: &Value, k: &str, default: f64, lo: f64, hi: f64| -> Result { + match c.get(k) { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_f64().filter(|x| x.is_finite()).map(|x| x.clamp(lo, hi)).ok_or_else(|| bad(format!("clone `{k}` must be a number"))), + } + }; + let mut dabs = 0usize; + let mut out = Vec::with_capacity(strokes.len()); + for (k, c) in strokes.iter().enumerate() { + let source = c.get("source").and_then(pt).filter(|q| finite(*q)).ok_or_else(|| bad(format!("clone {k}: `source` [x,y]")))?; + let raw = c.get("points").and_then(Value::as_array).ok_or_else(|| bad(format!("clone {k}: `points` [[x,y], …]")))?; + dabs = dabs.saturating_add(raw.len()); + if dabs > MAX_CLONE_DABS { + return Err(bad(format!("at most {MAX_CLONE_DABS} clone points in all"))); + } + let points = + raw.iter().map(|q| pt(q).filter(|q| finite(*q))).collect::>>().ok_or_else(|| bad(format!("clone {k}: every point is [x,y]")))?; + out.push(CloneSpec { + source, + points, + size: num(c, "size", 40.0, 1.0, 2000.0)?, + hardness: num(c, "hardness", 50.0, 0.0, 100.0)? / 100.0, + opacity: num(c, "opacity", 100.0, 0.0, 100.0)? / 100.0, + }); + } + Ok(out) +} + +/// Paints clone stroke `c` on `surf`, or, with `work` (the image it samples), on `work` and copies +/// the pixels it changed to `surf`. Returns the dabs painted. +pub fn clone_into(sc: &Scene, surf: &mut Surface, work: Option<&mut Surface>, c: &CloneSpec) -> usize { + let Some(first) = c.points.first() else { return 0 }; + let Some(work) = work else { + return clone_dabs(sc, surf, c.source, *first, &c.points, c.size, c.hardness, c.opacity as f32).0; + }; + let before = work.clone(); + let (dabs, area) = clone_dabs(sc, work, c.source, *first, &c.points, c.size, c.hardness, c.opacity as f32); + copy_changed(surf, &before, work, area); + dabs +} + +/// Copies to `dst` the pixels of `area` where `after` differs from `before` (same format). +pub fn copy_changed(dst: &mut Surface, before: &Surface, after: &Surface, area: Rect) { + if area.is_empty() { + return; + } + let n = dst.format().channels(); + let (nw, ow, mut cur) = (after.read_region(area), before.read_region(area), dst.read_region(area)); + for ((c, a), b) in cur.chunks_exact_mut(n).zip(nw.chunks_exact(n)).zip(ow.chunks_exact(n)) { + if a != b { + c.copy_from_slice(a); + } + } + dst.write_region(area, &cur); +} + +/// The image a `"newLayer"` run's clone strokes sample: the visible document. +pub fn visible_image(doc: &Document) -> Surface { + crate::file_cmds::flattened(doc, doc.pixel_format()) +} + fn has_layer(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) { @@ -134,7 +228,7 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { let width = item.get("width").and_then(Value::as_f64).unwrap_or(0.5).clamp(0.01, 10.0); pastes.push((plane, surf, rect, at, width)); } - let clones: Vec = p.get("clone").and_then(Value::as_array).cloned().unwrap_or_default(); + let clones = clone_specs(p)?; let new_layer = p.get("newLayer").and_then(Value::as_bool).unwrap_or(false); let mut dabs = 0usize; let target = s.edit("Vanishing Point", |doc: &mut Document, active| { @@ -147,7 +241,7 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { active.ok_or_else(|| EngineError::Other("no active layer".into()))? }; // A new layer clones from the visible image; otherwise from the layer itself. - let base: Option = new_layer.then(|| crate::file_cmds::flattened(doc, doc.pixel_format())); + let base: Option = new_layer.then(|| visible_image(doc)); let locks = doc.effective_locks(id); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; if locks.all || locks.pixels { @@ -159,36 +253,14 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { over(surf, &out); } } - for (k, c) in clones.iter().enumerate() { - let source = c.get("source").and_then(pt).ok_or_else(|| bad(format!("clone {k}: `source` [x,y]")))?; - let points: Vec<[f64; 2]> = c.get("points").and_then(Value::as_array).map(|a| a.iter().filter_map(pt).collect()).unwrap_or_default(); - let size = c.get("size").and_then(Value::as_f64).unwrap_or(40.0).clamp(1.0, 2000.0); - let hardness = c.get("hardness").and_then(Value::as_f64).unwrap_or(50.0).clamp(0.0, 100.0) / 100.0; - let opacity = (c.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) / 100.0) as f32; - // Sample from the original pixels (merged with what's been pasted). - let mut work = match &base { - Some(b) => { - let mut w = b.clone(); - over(&mut w, surf); - w - } - None => surf.clone(), - }; - let before = work.clone(); - dabs += clone_stroke(&sc, &mut work, source, &points, size, hardness, opacity); - // Copy back only what the stroke changed. - let b = work.content_bounds().union(&before.content_bounds()); - if !b.is_empty() { - let (nw, ow) = (work.read_region(b), before.read_region(b)); - let n = surf.format().channels(); - let mut cur = surf.read_region(b); - for i in 0..cur.len() / n { - if nw[i * n..(i + 1) * n] != ow[i * n..(i + 1) * n] { - cur[i * n..(i + 1) * n].copy_from_slice(&nw[i * n..(i + 1) * n]); - } - } - surf.write_region(b, &cur); - } + // A new layer samples the visible image (merged with what's been pasted) and takes only + // the pixels the strokes change; otherwise the strokes paint the layer itself. + let mut work = base.map(|mut w| { + over(&mut w, surf); + w + }); + for c in &clones { + dabs += clone_into(&sc, surf, work.as_mut(), c); } surf.prune(); Ok(id) @@ -282,4 +354,35 @@ mod tests { } assert!(s.execute(VP, json!({"planes": [{"corners": square}]})).is_ok()); } + + #[test] + fn rejects_hostile_clone_and_tear_off_params() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200, "depth": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let floor = json!({"corners": [[60, 60], [140, 60], [190, 190], [10, 190]]}); + for torn in [json!({"from": 0, "angle": 1e9}), json!({"from": 0, "depth": -1}), json!({"from": 0, "depth": 1e300})] { + let e = s.execute(VP, json!({"planes": [floor, torn]})).unwrap_err().to_string(); + assert!(e.contains("plane 1"), "{e}"); + } + let many: Vec<[f64; 2]> = vec![[100.0, 150.0]; MAX_CLONE_DABS + 1]; + for clone in [ + json!([{"points": [[100, 150]]}]), + json!([{"source": [100, 180], "points": [[100, 150], "x"]}]), + json!([{"source": [100, 180], "points": [[100, 150]], "size": "big"}]), + json!([{"source": [100, 180], "points": many}]), + json!({"source": [100, 180]}), + ] { + let label: String = clone.to_string().chars().take(80).collect(); + assert!(s.execute(VP, json!({"planes": [floor], "clone": clone})).is_err(), "{label}"); + } + let planes: Vec = std::iter::repeat_n(floor.clone(), MAX_PLANES + 1).collect(); + assert!(s.execute(VP, json!({"planes": planes})).is_err()); + // A clone on a torn-off wall, at 32 bits, sampling the floor. + let r = s + .execute(VP, json!({"planes": [floor, {"from": 0, "edge": "top", "angle": 90, "depth": 0.5}], "clone": [{"source": [100, 150], "points": [[100, 50], [104, 50]], "size": 8}]})) + .unwrap(); + assert_eq!(r["planes"].as_array().unwrap().len(), 2); + assert!(r["dabs"].as_u64().unwrap() >= 1, "{r}"); + } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3cd4d294d8..0f389f4971 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1164,6 +1164,13 @@ pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), no { return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); } + // Between Vanishing Point stamp previews (and the document): the areas the strokes painted. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::vp_ui::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } // Between hovered blend modes (and the document): where the layer's blending shows. if seen.0 == now.0 && let Some(st) = app.session.documents().get(idx) diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rs index 0a0d7914b0..1acb42e909 100644 --- a/crates/ui-egui/src/distort_ui.rs +++ b/crates/ui-egui/src/distort_ui.rs @@ -86,7 +86,8 @@ pub(crate) fn surface_image(surf: &Surface, r: Rect, max_side: usize) -> ColorIm ColorImage::new([tw, th], px) } -/// The document shown on the canvas while Puppet or Perspective Warp previews a layer. +/// The document shown on the canvas while Puppet or Perspective Warp previews a layer, or +/// Vanishing Point's Stamp has painted. pub fn display_doc(app: &PhotocraftApp, idx: usize) -> Option<(Arc, u64)> { if app.session.active_index() != Some(idx) { return None; @@ -97,7 +98,8 @@ pub fn display_doc(app: &PhotocraftApp, idx: usize) -> Option<(Arc, u6 if let Some(p) = &app.distort.perspective { return Some((p.preview_doc.clone(), (1 << 42) + p.key)); } - None + // Vanishing Point: the clone strokes painted so far. + app.distort.vanishing.as_ref().and_then(crate::vp_ui::VpSession::shown) } /// Menu / control routing. `Some` when this module handles the invocation. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b39e9381a8..ebcb09e1b4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2449,3 +2449,6 @@ fontWeight Italic Kurzíva Vanishing Point is not active Úběžník není aktivní Apply Vanishing Point ({key}) Použít úběžník ({key}) Fix the red plane first: its corners must form a convex quad Nejprve opravte červenou rovinu: její rohy musí tvořit konvexní čtyřúhelník + Alt-click a plane to set the clone source Klepnutím s Alt na rovinu nastavte zdroj klonování + Too many clone strokes: apply Vanishing Point first Příliš mnoho tahů klonování: nejprve použijte Úběžník + Stamp Razítko diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index b5eee5bed2..41ae8d221e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2487,3 +2487,5 @@ fontWeight Italic Kursiv Vanishing Point is not active Fluchtpunkt ist nicht aktiv Apply Vanishing Point ({key}) Fluchtpunkt anwenden ({key}) Fix the red plane first: its corners must form a convex quad Korrigieren Sie zuerst die rote Ebene: Ihre Ecken müssen ein konvexes Viereck bilden + Alt-click a plane to set the clone source Alt-Klick auf eine Ebene legt die Kopierquelle fest + Too many clone strokes: apply Vanishing Point first Zu viele Kopierstriche: Wenden Sie zuerst Fluchtpunkt an diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f01045950d..b156cd0717 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3553,3 +3553,5 @@ fontWeight Thin Πολύ λεπτά Vanishing Point is not active Το Σημείο φυγής δεν είναι ενεργό Apply Vanishing Point ({key}) Εφαρμογή σημείου φυγής ({key}) Fix the red plane first: its corners must form a convex quad Διορθώστε πρώτα το κόκκινο επίπεδο: οι γωνίες του πρέπει να σχηματίζουν κυρτό τετράπλευρο + Alt-click a plane to set the clone source Alt-κλικ σε ένα επίπεδο για να ορίσετε την πηγή κλωνοποίησης + Too many clone strokes: apply Vanishing Point first Πάρα πολλές πινελιές κλωνοποίησης: εφαρμόστε πρώτα το Σημείο φυγής diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5517d8dadf..79f84360c1 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2528,3 +2528,5 @@ fontWeight Italic Cursiva Vanishing Point is not active Punto de fuga no está activo Apply Vanishing Point ({key}) Aplicar punto de fuga ({key}) Fix the red plane first: its corners must form a convex quad Corrija primero el plano rojo: sus esquinas deben formar un cuadrilátero convexo + Alt-click a plane to set the clone source Haga Alt-clic en un plano para definir el origen de clonación + Too many clone strokes: apply Vanishing Point first Demasiados trazos de clonación: aplique primero Punto de fuga diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8d3121dd79..e319253071 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2864,3 +2864,5 @@ fontWeight Italic Italique Vanishing Point is not active Point de fuite n’est pas actif Apply Vanishing Point ({key}) Appliquer le point de fuite ({key}) Fix the red plane first: its corners must form a convex quad Corrigez d’abord le plan rouge : ses coins doivent former un quadrilatère convexe + Alt-click a plane to set the clone source Alt-clic sur un plan pour définir la source de duplication + Too many clone strokes: apply Vanishing Point first Trop de traits de duplication : appliquez d’abord Point de fuite diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 910342b185..66e496645b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2851,3 +2851,5 @@ fontWeight Italic Miring Vanishing Point is not active Vanishing Point tidak aktif Apply Vanishing Point ({key}) Terapkan Vanishing Point ({key}) Fix the red plane first: its corners must form a convex quad Perbaiki bidang merah dulu: sudut-sudutnya harus membentuk segi empat cembung + Alt-click a plane to set the clone source Alt-klik sebuah bidang untuk menetapkan sumber kloning + Too many clone strokes: apply Vanishing Point first Terlalu banyak goresan kloning: terapkan Vanishing Point terlebih dahulu diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 81c3145854..5857ef220b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2518,3 +2518,5 @@ fontWeight Italic Corsivo Vanishing Point is not active Punto di fuga non è attivo Apply Vanishing Point ({key}) Applica punto di fuga ({key}) Fix the red plane first: its corners must form a convex quad Correggi prima il piano rosso: i suoi angoli devono formare un quadrilatero convesso + Alt-click a plane to set the clone source Alt-clic su un piano per impostare l’origine della clonazione + Too many clone strokes: apply Vanishing Point first Troppi tratti di clonazione: applica prima Punto di fuga diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 08f56447ed..383e83dfed 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3464,3 +3464,5 @@ fontWeight Italic 斜体 Vanishing Point is not active 消点はアクティブではありません Apply Vanishing Point ({key}) 消点を適用({key}) Fix the red plane first: its corners must form a convex quad 先に赤い面を修正してください:角が凸四角形になる必要があります + Alt-click a plane to set the clone source Alt キーを押しながら平面をクリックしてコピー元を設定 + Too many clone strokes: apply Vanishing Point first コピースタンプのストロークが多すぎます:先に消点を適用してください diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 81b10fb7ce..4e37562ff0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3026,3 +3026,5 @@ fontWeight Italic 기울임 Vanishing Point is not active 소실점이 활성화되어 있지 않습니다 Apply Vanishing Point ({key}) 소실점 적용 ({key}) Fix the red plane first: its corners must form a convex quad 먼저 빨간색 평면을 수정하십시오: 모서리가 볼록 사각형을 이루어야 합니다 + Alt-click a plane to set the clone source Alt 키를 누른 채 평면을 클릭하여 복제 소스를 설정하십시오 + Too many clone strokes: apply Vanishing Point first 복제 획이 너무 많습니다. 먼저 소실점을 적용하십시오 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 456b8c3f44..106f3f347a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3623,3 +3623,5 @@ cameraRaw Whites Witten Vanishing Point is not active Verdwijnpunt is niet actief Apply Vanishing Point ({key}) Verdwijnpunt toepassen ({key}) Fix the red plane first: its corners must form a convex quad Herstel eerst het rode vlak: de hoeken moeten een convexe vierhoek vormen + Alt-click a plane to set the clone source Alt-klik op een vlak om de kloonbron in te stellen + Too many clone strokes: apply Vanishing Point first Te veel kloonstreken: pas eerst Verdwijnpunt toe diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8acdcd1c62..aaeed61b53 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3464,3 +3464,5 @@ cameraRaw Roughness Chropowatość Vanishing Point is not active Punkt zbieżności nie jest aktywny Apply Vanishing Point ({key}) Zastosuj punkt zbieżności ({key}) Fix the red plane first: its corners must form a convex quad Najpierw popraw czerwoną płaszczyznę: jej narożniki muszą tworzyć czworokąt wypukły + Alt-click a plane to set the clone source Kliknij płaszczyznę z Alt, aby ustawić źródło klonowania + Too many clone strokes: apply Vanishing Point first Zbyt wiele pociągnięć klonowania: najpierw zastosuj Punkt zbieżności diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 1b58102b86..b724f5d70c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2872,3 +2872,5 @@ fontWeight Italic Itálico Vanishing Point is not active Ponto de fuga não está ativo Apply Vanishing Point ({key}) Aplicar ponto de fuga ({key}) Fix the red plane first: its corners must form a convex quad Corrija primeiro o plano vermelho: seus cantos devem formar um quadrilátero convexo + Alt-click a plane to set the clone source Clique com Alt em um plano para definir a origem da clonagem + Too many clone strokes: apply Vanishing Point first Traços de clonagem demais: aplique Ponto de fuga primeiro diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 22eda77f08..6264aa9c00 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2731,3 +2731,5 @@ fontWeight Italic Курсив Vanishing Point is not active Точка схода не активна Apply Vanishing Point ({key}) Применить точку схода ({key}) Fix the red plane first: its corners must form a convex quad Сначала исправьте красную плоскость: ее углы должны образовывать выпуклый четырехугольник + Alt-click a plane to set the clone source Щёлкните плоскость с Alt, чтобы задать источник клонирования + Too many clone strokes: apply Vanishing Point first Слишком много мазков клонирования: сначала примените «Точку схода» diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3fd50ffaf1..cc39bf218b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3551,3 +3551,5 @@ cameraRaw Masking Маскування Vanishing Point is not active Точка сходження не активна Apply Vanishing Point ({key}) Застосувати точку сходження ({key}) Fix the red plane first: its corners must form a convex quad Спершу виправте червону площину: її кути мають утворювати опуклий чотирикутник + Alt-click a plane to set the clone source Клацніть площину з Alt, щоб задати джерело клонування + Too many clone strokes: apply Vanishing Point first Забагато мазків клонування: спочатку застосуйте «Точку сходження» diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 644eb96e9c..422ef6a1a0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2456,3 +2456,6 @@ fontWeight Italic 斜体 Vanishing Point is not active 消失点未处于活动状态 Apply Vanishing Point ({key}) 应用消失点({key}) Fix the red plane first: its corners must form a convex quad 请先修正红色平面:其四个角必须构成凸四边形 + Alt-click a plane to set the clone source 按住 Alt 键单击平面以设置仿制源 + Too many clone strokes: apply Vanishing Point first 仿制描边过多:请先应用消失点 + Stamp 图章 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2150018ee0..09887f0bd5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2426,3 +2426,6 @@ fontWeight Italic 斜體 Vanishing Point is not active 消失點未啟用 Apply Vanishing Point ({key}) 套用消失點 ({key}) Fix the red plane first: its corners must form a convex quad 請先修正紅色平面:其四個角必須構成凸四邊形 + Alt-click a plane to set the clone source 按住 Alt 鍵按一下平面以設定仿製來源 + Too many clone strokes: apply Vanishing Point first 仿製筆畫過多:請先套用消失點 + Stamp 印章 diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rs index bdaad601c6..4e32edc72b 100644 --- a/crates/ui-egui/src/vp_ui.rs +++ b/crates/ui-egui/src/vp_ui.rs @@ -2,19 +2,27 @@ //! //! **Create Plane** (C): four clicks set a plane's corners, in any order. **Edit Plane** (V): //! drag a corner node, or an edge node to slide that edge along the plane's own perspective; -//! click a plane to select it, Delete removes it. The plane's grid is drawn at the Grid Size and, +//! click a plane to select it, Delete removes it. Ctrl/Cmd-dragging an edge node tears off a +//! perpendicular plane; dragging the torn plane's far edge node sets its depth and Alt-dragging +//! it its angle (it stays a torn-off plane, so it follows its parent). The plane's grid is drawn +//! at the Grid Size and, //! like Photoshop's, in the accent colour when the plane is valid, yellow when its perspective is //! doubtful and red when it is invalid ([`VpPlane::check`]). With an image on the clipboard the -//! selected plane shows it pasted in perspective; drag it to move it on the plane. ↩ / OK runs -//! `filter.vanishingPoint` with the planes and the paste, so it is one history step and an -//! action or agent can replay it exactly. +//! selected plane shows it pasted in perspective; drag it to move it on the plane. **Stamp** (S): +//! Alt-click a plane to set the source, then paint to clone in perspective (Diameter, Hardness, +//! Opacity, Aligned); the canvas shows the strokes as they are painted. ↩ / OK runs +//! `filter.vanishingPoint` with the planes, the paste and the strokes, so the whole session is +//! one history step and an action or agent can replay it exactly. + +use std::sync::Arc; use egui::{Color32, Pos2, Stroke, TextureHandle, pos2}; use photocraft_algo::transform::Homography; -use photocraft_algo::vanishing::{PlaneCheck, Scene, VpPlane}; -use photocraft_doc::{LayerContent, LayerId}; -use photocraft_engine::vp_cmds::VP; +use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_dabs, clone_source}; +use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId}; +use photocraft_engine::vp_cmds::{CloneSpec, MAX_CLONE_DABS, MAX_CLONE_STROKES, VP, copy_changed, visible_image}; use photocraft_geom::Rect; +use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::PhotocraftApp; @@ -25,6 +33,45 @@ use crate::canvas::{ToolEvent, ViewXform}; pub enum VpTool { EditPlane, CreatePlane, + Stamp, +} + +/// A plane torn off an edge of an earlier plane: the engine's +/// `{"from", "edge", "angle", "depth"}`, so it follows its parent when that is edited. +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)] +pub struct Torn { + pub from: usize, + pub edge: Edge, + /// Degrees between the planes (90 = perpendicular). + pub angle: f64, + /// Extent as a multiple of the parent's adjacent side. + pub depth: f64, +} + +/// The Stamp tool's options. +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StampOptions { + /// Brush diameter in px where a stroke starts. + pub diameter: f64, + /// 0..=100. + pub hardness: f64, + /// 0..=100. + pub opacity: f64, + /// Later strokes keep the first stroke's source offset instead of restarting at the source. + pub aligned: bool, +} + +/// Edge node `i` (0 top, 1 right, 2 bottom, 3 left) as the engine's edge. +const EDGES: [Edge; 4] = [Edge::Top, Edge::Right, Edge::Bottom, Edge::Left]; + +fn edge_index(e: Edge) -> usize { + match e { + Edge::Top => 0, + Edge::Right => 1, + Edge::Bottom => 2, + Edge::Left => 3, + } } enum Drag { @@ -35,6 +82,28 @@ enum Drag { Edge { plane: usize, edge: usize, h: Homography, inv: Homography }, /// The pasted image, and the pointer offset from its top-left in plane coordinates. Paste { offset: [f64; 2] }, + /// The far edge node of torn-off plane `plane` (or of one being torn off): the drag sets + /// its depth, or with `rotate` (Alt) its angle, once it has left `start`. + Torn { plane: usize, rotate: bool, start: [f64; 2], moved: bool }, + /// Painting the last of the clone strokes. + Stamp, +} + +/// The clone strokes painted onto the target layer, shown on the canvas while stamping. +struct StampPreview { + /// The session's `rev` and New Layer it was painted with (either changing repaints it). + rev: u64, + new_layer: bool, + /// On a new layer: the visible image the strokes sample, with the strokes so far. + work: Option, + /// The target layer's pixels as painted so far. + out: Surface, + /// Strokes painted: those before `.0`, and the first `.1` points of stroke `.0`. + done: (usize, usize), + /// Preview keys shown, each with the area changed since the previous one (the first since + /// the document). + keys: Vec<(u64, Rect)>, + shown: Arc, } /// The clipboard image shown pasted onto the plane. @@ -47,7 +116,10 @@ struct Clip { pub struct VpSession { pub layer: LayerId, canvas: Rect, + /// The planes' corners; torn-off planes' are derived from their parents ([`Self::resolve`]). pub planes: Vec, + /// Per plane: how it was torn off, or `None` for a drawn plane (always the first one). + pub torn: Vec>, pub tool: VpTool, /// Corners clicked so far with Create Plane. pending: Vec<[f64; 2]>, @@ -63,21 +135,61 @@ pub struct VpSession { pub new_layer: bool, clip: Option, drag: Option, + pub stamp: StampOptions, + /// Stamp source (Alt-click), image px. + pub source: Option<[f64; 2]>, + /// Clone strokes painted so far, sent as `"clone"` on OK. + pub strokes: Vec, + /// The first stroke's (source, start) since the source was set: Aligned strokes keep its offset. + aligned_ref: Option<([f64; 2], [f64; 2])>, + /// Bumped whenever the planes or the strokes change other than by painting on. + rev: u64, + /// The document as the session began (the preview paints over it). + base: Arc, + doc_revision: u64, + preview: Option, } /// Most planes a session holds (the control channel can't make it allocate without bound). const MAX_PLANES: usize = 64; /// Most grid lines drawn per direction. const MAX_LINES: usize = 200; +/// Preview keys of the stamp preview: `PREVIEW_KEY + id` (see `canvas::display_doc`). +const PREVIEW_KEY: u64 = 1 << 42; + +fn union(a: Rect, b: Rect) -> Rect { + if a.is_empty() { + b + } else if b.is_empty() { + a + } else { + a.union(&b) + } +} impl VpSession { pub fn describe(&self) -> Value { let center = self.center(); - let planes: Vec = self.planes.iter().map(|p| json!({"corners": p.corners, "check": p.check(center)})).collect(); + let planes: Vec = self + .planes + .iter() + .enumerate() + .map(|(i, p)| { + let mut v = json!({"corners": p.corners, "check": p.check(center)}); + if let Some(t) = self.torn.get(i).copied().flatten() { + v["tornOff"] = json!(t); + } + v + }) + .collect(); json!({ "layer": self.layer.0, "tool": self.tool, "planes": planes, + "stamp": self.stamp, + "source": self.source, + "strokes": self.strokes.len(), + "dabs": self.dabs(), "pending": self.pending, "selected": self.selected, "gridSize": self.grid_size, @@ -125,19 +237,70 @@ impl VpSession { Some([self.paste_width, self.paste_width * lu / lv * c.height / c.width.max(1.0)]) } - /// The command's params: the planes, and the paste when there is one. + /// The command's params: the planes (torn-off ones as such), the paste and the clone + /// strokes when there are any. pub fn params(&self) -> Value { - let planes: Vec = self.planes.iter().map(|p| json!({"corners": p.corners})).collect(); + let planes: Vec = self + .planes + .iter() + .enumerate() + .map(|(i, p)| match self.torn.get(i).copied().flatten() { + Some(t) => json!({"from": t.from, "edge": t.edge, "angle": t.angle, "depth": t.depth}), + None => json!({"corners": p.corners}), + }) + .collect(); let mut p = json!({"planes": planes}); if let Some(i) = self.paste_plane() { p["paste"] = json!([{"plane": i, "at": self.paste_at, "width": self.paste_width}]); } + if !self.strokes.is_empty() { + let clone: Vec = self + .strokes + .iter() + .map(|c| json!({"source": c.source, "points": c.points, "size": c.size, "hardness": c.hardness * 100.0, "opacity": c.opacity * 100.0})) + .collect(); + p["clone"] = json!(clone); + } if self.new_layer { p["newLayer"] = json!(true); } p } + fn dabs(&self) -> usize { + self.strokes.iter().map(|c| c.points.len()).sum() + } + + /// Recomputes the torn-off planes' corners from their parents, in order (the way the engine + /// builds the scene), so they follow every edit. A plane that can't be torn off any more + /// (it would lie behind the camera) collapses to an invalid one. + fn resolve(&mut self) { + self.rev += 1; + self.torn.resize(self.planes.len(), None); + let Some(first) = self.planes.first().cloned() else { return }; + let fallback = f64::from(self.canvas.width().max(self.canvas.height())); + let mut sc = Scene::new(first, self.center(), None, fallback); + for i in 1..self.planes.len() { + match self.torn.get(i).copied().flatten().filter(|t| t.from < i) { + Some(t) => { + if sc.tear_off(t.from, t.edge, t.angle, t.depth).is_none() { + sc.planes.push(VpPlane { corners: [[0.0; 2]; 4] }); + } + } + None => sc.planes.push(self.planes[i].clone()), + } + } + self.planes = sc.planes; + } + + fn push_plane(&mut self, plane: VpPlane, torn: Option) { + self.torn.resize(self.planes.len(), None); + self.planes.push(plane); + self.torn.push(torn); + self.selected = Some(self.planes.len() - 1); + self.resolve(); + } + fn add_corner(&mut self, p: [f64; 2]) { if self.planes.len() >= MAX_PLANES { return; @@ -145,20 +308,194 @@ impl VpSession { self.pending.push(p); if let Ok(corners) = <[[f64; 2]; 4]>::try_from(self.pending.as_slice()) { self.pending.clear(); - self.planes.push(VpPlane { corners }.normalized()); - self.selected = Some(self.planes.len() - 1); + self.push_plane(VpPlane { corners }.normalized(), None); // Photoshop hands over to Edit Plane once a plane is closed. self.tool = VpTool::EditPlane; } } + /// Deletes the selected plane; planes torn off it keep their place as drawn planes. fn delete_selected(&mut self) { if let Some(i) = self.selected.take().filter(|i| *i < self.planes.len()) { + self.torn.resize(self.planes.len(), None); self.planes.remove(i); + self.torn.remove(i); + for t in self.torn.iter_mut() { + match t { + Some(c) if c.from == i => *t = None, + Some(c) if c.from > i => c.from -= 1, + _ => {} + } + } self.drag = None; + self.resolve(); } } + /// Starts tearing a plane off edge `edge` of plane `from` at the press `p`. + fn tear_off(&mut self, from: usize, edge: usize, p: [f64; 2]) { + if self.planes.len() >= MAX_PLANES { + return; + } + let Some(&e) = EDGES.get(edge) else { return }; + self.push_plane(VpPlane { corners: [[0.0; 2]; 4] }, Some(Torn { from, edge: e, angle: 90.0, depth: 0.5 })); + // As after closing a plane, Edit Plane takes over. + self.tool = VpTool::EditPlane; + self.pending.clear(); + self.drag = Some(Drag::Torn { plane: self.planes.len() - 1, rotate: false, start: p, moved: false }); + } + + /// Fits torn plane `i`'s depth (or with `rotate` its angle) so its far edge's middle is as + /// near `p` as it can get. + fn fit_torn(&mut self, i: usize, rotate: bool, p: [f64; 2]) { + let Some(t) = self.torn.get(i).copied().flatten() else { return }; + let Some(first) = self.planes.first().cloned() else { return }; + if t.from >= i || i >= self.planes.len() { + return; + } + let fallback = f64::from(self.canvas.width().max(self.canvas.height())); + let mut sc = Scene::new(first, self.center(), None, fallback); + sc.planes.extend(self.planes.iter().take(i).skip(1).cloned()); + let e = edge_index(t.edge); + let mut miss = |angle: f64, depth: f64| -> f64 { + if sc.tear_off(t.from, t.edge, angle, depth).is_none() { + return f64::MAX; + } + let Some(c) = sc.planes.pop().map(|pl| pl.corners) else { return f64::MAX }; + let (a, b) = (c[e], c[(e + 1) % 4]); + let d = ((a[0] + b[0]) / 2.0 - p[0]).hypot((a[1] + b[1]) / 2.0 - p[1]); + if d.is_finite() { d } else { f64::MAX } + }; + let best = |values: &mut dyn Iterator, miss: &mut dyn FnMut(f64) -> f64| { + values.map(|v| (miss(v), v)).filter(|m| m.0 < f64::MAX).min_by(|a, b| a.0.total_cmp(&b.0)).map(|m| m.1) + }; + let (angle, depth) = if rotate { + let Some(a) = best(&mut (1..180).map(f64::from), &mut |a| miss(a, t.depth)) else { return }; + let a = best(&mut (-10..=10).map(|k| a + f64::from(k) / 10.0), &mut |a| miss(a, t.depth)).unwrap_or(a); + (a.clamp(1.0, 179.0), t.depth) + } else { + let Some(d) = best(&mut (0..=160).map(|k| 0.02 * 1.06f64.powi(k)), &mut |d| miss(t.angle, d)) else { return }; + let d = best(&mut (-10..=10).map(|k| d * (1.0 + f64::from(k) * 0.006)), &mut |d| miss(t.angle, d)).unwrap_or(d); + (t.angle, d.clamp(0.02, 1000.0)) + }; + if let Some(Some(t)) = self.torn.get_mut(i) { + t.angle = angle; + t.depth = depth; + } + self.resolve(); + } + + /// Stamp press: Alt sets the source, otherwise a stroke starts. Returns a status message. + fn stamp_press(&mut self, p: [f64; 2], alt: bool) -> Option<&'static str> { + let sc = self.scene()?; + let on_plane = |q: [f64; 2]| sc.plane_at(q).is_some(); + if alt { + if !on_plane(p) { + return Some(tl!("Alt-click a plane to set the clone source")); + } + self.source = Some(p); + self.aligned_ref = None; + return None; + } + let Some(source) = self.source else { return Some(tl!("Alt-click a plane to set the clone source")) }; + if !on_plane(p) { + return None; + } + if self.strokes.len() >= MAX_CLONE_STROKES || self.dabs() >= MAX_CLONE_DABS { + return Some(tl!("Too many clone strokes: apply Vanishing Point first")); + } + let src = match self.aligned_ref.filter(|_| self.stamp.aligned) { + Some((s0, a0)) => clone_source(&sc, s0, a0, p).filter(|s| on_plane(*s)).unwrap_or(source), + None => source, + }; + if self.aligned_ref.is_none() { + self.aligned_ref = Some((src, p)); + } + let o = self.stamp; + self.strokes.push(CloneSpec { source: src, points: vec![p], size: o.diameter, hardness: o.hardness / 100.0, opacity: o.opacity / 100.0 }); + self.drag = Some(Drag::Stamp); + None + } + + /// Extends the current stroke to `p` with dabs a tenth of the brush apart. + fn stamp_to(&mut self, p: [f64; 2]) { + let room = MAX_CLONE_DABS.saturating_sub(self.dabs()); + let Some(c) = self.strokes.last_mut() else { return }; + let Some(last) = c.points.last().copied() else { return }; + let step = (c.size * 0.1).max(1.0); + let d = (p[0] - last[0]).hypot(p[1] - last[1]); + if !d.is_finite() || d < step { + return; + } + let n = ((d / step) as usize).min(room); + c.points.extend((1..=n).map(|k| { + let t = k as f64 * step / d; + [last[0] + (p[0] - last[0]) * t, last[1] + (p[1] - last[1]) * t] + })); + } + + /// Paints what the preview doesn't show yet (all of it after the planes changed). `key` + /// names a new preview. False when nothing changed. + fn paint_preview(&mut self, key: impl FnOnce() -> u64) -> bool { + if self.strokes.is_empty() { + let had = self.preview.is_some(); + self.preview = None; + return had; + } + let Some(sc) = self.scene() else { return false }; + let stale = self.preview.as_ref().is_none_or(|p| p.rev != self.rev || p.new_layer != self.new_layer); + let mut area = Rect::EMPTY; + if stale { + let Some(layer) = self.base.layer(self.layer).and_then(Layer::surface) else { return false }; + let (out, work) = if self.new_layer { (Surface::new(layer.format()), Some(visible_image(&self.base))) } else { (layer.clone(), None) }; + // The old preview's area changes back too. + let keys = self.preview.take().map(|p| p.keys).unwrap_or_default(); + area = keys.iter().fold(Rect::EMPTY, |a, k| union(a, k.1)); + self.preview = Some(StampPreview { rev: self.rev, new_layer: self.new_layer, work, out, done: (0, 0), keys, shown: self.base.clone() }); + } + let Some(pv) = self.preview.as_mut() else { return false }; + let (from_stroke, from_point) = pv.done; + for (si, c) in self.strokes.iter().enumerate().skip(from_stroke) { + let skip = if si == from_stroke { from_point } else { 0 }; + let (Some(anchor), Some(points)) = (c.points.first(), c.points.get(skip..)) else { continue }; + if points.is_empty() { + continue; + } + let (hard, opacity) = (c.hardness, c.opacity as f32); + let changed = match pv.work.as_mut() { + Some(work) => { + let before = work.clone(); + let (_, a) = clone_dabs(&sc, work, c.source, *anchor, points, c.size, hard, opacity); + copy_changed(&mut pv.out, &before, work, a); + a + } + None => clone_dabs(&sc, &mut pv.out, c.source, *anchor, points, c.size, hard, opacity).1, + }; + area = union(area, changed); + } + pv.done = (self.strokes.len() - 1, self.strokes.last().map_or(0, |c| c.points.len())); + if area.is_empty() && !stale { + return false; + } + let mut d = (*self.base).clone(); + if self.new_layer { + let mut l = Layer::raster(d.next_layer_name("Vanishing Point"), d.pixel_format()); + l.content = LayerContent::Raster(pv.out.clone()); + d.insert_above(Some(self.layer), l); + } else if let Some(LayerContent::Raster(s)) = d.layer_mut(self.layer).map(|l| &mut l.content) { + *s = pv.out.clone(); + } + pv.shown = Arc::new(d); + pv.keys.push((key(), area)); + true + } + + /// The document with the strokes painted, and its preview key. + pub(crate) fn shown(&self) -> Option<(Arc, u64)> { + let p = self.preview.as_ref()?; + Some((p.shown.clone(), PREVIEW_KEY + p.keys.last()?.0)) + } + /// Image positions of the edge nodes of plane `i`. fn edge_nodes(&self, i: usize) -> Option<[[f64; 2]; 4]> { let h = self.planes.get(i)?.homography()?; @@ -169,20 +506,40 @@ impl VpSession { Some([at(0.5, 0.0), at(1.0, 0.5), at(0.5, 1.0), at(0.0, 0.5)]) } - fn press(&mut self, p: [f64; 2], tol: f64) { - if self.tool == VpTool::CreatePlane { - self.add_corner(p); - return; + fn press(&mut self, p: [f64; 2], tol: f64, mods: egui::Modifiers) -> Option<&'static str> { + if self.tool == VpTool::Stamp { + return self.stamp_press(p, mods.alt); } let near = |c: [f64; 2]| (c[0] - p[0]).hypot(c[1] - p[1]) <= tol; // The selected plane's nodes win over the others'. let order: Vec = self.selected.into_iter().chain((0..self.planes.len()).rev()).filter(|i| *i < self.planes.len()).collect(); + // Ctrl/Cmd on an edge node tears off a perpendicular plane (with either plane tool). + if mods.command + && let Some((i, e)) = order.iter().find_map(|&i| Some((i, self.edge_nodes(i)?.iter().position(|c| near(*c))?))) + { + self.tear_off(i, e, p); + return None; + } + if self.tool == VpTool::CreatePlane { + self.add_corner(p); + return None; + } for &i in &order { + // A torn-off plane follows its parent: only its far edge node drags (depth, or + // with Alt the angle). + if let Some(t) = self.torn.get(i).copied().flatten() { + if self.edge_nodes(i).and_then(|n| n.get(edge_index(t.edge)).copied()).is_some_and(near) { + self.selected = Some(i); + self.drag = Some(Drag::Torn { plane: i, rotate: mods.alt, start: p, moved: false }); + return None; + } + continue; + } if let Some(ci) = self.planes[i].corners.iter().position(|c| near(*c)) { let c = self.planes[i].corners[ci]; self.selected = Some(i); self.drag = Some(Drag::Corner { plane: i, corner: ci, offset: [c[0] - p[0], c[1] - p[1]] }); - return; + return None; } if let Some(e) = self.edge_nodes(i).and_then(|n| n.iter().position(|c| near(*c))) && let Some(h) = self.planes[i].homography() @@ -190,7 +547,7 @@ impl VpSession { { self.selected = Some(i); self.drag = Some(Drag::Edge { plane: i, edge: e, h, inv }); - return; + return None; } } if let Some(i) = self.paste_plane() @@ -202,19 +559,30 @@ impl VpSession { let (a, b) = (self.paste_at, [self.paste_at[0] + ext[0], self.paste_at[1] + ext[1]]); if (a[0]..=b[0]).contains(&u) && (a[1]..=b[1]).contains(&v) { self.drag = Some(Drag::Paste { offset: [a[0] - u, a[1] - v] }); - return; + return None; } } self.selected = self.scene().and_then(|sc| sc.plane_at(p)); + None } fn drag_to(&mut self, p: [f64; 2]) { - match &self.drag { + match &mut self.drag { Some(Drag::Corner { plane, corner, offset }) => { if let Some(c) = self.planes.get_mut(*plane).and_then(|pl| pl.corners.get_mut(*corner)) { *c = [p[0] + offset[0], p[1] + offset[1]]; } + self.resolve(); } + Some(Drag::Torn { plane, rotate, start, moved }) => { + // A click without a drag leaves the plane as it is. + *moved |= (p[0] - start[0]).hypot(p[1] - start[1]) > 2.0; + if *moved { + let (i, r) = (*plane, *rotate); + self.fit_torn(i, r, p); + } + } + Some(Drag::Stamp) => self.stamp_to(p), Some(Drag::Edge { plane, edge, h, inv }) => { let (u, v) = inv.apply(p[0], p[1]); // The plane's (u, v) rectangle after the move. @@ -229,6 +597,7 @@ impl VpSession { { pl.corners = q; } + self.resolve(); } Some(Drag::Paste { offset }) => { let offset = *offset; @@ -277,6 +646,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> None => return Err("no active layer".into()), } let canvas = st.doc.bounds(); + let (base, doc_revision) = (st.doc.clone(), st.revision); let key = app.ui.alloc_id(); let clip = app.session.clipboard.as_ref().and_then(|c| { let r = c.surface.content_bounds(); @@ -290,6 +660,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> layer, canvas, planes: Vec::new(), + torn: Vec::new(), tool: VpTool::CreatePlane, pending: Vec::new(), selected: None, @@ -300,13 +671,21 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> new_layer: false, clip, drag: None, + stamp: StampOptions { diameter: 40.0, hardness: 50.0, opacity: 100.0, aligned: true }, + source: None, + strokes: Vec::new(), + aligned_ref: None, + rev: 0, + base, + doc_revision, + preview: None, }); app.ui.status = tl!("Vanishing Point: click four corners to create a plane").into(); Ok(()) } -/// OK: runs `filter.vanishingPoint` with the planes (and the paste). An invalid plane keeps the -/// mode open; with nothing to paste the mode just closes. +/// OK: runs `filter.vanishingPoint` with the planes (and the paste and the clone strokes). An +/// invalid plane keeps the mode open; with nothing to paste or clone the mode just closes. pub fn commit(app: &mut PhotocraftApp) -> Result { let Some(s) = app.distort.vanishing.as_ref() else { return Ok(Value::Null) }; let center = s.center(); @@ -317,7 +696,7 @@ pub fn commit(app: &mut PhotocraftApp) -> Result { } let params = s.params(); app.distort.vanishing = None; - if params.get("paste").is_none() { + if params.get("paste").is_none() && params.get("clone").is_none() { return Ok(json!({"committed": false})); } app.run(VP, params).map(|r| json!({"committed": true, "result": r})) @@ -337,19 +716,39 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { s.tool = match t { "edit" | "editPlane" => VpTool::EditPlane, "create" | "createPlane" => VpTool::CreatePlane, - other => return Err(format!("tool: edit|create, not `{other}`")), + "stamp" => VpTool::Stamp, + other => return Err(format!("tool: edit|create|stamp, not `{other}`")), }; s.pending.clear(); } if let Some(p) = ui.get("planes") { - let planes: Vec = serde_json::from_value(p.clone()).map_err(|e| format!("bad planes: {e}"))?; - if planes.len() > MAX_PLANES { - return Err(format!("at most {MAX_PLANES} planes")); - } + let (planes, torn) = parse_planes(p)?; s.planes = planes; + s.torn = torn; // A drag holds indices into the old list. s.drag = None; s.selected = (!s.planes.is_empty()).then(|| s.planes.len() - 1); + s.resolve(); + } + if let Some(o) = ui.get("stamp") { + let num = |k: &str, lo: f64, hi: f64| o.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).map(|v| v.clamp(lo, hi)); + let st = &mut s.stamp; + st.diameter = num("diameter", 1.0, 2000.0).unwrap_or(st.diameter); + st.hardness = num("hardness", 0.0, 100.0).unwrap_or(st.hardness); + st.opacity = num("opacity", 0.0, 100.0).unwrap_or(st.opacity); + st.aligned = o.get("aligned").and_then(Value::as_bool).unwrap_or(st.aligned); + } + if let Some(src) = ui.get("source") { + s.source = match src { + Value::Null => None, + v => Some(pt(v).ok_or("source: [x, y]")?), + }; + s.aligned_ref = None; + } + if let Some(c) = ui.get("clone") { + s.strokes = photocraft_engine::vp_cmds::clone_specs(&json!({"clone": c})).map_err(|e| e.to_string())?; + s.drag = None; + s.rev += 1; } if let Some(i) = ui.get("select").and_then(Value::as_u64) { s.selected = usize::try_from(i).ok().filter(|i| *i < s.planes.len()); @@ -369,20 +768,96 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { if let Some(b) = ui.get("newLayer").and_then(Value::as_bool) { s.new_layer = b; } - Ok(s.describe()) + sync_preview(app); + Ok(app.distort.vanishing.as_ref().map(VpSession::describe).unwrap_or(Value::Null)) } -pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) { +fn pt(v: &Value) -> Option<[f64; 2]> { + let p = [v.get(0)?.as_f64()?, v.get(1)?.as_f64()?]; + p.iter().all(|x| x.is_finite() && x.abs() < 1e7).then_some(p) +} + +/// The control channel's planes, in the command's form: `{"corners": [[x, y]×4]}` or +/// `{"from": earlier plane, "edge", "angle": 90, "depth": 1}`. +fn parse_planes(v: &Value) -> Result<(Vec, Vec>), String> { + let list = v.as_array().ok_or("planes: a list")?; + if list.len() > MAX_PLANES { + return Err(format!("at most {MAX_PLANES} planes")); + } + let (mut planes, mut torn) = (Vec::new(), Vec::new()); + for (i, p) in list.iter().enumerate() { + if let Some(c) = p.get("corners") { + let c = c.as_array().filter(|c| c.len() == 4).ok_or(format!("plane {i}: four corners"))?; + let corners = [0, 1, 2, 3].map(|k| c.get(k).and_then(pt)); + let [Some(a), Some(b), Some(c), Some(d)] = corners else { return Err(format!("plane {i}: corners are [x, y]")) }; + planes.push(VpPlane { corners: [a, b, c, d] }); + torn.push(None); + continue; + } + let from = p + .get("from") + .and_then(Value::as_u64) + .and_then(|f| usize::try_from(f).ok()) + .filter(|f| *f < i) + .ok_or(format!("plane {i}: `corners` or `from` (an earlier plane)"))?; + let edge = match p.get("edge").and_then(Value::as_str).unwrap_or("top") { + "top" => Edge::Top, + "right" => Edge::Right, + "bottom" => Edge::Bottom, + "left" => Edge::Left, + e => return Err(format!("plane {i}: unknown edge `{e}`")), + }; + let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(90.0); + let depth = p.get("depth").and_then(Value::as_f64).unwrap_or(1.0); + if !(0.0..=360.0).contains(&angle) || !(depth > 0.0 && depth <= 1000.0) { + return Err(format!("plane {i}: angle 0..360, depth above 0 and at most 1000")); + } + planes.push(VpPlane { corners: [[0.0; 2]; 4] }); + torn.push(Some(Torn { from, edge, angle, depth })); + } + Ok((planes, torn)) +} + +/// Brings the stamp preview up to date with the strokes (and repaints it after the planes +/// changed, once no plane is being dragged). +pub(crate) fn sync_preview(app: &mut PhotocraftApp) { + let Some(s) = app.distort.vanishing.as_mut() else { return }; + if matches!(s.drag, Some(Drag::Corner { .. } | Drag::Edge { .. } | Drag::Torn { .. })) { + return; + } + let ui = &mut app.ui; + s.paint_preview(|| ui.alloc_id()); +} + +/// What changed between stamp preview (or document) key `seen` and `now` of document `doc` at +/// `revision`: the areas the strokes painted. `None` when either key isn't the session's. +pub(crate) fn damage(app: &PhotocraftApp, doc: DocId, revision: u64, seen: u64, now: u64) -> Option { + let s = app.distort.vanishing.as_ref().filter(|s| s.base.id == doc && s.doc_revision == revision)?; + let keys = &s.preview.as_ref()?.keys; + let at = |k: u64| if k == 0 { Some(0) } else { keys.iter().position(|e| PREVIEW_KEY + e.0 == k).map(|i| i + 1) }; + let (a, b) = (at(seen)?, at(now)?); + if a == b { + return None; + } + Some(keys.get(a.min(b)..a.max(b))?.iter().fold(Rect::EMPTY, |r, k| union(r, k.1))) +} + +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { let tol = crate::distort_ui::tolerance(app); let Some(s) = app.distort.vanishing.as_mut() else { return }; match ev { - ToolEvent::Down { x, y, .. } => s.press([x, y], tol), + ToolEvent::Down { x, y, .. } => { + if let Some(msg) = s.press([x, y], tol, mods) { + app.ui.status = msg.into(); + } + } ToolEvent::Move { x, y, .. } => s.drag_to([x, y]), ToolEvent::Up { x, y } => { s.drag_to([x, y]); s.drag = None; } } + sync_preview(app); } /// Keys while the mode is active (↩ and Esc are handled by `distort_ui::keys`). @@ -398,9 +873,17 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { s.pending.clear(); } else if key(Key::C) { s.tool = VpTool::CreatePlane; + } else if key(Key::S) { + s.tool = VpTool::Stamp; + s.pending.clear(); } else if key(Key::Delete) || key(Key::Backspace) { s.delete_selected(); + } else if ctx.input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::Z)) && s.strokes.pop().is_some() { + // Undo inside the window: the last clone stroke. + s.drag = None; + s.rev += 1; } + sync_preview(app); } /// Esc: drops a half-clicked plane first, then leaves the mode. @@ -469,6 +952,50 @@ pub fn draw(s: &VpSession, painter: &egui::Painter, xf: &ViewXform) { painter.rect_filled(egui::Rect::from_center_size(*c, egui::vec2(6.0, 6.0)), 0.0, tokens.accent); } } + if s.tool == VpTool::Stamp { + draw_stamp(s, painter, xf, &scr); + } +} + +/// Stamp: the source as a crosshair and the brush under the pointer as the circle it paints on +/// the plane, foreshortened. +fn draw_stamp(s: &VpSession, painter: &egui::Painter, xf: &ViewXform, scr: &dyn Fn([f64; 2]) -> Pos2) { + let outline = |pts: &[Pos2]| { + painter.add(egui::Shape::closed_line(pts.to_vec(), Stroke::new(2.5, Color32::from_black_alpha(160)))); + painter.add(egui::Shape::closed_line(pts.to_vec(), Stroke::new(1.0, Color32::WHITE))); + }; + if let Some(src) = s.source { + let c = scr(src); + for (a, b) in [(egui::vec2(-7.0, 0.0), egui::vec2(7.0, 0.0)), (egui::vec2(0.0, -7.0), egui::vec2(0.0, 7.0))] { + painter.line_segment([c + a, c + b], Stroke::new(2.5, Color32::from_black_alpha(160))); + painter.line_segment([c + a, c + b], Stroke::new(1.0, Color32::WHITE)); + } + } + let Some(hover) = painter.ctx().pointer_hover_pos() else { return }; + let p = xf.to_doc(hover); + let Some(sc) = s.scene() else { return }; + let Some(i) = sc.plane_at(p) else { return }; + let Some((h, lu, lv)) = s.frame(i) else { return }; + let Some(inv) = h.inverse() else { return }; + let metric = |q: [f64; 2]| { + let (u, v) = inv.apply(q[0], q[1]); + [u * lu, v * lv] + }; + let (m, probe) = (metric(p), metric([p[0] + s.stamp.diameter / 2.0, p[1]])); + let r = (probe[0] - m[0]).hypot(probe[1] - m[1]); + if !r.is_finite() || r <= 0.0 { + return; + } + let ring: Vec = (0..48) + .map(|k| { + let a = f64::from(k) / 48.0 * std::f64::consts::TAU; + let (x, y) = h.apply((m[0] + r * a.cos()) / lu, (m[1] + r * a.sin()) / lv); + scr([x, y]) + }) + .collect(); + if ring.iter().all(|q| q.is_finite()) { + outline(&ring); + } } /// Plane coordinates (0..1, exclusive) of the grid lines across `u` (or `v`) for cells of @@ -515,6 +1042,8 @@ fn draw_paste(painter: &egui::Painter, scr: &dyn Fn([f64; 2]) -> Pos2, h: &Homog } pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + // New Layer toggled last frame repaints the stamp preview. + sync_preview(app); let Some(s) = app.distort.vanishing.as_mut() else { return }; if crate::widgets::pill_tab(ui, tl!("Edit Plane"), s.tool == VpTool::EditPlane).on_hover_text("V").clicked() { s.tool = VpTool::EditPlane; @@ -523,7 +1052,27 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if crate::widgets::pill_tab(ui, tl!("Create Plane"), s.tool == VpTool::CreatePlane).on_hover_text("C").clicked() { s.tool = VpTool::CreatePlane; } + if crate::widgets::pill_tab(ui, tl!("Stamp"), s.tool == VpTool::Stamp).on_hover_text("S").clicked() { + s.tool = VpTool::Stamp; + s.pending.clear(); + } crate::widgets::vline(ui, 22.0); + if s.tool == VpTool::Stamp { + let st = &mut s.stamp; + for (label, value, range, unit) in [ + (tl!("Diameter:"), &mut st.diameter, 1.0..=2000.0, "px"), + (tl!("Hardness:"), &mut st.hardness, 0.0..=100.0, "%"), + (tl!("Opacity:"), &mut st.opacity, 0.0..=100.0, "%"), + ] { + ui.label(label); + let mut v = *value as f32; + if crate::widgets::value_field(ui, &mut v, range, unit, 56.0).changed() { + *value = f64::from(v); + } + } + crate::widgets::checkbox(ui, &mut st.aligned, tl!("Aligned")); + crate::widgets::vline(ui, 22.0); + } ui.label(tl!("Grid Size:")); let mut g = s.grid_size as f32; if crate::widgets::value_field(ui, &mut g, 2.0..=2000.0, "px", 56.0).changed() { @@ -539,6 +1088,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { s.paste_width = f64::from(w) / 100.0; } } + } + if s.clip.is_some() || !s.strokes.is_empty() || s.tool == VpTool::Stamp { crate::widgets::checkbox(ui, &mut s.new_layer, tl!("New Layer")); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -608,4 +1159,70 @@ mod tests { assert!(l.rgba(x as i32, y as i32)[0] > 0.9, "{:?}", l.rgba(x as i32, y as i32)); assert!(l.rgba(230, 20)[0] < 0.5, "outside the plane"); } + + #[test] + fn ctrl_drag_tears_off_a_wall_and_the_stamp_clones_in_one_step() { + let (ctx, mut app) = app_with_layer(); + // A green mark near the floor's front edge to clone. + app.session.execute("select.rect", json!({"x": 100, "y": 135, "width": 40, "height": 8})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); + let ev = |app: &mut PhotocraftApp, e: ToolEvent, m: egui::Modifiers| crate::distort_ui::pointer(app, e, m); + let drag = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2], m: egui::Modifiers| { + ev(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); + ev(app, ToolEvent::Move { x: (a[0] + b[0]) / 2.0, y: (a[1] + b[1]) / 2.0, pressure: 1.0 }, m); + ev(app, ToolEvent::Up { x: b[0], y: b[1] }, m); + }; + fn vp(app: &PhotocraftApp) -> &VpSession { + app.distort.vanishing.as_ref().unwrap() + } + + // Ctrl/Cmd-drag the top edge node up: a wall torn off the floor's far edge, 90° to it. + let top = vp(&app).edge_nodes(0).unwrap()[0]; + drag(&mut app, top, [top[0], top[1] - 35.0], egui::Modifiers::COMMAND); + let s = vp(&app); + assert_eq!(s.planes.len(), 2); + let t = s.torn[1].unwrap(); + assert_eq!((t.from, t.edge, t.angle), (0, Edge::Top, 90.0)); + let c = s.planes[1].corners; + assert!((c[0][1] + c[1][1]) / 2.0 < 40.0, "the far edge followed the pointer up: {c:?}"); + assert_ne!(s.describe()["planes"][1]["check"], "invalid"); + assert_eq!(s.params()["planes"][1], json!({"from": 0, "edge": "top", "angle": 90.0, "depth": t.depth})); + // Alt-dragging its far edge node turns it; editing the floor carries it along. + let far = s.edge_nodes(1).unwrap()[0]; + drag(&mut app, far, [far[0], far[1] + 12.0], egui::Modifiers::ALT); + assert_ne!(vp(&app).torn[1].unwrap().angle, 90.0); + let before = vp(&app).planes[1].corners; + drag(&mut app, [220.0, 150.0], [228.0, 150.0], egui::Modifiers::NONE); + assert_ne!(vp(&app).planes[1].corners, before); + assert!(vp(&app).torn[1].is_some()); + + // Stamp: painting needs a source first; Alt-click sets it on the floor's green mark. + control(&mut app, &json!({"tool": "stamp", "stamp": {"diameter": 12, "hardness": 80}})).unwrap(); + drag(&mut app, [120.0, 100.0], [120.0, 100.0], egui::Modifiers::NONE); + assert!(vp(&app).strokes.is_empty() && app.ui.status.contains("Alt-click"), "{}", app.ui.status); + drag(&mut app, [120.0, 139.0], [120.0, 139.0], egui::Modifiers::ALT); + assert_eq!(vp(&app).source, Some([120.0, 139.0])); + drag(&mut app, [118.0, 100.0], [126.0, 100.0], egui::Modifiers::NONE); + assert_eq!(vp(&app).strokes.len(), 1); + assert!(vp(&app).strokes[0].points.len() >= 3, "dabs along the drag"); + // The canvas shows the stroke; the document is untouched until OK. + let layer = app.session.active().unwrap().active_layer.unwrap(); + let green = |d: &Document| d.layer(layer).unwrap().surface().unwrap().rgba(122, 100)[1]; + let (shown, key) = crate::distort_ui::display_doc(&app, 0).expect("a stamp preview"); + assert!(green(&shown) > 0.8, "{}", green(&shown)); + let st = app.session.active().unwrap(); + assert!(green(&st.doc) < 0.6); + let area = damage(&app, st.doc.id, st.revision, 0, key).unwrap(); + assert!(area.contains(122, 100) && !area.contains(20, 20), "only the stroke recomposites: {area:?}"); + + let before = app.session.active().unwrap().history.past_len(); + let r = commit(&mut app).unwrap(); + assert_eq!(r["committed"], true, "{r}"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), before + 1, "one history step for the whole session"); + assert!(green(&st.doc) > 0.8, "{}", green(&st.doc)); + } } diff --git a/docs/scorecard.md b/docs/scorecard.md index aad562e6c8..270a865d40 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 15 not run, 7 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 5 | 11 | 11 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 | -| [Tools](#tools) | 21 | 16 | 5 | | +| [Tools](#tools) | 22 | 15 | 5 | | | [Workspace and UI](#workspace-and-ui) | 6 | 7 | 10 | settings that do nothing: 43 of 150 (target 0) | | [Type](#type) | 0 | 3 | 6 | | | [Automation](#automation) | 3 | 2 | 6 | 630 of 630 menu items live (100.0%) | @@ -158,7 +158,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | partial | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke brush, pencil, eraser (vector_cmds.rs:1170); brush-only button, no dialog | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | select.convertToShape with tolerance (vector_cmds.rs:1256); radius as a field only | | TOOL-214-13 | Mask Properties: Density and Feather controls | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Vector-mask density/feather in the engine (vector_cmds.rs:948); no UI controls | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | done | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index cefb18e599..c346038427 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -204,9 +204,9 @@ note = "Vector-mask density/feather in the engine (vector_cmds.rs:948); no UI co [[item]] id = "TOOL-214-14" target = "Vanishing Point window: draw and edit planes, paste, clone in perspective" -status = "partial" +status = "done" issue = 214 -note = "filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing" +note = "filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing" [[item]] id = "TOOL-214-15" From 7db426981d8af28e9e02b7ef9f3dcd2de63f7d6c Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 18:40:45 +0200 Subject: [PATCH 03/15] i18n: hu/tr translations for vanishing point clone strings Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/hu.tsv | 2 ++ crates/ui-egui/src/i18n/tr.tsv | 2 ++ 2 files changed, 4 insertions(+) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 080e204aaa..8c30877039 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3954,6 +3954,8 @@ cameraRaw Yellow Sárga Draw to modify the curve Rajzoljon a görbe módosításához Edit points to modify the curve Szerkessze a pontokat a görbe módosításához Fix the red plane first: its corners must form a convex quad Először javítsa a piros síkot: sarkainak konvex négyszöget kell alkotniuk + Alt-click a plane to set the clone source Alt-kattintás egy síkra a klónforrás beállításához + Too many clone strokes: apply Vanishing Point first Túl sok klónvonás: először alkalmazza az Enyészpontot Grid Size: Rácsméret: Light Blue Világoskék Light Red Világospiros diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 617ad81fd9..16202a85ed 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3751,6 +3751,8 @@ cameraData Lens Lens Draw to modify the curve Eğriyi değiştirmek için çiz Edit points to modify the curve Eğriyi değiştirmek için noktaları düzenle Fix the red plane first: its corners must form a convex quad Önce kırmızı düzlemi düzeltin: köşeleri dışbükey bir dörtgen oluşturmalı + Alt-click a plane to set the clone source Klon kaynağını ayarlamak için bir düzleme Alt+tıklayın + Too many clone strokes: apply Vanishing Point first Çok fazla klon darbesi: önce Kaybolma Noktası'nı uygulayın Grid Size: Izgara Boyutu: Light Blue Açık Mavi Light Gray Açık Gri From dc8d468b6fedebd26b89872bc41d5817d808e240 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 12 Oct 2026 23:49:53 +0200 Subject: [PATCH 04/15] docs: regenerate scorecard after merging main Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 2d653afce6..745886de04 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 6 | 13 | 8 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 | -| [Tools](#tools) | 28 | 14 | 1 | | +| [Tools](#tools) | 26 | 15 | 2 | | | [Workspace and UI](#workspace-and-ui) | 13 | 5 | 5 | settings that do nothing: 27 of 156 (target 0) | | [Type](#type) | 4 | 2 | 3 | | | [Automation](#automation) | 4 | 2 | 5 | 631 of 631 menu items live (100.0%) | @@ -133,11 +133,11 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-213-1 | Pencil tool: aliased 1 px painting, square pixel-aligned cursor | done | [#213](https://github.com/storytold/photocraft/issues/213) | Tool::Pencil (B group): live aliased strokes on the pixel grid, square cursor, Auto Erase; pencil_tests.rs | | TOOL-213-2 | Mixer Brush tool on the toolbar | done | [#213](https://github.com/storytold/photocraft/issues/213) | Tool::MixerBrush in the Brush (B) flyout; Wet/Load/Mix/Flow/Sample All Layers options, command/control dispatch and selection-clipping tests | | TOOL-213-3 | Patch tool with a live preview of the patched area | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.patch (retouch_cmds/patch.rs, source/destination) + Tool::Patch (J group: lasso, then drag the selection); the drag shows the heal live (patch_preview.rs, coarse colour fit: 1000x1000 in 52 ms) | -| TOOL-213-4 | Content-Aware Move tool reusing inpaint completion | partial | [#213](https://github.com/storytold/photocraft/issues/213) | paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers, Transform On Drop's scaleX/scaleY/rotate; background job) + Tool::ContentAwareMove (J group: lasso, then drag; Transform On Drop puts a scale/rotate box on the dropped patch, cam_transform.rs: Enter commits as one step, Esc cancels). Missing: a live preview of the result (the drag and the box show the outline only) | +| TOOL-213-4 | Content-Aware Move tool reusing inpaint completion | partial | [#213](https://github.com/storytold/photocraft/issues/213) | paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers; background job) + Tool::ContentAwareMove (J group: lasso, then drag). Missing: Transform On Drop, a live preview of the result (the drag shows the outline only) | | TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize, then continues the stroke | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes then paints (two history states), Cancel does nothing; drivable via ui.dialog.confirm | | TOOL-213-6 | Fill dialog: contents, blend, opacity, preserve transparency; remembered; Shift+Backspace | done | [#213](https://github.com/storytold/photocraft/issues/213) | fill_ui.rs dialog over edit.fill (fill_cmds.rs): all contents, mode, opacity, preserve; remembered in prefs; Shift+F5 / Shift+Backspace | | TOOL-213-7 | Live stroke preview for every brush-based retouch tool | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Live (canvas.rs strokes_live): Brush, Pencil, Eraser, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040); the release commits the live stroke's pixels (P32). Not yet live: Spot Healing Brush, Mixer Brush, Background Eraser, Pattern Stamp | -| TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); W/H link (cloneSource.set linked, panel chain button, #3298); custom-tip clipping remains missing | +| TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping and auto-hide; W/H link, custom-tip clipping and overlay blend modes remain missing | | TOOL-213-9 | Eyedropper comparison ring (new colour above, current below) while sampling | done | [#213](https://github.com/storytold/photocraft/issues/213) | eyedropper_ring (canvas.rs): the sampled colour on the upper arc, the foreground below, drawn for the Eyedropper and Alt-sampling while the button is held; the Precise-cursor preference keeps the crosshair | | TOOL-213-10 | Ctrl+Alt drag resizes brush size/hardness with an on-canvas readout | done | [#213](https://github.com/storytold/photocraft/issues/213) | brush_resize.rs (#297, #370): Alt+right-drag, or Control+Option-drag on macOS (Control+Alt everywhere), sets diameter horizontally and hardness vertically, circle plus Diameter/Hardness readout, one coalesced tools.setBrush, no paint or history; 9 tests there | | TOOL-213-11 | Editable pressure curve, global and per control | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Global: Preferences › Tools › Pressure Curve (prefs tools.pressureCurve; monotone cubic, engine prefs::PressureCurve; applied to every pen sample in ui-egui stylus.rs before any brush; editor pressure_curve_ui.rs with Linear/Soft/Hard presets). Missing: per-control curves (each brush dynamic's own response to pressure, tilt, rotation) | @@ -150,15 +150,15 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-3 | Color Range test: Sampled Colors at Fuzziness 0 selects the exact match only | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Fuzziness-0 tests cover midtones/shadows only (selection_cmds.rs:444-447) | | TOOL-214-4 | Move tool: box-select layers, Auto-Select hover outline, double-click fit, drag to a tab | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Auto-Select hover outline (Preferences › Tools › Show Highlight on Rollover, #2834) and box-select layers from an empty spot (move_box.rs, layer.selectInRect, #2844) done; double-click fit and drag to a tab open | | TOOL-214-5 | Right-click menu during Free Transform (scale, rotate, skew, warp, flip, rotate 90/180) | done | [#214](https://github.com/storytold/photocraft/issues/214) | canvas_tool_menu.rs TRANSFORM_MENU: modes, Content-Aware Scale / Puppet Warp greyed, Rotate 180 / 90 CW / 90 CCW and Flip turn the open box (transform_tool::intercept, #2832) | -| TOOL-214-6 | Puppet Warp mesh follows the object outline (constrained triangulation) | done | [#214](https://github.com/storytold/photocraft/issues/214) | algo/puppet.rs build_mesh: traced outline of the opaque region grown by Expansion, triangulated with a Density-spaced lattice (conforming Delaunay); separate shapes get separate meshes (#3105) | -| TOOL-214-7 | Content-Aware Scale through the Free Transform box with a live proxy preview | done | [#214](https://github.com/storytold/photocraft/issues/214) | Edit > Content-Aware Scale opens a scale-only Free Transform box (cas_transform.rs) with Amount, Protect and Protect Skin Tones in the options bar; edit.contentAwareScale carves a 384 px copy in the background for the live preview, and Enter runs it with the box's size and x/y as one step (#3096) | +| TOOL-214-6 | Puppet Warp mesh follows the object outline (constrained triangulation) | missing | [#214](https://github.com/storytold/photocraft/issues/214) | algo/puppet.rs:136 builds a block-grid mesh | +| TOOL-214-7 | Content-Aware Scale through the Free Transform box with a live proxy preview | partial | [#214](https://github.com/storytold/photocraft/issues/214) | edit.contentAwareScale (edit_menu_cmds.rs:899) behind a parameter dialog | | TOOL-214-8 | A measured ruler angle prefills Image Rotation > Arbitrary (0.01 deg) | done | [#214](https://github.com/storytold/photocraft/issues/214) | analysis_ui.rs: image.rotation.arbitrary opens seeded with the ruler angle and the direction that straightens it; arbitrary_rotation_starts_at_the_ruler_angle checks 5.7106 deg within 1e-3 and cw/ccw for three measured lines | | TOOL-214-9 | Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar | done | [#214](https://github.com/storytold/photocraft/issues/214) | Ratio dropdown and fields, Straighten (TOOL-214-21); W x H x Resolution with units, built-in size presets and Front Image (crop_size.rs, image.crop targetWidth/targetHeight/resolution, #2443); New / Delete Crop Preset save and delete crop tool presets (crop_presets.rs, tool.presets.* with tool crop, persisted with the preferences) | | TOOL-214-10 | Pen: Alt breaks a handle, Shift 45 deg, Ctrl direct-selects, Backspace, close-drag handle | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Ctrl/Cmd = Direct Selection and Alt = Convert Point on existing paths (direct_select.rs, #790); Backspace/Delete retracts the last point while drawing (#1466); Alt during a drag breaks the handle pair, Alt-drag turns the last anchor's outgoing handle alone, and dragging on the first anchor closes with that anchor's handles (vector_ui.rs, #3306); no Shift 45 deg | -| TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) | +| TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | partial | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke brush, pencil, eraser (vector_cmds.rs:1170); brush-only button, no dialog | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | select.convertToShape with tolerance (vector_cmds.rs:1256); radius as a field only | | TOOL-214-13 | Mask Properties: Density and Feather controls | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Vector-mask density/feather in the engine (vector_cmds.rs:948); no UI controls | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | done | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | From e9ad9e728e8345ecdd0e82edbc46ae8216c49a97 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 15 Oct 2026 22:34:57 +0200 Subject: [PATCH 05/15] Regenerate docs/scorecard.md Co-Authored-By: Claude Opus 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 1e0576ba02..e91525ee49 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | -| [Tools](#tools) | 33 | 11 | 0 | | +| [Tools](#tools) | 34 | 10 | 0 | | | [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 166 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | @@ -158,7 +158,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle with Path Selection, the Rectangle tool and Move + Show Transform Controls: drag rounds every corner of every selected rectangle alike, Alt that corner on each, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256). Missing: shape feather | | TOOL-214-13 | Mask Properties: Density and Feather controls | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Vector-mask density/feather in the engine (vector_cmds.rs:948); no UI controls | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | done | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | From 24d6150ed4f94dd4b27aa7c81530a050c7e25f48 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Mon, 19 Oct 2026 02:30:52 +0200 Subject: [PATCH 06/15] Regenerate docs/scorecard.md after merging main Co-Authored-By: Claude Sonnet 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index b320028936..d22ea47eeb 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 24 | 58 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 19 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | -| [Tools](#tools) | 33 | 11 | 0 | | +| [Tools](#tools) | 34 | 10 | 0 | | | [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 168 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | @@ -160,7 +160,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle with Path Selection, the Rectangle tool and Move + Show Transform Controls: drag rounds every corner of every selected rectangle alike, Alt that corner on each, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256). Missing: shape feather | | TOOL-214-13 | Mask Properties: Density and Feather controls | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Vector-mask density/feather in the engine (vector_cmds.rs:948); no UI controls | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | done | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | From 037177abde9c58c77680247cc9272650c87ac42b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 20 Oct 2026 01:21:45 +0200 Subject: [PATCH 07/15] docs: regenerate the scorecard after merging main Co-Authored-By: Claude Sonnet 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index c4b53a20f8..8bdea9ae72 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 24 | 58 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 19 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | -| [Tools](#tools) | 33 | 11 | 0 | | +| [Tools](#tools) | 34 | 10 | 0 | | | [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 169 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | @@ -160,7 +160,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle with Path Selection, the Rectangle tool and Move + Show Transform Controls: drag rounds every corner of every selected rectangle alike, Alt that corner on each, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256). Missing: shape feather | | TOOL-214-13 | Mask Properties: Density and Feather controls | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Vector-mask density/feather in the engine (vector_cmds.rs:948); no UI controls | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | done | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | From 0741b128ff6c0c027681f7a5552e97aab1469467 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 20 Oct 2026 01:37:13 +0200 Subject: [PATCH 08/15] fix(vp): keep the Vanishing Point session when commit fails --- crates/ui-egui/src/vp_ui.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rs index 1a466e7bc4..c3dc645dd9 100644 --- a/crates/ui-egui/src/vp_ui.rs +++ b/crates/ui-egui/src/vp_ui.rs @@ -750,11 +750,18 @@ pub fn commit(app: &mut PhotocraftApp) -> Result { return Err(msg.into()); } let params = s.params(); - app.distort.vanishing = None; + let session = app.distort.vanishing.take(); if params.get("paste").is_none() && params.get("clone").is_none() { return Ok(json!({"committed": false})); } - app.run(VP, params).map(|r| json!({"committed": true, "result": r})) + match app.run(VP, params) { + Ok(r) => Ok(json!({"committed": true, "result": r})), + Err(e) => { + // Keep the planes, source and strokes so the user can fix the cause and retry. + app.distort.vanishing = session; + Err(e) + } + } } /// Control channel: `filter.vanishingPoint {"ui": {...}}` while the mode is active. From 9484e9e412d90cff79533fb6b99952677e305598 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 21 Oct 2026 20:27:51 +0200 Subject: [PATCH 09/15] Keep one clone source snapshot across Vanishing Point preview batches --- crates/algo/src/vanishing.rs | 47 +++++++++++++++++++++++++++++++++--- crates/engine/src/vp_cmds.rs | 10 +++++++- crates/ui-egui/src/vp_ui.rs | 44 ++++++++++++++++++++++++++++++--- 3 files changed, 92 insertions(+), 9 deletions(-) diff --git a/crates/algo/src/vanishing.rs b/crates/algo/src/vanishing.rs index 2ac85badb4..461c43a881 100644 --- a/crates/algo/src/vanishing.rs +++ b/crates/algo/src/vanishing.rs @@ -382,8 +382,9 @@ pub fn clone_source(scene: &Scene, source: [f64; 2], anchor: [f64; 2], p: [f64; } /// [`clone_stroke`]'s dabs at `points` for a stroke anchored at `anchor` (its first dab, which -/// fixes the offset and the brush's metric size), so a stroke can be painted in pieces exactly -/// as one. Returns the dabs painted and the area they changed. +/// fixes the offset and the brush's metric size). Samples a snapshot taken at this call. +/// For incremental painting use [`clone_dabs_from`] with one snapshot per stroke. +/// Returns the dabs painted and the area they changed. #[allow(clippy::too_many_arguments)] pub fn clone_dabs( scene: &Scene, @@ -395,9 +396,29 @@ pub fn clone_dabs( hardness: f64, opacity: f32, ) -> (usize, Rect) { + let src_copy = surf.clone(); + clone_dabs_from(scene, surf, &src_copy, source, anchor, points, size, hardness, opacity) +} + +/// Paint a batch of one stroke using the same immutable source snapshot for every batch. +/// Source and destination must have the same pixel format; otherwise no dabs are painted. +#[allow(clippy::too_many_arguments)] +pub fn clone_dabs_from( + scene: &Scene, + surf: &mut Surface, + src_copy: &Surface, + source: [f64; 2], + anchor: [f64; 2], + points: &[[f64; 2]], + size: f64, + hardness: f64, + opacity: f32, +) -> (usize, Rect) { + if surf.format() != src_copy.format() { + return (0, Rect::EMPTY); + } let Some(f) = CloneFrame::new(scene, source, anchor, size) else { return (0, Rect::EMPTY) }; let (lud, lvd) = f.ld; - let src_copy = surf.clone(); let fmt = surf.format(); let n = fmt.channels(); let mut dabs = 0; @@ -434,7 +455,7 @@ pub fn clone_dabs( let k = (fall * fall * (3.0 - 2.0 * fall)) as f32 * opacity; // Source pixel at the same metric offset. let (sx, sy) = f.hs.apply((m[0] + f.offset[0]) / f.ls.0, (m[1] + f.offset[1]) / f.ls.1); - let s = sample(&src_copy, sx - 0.5, sy - 0.5, n); + let s = sample(src_copy, sx - 0.5, sy - 0.5, n); for c in 0..n { px[c] += (s[c] - px[c]) * k; } @@ -555,4 +576,22 @@ mod tests { let back = clone_source(&sc, [sx, sy], [dx, dy], [dx, dy]).unwrap(); assert!((back[0] - sx).abs() < 1e-6 && (back[1] - sy).abs() < 1e-6, "{back:?}"); } + #[test] + fn incremental_clone_uses_one_source_snapshot_per_stroke() { + let sc = Scene::new(VpPlane { corners: [[0.0, 0.0], [100.0, 0.0], [100.0, 100.0], [0.0, 100.0]] }, [50.0, 50.0], None, 800.0); + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let mut original = Surface::new(fmt); + for x in 0..100 { + original.fill_rect(Rect::new(x, 0, x + 1, 100), &[x as f32 / 100.0, (x % 7) as f32 / 6.0, 0.3, 1.0]); + } + let points = [[40.0, 50.0], [44.0, 50.0], [48.0, 50.0], [52.0, 50.0]]; + let mut whole = original.clone(); + assert_eq!(clone_stroke(&sc, &mut whole, [36.0, 50.0], &points, 12.0, 0.8, 1.0), 4); + let mut pieces = original.clone(); + for part in points.chunks(2) { + clone_dabs_from(&sc, &mut pieces, &original, [36.0, 50.0], points[0], part, 12.0, 0.8, 1.0); + } + assert_eq!(whole.read_region(Rect::new(0, 0, 100, 100)), pieces.read_region(Rect::new(0, 0, 100, 100))); + } + } } diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/vp_cmds.rs index e1e342a10a..ee9a4c6d7f 100644 --- a/crates/engine/src/vp_cmds.rs +++ b/crates/engine/src/vp_cmds.rs @@ -361,9 +361,13 @@ mod tests { s.execute("file.new", json!({"width": 200, "height": 200, "depth": 32})).unwrap(); s.execute("layer.new.layer", json!({})).unwrap(); let floor = json!({"corners": [[60, 60], [140, 60], [190, 190], [10, 190]]}); + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); for torn in [json!({"from": 0, "angle": 1e9}), json!({"from": 0, "depth": -1}), json!({"from": 0, "depth": 1e300})] { let e = s.execute(VP, json!({"planes": [floor, torn]})).unwrap_err().to_string(); assert!(e.contains("plane 1"), "{e}"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); } let many: Vec<[f64; 2]> = vec![[100.0, 150.0]; MAX_CLONE_DABS + 1]; for clone in [ @@ -374,10 +378,14 @@ mod tests { json!({"source": [100, 180]}), ] { let label: String = clone.to_string().chars().take(80).collect(); - assert!(s.execute(VP, json!({"planes": [floor], "clone": clone})).is_err(), "{label}"); + assert!(s.execute(VP, json!({"planes": [floor], "clone": clone, "newLayer": true})).is_err(), "{label}"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); } let planes: Vec = std::iter::repeat_n(floor.clone(), MAX_PLANES + 1).collect(); assert!(s.execute(VP, json!({"planes": planes})).is_err()); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); // A clone on a torn-off wall, at 32 bits, sampling the floor. let r = s .execute(VP, json!({"planes": [floor, {"from": 0, "edge": "top", "angle": 90, "depth": 0.5}], "clone": [{"source": [100, 150], "points": [[100, 50], [104, 50]], "size": 8}]})) diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rs index c3dc645dd9..418b9516e0 100644 --- a/crates/ui-egui/src/vp_ui.rs +++ b/crates/ui-egui/src/vp_ui.rs @@ -18,7 +18,7 @@ use std::sync::Arc; use egui::{Color32, Pos2, Stroke, TextureHandle, pos2}; use photocraft_algo::transform::Homography; -use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_dabs, clone_source}; +use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_dabs_from, clone_source}; use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId}; use photocraft_engine::vp_cmds::{CloneSpec, MAX_CLONE_DABS, MAX_CLONE_STROKES, VP, copy_changed, visible_image}; use photocraft_geom::Rect; @@ -97,6 +97,8 @@ struct StampPreview { new_layer: bool, /// On a new layer: the visible image the strokes sample, with the strokes so far. work: Option, + /// The sampled image before the current stroke, retained across frame batches. + source: Option<(usize, Surface)>, /// The target layer's pixels as painted so far. out: Surface, /// Strokes painted: those before `.0`, and the first `.1` points of stroke `.0`. @@ -497,7 +499,8 @@ impl VpSession { // The old preview's area changes back too. let keys = self.preview.take().map(|p| p.keys).unwrap_or_default(); area = keys.iter().fold(Rect::EMPTY, |a, k| union(a, k.1)); - self.preview = Some(StampPreview { rev: self.rev, new_layer: self.new_layer, work, out, done: (0, 0), keys, shown: self.base.clone() }); + self.preview = + Some(StampPreview { rev: self.rev, new_layer: self.new_layer, work, source: None, out, done: (0, 0), keys, shown: self.base.clone() }); } let Some(pv) = self.preview.as_mut() else { return false }; let (from_stroke, from_point) = pv.done; @@ -507,15 +510,19 @@ impl VpSession { if points.is_empty() { continue; } + if pv.source.as_ref().is_none_or(|(stroke, _)| *stroke != si) { + pv.source = Some((si, pv.work.as_ref().unwrap_or(&pv.out).clone())); + } + let Some((_, source)) = pv.source.as_ref() else { continue }; let (hard, opacity) = (c.hardness, c.opacity as f32); let changed = match pv.work.as_mut() { Some(work) => { let before = work.clone(); - let (_, a) = clone_dabs(&sc, work, c.source, *anchor, points, c.size, hard, opacity); + let (_, a) = clone_dabs_from(&sc, work, source, c.source, *anchor, points, c.size, hard, opacity); copy_changed(&mut pv.out, &before, work, a); a } - None => clone_dabs(&sc, &mut pv.out, c.source, *anchor, points, c.size, hard, opacity).1, + None => clone_dabs_from(&sc, &mut pv.out, source, c.source, *anchor, points, c.size, hard, opacity).1, }; area = union(area, changed); } @@ -1329,4 +1336,33 @@ mod tests { assert!(s.torn[1].is_some()); assert!(crate::distort_ui::display_doc(&app, 0).is_some(), "the stroke shows again"); } + #[test] + fn overlapping_stamp_preview_matches_commit_across_batches() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + app.session + .edit("pattern", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for x in 0..240 { + surf.fill_rect(Rect::new(x, 0, x + 1, 160), &[x as f32 / 240.0, (x % 7) as f32 / 6.0, 0.3, 1.0]); + } + Ok(()) + }) + .unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + let points = [[80.0, 80.0], [84.0, 80.0], [88.0, 80.0], [92.0, 80.0]]; + let s = app.distort.vanishing.as_mut().unwrap(); + s.new_layer = new_layer; + s.strokes.push(CloneSpec { source: [76.0, 80.0], points: points[..2].to_vec(), size: 12.0, hardness: 0.8, opacity: 1.0 }); + assert!(s.paint_preview(|| 1)); + s.strokes[0].points.extend_from_slice(&points[2..]); + assert!(s.paint_preview(|| 2)); + let (shown, _) = s.shown().unwrap(); + let expected = photocraft_compose::flatten(&shown).px; + assert_ne!(expected, photocraft_compose::flatten(&app.session.active().unwrap().doc).px); + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); + } + } } From 07cfd9b219f0ebd41d5781d6d7d6e019f7573f33 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 21 Oct 2026 20:34:12 +0200 Subject: [PATCH 10/15] Regenerate Vanishing Point scorecard after merging main --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 5a59aad2a4..c8ee0c28aa 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 26 | 60 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 22 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 9 | 12 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | -| [Tools](#tools) | 36 | 8 | 0 | | +| [Tools](#tools) | 37 | 7 | 0 | | | [Workspace and UI](#workspace-and-ui) | 13 | 7 | 3 | settings that do nothing: 24 of 171 (target 0) | | [Type](#type) | 5 | 3 | 1 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | @@ -162,7 +162,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | done | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle with Path Selection, the Rectangle tool and Move + Show Transform Controls: drag rounds every corner of every selected rectangle alike, Alt that corner on each, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256); shape Density and Feather (Properties, layer.vectorMask.edit on a shape layer; the path as the fill's soft vector mask, Photoshop's 10 px feather ramp within 1 level; PSD mask parameters and .pcraft, #5846, 2026-10-15) | | TOOL-214-13 | Mask Properties: Density and Feather controls | done | [#214](https://github.com/storytold/photocraft/issues/214) | Properties panel shows Density (%) and Feather (px) sliders for a targeted pixel mask (layer.layerMask.edit) and a targeted vector mask (layer.vectorMask.edit), non-destructive and one undo step per drag, with Photoshop's Refine row (mask_props_ui.rs; mask_props_ui_tests.rs pixel_mask_properties_follow_target_for_raster_and_adjustment_in_both_themes, mask_slider_drags_preview_live_and_undo_as_separate_gestures, vector_mask_properties_edit_density_and_feather) | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | done | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | From 1fea3daa1c2dc46e00d510a5a59bf1850d1ecd97 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 22 Oct 2026 21:06:36 +0200 Subject: [PATCH 11/15] Regenerate docs/scorecard.md after the upstream merge Co-Authored-By: Claude Sonnet 5.5 --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 6e84b9847e..56df57db49 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -8,7 +8,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js |---|---:|---:|---:|---| | [Performance](#performance) | 3 | 22 | 26 | 60 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 22 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 9 | 13 | 5 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/256, round trip ≥ 258/256 | -| [Tools](#tools) | 36 | 8 | 0 | | +| [Tools](#tools) | 37 | 7 | 0 | | | [Workspace and UI](#workspace-and-ui) | 14 | 6 | 3 | settings that do nothing: 21 of 176 (target 0) | | [Type](#type) | 5 | 4 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | @@ -162,7 +162,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | done | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle, triangle, polygon and star (LiveShape::Polygon corner_radius, shape.create/edit cornerRadius, vector shapes::round_corners) with Path Selection, the Rectangle/Triangle/Polygon tools and Move + Show Transform Controls: drag rounds every corner of every selected shape alike, Alt one corner of a rectangle, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256); shape Density and Feather (Properties, layer.vectorMask.edit on a shape layer; the path as the fill's soft vector mask, Photoshop's 10 px feather ramp within 1 level; PSD mask parameters and .pcraft, #5846, 2026-10-15) | | TOOL-214-13 | Mask Properties: Density and Feather controls | done | [#214](https://github.com/storytold/photocraft/issues/214) | Properties panel shows Density (%) and Feather (px) sliders for a targeted pixel mask (layer.layerMask.edit) and a targeted vector mask (layer.vectorMask.edit), non-destructive and one undo step per drag, with Photoshop's Refine row (mask_props_ui.rs:34 pixel mask, :48 vector mask, :52 the sliders; mask_props_ui_tests.rs:39 pixel_mask_properties_follow_target_for_raster_and_adjustment_in_both_themes, :81 mask_slider_drags_preview_live_and_undo_as_separate_gestures, :147 vector_mask_properties_edit_density_and_feather) | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | done | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | From 47fa9fa3a57d7f17e303c62f184f2afa31046515 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 24 Oct 2026 14:32:41 +0200 Subject: [PATCH 12/15] Keep TOOL-214-14 partial and regenerate docs/scorecard.md The row's own note says the window's Marquee tool and the Stamp's Heal modes are still missing, so it stays partial; the scorecard is regenerated to match. Co-Authored-By: Claude Sonnet 5.5 --- docs/scorecard.md | 2 +- scorecard/tools.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index 09f8c61ab9..a23daa780a 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -166,7 +166,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | done | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle, triangle, polygon and star (LiveShape::Polygon corner_radius, shape.create/edit cornerRadius, vector shapes::round_corners) with Path Selection, the Rectangle/Triangle/Polygon tools and Move + Show Transform Controls: drag rounds every corner of every selected shape alike, Alt one corner of a rectangle, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256); shape Density and Feather (Properties, layer.vectorMask.edit on a shape layer; the path as the fill's soft vector mask, Photoshop's 10 px feather ramp within 1 level; PSD mask parameters and .pcraft, #5846, 2026-10-15) | | TOOL-214-13 | Mask Properties: Density and Feather controls | done | [#214](https://github.com/storytold/photocraft/issues/214) | Properties panel shows Density (%) and Feather (px) sliders for a targeted pixel mask (layer.layerMask.edit) and a targeted vector mask (layer.vectorMask.edit), non-destructive and one undo step per drag, with Photoshop's Refine row (mask_props_ui.rs:34 pixel mask, :48 vector mask, :52 the sliders; mask_props_ui_tests.rs:39 pixel_mask_properties_follow_target_for_raster_and_adjustment_in_both_themes, :81 mask_slider_drags_preview_live_and_undo_as_separate_gestures, :147 vector_mask_properties_edit_density_and_feather) | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 833fed4adc..7aea518610 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -204,7 +204,7 @@ note = "Properties panel shows Density (%) and Feather (px) sliders for a target [[item]] id = "TOOL-214-14" target = "Vanishing Point window: draw and edit planes, paste, clone in perspective" -status = "done" +status = "partial" issue = 214 note = "filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing" From b1794c6e0608ccfc887213dcf58398977c5cb75e Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 25 Oct 2026 09:45:03 -0400 Subject: [PATCH 13/15] Release 0.16.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 62 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b27d26a78a..794e35b1ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4742,7 +4742,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.15.1" +version = "0.16.0" dependencies = [ "arboard", "async-io", @@ -4791,7 +4791,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.15.1" +version = "0.16.0" dependencies = [ "crc32fast", "flate2", @@ -4801,7 +4801,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4815,7 +4815,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.15.1" +version = "0.16.0" dependencies = [ "base64 0.22.1", "cap-std", @@ -4839,7 +4839,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.15.1" +version = "0.16.0" dependencies = [ "clap", "clap_complete", @@ -4858,7 +4858,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.15.1" +version = "0.16.0" dependencies = [ "moxcms", "rayon", @@ -4866,7 +4866,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.15.1" +version = "0.16.0" dependencies = [ "craft-jpeg", "exr", @@ -4888,7 +4888,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-cms", "serde", @@ -4896,7 +4896,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.15.1" +version = "0.16.0" dependencies = [ "criterion", "photocraft-cms", @@ -4912,7 +4912,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4923,7 +4923,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.15.1" +version = "0.16.0" dependencies = [ "blake3", "chrono", @@ -4964,7 +4964,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.15.1" +version = "0.16.0" dependencies = [ "blake3", "crc32fast", @@ -4987,14 +4987,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.15.1" +version = "0.16.0" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.15.1" +version = "0.16.0" dependencies = [ "half", "log", @@ -5012,14 +5012,14 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.15.1" +version = "0.16.0" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.15.1" +version = "0.16.0" dependencies = [ "blake3", "craft-docpath", @@ -5050,18 +5050,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.15.1" +version = "0.16.0" [[package]] name = "photocraft-ops" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5072,7 +5072,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5088,7 +5088,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.15.1" +version = "0.16.0" dependencies = [ "flate2", "photocraft-psd", @@ -5099,7 +5099,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5110,7 +5110,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.15.1" +version = "0.16.0" dependencies = [ "flate2", "image", @@ -5125,7 +5125,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.15.1" +version = "0.16.0" dependencies = [ "block2 0.6.2", "objc2 0.6.4", @@ -5137,7 +5137,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.15.1" +version = "0.16.0" dependencies = [ "memory-stats", "serde_json", @@ -5145,7 +5145,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.15.1" +version = "0.16.0" dependencies = [ "flate2", "parley", @@ -5160,7 +5160,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.15.1" +version = "0.16.0" dependencies = [ "base64 0.22.1", "craft-print", @@ -5203,7 +5203,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5214,7 +5214,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.15.1" +version = "0.16.0" dependencies = [ "eframe", "egui", @@ -5236,7 +5236,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.15.1" +version = "0.16.0" dependencies = [ "flate2", "js-sys", @@ -8890,7 +8890,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.15.1" +version = "0.16.0" dependencies = [ "chrono", "serde", diff --git a/Cargo.toml b/Cargo.toml index 68d6ae90b1..43e4c87e27 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.15.1" +version = "0.16.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 248972cfa343ef46cee8f06ea16173310b2abba2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 14:52:51 +0100 Subject: [PATCH 14/15] Integration: clip VP clone copy-back to the canvas, paste in the stamp preview (#3281) A newLayer clone copied back the union of every dab's box: one point far off the canvas (e.g. [9e6, 9e6], accepted by the params) made it read a region of petabytes and abort. The command and the stamp preview now copy back and report damage only inside the canvas. With an image on the clipboard (Paste is on by default), OK pastes first and the strokes paint over and sample the paste, but the preview painted the strokes on the unpasted layer and drew the paste on top. The preview now pastes first too (shared paste_onto), repaints when the paste moves, and the overlay is only drawn when no current preview shows the paste. While the paste is dragged the baked preview is hidden so only one copy follows the pointer; a plane drag freezes preview and paste until release. Deleting the last plane now drops the stroke preview. Co-authored-by: Valentin Klein <271991477+vangel76@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/vp_cmds.rs | 49 ++++++-- crates/ui-egui/src/vp_ui.rs | 222 +++++++++++++++++++++++++++++++++-- 2 files changed, 250 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/vp_cmds.rs index ee9a4c6d7f..565d1f4965 100644 --- a/crates/engine/src/vp_cmds.rs +++ b/crates/engine/src/vp_cmds.rs @@ -137,15 +137,17 @@ pub fn clone_specs(p: &Value) -> Result> { } /// Paints clone stroke `c` on `surf`, or, with `work` (the image it samples), on `work` and copies -/// the pixels it changed to `surf`. Returns the dabs painted. -pub fn clone_into(sc: &Scene, surf: &mut Surface, work: Option<&mut Surface>, c: &CloneSpec) -> usize { +/// the pixels it changed inside `canvas` to `surf`. Returns the dabs painted. +pub fn clone_into(sc: &Scene, surf: &mut Surface, work: Option<&mut Surface>, c: &CloneSpec, canvas: Rect) -> usize { let Some(first) = c.points.first() else { return 0 }; let Some(work) = work else { return clone_dabs(sc, surf, c.source, *first, &c.points, c.size, c.hardness, c.opacity as f32).0; }; let before = work.clone(); let (dabs, area) = clone_dabs(sc, work, c.source, *first, &c.points, c.size, c.hardness, c.opacity as f32); - copy_changed(surf, &before, work, area); + // The dabs' boxes can span far off the canvas (points up to 1e7 px apart): reading their + // union back would allocate without bound. + copy_changed(surf, &before, work, area.intersect(&canvas)); dabs } @@ -178,8 +180,16 @@ fn has_layer(s: &Session) -> std::result::Result<(), String> { } } +/// Pastes `src` (content in `rect`) onto plane `plane` of `sc` over `surf`, as the command's +/// `"paste"` does. Returns the area the paste covers. +pub fn paste_onto(sc: &Scene, surf: &mut Surface, plane: usize, src: &Surface, rect: Rect, at: [f64; 2], width: f64) -> Result { + let Some(out) = paste(sc, plane, src, rect, at, width)? else { return Ok(Rect::EMPTY) }; + over(surf, &out); + Ok(out.content_bounds()) +} + /// Composites `top` over `dst` (premultiplied source-over), same format. -fn over(dst: &mut Surface, top: &Surface) { +pub fn over(dst: &mut Surface, top: &Surface) { let b = top.content_bounds(); if b.is_empty() { return; @@ -249,9 +259,7 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { } let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Vanishing Point needs a pixel layer".into()))?; for (plane, src, rect, at, width) in &pastes { - if let Some(out) = paste(&sc, *plane, src, *rect, *at, *width)? { - over(surf, &out); - } + paste_onto(&sc, surf, *plane, src, *rect, *at, *width)?; } // A new layer samples the visible image (merged with what's been pasted) and takes only // the pixels the strokes change; otherwise the strokes paint the layer itself. @@ -260,7 +268,7 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { w }); for c in &clones { - dabs += clone_into(&sc, surf, work.as_mut(), c); + dabs += clone_into(&sc, surf, work.as_mut(), c, canvas); } surf.prune(); Ok(id) @@ -393,4 +401,29 @@ mod tests { assert_eq!(r["planes"].as_array().unwrap().len(), 2); assert!(r["dabs"].as_u64().unwrap() >= 1, "{r}"); } + + #[test] + fn new_layer_clone_stays_on_the_canvas() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#40c040"})).unwrap(); + // A red stripe where the first dab samples, so cloning it changes pixels. + s.edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(140, 80, 160, 120), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let planes = json!([{"corners": [[0, 0], [200, 0], [200, 200], [0, 200]]}]); + // The second dab lies left of the canvas and samples the canvas 50 px to its right; the + // third is far off it (its box joined with the first's once asked for petabytes). + for points in [json!([[100, 100], [-30, 100]]), json!([[100, 100], [-30, 100], [9_000_000, 9_000_000]])] { + let r = s.execute(VP, json!({"planes": planes, "newLayer": true, "clone": [{"source": [150, 100], "points": points, "size": 20}]})).unwrap(); + let l = s.active().unwrap().doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap().surface().unwrap(); + let b = l.content_bounds(); + assert!(!b.is_empty() && Rect::new(0, 0, 200, 200).contains_rect(&b), "{b:?}"); + assert!(l.rgba(100, 100)[0] > 0.9, "{:?}", l.rgba(100, 100)); + s.undo(); + } + } } diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rs index 65c629e590..fc4476dca3 100644 --- a/crates/ui-egui/src/vp_ui.rs +++ b/crates/ui-egui/src/vp_ui.rs @@ -20,7 +20,7 @@ use egui::{Color32, Pos2, Stroke, TextureHandle, pos2}; use photocraft_algo::transform::Homography; use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_dabs_from, clone_source}; use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId}; -use photocraft_engine::vp_cmds::{CloneSpec, MAX_CLONE_DABS, MAX_CLONE_STROKES, VP, copy_changed, visible_image}; +use photocraft_engine::vp_cmds::{CloneSpec, MAX_CLONE_DABS, MAX_CLONE_STROKES, VP, copy_changed, over, paste_onto, visible_image}; use photocraft_geom::Rect; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -92,9 +92,13 @@ enum Drag { /// The clone strokes painted onto the target layer, shown on the canvas while stamping. struct StampPreview { - /// The session's `rev` and New Layer it was painted with (either changing repaints it). + /// The session's `rev`, New Layer and paste it was painted with (any changing repaints it). rev: u64, new_layer: bool, + /// The paste (plane, top-left, width) baked in under the strokes, as OK pastes before it clones. + paste: Option<(usize, [f64; 2], f64)>, + /// The paste landed in `out` (it can fail, or miss the plane). + baked: bool, /// On a new layer: the visible image the strokes sample, with the strokes so far. work: Option, /// The sampled image before the current stroke, retained across frame batches. @@ -111,6 +115,9 @@ struct StampPreview { /// The clipboard image shown pasted onto the plane. struct Clip { + /// The clipboard pixels and their content bounds, which the preview pastes like OK does. + surface: Surface, + rect: Rect, texture: TextureHandle, width: f64, height: f64, @@ -251,6 +258,28 @@ impl VpSession { self.selected.filter(|i| *i < self.planes.len()).or_else(|| (!self.planes.is_empty()).then_some(0)) } + /// What OK pastes: the plane, the top-left and the width. + fn paste_key(&self) -> Option<(usize, [f64; 2], f64)> { + self.paste_plane().map(|i| (i, self.paste_at, self.paste_width)) + } + + /// The stamp preview is current and already shows the paste under the strokes. + fn preview_has_paste(&self) -> bool { + self.preview.as_ref().is_some_and(|p| p.baked && p.rev == self.rev && p.paste == self.paste_key()) + } + + /// The paste is dragged while the stamp preview holds it in its old place. + fn moving_baked_paste(&self) -> bool { + matches!(self.drag, Some(Drag::Paste { .. })) && self.preview.as_ref().is_some_and(|p| p.baked) + } + + /// [`draw_content`] draws the paste overlay: not when the stamp preview shows the paste, and + /// not while a plane drag freezes that preview (as it freezes the strokes) until release. + fn paste_overlay(&self) -> bool { + let frozen = matches!(self.drag, Some(Drag::Corner { .. } | Drag::Edge { .. } | Drag::Torn { .. })) && self.preview.as_ref().is_some_and(|p| p.baked); + !self.preview_has_paste() && !frozen + } + /// Size of the pasted image in plane coordinates (the engine keeps its metric aspect). fn paste_extent(&self, lu: f64, lv: f64) -> Option<[f64; 2]> { let c = self.clip.as_ref()?; @@ -493,17 +522,46 @@ impl VpSession { self.preview = None; return had; } - let Some(sc) = self.scene() else { return false }; - let stale = self.preview.as_ref().is_none_or(|p| p.rev != self.rev || p.new_layer != self.new_layer); + let Some(sc) = self.scene() else { + // No planes left: nothing to show the strokes on. + return self.preview.take().is_some(); + }; + let paste = self.paste_key(); + let canvas = self.canvas; + let stale = self.preview.as_ref().is_none_or(|p| p.rev != self.rev || p.new_layer != self.new_layer || p.paste != paste); let mut area = Rect::EMPTY; + let mut baked = false; if stale { let Some(layer) = self.base.layer(self.layer).and_then(Layer::surface) else { return false }; - let (out, work) = if self.new_layer { (Surface::new(layer.format()), Some(visible_image(&self.base))) } else { (layer.clone(), None) }; + let mut out = if self.new_layer { Surface::new(layer.format()) } else { layer.clone() }; + // OK pastes first and the strokes then paint over (and sample) the pasted pixels. + if let (Some((i, at, width)), Some(c)) = (paste, self.clip.as_ref()) + && self.planes.get(i).is_some_and(|p| p.check(self.center()) != PlaneCheck::Invalid) + && let Ok(r) = paste_onto(&sc, &mut out, i, &c.surface, c.rect, at, width) + { + area = r.intersect(&canvas); + baked = !r.is_empty(); + } + let work = self.new_layer.then(|| { + let mut w = visible_image(&self.base); + over(&mut w, &out); + w + }); // The old preview's area changes back too. let keys = self.preview.take().map(|p| p.keys).unwrap_or_default(); - area = keys.iter().fold(Rect::EMPTY, |a, k| union(a, k.1)); - self.preview = - Some(StampPreview { rev: self.rev, new_layer: self.new_layer, work, source: None, out, done: (0, 0), keys, shown: self.base.clone() }); + area = keys.iter().fold(area, |a, k| union(a, k.1)); + self.preview = Some(StampPreview { + rev: self.rev, + new_layer: self.new_layer, + paste, + baked, + work, + source: None, + out, + done: (0, 0), + keys, + shown: self.base.clone(), + }); } let Some(pv) = self.preview.as_mut() else { return false }; let (from_stroke, from_point) = pv.done; @@ -522,10 +580,12 @@ impl VpSession { Some(work) => { let before = work.clone(); let (_, a) = clone_dabs_from(&sc, work, source, c.source, *anchor, points, c.size, hard, opacity); + // As OK does: only the canvas (the dabs' boxes can span far off it). + let a = a.intersect(&canvas); copy_changed(&mut pv.out, &before, work, a); a } - None => clone_dabs_from(&sc, &mut pv.out, source, c.source, *anchor, points, c.size, hard, opacity).1, + None => clone_dabs_from(&sc, &mut pv.out, source, c.source, *anchor, points, c.size, hard, opacity).1.intersect(&canvas), }; area = union(area, changed); } @@ -546,9 +606,14 @@ impl VpSession { true } - /// The document with the strokes painted, and its preview key. + /// The document with the strokes painted, and its preview key. Not while the paste is + /// dragged out of its baked-in place: the overlay follows the pointer instead, and the + /// strokes repaint over it on release. pub(crate) fn shown(&self) -> Option<(Arc, u64)> { let p = self.preview.as_ref()?; + if self.moving_baked_paste() { + return None; + } Some((p.shown.clone(), PREVIEW_KEY + p.keys.last()?.0)) } @@ -707,6 +772,8 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> let clip = app.session.clipboard.as_ref().and_then(|c| { let r = c.surface.content_bounds(); (!r.is_empty()).then(|| Clip { + surface: c.surface.clone(), + rect: r, texture: ctx.load_texture(format!("vp-paste-{key}"), crate::distort_ui::surface_image(&c.surface, r, 1024), egui::TextureOptions::LINEAR), width: f64::from(r.width()), height: f64::from(r.height()), @@ -896,7 +963,7 @@ fn parse_planes(v: &Value) -> Result<(Vec, Vec>), String> /// changed, once no plane is being dragged). pub(crate) fn sync_preview(app: &mut PhotocraftApp) { let Some(s) = app.distort.vanishing.as_mut() else { return }; - if matches!(s.drag, Some(Drag::Corner { .. } | Drag::Edge { .. } | Drag::Torn { .. })) { + if matches!(s.drag, Some(Drag::Corner { .. } | Drag::Edge { .. } | Drag::Torn { .. } | Drag::Paste { .. })) { return; } let ui = &mut app.ui; @@ -967,10 +1034,12 @@ pub fn escape(app: &mut PhotocraftApp) { } /// The paste on its plane: image content, drawn under the grid and guides like the document so a -/// guide stays visible across it (#7781). The planes and their grids are [`draw`]. +/// guide stays visible across it (#7781). The planes and their grids are [`draw`]. A current +/// stamp preview already shows the paste under its strokes. pub fn draw_content(s: &VpSession, painter: &egui::Painter, xf: &ViewXform) { let scr = |p: [f64; 2]| xf.to_screen(p[0] as f32, p[1] as f32); - if let Some(i) = s.paste_plane() + if s.paste_overlay() + && let Some(i) = s.paste_plane() && s.planes.get(i).is_some_and(|p| p.check(s.center()) != PlaneCheck::Invalid) && let (Some((h, lu, lv)), Some(c)) = (s.frame(i), s.clip.as_ref()) && let Some(ext) = s.paste_extent(lu, lv) @@ -1183,6 +1252,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some(s) = app.distort.vanishing.as_mut() { s.settle(ui.input(|i| i.pointer.any_down())); } + // A paste Width or Paste change shows in this frame's canvas, the paste under the strokes. + sync_preview(app); } #[cfg(test)] @@ -1375,4 +1446,129 @@ mod tests { assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); } } + + /// A red square on the clipboard (copied from the layer's top-left corner). + fn copy_red_square(app: &mut PhotocraftApp) { + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("edit.copy", json!({})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + } + + #[test] + fn stamp_preview_paints_over_the_paste_like_ok() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "newLayer": new_layer})).unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.paste && s.paste_plane() == Some(0), "the clipboard pastes by default"); + // The paste covers x 65..175 from y 45 down. One stroke clones it onto the base + // layer, the other paints across its right edge. + control( + &mut app, + &json!({"clone": [ + {"source": [100, 60], "points": [[40, 120], [48, 120], [56, 120]], "size": 16, "hardness": 80}, + {"source": [40, 130], "points": [[150, 60], [170, 60], [190, 60]], "size": 16, "hardness": 80}, + ]}), + ) + .unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.preview_has_paste(), "the preview shows the paste, so the overlay isn't drawn over the strokes"); + let (shown, _) = s.shown().unwrap(); + let expected = photocraft_compose::flatten(&shown).px; + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); + } + } + + #[test] + fn moving_the_paste_repaints_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [200, 130], "points": [[30, 130]], "size": 8}]})).unwrap(); + let red = |app: &PhotocraftApp, x: i32, y: i32| { + let (shown, _) = app.distort.vanishing.as_ref().unwrap().shown().unwrap(); + let l = app.session.active().unwrap().active_layer.unwrap(); + shown.layer(l).unwrap().surface().unwrap().rgba(x, y)[0] + }; + assert!(red(&app, 100, 60) > 0.9); + control(&mut app, &json!({"pasteAt": [0.0, 0.5]})).unwrap(); + assert!(red(&app, 100, 60) < 0.5, "the paste left its old place"); + assert!(red(&app, 30, 100) > 0.9, "and shows at the new one"); + control(&mut app, &json!({"paste": false})).unwrap(); + assert!(red(&app, 30, 100) < 0.5, "paste off: gone from the preview"); + assert!(!app.distort.vanishing.as_ref().unwrap().preview_has_paste()); + } + + #[test] + fn dragging_the_paste_shows_it_once() { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "tool": "edit"})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [200, 130], "points": [[30, 130]], "size": 8}]})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + let red = |app: &PhotocraftApp, x: i32, y: i32| { + let (shown, _) = crate::distort_ui::display_doc(app, 0)?; + Some(shown.layer(layer).unwrap().surface().unwrap().rgba(x, y)[0]) + }; + assert!(red(&app, 100, 60).unwrap() > 0.9, "the paste is in the preview"); + let ev = |app: &mut PhotocraftApp, e: ToolEvent| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE); + ev(&mut app, ToolEvent::Down { x: 100.0, y: 60.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 60.0, y: 100.0, pressure: 1.0 }); + // Mid-drag: no copy left behind at the old place, only the overlay at the pointer. + assert!(red(&app, 100, 60).is_none_or(|r| r < 0.5), "{:?}", red(&app, 100, 60)); + assert!(app.distort.vanishing.as_ref().unwrap().paste_overlay(), "the overlay draws the moving paste"); + ev(&mut app, ToolEvent::Up { x: 60.0, y: 100.0 }); + assert!(red(&app, 100, 60).unwrap() < 0.5); + assert!(red(&app, 60, 100).unwrap() > 0.9, "released: the preview pastes at the new place"); + assert!(!app.distort.vanishing.as_ref().unwrap().paste_overlay()); + // A plane corner drag freezes the preview, paste included, until release: one copy. + ev(&mut app, ToolEvent::Down { x: 230.0, y: 150.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 236.0, y: 156.0, pressure: 1.0 }); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(matches!(s.drag, Some(Drag::Corner { .. }))); + assert!(red(&app, 60, 100).unwrap() > 0.9 && !s.paste_overlay(), "frozen preview, no overlay on top"); + ev(&mut app, ToolEvent::Up { x: 236.0, y: 156.0 }); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.preview_has_paste() && !s.paste_overlay()); + } + + #[test] + fn new_layer_stamp_preview_stays_on_the_canvas() { + let (ctx, mut app) = app_with_layer(); + // A red stripe where the first dab samples, so cloning it changes pixels. + app.session.execute("select.rect", json!({"x": 130, "y": 70, "width": 20, "height": 20})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "newLayer": true})).unwrap(); + // The second dab lies left of the canvas and samples the canvas 100 px to its right. + control(&mut app, &json!({"clone": [{"source": [140, 80], "points": [[40, 80], [-30, 80]], "size": 16}]})).unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + let out = s.preview.as_ref().unwrap().out.content_bounds(); + assert!(!out.is_empty() && s.canvas.contains_rect(&out), "{out:?}"); + let st = app.session.active().unwrap(); + let area = damage(&app, st.doc.id, st.revision, 0, s.shown().unwrap().1).unwrap(); + assert!(s.canvas.contains_rect(&area), "{area:?}"); + } + + #[test] + fn deleting_the_last_plane_drops_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [120, 139], "points": [[118, 100], [126, 100]], "size": 12}]})).unwrap(); + assert!(crate::distort_ui::display_doc(&app, 0).is_some()); + let s = app.distort.vanishing.as_mut().unwrap(); + s.selected = Some(0); + s.delete_selected(); + sync_preview(&mut app); + assert!(app.distort.vanishing.as_ref().unwrap().planes.is_empty()); + assert!(crate::distort_ui::display_doc(&app, 0).is_none(), "no strokes shown without a plane"); + } } From eb4494b915e113062e0bbe7974821618c36d25ea Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 25 Oct 2026 15:29:02 +0100 Subject: [PATCH 15/15] Integration: VP preview keyed to its document, OK paints the session's layer (#3281) Vanishing Point is not modal, so the Layers panel and menu commands stay usable while it is open. The stamp preview kept painting over the document as it was when the mode opened, and OK painted whichever layer was active by then: stamp on layer 1, click layer 2, and the canvas still showed layer 1 while OK cloned onto layer 2 (a filter run meanwhile was hidden). filter.vanishingPoint now takes an optional `layer` (the UI passes the session's when another layer was picked, so recorded actions stay portable) and makes the painted layer active, so Fade and a colour-channel target follow it. The preview repaints over the document as it is now when its pixels change (the canvas syncs it before drawing, so no frame goes without the strokes); a selection or view change keeps it as it is. display_doc's VP branch is also keyed to the session's document, as main's Puppet and Perspective Warp branches are (#5115): a document opened in the same frame no longer shows the other document's strokes. Co-authored-by: Valentin Klein <271991477+vangel76@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/vp_cmds.rs | 52 ++++++++++- crates/ui-egui/src/canvas.rs | 3 + crates/ui-egui/src/distort_ui.rs | 6 +- crates/ui-egui/src/vp_ui.rs | 144 ++++++++++++++++++++++++++++++- 4 files changed, 197 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/vp_cmds.rs index 565d1f4965..9809888446 100644 --- a/crates/engine/src/vp_cmds.rs +++ b/crates/engine/src/vp_cmds.rs @@ -240,15 +240,26 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { } let clones = clone_specs(p)?; let new_layer = p.get("newLayer").and_then(Value::as_bool).unwrap_or(false); + // The layer the mode was opened on (the UI passes it: other layers can be picked meanwhile). + let layer = crate::commands::explicit_layer(s, p)?; let mut dabs = 0usize; let target = s.edit("Vanishing Point", |doc: &mut Document, active| { + if let Some(l) = layer + && doc.layer(l).is_none() + { + return Err(EngineError::NoLayer(l)); + } + let on = layer.or(*active); let id = if new_layer { let l = Layer::raster(doc.next_layer_name("Vanishing Point"), doc.pixel_format()); - let nid = doc.insert_above(*active, l); + let nid = doc.insert_above(on, l); *active = Some(nid); nid } else { - active.ok_or_else(|| EngineError::Other("no active layer".into()))? + // The painted layer becomes active, so Fade and a colour-channel target follow it. + let id = on.ok_or_else(|| EngineError::Other("no active layer".into()))?; + *active = Some(id); + id }; // A new layer clones from the visible image; otherwise from the layer itself. let base: Option = new_layer.then(|| visible_image(doc)); @@ -291,7 +302,7 @@ pub fn specs() -> Vec { label: "Vanishing Point…", menu: &["Filter"], shortcut: Some("Cmd+Alt+V"), - params: r##"{"planes":[{"corners":[[x,y]×4]} | {"from":plane,"edge":"top|right|bottom|left","angle":deg=90,"depth":1}],"focalLength":px=0,"paste":[{"plane":0,"layer":id? (else the clipboard),"at":[u,v]=[0.25,0.25],"width":0..1=0.5}],"clone":[{"source":[x,y],"points":[[x,y]],"size":px=40,"hardness":0..100=50,"opacity":0..100=100}],"newLayer":bool=false}"##, + params: r##"{"planes":[{"corners":[[x,y]×4]} | {"from":plane,"edge":"top|right|bottom|left","angle":deg=90,"depth":1}],"focalLength":px=0,"paste":[{"plane":0,"layer":id? (else the clipboard),"at":[u,v]=[0.25,0.25],"width":0..1=0.5}],"clone":[{"source":[x,y],"points":[[x,y]],"size":px=40,"hardness":0..100=50,"opacity":0..100=100}],"newLayer":bool=false,"layer":id|name? (else the active layer)}"##, enabled: has_layer, run: vanishing_point, journal: true, @@ -426,4 +437,39 @@ mod tests { s.undo(); } } + + #[test] + fn layer_param_paints_that_layer_not_the_active_one() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + s.execute("layer.new.layer", json!({"name": "floor"})).unwrap(); + s.execute("edit.fill", json!({"color": "#40c040"})).unwrap(); + s.edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(140, 80, 160, 120), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let floor = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "other"})).unwrap(); + let other = s.active().unwrap().active_layer.unwrap(); + let planes = json!([{"corners": [[0, 0], [200, 0], [200, 200], [0, 200]]}]); + let clone = json!([{"source": [150, 100], "points": [[100, 100]], "size": 20}]); + let surf = |s: &Session, id| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); + let r = s.execute(VP, json!({"planes": planes, "clone": clone, "layer": floor.0})).unwrap(); + assert_eq!(r["layer"].as_u64(), Some(floor.0)); + assert!(surf(&s, floor).rgba(100, 100)[0] > 0.9, "{:?}", surf(&s, floor).rgba(100, 100)); + assert!(surf(&s, other).content_bounds().is_empty(), "the active layer stays untouched"); + s.undo(); + // A new layer goes right above the named layer. + let r = s.execute(VP, json!({"planes": planes, "clone": clone, "layer": floor.0, "newLayer": true})).unwrap(); + let d = &s.active().unwrap().doc; + let ids: Vec = d.layers.iter().map(|l| l.id.0).collect(); + let at = |id: u64| ids.iter().position(|&i| i == id).unwrap(); + assert_eq!(at(r["layer"].as_u64().unwrap()), at(floor.0) + 1, "{ids:?}"); + s.undo(); + let before = s.active().unwrap().doc.clone(); + assert!(s.execute(VP, json!({"planes": planes, "clone": clone, "layer": 999_999})).is_err()); + assert!(s.execute(VP, json!({"planes": planes, "clone": clone, "layer": 999_999, "newLayer": true})).is_err()); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7a3d27e66a..3072eaa11c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1423,6 +1423,9 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Ar if let Some(shown) = crate::type_font_preview::display_doc(app, idx) { return shown; } + // Vanishing Point's strokes over the document as it is now (the Layers panel may have + // changed it since the options bar synced them this frame). + crate::vp_ui::sync_preview(app); // Puppet / Perspective Warp previews hide the layer they draw on a mesh. if let Some(shown) = crate::distort_ui::display_doc(app, idx) { return shown; diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rs index cd0b41512b..3a5c765da6 100644 --- a/crates/ui-egui/src/distort_ui.rs +++ b/crates/ui-egui/src/distort_ui.rs @@ -144,7 +144,7 @@ pub fn display_doc(app: &PhotocraftApp, idx: usize) -> Option<(Arc, u6 if app.session.active_index() != Some(idx) { return None; } - let id = app.session.documents().get(idx).map(|st| st.doc.id)?; + let (id, revision) = app.session.documents().get(idx).map(|st| (st.doc.id, st.revision))?; if let Some(p) = &app.distort.puppet && p.document == id { @@ -155,8 +155,8 @@ pub fn display_doc(app: &PhotocraftApp, idx: usize) -> Option<(Arc, u6 { return Some((p.preview_doc.clone(), (1 << 42) + p.key)); } - // Vanishing Point: the clone strokes painted so far. - app.distort.vanishing.as_ref().and_then(crate::vp_ui::VpSession::shown) + // Vanishing Point: the clone strokes painted so far, on the document as they were painted. + app.distort.vanishing.as_ref().and_then(|v| v.shown_on(id, revision)) } /// Menu / control routing. `Some` when this module handles the invocation. diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rs index fc4476dca3..d93cc9dc20 100644 --- a/crates/ui-egui/src/vp_ui.rs +++ b/crates/ui-egui/src/vp_ui.rs @@ -532,7 +532,10 @@ impl VpSession { let mut area = Rect::EMPTY; let mut baked = false; if stale { - let Some(layer) = self.base.layer(self.layer).and_then(Layer::surface) else { return false }; + let Some(layer) = self.base.layer(self.layer).and_then(Layer::surface) else { + // The layer is gone (or no longer pixels): nothing to show the strokes on. + return self.preview.take().is_some(); + }; let mut out = if self.new_layer { Surface::new(layer.format()) } else { layer.clone() }; // OK pastes first and the strokes then paint over (and sample) the pasted pixels. if let (Some((i, at, width)), Some(c)) = (paste, self.clip.as_ref()) @@ -617,6 +620,31 @@ impl VpSession { Some((p.shown.clone(), PREVIEW_KEY + p.keys.last()?.0)) } + /// [`Self::shown`], only on the document at the revision the strokes were painted on. + pub(crate) fn shown_on(&self, doc: DocId, revision: u64) -> Option<(Arc, u64)> { + if self.document != doc || self.doc_revision != revision { + return None; + } + self.shown() + } + + /// The document changed under the mode (a menu command, the Layers panel): paint the + /// strokes over it as it is now, as OK will. + fn rebase(&mut self, doc: &Arc, revision: u64) { + if doc.id != self.document || revision == self.doc_revision { + return; + } + if Arc::ptr_eq(doc, &self.base) { + // A view change (layer selection, channel view): the same pixels, keep the preview. + self.doc_revision = revision; + return; + } + self.base = doc.clone(); + self.doc_revision = revision; + self.canvas = doc.bounds(); + self.preview = None; + } + /// Image positions of the edge nodes of plane `i`. fn edge_nodes(&self, i: usize) -> Option<[[f64; 2]; 4]> { let h = self.planes.get(i)?.homography()?; @@ -827,7 +855,15 @@ pub fn commit(app: &mut PhotocraftApp) -> Result { app.ui.status = msg.into(); return Err(msg.into()); } - let params = s.params(); + let mut params = s.params(); + // The layer the mode was opened on, when another one was picked meanwhile (the mode isn't + // modal). Left out otherwise, so a recorded action stays portable. + if let Some(st) = app.session.active() + && st.active_layer != Some(s.layer) + && st.doc.layer(s.layer).is_some() + { + params["layer"] = json!(s.layer.0); + } let session = app.distort.vanishing.take(); if params.get("paste").is_none() && params.get("clone").is_none() { return Ok(json!({"committed": false})); @@ -963,6 +999,9 @@ fn parse_planes(v: &Value) -> Result<(Vec, Vec>), String> /// changed, once no plane is being dragged). pub(crate) fn sync_preview(app: &mut PhotocraftApp) { let Some(s) = app.distort.vanishing.as_mut() else { return }; + if let Some(st) = app.session.active() { + s.rebase(&st.doc, st.revision); + } if matches!(s.drag, Some(Drag::Corner { .. } | Drag::Edge { .. } | Drag::Torn { .. } | Drag::Paste { .. })) { return; } @@ -1571,4 +1610,105 @@ mod tests { assert!(app.distort.vanishing.as_ref().unwrap().planes.is_empty()); assert!(crate::distort_ui::display_doc(&app, 0).is_none(), "no strokes shown without a plane"); } + + /// Opens the mode on the active layer of `app_with_layer` and stamps one stroke. + fn stamp_a_stroke(app: &mut PhotocraftApp, ctx: &egui::Context) { + crate::distort_ui::menu(app, ctx, VP, &json!({})).unwrap().unwrap(); + control(app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + control(app, &json!({"clone": [{"source": [60, 80], "points": [[120, 80], [126, 80]], "size": 12}]})).unwrap(); + } + + #[test] + fn stamp_preview_is_not_shown_on_another_document() { + let (ctx, mut app) = app_with_layer(); + stamp_a_stroke(&mut app, &ctx); + assert!(crate::distort_ui::display_doc(&app, 0).is_some()); + app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); + let active = app.session.active_index().unwrap(); + // The session stays until drop_foreign; the preview must not follow this document (#5115). + assert!(app.distort.vanishing.is_some()); + assert!(crate::distort_ui::display_doc(&app, active).is_none()); + } + + #[test] + fn ok_paints_the_layer_the_mode_was_opened_on() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session + .edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 70, 70, 90), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + stamp_a_stroke(&mut app, &ctx); + app.distort.vanishing.as_mut().unwrap().new_layer = new_layer; + sync_preview(&mut app); + // Another layer is picked while the mode is open (it isn't modal). + app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); + let other = app.session.active().unwrap().active_layer.unwrap(); + sync_preview(&mut app); + let expected = photocraft_compose::flatten(&crate::distort_ui::display_doc(&app, 0).unwrap().0).px; + commit(&mut app).unwrap(); + let d = &app.session.active().unwrap().doc; + assert!(d.layer(other).unwrap().surface().unwrap().content_bounds().is_empty(), "newLayer={new_layer}"); + if !new_layer { + assert!(d.layer(layer).unwrap().surface().unwrap().rgba(120, 80)[0] > 0.9, "the stroke lands on the session's layer"); + // And it becomes active, so Fade and a colour-channel target follow it. + assert_eq!(app.session.active().unwrap().active_layer, Some(layer)); + } + assert_eq!(photocraft_compose::flatten(d).px, expected, "newLayer={new_layer}"); + } + } + + #[test] + fn an_edit_under_the_mode_shows_on_the_canvas() { + let (ctx, mut app) = app_with_layer(); + app.session + .edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 70, 70, 90), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + stamp_a_stroke(&mut app, &ctx); + let before = crate::distort_ui::display_doc(&app, 0).unwrap(); + app.session + .edit("edit", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(200, 20, 220, 40), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + // Not the stale preview, even before the mode catches up. + assert!(crate::distort_ui::display_doc(&app, 0).is_none_or(|(d, _)| !Arc::ptr_eq(&d, &before.0))); + // The canvas catches up before it draws: the strokes over the edit, no frame without them. + let (shown, key) = crate::canvas::display_doc(&mut app, 0); + assert_ne!(key, before.1); + let st = app.session.active().unwrap(); + let layer = st.active_layer.unwrap(); + let px = shown.layer(layer).unwrap().surface().unwrap(); + assert!(px.rgba(210, 30)[1] > 0.9, "the edit shows: {:?}", px.rgba(210, 30)); + assert!(px.rgba(120, 80) != st.doc.layer(layer).unwrap().surface().unwrap().rgba(120, 80), "and so does the stroke"); + let expected = photocraft_compose::flatten(&shown).px; + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected); + } + + #[test] + fn selecting_another_layer_keeps_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); + app.session.execute("layer.select", json!({"layer": layer.0})).unwrap(); + app.sync_views(); + stamp_a_stroke(&mut app, &ctx); + let before = crate::canvas::display_doc(&mut app, 0); + let (doc, revision) = app.session.active().map(|st| (st.doc.clone(), st.revision)).unwrap(); + app.session.execute("layer.select", json!({"layer": "other"})).unwrap(); + let st = app.session.active().unwrap(); + assert!(st.revision != revision && Arc::ptr_eq(&st.doc, &doc), "a selection change leaves the pixels alone"); + // Same preview, same key: nothing to repaint or recomposite. + let after = crate::canvas::display_doc(&mut app, 0); + assert!(Arc::ptr_eq(&after.0, &before.0)); + assert_eq!(after.1, before.1); + } }