Pencil: a tall redraw keeps an open line's ends and a thin shape's body (#3793)

This commit is contained in:
ncic committed 2026-11-22 21:59:44 +01:00
1 parent 6cd0de02b1
commit 3b668aec46
4 files changed
+117 -17

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Pencil",
[],
None,
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one, or the part of an open one, that lies nearer the stroke; an open one's ends beyond them when the stroke lies along those, which closes it), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1: the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks. A pressure, tilt, rotation or wheel outside its range, or a point array of more than seven numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), leaveSelection?: bool (false; true with keepSelected false: a new path leaves the selection as it is, as the Pencil previews a stroke that redraws a path), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the way round a closed one that leaves the bigger shape; on an open one, the ends beyond them instead, which closes it, when the stroke lies along those, the opening between the ends is smaller than that section and the stroke runs nearer the opening than that section), the stroke's ends bent smoothly onto the path; a stroke that starts on it and returns to the same point adds a loop there, and one lifted farther than `within` from it takes the path with it: a closed subpath opens where the stroke starts, an open one is cut there and drops the part the stroke heads along, and the path ends where the stroke does. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes",
has_doc,
freehand
),
+73 -15
View File
@@ -264,16 +264,11 @@ fn run_distance_sum(sp: &SubPath, i: usize, j: usize, pts: &[Point]) -> (f64, us
if n == 0 || pts.is_empty() {
return (0.0, 0);
}
let step = pts.len().div_ceil(200).max(1);
let line: Vec<Point> = pts.iter().step_by(step).chain(pts.last()).copied().collect();
let line = thinned(pts);
let to_line = |q: Point| {
line.windows(2)
.map(|w| {
let (a, b) = (w[0], w[1]);
let ab = b - a;
let t = if ab.hypot2() > 1e-18 { ((q - a).dot(ab) / ab.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
q.distance(a + ab * t)
})
line.iter()
.zip(line.iter().skip(1))
.map(|(&a, &b)| straight_distance(q, a, b))
.fold(line.first().map_or(f64::INFINITY, |a| q.distance(*a)), f64::min)
};
let segs = (j + n - i) % n;
@@ -288,6 +283,65 @@ fn run_distance_sum(sp: &SubPath, i: usize, j: usize, pts: &[Point]) -> (f64, us
(sum, count)
}
/// Stroke `pts` thinned to at most about 200 points, its last kept, to measure it by.
fn thinned(pts: &[Point]) -> Vec<Point> {
let step = pts.len().div_ceil(200).max(1);
pts.iter().step_by(step).chain(pts.last()).copied().collect()
}
/// How far `q` lies from the straight piece from `a` to `b`.
fn straight_distance(q: Point, a: Point, b: Point) -> f64 {
let ab = b - a;
let t = if ab.hypot2() > 1e-18 { ((q - a).dot(ab) / ab.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
q.distance(a + ab * t)
}
/// Is there an opening in open subpath `sp` for stroke `pts`, from anchor `lo` to anchor `hi` of
/// it, to close? Only when the opening between the subpath's ends is smaller than the part the
/// stroke would replace, and the stroke runs nearer the opening (straight from `lo` to `hi`) than
/// that part. Without this, a tall bump redrawn over most of a line deletes the line's ends and
/// closes it: the ends lie nearer such a stroke than the part under the bump does.
fn closes_opening(sp: &SubPath, lo: usize, hi: usize, pts: &[Point]) -> bool {
use kurbo::ParamCurveArclen;
let Some(last) = sp.anchors.len().checked_sub(1) else { return false };
let (Some(head), Some(tail), Some(a), Some(b)) = (sp.anchors.first(), sp.anchors.get(last), sp.anchors.get(lo), sp.anchors.get(hi)) else {
return false;
};
// Lengths are measured to 0.01: a straight line's opening is as long as the whole line.
let replaced: f64 = (lo..hi).map(|k| sp.segment(k).arclen(0.01)).sum();
if head.p.distance(tail.p) + 0.01 >= replaced {
return false;
}
let Some(run) = sp.anchors.get_range(lo..=hi) else { return false };
let run = PathData::single(SubPath::new(run, false));
let line = thinned(pts);
// Weighted by length, so where the hand slowed down doesn't count for more.
let (mut to_opening, mut to_run, mut total) = (0.0, 0.0, 0.0);
for (&p, &q) in line.iter().zip(line.iter().skip(1)) {
let (len, mid) = (p.distance(q), p.midpoint(q));
let Some(on_run) = run.nearest(mid) else { return false };
to_opening += len * straight_distance(mid, a.p, b.p);
to_run += len * on_run.4;
total += len;
}
to_opening + 1e-6 * total < to_run
}
/// The area closed subpath `sp` would have with `stroke` (running from anchor `start` to anchor
/// `end`) in place of its run from `start` forward to `end`.
fn redrawn_area(sp: &SubPath, start: usize, end: usize, stroke: impl Iterator<Item = Point>) -> f64 {
use kurbo::ParamCurveArea;
let n = sp.anchors.len();
let (Some(from), Some(to)) = (sp.anchors.get(start), sp.anchors.get(end)) else { return 0.0 };
let mut area: f64 = (0..(start + n - end) % n).map(|k| sp.segment((end + k) % n).signed_area()).sum();
let mut at = from.p;
for q in stroke.chain([to.p]) {
area += kurbo::Line::new(at, q).signed_area();
at = q;
}
area.abs()
}
/// An open subpath `sp` redrawn by a stroke from anchor `from` to anchor `to` across its open
/// ends: the part between them stays, the ends beyond them go, and the stroke closes the path.
fn redraw_across_gap(sp: &SubPath, from: usize, to: usize, pts: &[Point], tol: Option<f64>, within: f64) -> Option<SubPath> {
@@ -315,8 +369,9 @@ fn redraw_across_gap(sp: &SubPath, from: usize, to: usize, pts: &[Point], tol: O
/// Pencil's Edit Selected Paths in the middle of a path: a stroke that starts and ends within
/// `within` of a subpath of `pd` replaces the section between with the stroke fitted at `tol` (with
/// no `tol`, unfitted), its ends bent onto the path ([`bend_ends`]). On a closed subpath that is the
/// way round that lies nearer the stroke, so the stroke takes the side it was drawn along. The subpath's index and its new shape; None
/// when the stroke doesn't start and end on the same subpath.
/// way round that leaves the bigger shape. An open one closes only over an opening
/// ([`closes_opening`]). The subpath's index and its new shape; None when the stroke doesn't start
/// and end on the same subpath.
fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -> Option<(usize, SubPath)> {
let (first, last) = (*pts.first()?, *pts.last()?);
let (si, _, _, _, d_a) = pd.nearest(first)?;
@@ -349,16 +404,19 @@ fn redraw_section(pd: &PathData, pts: &[Point], tol: Option<f64>, within: f64) -
let (s2, c2) = run_distance_sum(&sp, hi, n - 1, pts);
// Both ends taken: the stroke only spans the gap.
let outer = if c1 + c2 == 0 { 0.0 } else { (s1 + s2) / (c1 + c2) as f64 };
if outer < inner {
if outer < inner && closes_opening(&sp, lo, hi, pts) {
return redraw_across_gap(&sp, from, to, pts, tol, within).map(|sp| (si, sp));
}
}
// The stroke goes from `start` to `end` and replaces the run between them; `kept` runs from
// `end` round to `start`, then the stroke's inner anchors follow.
let (start, end, reversed) = if sp.closed {
// The way round that lies along the stroke: carving across a shape replaces the part the
// stroke cuts off, drawing round outside it replaces the part it follows.
if run_distance(&sp, from, to, pts) <= run_distance(&sp, to, from, pts) { (from, to, false) } else { (to, from, true) }
// The bigger of the two shapes the stroke could make stays: carving across a shape replaces
// the part it cuts off, drawing round outside it the part it goes round. Picking the side
// nearer the stroke instead threw away a thin shape under a tall arch over its long side.
let forward = redrawn_area(&sp, from, to, pts.iter().copied());
let backward = redrawn_area(&sp, to, from, pts.iter().rev().copied());
if forward >= backward { (from, to, false) } else { (to, from, true) }
} else if from < to {
(from, to, false)
} else {
+42
View File
@@ -6654,6 +6654,48 @@ fn a_stroke_over_an_open_shapes_ends_closes_it_along_the_stroke() {
}
}
/// A tall bump redrawn over most of an open line replaces that part: the ends beyond it stay and
/// the line stays open, as there is no opening for the stroke to close.
#[test]
fn a_tall_redraw_over_most_of_an_open_line_keeps_its_ends() {
for reversed in [false, true] {
let mut s = session();
let id = line(&mut s, 100.0, 300.0, 700.0, 300.0);
let mut bump =
vec![json!([200, 300]), json!([250, 226]), json!([325, 148]), json!([400, 120]), json!([475, 148]), json!([550, 226]), json!([600, 300])];
if reversed {
bump.reverse();
}
s.execute("path.freehand", &json!({"points": bump, "redraw": {"id": id.0, "within": 12}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(!sp.closed, "reversed {reversed}: still open");
assert!(ends_at(sp, Point::new(100.0, 300.0), Point::new(700.0, 300.0), 1e-6), "reversed {reversed}: both ends stay: {sp:?}");
assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 135.0, "reversed {reversed}: the bump");
}
}
/// A tall arch over one long side of a thin closed shape replaces that side: the result is the
/// bigger of the two shapes the stroke could make, not the arch alone.
#[test]
fn a_tall_arch_over_a_thin_shapes_side_keeps_the_shape() {
for reversed in [false, true] {
let mut s = session();
let id = rect(&mut s, 100.0, 300.0, 600.0, 60.0);
let mut arch =
vec![json!([130, 300]), json!([197, 216]), json!([265, 144]), json!([400, 80]), json!([535, 144]), json!([603, 216]), json!([670, 300])];
if reversed {
arch.reverse();
}
s.execute("path.freehand", &json!({"points": arch, "redraw": {"id": id.0, "within": 12}})).unwrap();
let sp = &path(&s, id).subpaths[0];
assert!(sp.closed, "reversed {reversed}");
for corner in [(100.0, 300.0), (700.0, 300.0), (700.0, 360.0), (100.0, 360.0)] {
assert!(sp.anchors.iter().any(|a| near(a.p, Point::new(corner.0, corner.1))), "reversed {reversed}: {corner:?} kept: {sp:?}");
}
assert!(kurbo::Shape::bounding_box(&path(&s, id).to_bezpath()).y0 < 95.0, "reversed {reversed}: the arch");
}
}
/// A stroke that comes back near the path, within Edit selected paths within but not on it, joins
/// it again: the shape stays one closed path, and the stroke's end bends onto it, so no anchor
/// lies off the stroke's way back.
+1 -1
View File
@@ -223,7 +223,7 @@ tools, never checked side by side) isn't captured row by row.
| Blend Replace Spine, move and Undo redraw (#5179) | CPU regression-tested | Renderer damage bounds include keys and steps rotated along a curved spine. Both original straight and curved CPU regressions pass, checking full-frame agreement and that every changed pixel lies inside the advertised redraw area. |
| Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away |
| Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles; Alt held while dragging a handle links it with the opposite handle and makes the anchor smooth, on a blend's spine too |
| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the way round a closed path that lies nearer the stroke, so a stroke across a shape carves off the part it crosses; #2850), the stroke's ends bent smoothly onto the path; a stroke lifted farther than the distance takes the path with it (a closed path opens where the stroke starts, an open one is cut there and drops the part the stroke heads along), one back to its starting point adds a loop, one over an open path's two ends closes it, and a selected compound path's member paths are redrawn too (#3793); while such a stroke is drawn the preview shows the stroke as drawn and the path changes at the release; with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path |
| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Fidelity is in screen pixels, the same at any zoom, and goes down to 0.01 px in the dialog and the tool, which sends `path.freehand` the value in points at the current zoom (#5729; the Smooth tool keeps 0.05 pt); its slider runs across the Tool Options row on a logarithmic rail from 0.01 to 20 px, the field shows hundredths, and the slider's and the field's arrow keys step hundredths up to 0.1 px, tenths up to 1 px and whole pixels above (Shift ×10) (#3328); Alt key toggles to Smooth Tool (#2001); Shift held at the press draws a straight line at 45° steps from the Constrain Angle, and Alt held at the press (with Alt key toggles to Smooth Tool off) a straight line at any angle (#3799), with a straight-line cursor (a short level line) while Shift or Alt is held before the press, and a path-continuation cursor (a short rising line) over an end of a selected open path, where the stroke continues the path, freehand or straight, and while a continuing stroke ends near an open end of another selected path it connects to; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the way round a closed path that leaves the bigger shape, so a stroke across a shape carves off its smaller part and an arch over a thin shape's side keeps the shape; an open path closes only over an opening smaller than that section, when the stroke runs nearer the opening; #2850), the stroke's ends bent smoothly onto the path; a stroke lifted farther than the distance takes the path with it (a closed path opens where the stroke starts, an open one is cut there and drops the part the stroke heads along), one back to its starting point adds a loop, one over an open path's two ends closes it, and a selected compound path's member paths are redrawn too (#3793); while such a stroke is drawn the preview shows the stroke as drawn and the path changes at the release; with Keep selected (Pencil and Paintbrush, on by default) on, a stroke selects the path it draws or continues and replaces the earlier selection, and off a new stroke leaves nothing selected, the earlier selection included, while a continued or redrawn path is deselected and the rest of the selection stays; a filled Pencil path keeps a stroke of None (#1804, part of #1679); while a freehand stroke is drawn back to within Close Paths When Ends Are Within of its start, or a stroke continuing a selected path (a straight line too) to within it of that path's other end, the Pencil and the Paintbrush show the closing cursor, and a release there closes the path; a Pencil stroke from an end of one selected open path to an end of another connects the two into one path |
| Drop Shadow, Outer Glow and Inner Glow: Opacity, the offsets, Blur and Darkness have spinner arrows that step by one (a unit for distances), repeat when held and stop at the fields' ends (#5367, #5368) | done | dialogs::effect test drop_shadow_and_outer_glow_fields_have_spinner_arrows; other effect dialogs' number fields still have none |
| Effect dialogs' colour fields: a swatch beside the hex follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills it and Cancel comes back unchanged (#5365) | done | dialogs::effect tests outer_glow_colour_swatch_opens_the_color_picker and drop_shadow_colour_swatch_opens_the_color_picker (Drop Shadow's Color, #5364); the picker previews nothing itself, the effect dialog previews the returned colour |
| Join tool scrubbing, Average, Join | done | Join merges the direct-selected anchors lying on one another along a path, as after Average, into one (#1533); the Join tool trims two crossing open paths whose overhanging ends it scrubs over and joins them at the crossing, instead of drawing a segment between their ends (#5844) |