Merge #16655 into the merge queue batch

Warp: remove the split line at the picked anchor
This commit is contained in:
David Mann committed 2026-11-24 18:46:09 +01:00
commit 01459afbd7
6 files changed
+329 -21

No files matched your search

+47 -17
View File
@@ -524,6 +524,10 @@ fn commit_default_sections(mesh: &mut BezierMesh, how: Split) {
/// Applies a split (or removes the split nearest `at`) on `w`'s mesh (presets become custom).
pub fn split_warp(w: &Warp, at: Option<[f64; 2]>, how: Split) -> Option<Warp> {
split_warp_inner(w, at, how, None)
}
fn split_warp_inner(w: &Warp, at: Option<[f64; 2]>, how: Split, picked_anchor: Option<usize>) -> Option<Warp> {
let mut mesh = w.to_mesh(1, 1);
if !matches!(how, Split::Remove) && w.style == WarpStyle::Custom && mesh.us.len() == 2 && mesh.vs.len() == 2 {
commit_default_sections(&mut mesh, how);
@@ -547,18 +551,7 @@ pub fn split_warp(w: &Warp, at: Option<[f64; 2]>, how: Split) -> Option<Warp> {
// A horizontal split line divides rows; a vertical one divides columns.
Split::Horizontal => mesh.split_v(t),
Split::Vertical => mesh.split_u(s),
Split::Remove => {
let near = |k: &[f64], v: f64| (1..k.len() - 1).min_by(|a, b| (k[*a] - v).abs().total_cmp(&(k[*b] - v).abs()));
let (iu, iv) = (near(&mesh.us, s), near(&mesh.vs, t));
let du = iu.map_or(f64::MAX, |i| (mesh.us[i] - s).abs());
let dv = iv.map_or(f64::MAX, |i| (mesh.vs[i] - t).abs());
match (iu, iv) {
(Some(i), _) if du <= dv => mesh.remove_split_u(i),
(_, Some(i)) => mesh.remove_split_v(i),
(Some(i), None) => mesh.remove_split_u(i),
_ => false,
}
}
Split::Remove => remove_split(&mut mesh, s, t, if at.is_none() { picked_anchor } else { None }),
};
if ok && matches!(how, Split::Remove) {
restore_default_grid(&mut mesh);
@@ -566,6 +559,42 @@ pub fn split_warp(w: &Warp, at: Option<[f64; 2]>, how: Split) -> Option<Warp> {
ok.then(|| Warp::custom(mesh, w.bounds))
}
fn remove_split(mesh: &mut BezierMesh, s: f64, t: f64, picked: Option<usize>) -> bool {
// Use the anchor's knot directly. Inverting a deformed mesh can land in a different patch.
if let Some(index) = picked.filter(|&i| i < mesh.points.len()) {
let (nx, ny) = (mesh.nx(), mesh.ny());
let (x, y) = (index % nx, index / nx);
if x.is_multiple_of(3) && y.is_multiple_of(3) {
let vertical = x > 0 && x < nx - 1;
let horizontal = y > 0 && y < ny - 1;
// A one-way split on the Default grid materializes the perpendicular thirds.
// Its inner anchors still identify only the added line.
if vertical && (!horizontal || mesh.us.len() == 3 && is_default_thirds(&mesh.vs)) {
return mesh.remove_split_u(x / 3);
}
if horizontal && (!vertical || mesh.vs.len() == 3 && is_default_thirds(&mesh.us)) {
return mesh.remove_split_v(y / 3);
}
}
}
let near = |k: &[f64], v: f64| (1..k.len() - 1).min_by(|a, b| (k[*a] - v).abs().total_cmp(&(k[*b] - v).abs()));
let (iu, iv) = (near(&mesh.us, s), near(&mesh.vs, t));
let du = iu.map_or(f64::MAX, |i| (mesh.us[i] - s).abs());
let dv = iv.map_or(f64::MAX, |i| (mesh.vs[i] - t).abs());
match (iu, iv) {
(Some(i), _) if du <= dv => mesh.remove_split_u(i),
(_, Some(i)) => mesh.remove_split_v(i),
(Some(i), None) => mesh.remove_split_u(i),
_ => false,
}
}
fn is_default_thirds(knots: &[f64]) -> bool {
const THIRDS: [f64; 4] = [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0];
knots.len() == THIRDS.len() && knots.iter().zip(THIRDS).all(|(a, b)| (a - b).abs() < 1e-9)
}
/// After a split is removed: when what is left is the Default grid's thirds that a one-way split
/// made real (`commit_default_sections`) and nothing else, merge them back into the Default grid's
/// one patch, which draws them as guides again (#12912). Only when that loses nothing: splitting
@@ -574,10 +603,8 @@ pub fn split_warp(w: &Warp, at: Option<[f64; 2]>, how: Split) -> Option<Warp> {
/// sections came from, so a straight 3 x 1 (or 1 x 3) grid at exactly the thirds made another way
/// merges too; nothing is lost, as the Default grid draws the same lines as guides.
fn restore_default_grid(mesh: &mut BezierMesh) {
const THIRDS: [f64; 4] = [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0];
let is = |k: &[f64], want: &[f64]| k.len() == want.len() && k.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9);
let columns = is(&mesh.us, &THIRDS) && is(&mesh.vs, &[0.0, 1.0]);
let rows = is(&mesh.vs, &THIRDS) && is(&mesh.us, &[0.0, 1.0]);
let columns = is_default_thirds(&mesh.us) && mesh.vs == [0.0, 1.0];
let rows = is_default_thirds(&mesh.vs) && mesh.us == [0.0, 1.0];
if !(columns || rows) {
return;
}
@@ -615,7 +642,10 @@ fn inline_warp(cmd: &str, p: &Value) -> Result<Option<Warp>> {
fn split(s: &mut Session, p: &Value, cmd: &str, how: Split) -> Result<Value> {
let at = p.get("at").and_then(Value::as_array).and_then(|a| Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?]));
if let Some(w) = inline_warp(cmd, p)? {
let out = split_warp(&w, at, how).ok_or_else(|| bad(cmd, "nothing to split or remove there"))?;
// Only the canvas's inline warp uses a grid pick. Commands on a stored smart object
// continue to take document coordinates.
let picked = p.get("_pickedAnchor").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
let out = split_warp_inner(&w, at, how, picked).ok_or_else(|| bad(cmd, "nothing to split or remove there"))?;
return Ok(json!({"warp": out}));
}
// The active smart object's stored warp.
@@ -123,6 +123,7 @@ pub struct OpenPreview {
/// The armed split tool of the Warp phase, one-shot (#12498). Hover, placing and the quick split are the
/// warp grid's.
split: Option<WarpSplit>,
warp_grid: warp::GridSelection,
/// The tool the session began with: picking another one applies the transform.
tool: Tool,
/// Free Transform Path: the path as it was, drawn through the box instead of pixels.
@@ -155,6 +156,7 @@ impl OpenPreview {
above: None,
styled: None,
split: None,
warp_grid: warp::GridSelection::default(),
tool,
path: None,
follow: None,
@@ -11,7 +11,7 @@ use craft::imaging::ui::selection::PointMap;
use craft::imaging::ui::transform_preview::{PreviewDisplay, PreviewMap, TransformPreview};
use craft::imaging::ui::warp::{CylinderValues, CylinderWarp, WarpEdit, WarpGrid, WarpMesh};
use craft::ui::canvas::RasterDisplay;
use craft::ui::contract::{Bind, Show as _};
use craft::ui::contract::{Bind, Props as _, Show as _};
use craft::ui::primitives::PaintSlot;
use photocraft_doc::DocId;
use photocraft_geom::warp::WarpStyle;
@@ -36,6 +36,7 @@ struct Shown {
discard: bool,
/// The warp grid's events and whether it placed a split this pass.
mesh: Option<(EditEvents<WarpMesh>, bool)>,
picked: Option<usize>,
cylinder: Option<EditEvents<CylinderValues>>,
/// A warp control has the pointer button down on it.
busy: bool,
@@ -57,11 +58,17 @@ struct Shown {
/// transform controls share its id and must not open a second box in the same pass), and the box's snap lines, which
/// the session's canvas tool hands to the host in this frame's pass ([`super::canvas_tool`]).
pub fn show_in_canvas(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: egui::Rect, now: f64) -> SessionShown {
if let Some(pv) = app.transform_preview.as_mut() {
pv.warp_grid.sync(app.ui.transform.as_ref().and_then(|t| t.session.warp()));
}
let shown = {
let (Some(t), Some(pv)) = (&app.ui.transform, &app.transform_preview) else { return SessionShown::default() };
show_session(app, t, pv, ui, rect)
};
let Shown { edits, snapped, apply, discard, mesh, cylinder, busy, picture } = shown;
let Shown { edits, snapped, apply, discard, mesh, picked, cylinder, busy, picture } = shown;
if let Some(pv) = app.transform_preview.as_mut() {
pv.warp_grid.picked = picked;
}
let mut need_warp = false;
if let Some(t) = app.ui.transform.as_mut() {
for edit in edits.iter().cloned() {
@@ -225,7 +232,7 @@ fn show_warp(t: &FreeTransform, pv: &OpenPreview, w: &SessionWarp, ui: &mut egui
let preset = one_patch && !matches!(w.warp.style, WarpStyle::None | WarpStyle::Custom);
// No splits on type (#3004).
let split = pv.split.filter(|_| !w.on_type);
let mut grid = WarpGrid::new("Warp grid", Bind::given(w.mesh.clone()), t.session.rect());
let mut grid = WarpGrid::new("Warp grid", Bind::given(w.mesh.clone()), t.session.rect()).id_salt((pv.session, pv.warp_grid.generation));
if preset {
grid = grid.preset();
}
@@ -237,6 +244,7 @@ fn show_warp(t: &FreeTransform, pv: &OpenPreview, w: &SessionWarp, ui: &mut egui
}
let shown = grid.show_at(ui, rect);
out.busy |= gesture_open(&shown.mesh.events);
out.picked = shown.picked;
out.mesh = Some((shown.mesh.events, matches!(shown.edit, Some(WarpEdit::Split { .. }))));
}
@@ -2215,3 +2215,6 @@ fn an_unskewed_box_shows_its_horizontal_skew_as_zero() {
h.run_steps(2);
assert_eq!(h.get_by_label("Horizontal skew").value().as_deref(), Some("0"));
}
#[path = "warp_remove_split_tests.rs"]
mod warp_remove_split_tests;
@@ -6,6 +6,42 @@ use super::begin::warps_type;
use super::{BezierMesh, PhotocraftApp, Warp, WarpStyle, json};
use crate::state::SessionWarp;
/// Keeps the widget's point index tied to the knot layout it was picked on.
#[derive(Default)]
pub(super) struct GridSelection {
knots: Option<(Vec<f64>, Vec<f64>)>,
/// Gives the grid fresh widget memory when the old point indices no longer apply.
pub(super) generation: u64,
pub(super) picked: Option<usize>,
}
impl GridSelection {
fn layout(warp: &SessionWarp) -> Option<(&[f64], &[f64])> {
(!warp.on_type && warp.warp.style != WarpStyle::Cylinder).then_some((warp.mesh.us.as_slice(), warp.mesh.vs.as_slice()))
}
fn knots(&self) -> Option<(&[f64], &[f64])> {
self.knots.as_ref().map(|(us, vs)| (us.as_slice(), vs.as_slice()))
}
pub(super) fn sync(&mut self, warp: Option<&SessionWarp>) {
let layout = warp.and_then(Self::layout);
if self.knots() != layout {
self.knots = layout.map(|(us, vs)| (us.to_vec(), vs.to_vec()));
self.generation += 1;
self.picked = None;
}
}
fn picked(&self, warp: &SessionWarp) -> Option<usize> {
// A menu or control request can arrive before the next canvas pass.
if self.knots() != Self::layout(warp) {
return None;
}
self.picked
}
}
/// Gives the session `warp` as its new warp (one `TransformEdit::Warp`), keeping whether it is on
/// a type layer. The one place the warp glue writes the session's warp.
pub(super) fn set_warp(app: &mut PhotocraftApp, warp: Warp) {
@@ -13,6 +49,9 @@ pub(super) fn set_warp(app: &mut PhotocraftApp, warp: Warp) {
let on_type = app.ui.transform.as_ref().and_then(|t| t.session.warp()).map_or_else(|| warps_type(app), |w| w.on_type);
if let Some(t) = app.ui.transform.as_mut() {
t.session.apply(TransformEdit::Warp(SessionWarp::new(warp, on_type)), now);
if let Some(pv) = app.transform_preview.as_mut() {
pv.warp_grid.sync(t.session.warp());
}
}
}
@@ -82,12 +121,18 @@ pub fn edit_session_warp(app: &mut PhotocraftApp, id: &str, params: &serde_json:
Ok(())
}
/// Applies a split-warp command to the mesh being edited (at the box centre unless `at`).
/// Applies a split-warp command to the mesh being edited. Remove can use the grid's picked point
/// when no explicit `at` is supplied.
// PLAN: sheet note 8 says a split without `at` arms `pv.split`; the base splits at the box centre and the menu's callers rely on it, and tools-w27 does not name the command-to-`WarpSplit` function arming would need, so this keeps the base rule.
pub fn split(app: &mut PhotocraftApp, id: &str, at: Option<[f64; 2]>) -> Result<(), String> {
let mut p = json!({});
if let Some(a) = at {
p["at"] = json!(a);
} else if id == "edit.transform.removeWarpSplit"
&& let (Some(pv), Some(warp)) = (&app.transform_preview, app.ui.transform.as_ref().and_then(|t| t.session.warp()))
&& let Some(picked) = pv.warp_grid.picked(warp)
{
p["_pickedAnchor"] = json!(picked);
}
edit_session_warp(app, id, &p)
}
@@ -0,0 +1,220 @@
use super::*;
use crate::canvas::document_display::active_view;
use crate::control::{ControlRequest, Reply, handle};
use photocraft_engine::warp_cmds::{Split, split_warp};
const REMOVE: &str = "edit.transform.removeWarpSplit";
fn invoke(h: &mut Harness, command: &str, params: serde_json::Value) {
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, command, params).unwrap();
}
fn pick(h: &mut Harness, column: usize, row: usize) {
let anchor = session_warp(h.state()).mesh.point(3 * column, 3 * row);
let p = active_view(h.state()).unwrap().to_screen(anchor);
h.hover_at(p);
h.run_steps(1);
h.drag_at(p);
h.run_steps(1);
h.drop_at(p);
h.run_steps(2);
}
fn warp_harness() -> Harness {
let mut app = app_with_square(640, photocraft_geom::Rect::new(80, 80, 560, 560));
let ctx = app.ctx().clone();
begin_warp(&mut app, &ctx).unwrap();
harness(app, egui::vec2(1400.0, 900.0))
}
fn grid(h: &mut Harness, size: usize) {
invoke(h, "edit.transform.warpGrid", json!({"size": size}));
h.run_steps(3);
}
#[test]
fn removing_a_warp_split_uses_the_picked_line() {
let mut h = warp_harness();
grid(&mut h, 3);
let before = session_warp(h.state()).mesh.clone();
pick(&mut h, 1, 0);
invoke(&mut h, REMOVE, json!({}));
let after = &session_warp(h.state()).mesh;
assert!(!after.us.contains(&before.us[1]), "the picked vertical line remains: {:?}", after.us);
assert!(after.us.contains(&before.us[2]));
assert_eq!(after.vs, before.vs);
}
#[test]
fn picked_horizontal_split_is_one_undoable_warp_edit() {
let mut h = warp_harness();
grid(&mut h, 3);
let mut mesh = warp_mesh(h.state());
for point in [0, 1, mesh.width()] {
mesh.points[point].x -= 16.0;
}
pull_mesh(h.state_mut(), 1, mesh);
h.run_steps(3);
let before = session_warp(h.state()).warp.clone();
let history = h.state().session.active().unwrap().history.past_len();
pick(&mut h, 0, 1);
invoke(&mut h, REMOVE, json!({}));
let after = session_warp(h.state()).warp.clone();
let (before_mesh, after_mesh) = (before.mesh.as_ref().unwrap(), after.mesh.as_ref().unwrap());
assert_eq!(after_mesh.us, before_mesh.us);
assert!(!after_mesh.vs.contains(&before_mesh.vs[1]));
assert!(after_mesh.vs.contains(&before_mesh.vs[2]));
assert_eq!(h.state().session.active().unwrap().history.past_len(), history, "the removal is still a preview");
invoke(&mut h, "edit.undo", json!({}));
assert_eq!(session_warp(h.state()).warp, before);
invoke(&mut h, "edit.redo", json!({}));
assert_eq!(session_warp(h.state()).warp, after);
commit(h.state_mut());
assert_eq!(h.state().session.active().unwrap().history.past_len(), history + 1, "the whole warp commits in one step");
}
#[test]
fn picking_the_only_added_split_restores_the_default_grid() {
for (command, column, row) in [("edit.transform.splitWarpHorizontally", 0, 1), ("edit.transform.splitWarpVertically", 1, 0)] {
let mut h = warp_harness();
invoke(&mut h, command, json!({"at": [248, 248]}));
h.run_steps(3);
pick(&mut h, column, row);
invoke(&mut h, REMOVE, json!({}));
let warp = session_warp(h.state());
assert_eq!((warp.mesh.columns(), warp.mesh.rows()), (1, 1), "{command} put back the guide-only grid");
assert!(warp.warp.is_identity());
}
}
fn assert_inner_anchors_restore_default(command: &str, anchors: [(usize, usize); 2]) {
for (column, row) in anchors {
let mut h = warp_harness();
invoke(&mut h, command, json!({"at": [320, 320]}));
h.run_steps(3);
pick(&mut h, column, row);
invoke(&mut h, REMOVE, json!({}));
let warp = session_warp(h.state());
assert_eq!((warp.mesh.columns(), warp.mesh.rows()), (1, 1), "{command} at ({column}, {row}) restores the Default grid");
assert!(warp.warp.is_identity());
}
}
#[test]
fn inner_anchors_remove_the_only_horizontal_split() {
assert_inner_anchors_restore_default("edit.transform.splitWarpHorizontally", [(1, 1), (2, 1)]);
}
#[test]
fn inner_anchors_remove_the_only_vertical_split() {
assert_inner_anchors_restore_default("edit.transform.splitWarpVertically", [(1, 1), (1, 2)]);
}
#[test]
fn an_explicit_control_channel_point_takes_precedence_over_the_pick() {
let mut h = warp_harness();
grid(&mut h, 3);
pick(&mut h, 1, 0);
let before = warp_mesh(h.state());
let target = before.point(0, 6);
let (req, _) = ControlRequest::new("ui.menu.invoke", json!({"command": REMOVE, "params": {"at": [target.x, target.y]}}));
let ctx = h.ctx.clone();
assert!(matches!(handle(h.state_mut(), &ctx, &req), Reply::Done(v) if v["ok"] == true));
let after = &session_warp(h.state()).mesh;
assert_eq!(after.us, before.us);
assert!(!after.vs.contains(&before.vs[2]));
assert!(after.vs.contains(&before.vs[1]));
}
fn assert_uses_center(h: &mut Harness) {
let expected = split_warp(&session_warp(h.state()).warp, None, Split::Remove).unwrap();
invoke(h, REMOVE, json!({}));
assert_eq!(session_warp(h.state()).warp, expected);
}
#[test]
fn a_crossing_or_an_unpicked_grid_uses_the_center() {
let mut h = warp_harness();
grid(&mut h, 3);
pick(&mut h, 1, 1);
assert_uses_center(&mut h);
invoke(&mut h, "edit.undo", json!({}));
h.run_steps(2);
assert_uses_center(&mut h);
}
#[test]
fn a_crossing_of_two_added_splits_uses_the_center() {
let mut h = warp_harness();
invoke(&mut h, "edit.transform.splitWarpHorizontally", json!({"at": [320, 320]}));
invoke(&mut h, "edit.transform.splitWarpVertically", json!({"at": [344, 320]}));
h.run_steps(3);
pick(&mut h, 2, 1);
assert_uses_center(&mut h);
}
#[test]
fn a_pick_on_the_old_grid_is_cleared_when_the_grid_changes() {
let mut h = warp_harness();
grid(&mut h, 4);
pick(&mut h, 1, 0);
// The picked index also names a vertical anchor on the new grid. It must not be reused.
grid(&mut h, 3);
assert_uses_center(&mut h);
}
#[test]
fn paging_to_a_warp_point_can_select_its_split() {
let mut h = warp_harness();
grid(&mut h, 3);
pick(&mut h, 0, 0);
let before = warp_mesh(h.state());
for _ in 0..=before.handles(0).len() {
h.key_press(egui::Key::PageDown);
h.run_steps(1);
}
invoke(&mut h, REMOVE, json!({}));
let after = &session_warp(h.state()).mesh;
assert!(!after.us.contains(&before.us[1]), "the line reached with Page Down was removed");
assert_eq!(after.vs, before.vs);
}
#[test]
fn the_picked_line_keeps_its_identity_on_a_folded_mesh() {
let mut h = warp_harness();
let bounds = session_warp(h.state()).warp.bounds;
let mesh = BezierMesh::fit(
&|s, t| {
// The first interior anchor projects onto a point on the far patch.
let x = if s <= 0.28 {
0.75 * s / 0.28
} else if s <= 0.7 {
0.75 - 0.35 * (s - 0.28) / (0.7 - 0.28)
} else {
0.4 + 0.6 * (s - 0.7) / (1.0 - 0.7)
};
[bounds[0] + x * (bounds[2] - bounds[0]), bounds[1] + t * (bounds[3] - bounds[1])]
},
vec![0.0, 0.28, 0.7, 1.0],
vec![0.0, 1.0],
);
let anchor = mesh.points[3];
let warp = Warp::custom(mesh, bounds);
let hit = split_warp(&warp, Some(anchor), Split::Remove).unwrap().mesh.unwrap();
assert!(hit.us.contains(&0.28), "the document point alone found the other line");
set_warp(h.state_mut(), warp);
h.run_steps(3);
pick(&mut h, 1, 0);
invoke(&mut h, REMOVE, json!({}));
assert!(!session_warp(h.state()).mesh.us.contains(&0.28));
assert!(session_warp(h.state()).mesh.us.contains(&0.7));
}