Merge pull request #10960 from dotCooCoo/fix/anchor-marks-move-translate

Canvas: a drag moves the kept anchor marks mesh instead of tessellating it
This commit is contained in:
.CooCoo
2026-12-05 14:37:17 -08:00
committed by GitHub
2 changed files with 265 additions and 4 deletions
+103 -4
View File
@@ -688,6 +688,89 @@ struct MeshKey {
pub(crate) struct KeptMesh {
key: MeshKey,
mesh: Arc<egui::Mesh>,
/// How far the marks moved on screen since they were tessellated, in physical pixels, unrounded
/// ([`KeptMesh::translate`]). The mesh moved by this distance rounded.
moved: [f64; 2],
}
/// How far from a whole number of physical pixels the marks' move since they were tessellated may be on screen, and
/// still count as whole: rounding noise of the screen position, well under what the tessellator's `f32` positions hold.
const PIXEL_SLACK: f64 = 1e-6;
impl KeptMesh {
/// Moves the mesh by `by` in the document when tessellating the moved marks would give the same mesh moved, and
/// returns whether it did. `points` are the marks' anchors and direction handles before the move ([`knot_points`]),
/// and `options` the Path Options they are drawn with. The mesh moves when the marks' whole move since they were
/// tessellated is a whole number of physical pixels on screen, and when every point's `f32` screen position moves
/// by this move's whole pixels too. Every square [`mark_shapes`] could draw at a point, at the anchor side and at
/// the handle side, must keep its `f32` size and have each edge round to pixels as the tessellator rounds it, moved
/// by the same whole pixels; a square thin enough for the tessellator to draw as a line is tessellated again. It
/// also needs every point inside the canvas before and after the move, so the marks are drawn near and inside the
/// clip on both sides and no anchor, handle or outline is left out or culled.
fn translate(&mut self, by: Vec2, points: impl IntoIterator<Item = Point>, options: &PathOptionsSettings) -> bool {
let key = &self.key;
let ppp = f64::from(key.pixels_per_point);
let view = key.view.affine();
let shift = (view * (Point::ZERO + by)) - (view * Point::ZERO);
let moved = [self.moved[0] + shift.x * ppp, self.moved[1] + shift.y * ppp];
if moved.iter().any(|p| !p.is_finite() || (p - p.round()).abs() > PIXEL_SLACK) {
return false;
}
// This move in whole physical pixels.
let pixels = [moved[0].round() - self.moved[0].round(), moved[1].round() - self.moved[1].round()];
let area = key.rect.expand(key.look.reach).intersect(key.clip);
// `CanvasView::to_screen` with the affine computed once.
let screen = |p: Point| {
let s = view * p;
egui::pos2(s.x as f32, s.y as f32)
};
let whole = |from: f32, to: f32, px: f64| ((f64::from(to) - f64::from(from)) * ppp - px).abs() <= PIXEL_SLACK;
// The tessellator's `f32` rounding of an edge to pixels (`GuiRounding::round_to_pixels`), in whole pixels.
let ppp_f32 = key.pixels_per_point;
let snapped = |edge: f32| f64::from((edge * ppp_f32).round());
let lands = |from: f32, to: f32, px: f64| snapped(to) - snapped(from) == px;
let sides = mark_sides(options, &key.look);
// Below this side the tessellator draws a filled square as a line, which it rounds other ways.
let feathering = if key.options.feathering { key.options.feathering_size_in_pixels / ppp_f32 } else { 0.0 };
if sides.iter().any(|side| *side <= 2.0 * feathering) {
return false;
}
for p in points {
let (from, to) = (screen(p), screen(p + by));
if !(area.contains(from) && area.contains(to) && whole(from.x, to.x, pixels[0]) && whole(from.y, to.y, pixels[1])) {
return false;
}
for side in sides {
let (a, b) = (Rect::from_center_size(from, egui::Vec2::splat(side)), Rect::from_center_size(to, egui::Vec2::splat(side)));
// The tessellator tests the built square's `f32` width and height, which can come out below `side`.
if a.size() != b.size()
|| [a, b].iter().any(|r| r.width() <= 2.0 * feathering || r.height() <= 2.0 * feathering)
|| !(lands(a.min.x, b.min.x, pixels[0])
&& lands(a.max.x, b.max.x, pixels[0])
&& lands(a.min.y, b.min.y, pixels[1])
&& lands(a.max.y, b.max.y, pixels[1]))
{
return false;
}
}
}
let offset = vec2((pixels[0] / ppp) as f32, (pixels[1] / ppp) as f32);
self.moved = moved;
Arc::make_mut(&mut self.mesh).translate(offset);
true
}
}
/// Every anchor and direction handle of `anchors`, in document units. The outlines lie inside the hull of these
/// points, as a curve lies inside the hull of its points.
fn knot_points(anchors: &Anchors) -> impl Iterator<Item = Point> + '_ {
anchors
.paths
.iter()
.chain(&anchors.plain)
.flat_map(|p| &p.subpaths)
.flat_map(|sp| &sp.knots)
.flat_map(|knot| [knot.anchor, knot.in_ctrl, knot.out_ctrl])
}
/// One set of anchors as `BezierOverlay` took it: the paths, which anchors are selected and how they show.
@@ -809,7 +892,7 @@ impl Component for AnchorMarks<'_> {
None => {
let shapes = shapes();
let mesh = Arc::new(tessellate(shapes, &key));
*kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh) });
*kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh), moved: [0.0; 2] });
mesh
}
};
@@ -864,14 +947,20 @@ enum MarkFill {
Path,
}
/// The side of an anchor's mark, then of a direction handle's end, under `options`.
fn mark_sides(options: &PathOptionsSettings, look: &MarkLook) -> [f32; 2] {
let anchor = options.anchor_size.unwrap_or(look.anchor);
let handle = if options.handles == HandleStyle::Large { look.large } else { look.anchor };
[anchor, handle]
}
/// The egui shapes `BezierOverlay` paints for `set` under `BezierTool::Anchors`, in its order: every outline, the
/// selected segment, then the anchors and handles near `rect`, then the handles of the other paths' selected anchors.
fn mark_shapes(out: &mut Vec<Shape>, set: &MarkSet<'_>, view: &CanvasView, rect: Rect, look: &MarkLook) {
let options = set.options;
let option_color = options.color.map(|[r, g, b]| Color32::from(Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0)));
let path_color = |path: &EditPath| path.color.map(Color32::from);
let anchor_side = options.anchor_size.unwrap_or(look.anchor);
let handle_side = if options.handles == HandleStyle::Large { look.large } else { look.anchor };
let [anchor_side, handle_side] = mark_sides(options, look);
let circles = set.shown == AnchorsShown::Curvature;
let line = |out: &mut Vec<Shape>, points: Vec<egui::Pos2>, closed: bool, segment: bool, color: Option<Color32>| {
let named = if segment { look.thick } else { look.medium };
@@ -1198,12 +1287,22 @@ impl SelectionMarks {
self.from = (moved.from.clone(), moved.by);
self.doc = moved.to.clone();
}
// The kept mesh shows these marks, so it stays theirs under the new key.
let was = self.key;
if let Some(kept) = self.mesh.get_mut().as_mut().filter(|kept| kept.key.marks == was) {
kept.key.marks = key;
}
self.key = key;
Some(self)
}
/// Moves every mark by `by`.
/// Moves every mark by `by`, and the kept mesh of the anchor marks with them when it can move as it is
/// ([`KeptMesh::translate`]); otherwise the next paint tessellates the marks again.
fn translate(&mut self, by: Vec2) {
let mesh = self.mesh.get_mut();
if mesh.as_mut().is_some_and(|kept| !kept.translate(by, knot_points(&self.anchors), &self.anchors.options)) {
*mesh = None;
}
let shift = vectorcraft_geom::Affine::translate(by);
for o in &mut self.outlines {
o.paths.iter_mut().chain(o.key.as_mut()).for_each(|path| path.apply_affine(shift));
@@ -1283,3 +1283,165 @@ fn a_move_of_the_selection_moves_its_marks_without_building_them() {
assert_eq!(frames(&mut app, 3), 1, "an undo");
assert!(kept_marks_are_current(&app), "after an undo");
}
/// The mesh of the anchor marks the canvas keeps.
fn kept_mesh(app: &VectorcraftApp) -> Arc<egui::Mesh> {
let marks = app.canvas.selection_marks.as_ref().expect("the canvas drew the selection's marks");
let kept = marks.mesh.borrow();
Arc::clone(&kept.as_ref().expect("the canvas kept the anchor marks' mesh").mesh)
}
// A drag of the selection moves the kept mesh of its anchor marks instead of tessellating them again: steps of whole
// pixels tessellate nothing and leave the mesh a new tessellation gives, a new revision of the same marks keeps it, and
// a step of part of a pixel or one that takes the marks past the canvas's edge tessellates them once.
#[test]
fn a_drag_of_the_selection_moves_the_anchor_marks_mesh_without_tessellating_it() {
let (mut app, curve) = canvas_app();
app.select_tool("selection");
app.run("select.set", json!({"ids": [curve.0]})).unwrap();
let ctx = crate::testing::ui_context();
let frames = |app: &mut VectorcraftApp, n: usize| {
let before = MESHES_BUILT.with(std::cell::Cell::get);
for _ in 0..n {
canvas_frame(app, &ctx, vec![]);
}
MESHES_BUILT.with(std::cell::Cell::get) - before
};
assert_eq!(frames(&mut app, 2), 1, "the first frame tessellates the marks");
// A document distance that is `px` physical pixels across on screen.
let pixels = |app: &VectorcraftApp, px: f64| px / (app.canvas_view().unwrap().zoom * f64::from(ctx.pixels_per_point()));
let step = |app: &mut VectorcraftApp, dx: f64| {
app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, dx, 0], "copy": false})).unwrap();
};
let layer = app.session.active().unwrap().doc.layers[0].id;
app.run("layer.setCurrent", json!({"id": layer.0})).unwrap();
assert_eq!(frames(&mut app, 2), 0, "a new revision of the same document and selection");
// The kept mesh matches the one marks built now tessellate; the kept marks go back afterwards, so the drag
// goes on moving them.
let matches_new = |app: &mut VectorcraftApp, case: &str| {
let moved = kept_mesh(app);
let kept = app.canvas.selection_marks.take();
canvas_frame(app, &ctx, vec![]);
let fresh = kept_mesh(app);
app.canvas.selection_marks = kept;
assert!(!fresh.vertices.is_empty(), "{case}: the marks drew something");
assert_eq!(moved.indices, fresh.indices, "{case}: the moved mesh has the triangles of a new one");
assert_eq!(moved.vertices.len(), fresh.vertices.len(), "{case}");
for (a, b) in moved.vertices.iter().zip(&fresh.vertices) {
assert_eq!(a.color, b.color, "{case}");
assert!((a.pos - b.pos).length() < 1e-3, "{case}: a moved vertex at {:?}, a new one at {:?}", a.pos, b.pos);
}
};
app.session.begin_interaction("Move").unwrap();
let built = MARKS_BUILT.with(std::cell::Cell::get);
for px in [3.0, 10.0, -4.0] {
let dx = pixels(&app, px);
step(&mut app, dx);
assert_eq!(frames(&mut app, 2), 0, "a drag's step to {px} pixels");
}
assert_eq!(MARKS_BUILT.with(std::cell::Cell::get), built, "the drag moved the kept marks");
matches_new(&mut app, "after whole pixels");
let built = MARKS_BUILT.with(std::cell::Cell::get);
let dx = pixels(&app, -4.5);
step(&mut app, dx);
assert_eq!(frames(&mut app, 2), 1, "a step to part of a pixel");
let dx = pixels(&app, -3.5);
step(&mut app, dx);
assert_eq!(frames(&mut app, 2), 0, "a whole pixel from the marks tessellated at part of one");
assert_eq!(MARKS_BUILT.with(std::cell::Cell::get), built, "the drag moved the kept marks");
matches_new(&mut app, "after part of a pixel and a whole one");
// Whole pixels from the last step.
let dx = pixels(&app, 1996.5);
step(&mut app, dx);
assert_eq!(frames(&mut app, 2), 1, "a step past the canvas's edge");
app.session.commit_interaction().unwrap();
}
// A move of whole pixels keeps the mesh only when every point's `f32` screen position moves by those whole pixels:
// at x = 255.999991 the screen position before a one-pixel move is 255.99998 and after it 257.0, so the marks'
// squares would round to other pixels than the moved mesh's.
#[test]
fn a_whole_pixel_move_keeps_the_mesh_only_when_the_screen_positions_move_by_whole_pixels() {
let by = Vec2::new(1.0, 0.0);
let options = PathOptionsSettings::default();
assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(255.5, 10.0)], &options), "a point whose screen position moves one whole pixel");
let mut off = kept_at_one_pixel_per_point();
assert!(!off.translate(by, [Point::new(255.5, 10.0), Point::new(255.999_991, 10.0)], &options), "a point that moves 1.0000153 pixels");
assert_eq!(off.moved, [0.0; 2], "the refused move leaves the mesh where it was");
}
/// A kept mesh of no marks at one physical pixel per point, with the document's coordinates on screen unchanged.
fn kept_at_one_pixel_per_point() -> KeptMesh {
let screen = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(1000.0, 1000.0));
let look = MarkLook {
line: Color32::BLACK,
fill: Color32::WHITE,
edge: Color32::BLACK,
anchor: 5.0,
large: 7.0,
thin: 1.0,
medium: 2.0,
thick: 3.0,
reach: 20.0,
};
KeptMesh {
key: MeshKey {
marks: 0,
view: CanvasView::new(screen, Point::new(500.0, 500.0), 1.0),
rect: screen,
clip: screen,
pixels_per_point: 1.0,
options: egui::epaint::TessellationOptions::default(),
look,
},
mesh: Arc::new(egui::Mesh::default()),
moved: [0.0; 2],
}
}
// A point whose `f32` screen position moves by exactly one pixel can still put a square's edge on other pixels: an
// anchor at x = 252.99998 moves to 253.99998, but its 5 pt square's right edge goes from 255.49998 to 256.5, which
// round to 255 and 257, so the moved mesh's edge at 256 is not the one a new tessellation draws. A 6 pt square there
// has edges that round one pixel on, but its `f32` width grows from 6 to 6.0000153, and the tessellator compares the
// width with its thresholds for drawing a square as a line or a stroke as a fill.
#[test]
fn a_whole_pixel_move_keeps_the_mesh_only_when_every_square_edge_rounds_by_those_pixels() {
let by = Vec2::new(1.0, 0.0);
let options = PathOptionsSettings::default();
// The `f32` just under 253: 252.99998474121094.
let center = f64::from(253.0_f32 - 2.0_f32.powi(-16));
let mut kept = kept_at_one_pixel_per_point();
assert!(!kept.translate(by, [Point::new(center, 10.0)], &options), "a right edge that rounds two pixels on");
assert_eq!(kept.moved, [0.0; 2], "the refused move leaves the mesh where it was");
assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "edges on whole pixels");
// Near the origin a move is whole within the rounding noise: an anchor at x = 2.9999998 (the `f32` just under 3)
// moved to 4 keeps its square's width, but the left edge goes from 0.4999998 to 1.5, which round to 0 and 2.
let near = f64::from(3.0_f32 - 2.0_f32.powi(-22));
let step = Vec2::new(4.0 - near, 0.0);
assert!(!kept_at_one_pixel_per_point().translate(step, [Point::new(near, 10.0)], &options), "a left edge that rounds two pixels on");
// Anchors and handle ends 6 pt across.
let mut six = kept_at_one_pixel_per_point();
six.key.look.anchor = 6.0;
assert!(!six.translate(by, [Point::new(center, 10.0)], &options), "a square whose width changes");
}
// The tessellator draws a filled square no wider than twice its feathering as a line and rounds it another way, so a
// square that small is tessellated again after any move.
#[test]
#[allow(clippy::field_reassign_with_default)] // `PathOptionsSettings` is non-exhaustive: no struct literal outside its crate
fn a_move_tessellates_the_marks_again_when_a_square_is_drawn_as_a_line() {
let by = Vec2::new(1.0, 0.0);
let mut options = PathOptionsSettings::default();
options.anchor_size = Some(2.0);
assert!(!kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a 2 pt anchor at 1 pixel per point");
// The `f32` just over 2 passes the check on the side, but the square built at x = 252.5 spans 251.5 to 253.5 in
// `f32`, 2 pixels wide, so the tessellator draws it as a line.
options.anchor_size = Some(f32::from_bits(2.0_f32.to_bits() + 1));
assert!(!kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a square built 2 pixels wide");
options.anchor_size = Some(3.0);
assert!(kept_at_one_pixel_per_point().translate(by, [Point::new(252.5, 10.0)], &options), "a 3 pt anchor");
}