From 38e36aeb819c32de4cde8d3f90c7900b2a180931 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:53:49 -0800 Subject: [PATCH 1/4] Paths: Object > Path > Simplify and Smooth keep a closed path's start Simplify and Smooth refit a closed path from its first corner and kept that order, so the path's first anchor moved and its dashes started somewhere else. A refit now starts at the old first anchor when it keeps one there, otherwise at a new anchor where the refit passes nearest that point while the result still has fewer anchors than the path had, and otherwise at the refit's nearest anchor. Its direction stays the same. A direct-selected run across the start follows the same rule; before, the path started at the run's end anchor. The Smooth tool's start_nearest moves into vectorcraft-pathops, and both commands call it with the limit on anchor count above. --- crates/engine/src/cmd/draw2/smooth.rs | 81 +------------ crates/engine/src/tests/simplify_part.rs | 81 ++++++++++--- crates/pathops/src/edit.rs | 147 +++++++++++++++++++++-- crates/pathops/src/lib.rs | 6 +- crates/pathops/tests/it/ops.rs | 68 +++++++++++ docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 7 files changed, 287 insertions(+), 107 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..e730401b60 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,4 +1,5 @@ use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_pathops::start_nearest; use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; use super::{ @@ -323,84 +324,6 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec (usize, f64) { - let mut best: Option<(f64, usize, f64)> = None; - for j in 0..orig.anchors.len() { - let hit = orig.segment(j).nearest(p, 1e-9); - if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { - best = Some((hit.distance_sq, j, hit.t)); - } - } - best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) -} - -/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new -/// anchor split into the segment there, which leaves the outline as it is. Of points equally near -/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used, -/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point, -/// is returned as it is. -fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath { - let n = sp.anchors.len(); - if !sp.closed || n < 2 { - return sp; - } - // (distance, place along `orig` once a tie needs it, segment of `sp`, parameter) - type Best = (f64, Option<(usize, f64)>, usize, f64); - let mut best: Option = None; - for i in 0..n { - let c = sp.segment(i); - let hit = c.nearest(start, 1e-9); - if !hit.distance_sq.is_finite() || !hit.t.is_finite() { - continue; - } - let d = hit.distance_sq.sqrt(); - match &mut best { - None => best = Some((d, None, i, hit.t)), - Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => { - let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt))); - let place = place_along(orig, c.eval(hit.t)); - if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { - best = Some((d, Some(place), i, hit.t)); - } - } - Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)), - Some(_) => {} - } - } - let Some((_, _, i, t)) = best else { return sp }; - let c = sp.segment(i); - let at = c.eval(t); - let first = if at.distance(c.p0) <= START_SNAP { - i - } else if at.distance(c.p3) <= START_SNAP { - (i + 1) % n - } else { - let mid = if sp.segment_is_line(i) { - Anchor::corner(at) - } else { - let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); - sp.anchors[i].h_out = l.p1; - sp.anchors[(i + 1) % n].h_in = r.p2; - Anchor::with_handles(at, l.p2, r.p1) - }; - sp.anchors.insert(i + 1, mid); - i + 1 - }; - sp.anchors.rotate_left(first); - sp -} - /// Pieces of curve that one Smooth drag measures against the drag while it searches the segments /// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach, /// each of which gets at least one: enough to search 300,000 pt of curve within the default reach @@ -1009,6 +932,8 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { + use vectorcraft_pathops::START_SNAP; + use super::*; /// A closed ring of four smooth anchors round (100, 100) with radius 50. diff --git a/crates/engine/src/tests/simplify_part.rs b/crates/engine/src/tests/simplify_part.rs index f3ab93f274..82f6cdc628 100644 --- a/crates/engine/src/tests/simplify_part.rs +++ b/crates/engine/src/tests/simplify_part.rs @@ -122,34 +122,87 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() { assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); } +/// The points of a closed 80-gon of radius 100 round (300, 300), starting at (400, 300). +fn eighty_gon() -> Vec<(f64, f64)> { + (0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect() +} + /// On a closed 80-gon, a run from anchor 70 through the start point to anchor 10 simplifies as one -/// run: anchor 0 goes, anchors 11–69 stay exactly as they were (the path now starts at anchor 10), -/// anchors 10 and 70 stay where they were with their outer handles, and the path stays closed. +/// run: anchor 0 goes, and the path starts at a new anchor where the refitted run passes nearest +/// it; anchors 11–69 stay exactly as they were, anchors 10 and 70 stay where they were with their +/// outer handles, the path stays closed, and the refitted run stays direct-selected. #[test] fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() { let mut s = session(); - let pts: Vec<(f64, f64)> = - (0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect(); - let id = polyline(&mut s, &pts, true); + let id = polyline(&mut s, &eighty_gon(), true); let original = path_of(&s, id).subpaths[0].clone(); select_anchors(&mut s, id, &[(70, 79), (0, 10)]); s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap(); let sp = path_of(&s, id).subpaths[0].clone(); assert!(sp.closed); assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len()); - assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run"); - assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); - assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); - assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); - for i in 0..60 { - assert_eq!(sp.segment(i), original.segment(10 + i)); - } + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt"); let n = sp.anchors.len(); - assert!(worst_offset(&original, (70..80).chain(0..10), &sp, 60..n) <= 1.0 + 1e-6); - let sel: BTreeSet<_> = std::iter::once((0, 0)).chain((60..n).map(|i| (0, i))).collect(); + let k = sp.anchors.iter().position(|a| a.p == original.anchors[10].p).unwrap(); + let mut turned = sp.clone(); + turned.anchors.rotate_left(k); + assert_eq!(turned.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); + assert_eq!((turned.anchors[0].p, turned.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); + assert_eq!((turned.anchors[60].p, turned.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); + for i in 0..60 { + assert_eq!(turned.segment(i), original.segment(10 + i)); + } + assert!(worst_offset(&original, (70..80).chain(0..10), &turned, 60..n) <= 1.0 + 1e-6); + let sel: BTreeSet<_> = (0..=k).chain(k + 60..n).map(|i| (0, i)).collect(); assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); } +/// Smooth of a direct-selected run across the start of a closed 80-gon starts the path near where it +/// started too, with fewer anchors. +#[test] +fn smoothing_a_run_across_the_start_keeps_the_start() { + let mut s = session(); + let id = polyline(&mut s, &eighty_gon(), true); + let original = path_of(&s, id).subpaths[0].clone(); + select_anchors(&mut s, id, &[(70, 79), (0, 10)]); + s.execute("object.path.smooth", &json!({"level": 50})).unwrap(); + let sp = path_of(&s, id).subpaths[0].clone(); + assert!(sp.closed && sp.anchors.len() < 80, "{}", sp.anchors.len()); + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", sp.anchors[0].p); +} + +/// A dashed closed path keeps its start, where its dashes begin, through Simplify and through +/// Smooth: a loop of radius 50 round (300, 300) with a needle out to (550, 300), starting on the far +/// side of the loop at (250, 300). Its stroke stays as it was, and each command is one undo step. +#[test] +fn a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth() { + let mut s = session(); + let at = |deg: f64| (300.0 + 50.0 * deg.to_radians().cos(), 300.0 + 50.0 * deg.to_radians().sin()); + let pts: Vec<(f64, f64)> = + (0..=20).map(|i| at(180.0 + 8.95 * f64::from(i))).chain([(550.0, 300.0)]).chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))).collect(); + let id = polyline(&mut s, &pts, true); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 2, "dash": [10, 5]})).unwrap(); + let stroke = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.clone(); + let style = stroke(&s); + let original = path_of(&s, id).subpaths[0].clone(); + // (command, params, how far the start may move: Simplify's tolerance, or Smooth's smoothing and tolerance) + let commands = [("object.path.simplify", json!({"tolerance": 1}), 1.0 + 1e-9), ("object.path.smooth", json!({"level": 50}), 5.0)]; + for (command, params, limit) in commands { + let steps = undo_len(&s); + s.execute(command, ¶ms).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "{command}"); + let sp = path_of(&s, id).subpaths[0].clone(); + assert!(sp.closed && sp.anchors.len() < original.anchors.len(), "{command}: {}", sp.anchors.len()); + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= limit, "{command}: the start moved {moved} pt, to {:?}", sp.anchors[0].p); + assert_eq!(stroke(&s), style, "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id).subpaths[0], original, "{command}"); + } +} + /// Segments picked with the Direct Selection tool simplify the same way, and stay picked as /// segments. #[test] diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 3ad1281eb2..a26da95828 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -97,7 +97,10 @@ fn turn_deg(a: &Seg, b: &Seg) -> f64 { d.acos().to_degrees() } -/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. +/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. A closed +/// subpath starts where it did: at its first anchor when the refit keeps an anchor there, otherwise +/// at a new anchor split into the refit at its point nearest there when the refit still has fewer +/// anchors than the subpath with that one, and otherwise at the refit's anchor nearest there. pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { let mut out = Vec::new(); for sp in &path.subpaths { @@ -108,15 +111,132 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { PathData::new(out) } -/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed subpath -/// whose refit is one segment, or lines that enclose no area, is refitted in two parts, cut at the -/// point farthest from its start, or in three when two still give that. When three parts still give -/// no area, straight lines follow the subpath within the tolerance, and without straight lines it +/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed refit +/// starts where the subpath started ([`keep_start`]). +fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { + refit_subpath(sp, opts).map(|fit| keep_start(fit, sp).0) +} + +/// Distance (points) from an anchor within which a closed path restarted by [`start_nearest`] +/// starts at that anchor instead of at a new one split in beside it. +pub const START_SNAP: f64 = 1e-3; + +/// Distance (points) within which two points of a closed path count as equally near its old start. +const START_TIE: f64 = 1e-6; + +/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of +/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place +/// when there is none. +fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { + let mut best: Option<(f64, usize, f64)> = None; + for j in 0..orig.anchors.len() { + let hit = orig.segment(j).nearest(p, 1e-9); + if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { + best = Some((hit.distance_sq, j, hit.t)); + } + } + best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) +} + +/// Of the candidates (distance, point, value), the value of the nearest, with a finite distance: +/// of those within [`START_TIE`] of each other, the one whose point is earliest along `orig` from +/// its first anchor, then the first given. +fn earliest_nearest(candidates: impl IntoIterator, orig: &SubPath) -> Option { + // (distance, place along `orig` once a tie needs it, point, value) + type Best = (f64, Option<(usize, f64)>, Point, T); + let mut best: Option> = None; + for (d, p, x) in candidates { + if !d.is_finite() { + continue; + } + match &mut best { + None => best = Some((d, None, p, x)), + Some((bd, bplace, bp, _)) if (d - *bd).abs() <= START_TIE => { + let held = *bplace.get_or_insert_with(|| place_along(orig, *bp)); + let place = place_along(orig, p); + if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { + best = Some((d, Some(place), p, x)); + } + } + Some((bd, ..)) if d < *bd => best = Some((d, None, p, x)), + Some(_) => {} + } + } + best.map(|(.., x)| x) +} + +/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new +/// anchor split into the segment there, which leaves the outline as it is. Of points equally near +/// `start`, the one earliest along `orig` (the path before it was refitted) from its first anchor is +/// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest +/// point, is returned as it is. +pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { + start_near(sp, start, orig, true).0 +} + +/// [`start_nearest`], splitting a segment only when `split` is set; otherwise, when no anchor lies +/// at the nearest point, the path starts at its anchor nearest `start`, with the same tie rule. → +/// (the path, the segment split when one was, where the new start was before the anchors turned). +fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (SubPath, Option, usize) { + let n = sp.anchors.len(); + if !sp.closed || n < 2 { + return (sp, None, 0); + } + let hits = (0..n).map(|i| { + let c = sp.segment(i); + let hit = c.nearest(start, 1e-9); + let d = if hit.distance_sq.is_finite() && hit.t.is_finite() { hit.distance_sq.sqrt() } else { f64::NAN }; + (d, c.eval(hit.t), (i, hit.t)) + }); + let Some((i, t)) = earliest_nearest(hits, orig) else { return (sp, None, 0) }; + let c = sp.segment(i); + let at = c.eval(t); + let (first, cut) = if at.distance(c.p0) <= START_SNAP { + (i, None) + } else if at.distance(c.p3) <= START_SNAP { + ((i + 1) % n, None) + } else if split { + let mid = if sp.segment_is_line(i) { + Anchor::corner(at) + } else { + let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); + sp.anchors[i].h_out = l.p1; + sp.anchors[(i + 1) % n].h_in = r.p2; + Anchor::with_handles(at, l.p2, r.p1) + }; + sp.anchors.insert(i + 1, mid); + (i + 1, Some(i)) + } else { + let near = sp.anchors.iter().enumerate().map(|(j, a)| (a.p.distance(start), a.p, j)); + (earliest_nearest(near, orig).unwrap_or(0), None) + }; + sp.anchors.rotate_left(first); + (sp, cut, first) +} + +/// The closed refit `fit` of the closed `orig` started where `orig` starts: at its anchor at +/// `orig`'s first anchor, or at a new anchor split in at its point nearest there when it still has +/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]). An +/// open `orig` keeps `fit` as it is. +fn keep_start(fit: SubPath, orig: &SubPath) -> (SubPath, Option, usize) { + match orig.anchors.first() { + Some(a) if orig.closed => { + let split = fit.anchors.len() + 1 < orig.anchors.len(); + start_near(fit, a.p, orig, split) + } + _ => (fit, None, 0), + } +} + +/// [`simplify_subpath`] before the start is put back: a closed subpath whose refit is one segment, +/// or lines that enclose no area, is refitted in two parts, cut at the point farthest from its +/// start, or in three when two still give that. When three parts still give no area, straight lines +/// follow the subpath within the tolerance, and without straight lines it /// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose /// an area, it stays as it is, or with straight lines follows the lines between samples of each /// curved segment when the limits leave room for lines within the tolerance; one that is all in line /// keeps the refit. -fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { +fn refit_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); if n == 0 || sp.closed && n < 2 { @@ -694,7 +814,8 @@ pub struct SimplifiedPart { /// two end anchors, which stay where they are with their handles on the side away from the run. /// The other segments and anchors stay exactly as they are. A subpath whose every segment is in /// `segments` is simplified whole, as [`simplify_with`] does. A run whose refit would have more -/// segments than it had is left as it is (except with Convert to Straight Lines). +/// segments than it had is left as it is (except with Convert to Straight Lines). A closed subpath +/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]). pub fn simplify_part(path: &PathData, segments: &BTreeSet<(usize, usize)>, opts: &SimplifyOptions) -> SimplifiedPart { let opts = &SimplifyOptions { free_start: false, free_end: false, ..*opts }; let (mut runs, mut anchors) = (BTreeSet::new(), BTreeMap::new()); @@ -782,7 +903,17 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } k += len; } - (SubPath::new(anchors, sp.closed), runs, kept) + // A closed subpath starts where it did ([`keep_start`]), with the runs and anchors kept renumbered. + let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp); + let len = out.anchors.len(); + if (cut, first) == (None, 0) || len == 0 { + return (out, runs, kept); + } + let turned = |i: usize| (i + len - first) % len; + let after_cut = |i: usize| i + usize::from(cut.is_some_and(|c| i > c)); + let runs = runs.into_iter().flat_map(|s| if cut == Some(s) { vec![s, s + 1] } else { vec![after_cut(s)] }).map(turned).collect(); + let kept = kept.into_iter().map(|(old, new)| (old, turned(after_cut(new)))).collect(); + (out, runs, kept) } /// `a` with its out (`out`) or in handle at `h` and the other as it is: still smooth when it was diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d500182401..0ff1b82594 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -22,9 +22,9 @@ pub use boolean::{ try_unite_all_with, unite_all, unite_all_with, }; pub use edit::{ - AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, - remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, - smooth_options, split_into_grid, + AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, START_SNAP, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, + join, remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, + smooth_level, smooth_options, split_into_grid, start_nearest, }; pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index a31c9af2e4..60410a0d5d 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -742,6 +742,74 @@ fn smooth_level_0_keeps_a_closed_paths_start_corner_within_tolerance() { assert!(moved <= limit, "level 0 moved the path by {moved} pt, more than {limit} pt: {:?}", s.subpaths[0].anchors[0]); } +/// Twice the area `sp` encloses, from 16 points along each segment: positive when it runs +/// counterclockwise in y-up terms. +fn signed_area(sp: &SubPath) -> f64 { + let pts: Vec = (0..sp.segment_count()).flat_map(|i| (0..16).map(move |k| sp.segment(i).eval(f64::from(k) / 16.0))).collect(); + (0..pts.len()).map(|i| pts[i].to_vec2().cross(pts[(i + 1) % pts.len()].to_vec2())).sum() +} + +/// A D of 41 corner points round (0, 0): the arc of radius 100 from (100, 0) up to (0, 100), the +/// straight side down to (0, -100), and the arc back. It starts in the middle of its arc, and its +/// first corner is at the top. +fn d_shape() -> SubPath { + let at = |deg: f64| Point::new(100.0 * deg.to_radians().cos(), 100.0 * deg.to_radians().sin()); + let pts: Vec = (0..=20).map(|i| at(4.5 * f64::from(i))).chain((0..20).map(|i| at(-90.0 + 4.5 * f64::from(i)))).collect(); + SubPath::polyline(&pts, true) +} + +/// Object › Path › Simplify starts a closed path where it started, though the refit runs from the +/// first corner: on the D, the refit starts within the tolerance of the old start, runs the same way +/// round, and has fewer anchors. +#[test] +fn simplify_keeps_a_closed_paths_start() { + let sp = d_shape(); + let path = PathData::single(sp.clone()); + let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, ..Default::default() }); + let out = &s.subpaths[0]; + assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}"); + let moved = out.anchors[0].p.distance(sp.anchors[0].p); + assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt, to {:?}", out.anchors[0].p); + assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays"); + assert!(one_way_distance(&path, &s).max(one_way_distance(&s, &path)) <= 1.0 + 1e-6); +} + +/// Object › Path › Smooth starts a closed path near where it started, though the refit runs from the +/// point where the path turns back: a round loop of radius 50 with a needle out to (250, 0), which +/// starts on the far side of the loop at (-50, 0). +#[test] +fn smooth_keeps_a_closed_paths_start() { + let at = |deg: f64| Point::new(50.0 * deg.to_radians().cos(), 50.0 * deg.to_radians().sin()); + let pts: Vec = (0..=20) + .map(|i| at(180.0 + 8.95 * f64::from(i))) + .chain([Point::new(250.0, 0.0)]) + .chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))) + .collect(); + let sp = SubPath::polyline(&pts, true); + let path = PathData::single(sp.clone()); + let s = smooth_level(&path, SMOOTH_AUTO_LEVEL); + let out = &s.subpaths[0]; + assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}"); + let moved = out.anchors[0].p.distance(sp.anchors[0].p); + assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", out.anchors[0].p); + assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays"); +} + +/// A refit with only one anchor fewer than the closed path gets no anchor split in to keep its +/// start: it starts at its anchor nearest the old start. A rectangle with a straight point at +/// (30, 0) simplifies to its four corners, starting at (0, 0). +#[test] +fn simplify_starts_at_the_nearest_anchor_rather_than_add_one_back() { + let pts = [(30.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)); + let path = PathData::single(SubPath::polyline(&pts, true)); + let want = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(|(x, y)| Point::new(x, y)); + for straight_lines in [false, true] { + let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, straight_lines, ..Default::default() }); + let got: Vec = s.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(got, want, "straight_lines {straight_lines}"); + } +} + #[test] fn remove_redundant_collinear_and_curve() { let p = PathData::single(SubPath::polyline( diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..9ca5ab7c48 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7113,8 +7113,10 @@ result and the original path stay within `tolerance` of each other, except that is dropped, so a small circle in a compound path can be removed at a large `tolerance`. A segment that would need more than 65,536 samples at that tolerance stays as it is, and so does a segment after a run's first 16,777,216 samples or 2,097,152 result segments. With `straightLines`, such a segment becomes evenly spaced lines, up to 65,536, and past those -limits the lines can be farther than `tolerance` from the segment. With `level` or `auto`, the reply also has the `level` -used: +limits the lines can be farther than `tolerance` from the segment. A closed path keeps its start, where its dashes +begin: it starts at its old first anchor when the refit keeps an anchor there, otherwise at a new anchor where the refit +passes nearest that point when the result with that anchor still has fewer anchors than the path had, and otherwise at +the refit's anchor nearest that point. It runs the same way round as before. With `level` or `auto`, the reply also has the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} @@ -7123,7 +7125,7 @@ used: With segments of a path direct-selected (`select.segments`, or `select.anchors` with both anchors of a segment), Simplify refits only each run of consecutive selected segments, between the run's end anchors: they stay where they are, with their handles on the side away from the run, and every other anchor and segment of the path stays exactly as it was. A -closed path's run may cross its start point; the path then starts at the run's end anchor. Separate runs on one path +closed path's run may cross its start point; the path then keeps its start as a whole path does. Separate runs on one path simplify independently, in one undo step, and the runs stay direct-selected (as segments when segments were picked). A path with only lone anchors selected, and every path with `wholePaths: true`, simplifies whole: @@ -7151,7 +7153,7 @@ side) to 100 (maximum smoothing); `auto: true` (Auto-Smooth) uses level 50, the its length (by up to 5% of its longer side; none at level 0) and refitted with curves within 0.1% to 2.5% of it, keeping a corner only where it turns back on itself, so bumps, jags and kinks become one curve; with anchor points or segments of a path direct-selected (and no `ids`), only the sections between them are smoothed, as Simplify does. A refit never has more anchor points than the path had, so a shape whose corners the tolerance can't -round, such as a rectangle, stays as it is. Closed paths stay closed and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: +round, such as a rectangle, stays as it is. Closed paths stay closed and keep their start as Simplify keeps it, and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.smooth","params":{"level":80}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3af61d620e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1723,6 +1723,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. + Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way round. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is smoothed along its length (by up to 5% of its longer side, so a shaky line comes out as one curve at Auto-Smooth) and refitted with curves within 0.1% (level 0) to 2.5% (level 100) of it, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. With anchor points of a path direct-selected, only the section between them is smoothed. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests/devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. From 956a76baa65af79fc6212a7cb89023cc4a812a8d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:36:06 -0800 Subject: [PATCH 2/4] Paths: tied start candidates at one point search the old path once When several refit points tie for nearest to a closed path's old start, the earliest-along-the-path tie rule now places each distinct point on the old path once, so many segments meeting at one point no longer search every old segment once each. The tie rule is unchanged. Also "the same way around" in the docs. --- crates/pathops/src/edit.rs | 42 ++++++++++++++++++++++++++++++++------ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index a26da95828..d95a6c9037 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -1,7 +1,7 @@ //! Object → Path commands: Simplify, Smooth, Remove redundant points, Add Anchor Points, Average, //! Join, Split Into Grid. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; @@ -128,6 +128,8 @@ const START_TIE: f64 = 1e-6; /// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place /// when there is none. fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { + #[cfg(test)] + tests::count_places(); let mut best: Option<(f64, usize, f64)> = None; for j in 0..orig.anchors.len() { let hit = orig.segment(j).nearest(p, 1e-9); @@ -140,11 +142,14 @@ fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { /// Of the candidates (distance, point, value), the value of the nearest, with a finite distance: /// of those within [`START_TIE`] of each other, the one whose point is earliest along `orig` from -/// its first anchor, then the first given. +/// its first anchor, then the first given. Each distinct point is placed along `orig` once. fn earliest_nearest(candidates: impl IntoIterator, orig: &SubPath) -> Option { // (distance, place along `orig` once a tie needs it, point, value) type Best = (f64, Option<(usize, f64)>, Point, T); let mut best: Option> = None; + // Places along `orig` by the bits of the point, so many ties at one point search `orig` once. + let mut placed: HashMap<[u64; 2], (usize, f64)> = HashMap::new(); + let mut place = |p: Point| *placed.entry([p.x.to_bits(), p.y.to_bits()]).or_insert_with(|| place_along(orig, p)); for (d, p, x) in candidates { if !d.is_finite() { continue; @@ -152,10 +157,10 @@ fn earliest_nearest(candidates: impl IntoIterator, or match &mut best { None => best = Some((d, None, p, x)), Some((bd, bplace, bp, _)) if (d - *bd).abs() <= START_TIE => { - let held = *bplace.get_or_insert_with(|| place_along(orig, *bp)); - let place = place_along(orig, p); - if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { - best = Some((d, Some(place), p, x)); + let held = *bplace.get_or_insert_with(|| place(*bp)); + let at = place(p); + if at.0 < held.0 || (at.0 == held.0 && at.1 < held.1) { + best = Some((d, Some(at), p, x)); } } Some((bd, ..)) if d < *bd => best = Some((d, None, p, x)), @@ -1533,6 +1538,31 @@ mod tests { MOVES.set(MOVES.get() + n); } + std::thread_local! { + /// Calls of [`place_along`], each a search of every segment of the path before the refit. + static PLACES: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub(super) fn count_places() { + PLACES.set(PLACES.get() + 1); + } + + /// Candidates tied at one point are placed along the old path once, not once each, and the first + /// given still wins the tie. + #[test] + fn tied_candidates_at_one_point_are_placed_once() { + let orig = SubPath::new( + vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 0.0)), Anchor::corner(Point::new(100.0, 100.0))], + true, + ); + let candidates = (0..1000).map(|i| (0.0, Point::new(0.0, 0.0), i)); + PLACES.set(0); + let got = earliest_nearest(candidates, &orig); + let places = PLACES.get(); + assert_eq!(got, Some(0)); + assert_eq!(places, 1, "searches of the old path for 1000 candidates at one point"); + } + /// A subpath of `n` anchors from `seed`: corners, smooth points and points with one handle. fn random_subpath(seed: &mut u64, n: usize, closed: bool) -> SubPath { let mut rnd = || { diff --git a/docs/mcp.md b/docs/mcp.md index 9ca5ab7c48..e3043ece27 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7116,7 +7116,7 @@ than 65,536 samples at that tolerance stays as it is, and so does a segment afte limits the lines can be farther than `tolerance` from the segment. A closed path keeps its start, where its dashes begin: it starts at its old first anchor when the refit keeps an anchor there, otherwise at a new anchor where the refit passes nearest that point when the result with that anchor still has fewer anchors than the path had, and otherwise at -the refit's anchor nearest that point. It runs the same way round as before. With `level` or `auto`, the reply also has the `level` used: +the refit's anchor nearest that point. It runs the same way around as before. With `level` or `auto`, the reply also has the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3af61d620e..677cc05923 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1723,7 +1723,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. - Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way round. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. + Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way around. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is smoothed along its length (by up to 5% of its longer side, so a shaky line comes out as one curve at Auto-Smooth) and refitted with curves within 0.1% (level 0) to 2.5% (level 100) of it, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. With anchor points of a path direct-selected, only the section between them is smoothed. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests/devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. From 263718ffd24f5dc41b5c60d6fda529fdfb41a5b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:58:10 -0800 Subject: [PATCH 3/4] Paths: a run across a closed path's start keeps the new start on that run When a direct-selected run holds a closed path's first anchor, Simplify and Smooth now look for the new start on that run alone, so an unselected segment that passes through the old start is not split. When the first anchor stays, the path already starts there and is left as it is. --- crates/pathops/src/edit.rs | 85 +++++++++++++++++++++++++++++++------- docs/mcp.md | 3 +- 2 files changed, 71 insertions(+), 17 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index d95a6c9037..dd5d84ebe7 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -2,6 +2,7 @@ //! Join, Split Into Grid. use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::ops::Range; use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; @@ -114,7 +115,10 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { /// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed refit /// starts where the subpath started ([`keep_start`]). fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { - refit_subpath(sp, opts).map(|fit| keep_start(fit, sp).0) + refit_subpath(sp, opts).map(|fit| { + let n = fit.anchors.len(); + keep_start(fit, sp, 0..n).0 + }) } /// Distance (points) from an anchor within which a closed path restarted by [`start_nearest`] @@ -176,18 +180,21 @@ fn earliest_nearest(candidates: impl IntoIterator, or /// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest /// point, is returned as it is. pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { - start_near(sp, start, orig, true).0 + let n = sp.anchors.len(); + start_near(sp, start, orig, true, 0..n).0 } -/// [`start_nearest`], splitting a segment only when `split` is set; otherwise, when no anchor lies -/// at the nearest point, the path starts at its anchor nearest `start`, with the same tie rule. → -/// (the path, the segment split when one was, where the new start was before the anchors turned). -fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (SubPath, Option, usize) { +/// [`start_nearest`] on the segments `within` alone, splitting a segment only when `split` is set; +/// otherwise, when no anchor lies at the nearest point, the path starts at the anchor of those +/// segments nearest `start`, with the same tie rule. → (the path, the segment split when one was, +/// where the new start was before the anchors turned). +fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within: Range) -> (SubPath, Option, usize) { let n = sp.anchors.len(); if !sp.closed || n < 2 { return (sp, None, 0); } - let hits = (0..n).map(|i| { + let within = within.start.min(n)..within.end.min(n); + let hits = within.clone().map(|i| { let c = sp.segment(i); let hit = c.nearest(start, 1e-9); let d = if hit.distance_sq.is_finite() && hit.t.is_finite() { hit.distance_sq.sqrt() } else { f64::NAN }; @@ -212,7 +219,8 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (Su sp.anchors.insert(i + 1, mid); (i + 1, Some(i)) } else { - let near = sp.anchors.iter().enumerate().map(|(j, a)| (a.p.distance(start), a.p, j)); + // The anchors of the segments `within`: each one's first, and the last one's end. + let near = (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); (earliest_nearest(near, orig).unwrap_or(0), None) }; sp.anchors.rotate_left(first); @@ -221,13 +229,13 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (Su /// The closed refit `fit` of the closed `orig` started where `orig` starts: at its anchor at /// `orig`'s first anchor, or at a new anchor split in at its point nearest there when it still has -/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]). An -/// open `orig` keeps `fit` as it is. -fn keep_start(fit: SubPath, orig: &SubPath) -> (SubPath, Option, usize) { +/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]), +/// looking only at the segments `within`. An open `orig` keeps `fit` as it is. +fn keep_start(fit: SubPath, orig: &SubPath, within: Range) -> (SubPath, Option, usize) { match orig.anchors.first() { Some(a) if orig.closed => { let split = fit.anchors.len() + 1 < orig.anchors.len(); - start_near(fit, a.p, orig, split) + start_near(fit, a.p, orig, split, within) } _ => (fit, None, 0), } @@ -820,7 +828,8 @@ pub struct SimplifiedPart { /// The other segments and anchors stay exactly as they are. A subpath whose every segment is in /// `segments` is simplified whole, as [`simplify_with`] does. A run whose refit would have more /// segments than it had is left as it is (except with Convert to Straight Lines). A closed subpath -/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]). +/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]), on the run that held its +/// first anchor when that anchor goes. pub fn simplify_part(path: &PathData, segments: &BTreeSet<(usize, usize)>, opts: &SimplifyOptions) -> SimplifiedPart { let opts = &SimplifyOptions { free_start: false, free_end: false, ..*opts }; let (mut runs, mut anchors) = (BTreeSet::new(), BTreeMap::new()); @@ -859,6 +868,7 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP let mut anchors = vec![sp.anchors[start]]; let mut kept = vec![(start, 0)]; let mut runs = vec![]; + let mut start_run = None; let mut k = 0; while k < n { let j = (start + k) % n; @@ -891,7 +901,12 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } // The run's segments, from its first anchor on: a run back to the walk's start ends with // the closing segment, the last index. - runs.extend(first..first + if keep_original { run.len() } else { fitted.len() }); + let segs = first..first + if keep_original { run.len() } else { fitted.len() }; + if sp.closed && (k + 1..k + len).any(|i| (start + i) % m == 0) { + // The run that held the old first anchor. + start_run = Some(segs.clone()); + } + runs.extend(segs); let end_seg = fitted.last().filter(|_| !keep_original); if sp.closed && k + len == n { // The run ends where the walk started. @@ -908,8 +923,11 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } k += len; } - // A closed subpath starts where it did ([`keep_start`]), with the runs and anchors kept renumbered. - let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp); + // A closed subpath starts where it did: the walk already starts at its first anchor when that + // stays, and otherwise the run that held it starts the path ([`keep_start`] on that run's + // segments alone, so no other segment changes), with the runs and anchors kept renumbered. + let Some(within) = start_run else { return (SubPath::new(anchors, sp.closed), runs, kept) }; + let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp, within); let len = out.anchors.len(); if (cut, first) == (None, 0) || len == 0 { return (out, runs, kept); @@ -1547,6 +1565,41 @@ mod tests { PLACES.set(PLACES.get() + 1); } + /// A refitted run across the start of a closed path that crosses itself at its start keeps the + /// start on the run: the unselected segment through the old start is not split. + #[test] + fn a_run_across_the_start_keeps_the_start_on_the_run() { + let pts = [ + (0.0, 0.0), + (10.0, 0.3), + (20.0, -0.3), + (30.0, 0.3), + (40.0, 0.6), + (40.0, 50.0), + (0.0, 50.0), + (0.0, -50.0), + (-40.0, -50.0), + (-40.0, 0.6), + (-30.0, 0.3), + (-20.0, -0.3), + (-10.0, 0.3), + ]; + let sp = SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true); + let path = PathData::new(vec![sp]); + let picked: BTreeSet<(usize, usize)> = [9, 10, 11, 12, 0, 1, 2, 3].into_iter().map(|s| (0, s)).collect(); + let out = simplify_part(&path, &picked, &SimplifyOptions { tolerance: 1.0, ..SimplifyOptions::default() }); + let got = &out.path.subpaths[0]; + let n = got.anchors.len(); + assert!(n < pts.len(), "{n} anchors"); + let (top, bottom) = (Point::new(0.0, 50.0), Point::new(0.0, -50.0)); + assert!( + (0..n).any(|i| got.anchors[i].p == top && got.anchors[(i + 1) % n].p == bottom), + "the segment through the old start was split: {:?}", + got.anchors.iter().map(|a| a.p).collect::>() + ); + assert!(got.anchors[0].p.x.abs() < 40.0 && got.anchors[0].p.y.abs() <= 1.0, "start {:?}", got.anchors[0].p); + } + /// Candidates tied at one point are placed along the old path once, not once each, and the first /// given still wins the tie. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e3043ece27..8f907cea87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7125,7 +7125,8 @@ the refit's anchor nearest that point. It runs the same way around as before. Wi With segments of a path direct-selected (`select.segments`, or `select.anchors` with both anchors of a segment), Simplify refits only each run of consecutive selected segments, between the run's end anchors: they stay where they are, with their handles on the side away from the run, and every other anchor and segment of the path stays exactly as it was. A -closed path's run may cross its start point; the path then keeps its start as a whole path does. Separate runs on one path +closed path's run may cross its start point; the path then keeps its start as a whole path does, with the new start on +that run. Separate runs on one path simplify independently, in one undo step, and the runs stay direct-selected (as segments when segments were picked). A path with only lone anchors selected, and every path with `wholePaths: true`, simplifies whole: From 8e6f06574f212f3315bf1fa7aef6149a3f61d6e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:49:58 -0800 Subject: [PATCH 4/4] Paths: a closed path starts at a kept anchor at its old start When the refit keeps an anchor at a closed path's old start, Simplify and Smooth now start the path at that anchor, even where a segment of the refit crosses the path at the same point. Before, a crossing segment that came first could be split there instead, adding an anchor and changing the segment the path starts along. --- crates/pathops/src/edit.rs | 57 +++++++++++++++++++++++++++++++++----- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index dd5d84ebe7..c5a340365a 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -174,10 +174,11 @@ fn earliest_nearest(candidates: impl IntoIterator, or best.map(|(.., x)| x) } -/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new -/// anchor split into the segment there, which leaves the outline as it is. Of points equally near -/// `start`, the one earliest along `orig` (the path before it was refitted) from its first anchor is -/// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest +/// The closed `sp` started at the point on it nearest `start`: at an anchor within [`START_SNAP`] of +/// `start` when it has one, even where a segment crosses the path there, otherwise at the anchor at +/// that point or at a new anchor split into the segment there, which leaves the outline as it is. Of +/// points equally near `start`, the one earliest along `orig` (the path before it was refitted) from +/// its first anchor is used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest /// point, is returned as it is. pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { let n = sp.anchors.len(); @@ -194,6 +195,14 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within return (sp, None, 0); } let within = within.start.min(n)..within.end.min(n); + // The anchors of the segments `within`: each one's first, and the last one's end. + let anchors = || (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); + // An anchor within [`START_SNAP`] of `start` starts the path, before any segment through there. + let snapped = if within.is_empty() { None } else { earliest_nearest(anchors().filter(|(d, ..)| *d <= START_SNAP), orig) }; + if let Some(first) = snapped { + sp.anchors.rotate_left(first); + return (sp, None, first); + } let hits = within.clone().map(|i| { let c = sp.segment(i); let hit = c.nearest(start, 1e-9); @@ -219,9 +228,7 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within sp.anchors.insert(i + 1, mid); (i + 1, Some(i)) } else { - // The anchors of the segments `within`: each one's first, and the last one's end. - let near = (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); - (earliest_nearest(near, orig).unwrap_or(0), None) + (earliest_nearest(anchors(), orig).unwrap_or(0), None) }; sp.anchors.rotate_left(first); (sp, cut, first) @@ -1600,6 +1607,42 @@ mod tests { assert!(got.anchors[0].p.x.abs() < 40.0 && got.anchors[0].p.y.abs() <= 1.0, "start {:?}", got.anchors[0].p); } + /// A closed polyline from its start at (0, 0) up to (0, 10) whose diagonal from (-20, -20) to + /// (20, 20) crosses it at that start, with two anchors on the diagonal that a refit drops. + fn crossing_at_start() -> SubPath { + let pts = [(0, 0), (0, 10), (40, 10), (40, -20), (-20, -20), (-10, -10), (10, 10), (20, 20), (20, 30), (-10, 30), (-10, 0)]; + SubPath::polyline(&pts.map(|(x, y)| Point::new(f64::from(x), f64::from(y))), true) + } + + /// A refitted run that keeps an anchor at the old start of a closed path starts the path at that + /// anchor, though a segment of the run that crosses the path there comes first in the run. + #[test] + fn a_run_that_keeps_the_start_anchor_starts_there() { + let path = PathData::new(vec![crossing_at_start()]); + let picked: BTreeSet<(usize, usize)> = [0, 4, 5, 6, 7, 8, 9, 10].into_iter().map(|s| (0, s)).collect(); + let opts = SimplifyOptions { tolerance: 0.01, corner_angle_deg: 1.0, straight_lines: true, ..SimplifyOptions::default() }; + let got = &simplify_part(&path, &picked, &opts).path.subpaths[0]; + let ps: Vec = got.anchors.iter().map(|a| a.p).collect(); + assert_eq!(ps.len(), 9, "{ps:?}"); + assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}"); + assert_eq!(ps.iter().filter(|&&p| p == Point::ZERO).count(), 1, "{ps:?}"); + } + + /// The whole closed path refitted keeps its start anchor first when a segment of the refit + /// crosses the path there. + #[test] + fn a_refit_that_keeps_the_start_anchor_starts_there() { + let sp = crossing_at_start(); + let mut fit = sp.clone(); + fit.anchors.retain(|a| ![Point::new(-10.0, -10.0), Point::new(10.0, 10.0)].contains(&a.p)); + fit.anchors.rotate_left(4); + let n = fit.anchors.len(); + let (got, cut, _) = keep_start(fit, &sp, 0..n); + let ps: Vec = got.anchors.iter().map(|a| a.p).collect(); + assert_eq!(cut, None, "{ps:?}"); + assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}"); + } + /// Candidates tied at one point are placed along the old path once, not once each, and the first /// given still wins the tie. #[test]