mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 19:36:16 +00:00
Merge pull request #8439 from ncic/pencil-redraw-smooth
Pencil: a redraw stroke's bend stops at the edit distance, and its preview shows on top in any drawing mode
This commit is contained in:
@@ -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 that leaves the bigger shape; on an open one the way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), 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), preview?: bool (false; true: the stroke is drawn as a new path on top, as with Draw Normal, and the selection stays 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 way the stroke runs along it at each end decides: it replaces the part it runs along where it starts and joins the part it runs into where it lands, so it replaces the part between, keeps it and closes the path along the stroke, or, when its ends disagree, ends where it is lifted; an end that leaves or meets the path squarely follows the other end, and when both do it closes only if it goes round both pieces beyond), 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
|
||||
),
|
||||
|
||||
@@ -130,8 +130,9 @@ fn fit_from(a: Point, pts: &[Point], tol: Option<f64>, reach: f64) -> Vec<Anchor
|
||||
/// and the stroke behind it less and less, to not at all `reach` along it (Edit selected paths
|
||||
/// within), so a stroke that starts or ends near the path joins it smoothly instead of with a
|
||||
/// straight piece. A stroke shorter than `reach` bends over its own length, so each end still
|
||||
/// lands on its target and the other end's bend doesn't move it off.
|
||||
fn bend_ends(stroke: &mut [Point], a: Option<Point>, b: Option<Point>, reach: f64) {
|
||||
/// lands on its target and the other end's bend doesn't move it off. Where a bend stops between two
|
||||
/// points far apart, a point is added there, so the stroke beyond `reach` stays as drawn.
|
||||
fn bend_ends(stroke: &mut Vec<Point>, a: Option<Point>, b: Option<Point>, reach: f64) {
|
||||
let (Some(&first), Some(&last)) = (stroke.first(), stroke.last()) else { return };
|
||||
// How far along the stroke each point lies, measured before anything moves.
|
||||
let mut along = Vec::with_capacity(stroke.len());
|
||||
@@ -153,6 +154,39 @@ fn bend_ends(stroke: &mut [Point], a: Option<Point>, b: Option<Point>, reach: f6
|
||||
}
|
||||
return;
|
||||
}
|
||||
// A point where each bend stops, when that falls between two points (strokes sent by a script
|
||||
// can have few, far apart): without it, the straight piece to the next point would tilt beyond
|
||||
// `reach`.
|
||||
let (mut c0, mut c1) = (a.map(|_| reach), b.map(|_| total - reach));
|
||||
if let (Some(x), Some(y)) = (c0, c1)
|
||||
&& x > y
|
||||
{
|
||||
(c0, c1) = (Some(y), Some(x));
|
||||
}
|
||||
// Both bends stop at the same place (a stroke twice `reach` long): one point there.
|
||||
if let (Some(x), Some(y)) = (c0, c1)
|
||||
&& (y - x).abs() < 1e-9
|
||||
{
|
||||
c1 = None;
|
||||
}
|
||||
let mut points = Vec::with_capacity(stroke.len() + 2);
|
||||
let mut dists = Vec::with_capacity(stroke.len() + 2);
|
||||
let mut before: Option<(Point, f64)> = None;
|
||||
for (&p, &d) in stroke.iter().zip(&along) {
|
||||
if let Some((q, e)) = before {
|
||||
for c in [c0, c1].into_iter().flatten() {
|
||||
if e + 1e-9 < c && c < d - 1e-9 {
|
||||
points.push(q.lerp(p, (c - e) / (d - e)));
|
||||
dists.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
points.push(p);
|
||||
dists.push(d);
|
||||
before = Some((p, d));
|
||||
}
|
||||
*stroke = points;
|
||||
let along = dists;
|
||||
let weight = |d: f64| (1.0 - d / reach).max(0.0);
|
||||
let (shift_a, shift_b) = (a.map(|a| a - first), b.map(|b| b - last));
|
||||
for (p, &d) in stroke.iter_mut().zip(&along) {
|
||||
@@ -528,7 +562,7 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
// The Pencil's preview of a stroke that redraws a path draws it as a new path but leaves the
|
||||
// selection as it is: the path being redrawn stays selected until the release redraws it.
|
||||
let leave_selection = switch_or(p, "leaveSelection", false, C)?;
|
||||
let preview = switch_or(p, "preview", false, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
let extend = p.get("extend").filter(|v| !v.is_null());
|
||||
if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) {
|
||||
@@ -779,8 +813,13 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected)?;
|
||||
if !keep_selected && !leave_selection {
|
||||
// A preview goes on top as Draw Normal places it: Draw Inside would put it in the selected
|
||||
// path's clip group, clipped, and Draw Behind behind the path.
|
||||
let mode = if preview { std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal) } else { s.draw_mode };
|
||||
let out = insert_look(s, label, path_kind(PathData::single(sp)), look, None, keep_selected && !preview);
|
||||
s.draw_mode = mode;
|
||||
let out = out?;
|
||||
if !keep_selected && !preview {
|
||||
// A new stroke with Keep selected off leaves nothing selected: Illustrator starts the stroke
|
||||
// by dropping the earlier selection, it does not keep it (#5752).
|
||||
s.select(|_, sel| sel.clear())?;
|
||||
@@ -978,4 +1017,23 @@ mod bend_tests {
|
||||
assert_eq!(pts[2], Point::new(48.0, 0.0), "{pts:?}");
|
||||
assert_eq!(pts[1], Point::new(44.0, 0.0), "halfway, half of each end's shift: {pts:?}");
|
||||
}
|
||||
|
||||
/// With points far apart (a stroke sent by a script), the bend still stops `reach` along the
|
||||
/// stroke: a point is added there, and the stroke beyond it stays as drawn.
|
||||
#[test]
|
||||
fn bend_ends_stops_at_the_reach_between_points_far_apart() {
|
||||
let mut pts = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(200.0, 0.0)];
|
||||
bend_ends(&mut pts, Some(Point::new(0.0, 10.0)), Some(Point::new(200.0, 0.0)), 40.0);
|
||||
assert_eq!(pts.first(), Some(&Point::new(0.0, 10.0)), "{pts:?}");
|
||||
assert!(pts.contains(&Point::new(40.0, 0.0)), "a point where the bend stops: {pts:?}");
|
||||
assert!(pts.iter().filter(|p| p.x >= 40.0).all(|p| p.y == 0.0), "beyond the reach, as drawn: {pts:?}");
|
||||
}
|
||||
|
||||
/// Where both bends stop at the same place, one point is added there, not two.
|
||||
#[test]
|
||||
fn bend_ends_adds_one_point_where_both_bends_stop() {
|
||||
let mut pts = vec![Point::new(0.0, 0.0), Point::new(100.0, 0.0)];
|
||||
bend_ends(&mut pts, Some(Point::new(0.0, 10.0)), Some(Point::new(100.0, 10.0)), 50.0);
|
||||
assert_eq!(pts, [Point::new(0.0, 10.0), Point::new(50.0, 0.0), Point::new(100.0, 10.0)]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1357,10 +1357,7 @@ fn brush_freehand_refuses_unknown_keys() {
|
||||
let spec = crate::cmd::find_command("brush.freehand").unwrap();
|
||||
let mut keys = crate::cmd::params::accepted_keys(spec.params).expect("the description names every key");
|
||||
keys.sort_unstable();
|
||||
assert_eq!(
|
||||
keys,
|
||||
["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "leaveSelection", "points", "redraw", "style"]
|
||||
);
|
||||
assert_eq!(keys, ["brush", "closed", "connect", "extend", "fidelity", "fill", "fit", "keepSelected", "points", "preview", "redraw", "style"]);
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
select(&mut s, &[a]);
|
||||
|
||||
@@ -552,6 +552,28 @@ fn pencil_redraws_the_shorter_way_round_a_closed_path() {
|
||||
assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "redraw": {"id": id.0, "within": -1}})).is_err());
|
||||
}
|
||||
|
||||
/// `preview` draws the stroke as a new path on top, beside the selected path, and leaves the
|
||||
/// selection as it was, in Draw Behind and Draw Inside too, as the Pencil previews a stroke that
|
||||
/// redraws a selected path.
|
||||
#[test]
|
||||
fn pencil_preview_draws_on_top_and_leaves_the_selection_as_it_was() {
|
||||
for mode in ["normal", "behind", "inside"] {
|
||||
let mut s = session();
|
||||
let r = rect(&mut s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
|
||||
s.execute("view.drawMode", &json!({ "mode": mode })).unwrap();
|
||||
let (parent, _, _) = s.doc().unwrap().doc.position(r).unwrap();
|
||||
let out =
|
||||
s.execute("path.freehand", &json!({"points": [[100, 200], [150, 220], [200, 200]], "keepSelected": false, "preview": true})).unwrap();
|
||||
let id = NodeId(out["id"].as_u64().unwrap());
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let ((rp, ri, _), (np, ni, _)) = (d.position(r).unwrap(), d.position(id).unwrap());
|
||||
assert!(rp == parent && np == parent, "{mode}: beside the path, in no clip group");
|
||||
assert!(ni > ri, "{mode}: on top of the path");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, vec![r], "{mode}: the selection as it was");
|
||||
}
|
||||
}
|
||||
|
||||
/// With Keep selected off, a new stroke leaves nothing selected (the earlier selection goes too,
|
||||
/// as Illustrator starts the stroke by dropping it, #5752); a continued or redrawn path is
|
||||
/// deselected and the rest of the selection stays. The stroke is one undo step.
|
||||
@@ -617,8 +639,14 @@ fn freehand_with_fit_off_joins_the_points_with_straight_segments() {
|
||||
.unwrap();
|
||||
let sp = path(&s, r).subpaths[0].clone();
|
||||
assert!(corners(&sp), "{:?}", sp.anchors);
|
||||
// Each end's bend stops `within` (4) along the stroke, at a point added on its first and last
|
||||
// piece; the drawn points beyond stay as drawn.
|
||||
let inner: Vec<_> = at(&sp).into_iter().filter(|p| p.1 < 499.0).collect();
|
||||
assert_eq!(inner, [(125.0, 470.0), (150.0, 460.0), (175.0, 470.0)]);
|
||||
let t = 4.0 / 25f64.hypot(31.0);
|
||||
let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9;
|
||||
assert_eq!(inner.len(), 5, "{inner:?}");
|
||||
assert!(near(inner[0], (100.0 + 25.0 * t, 501.0 - 31.0 * t)) && near(inner[4], (200.0 - 25.0 * t, 501.0 - 31.0 * t)), "{inner:?}");
|
||||
assert_eq!(inner[1..4], [(125.0, 470.0), (150.0, 460.0), (175.0, 470.0)]);
|
||||
assert!(s.execute("path.freehand", &json!({"points": [[0, 0], [1, 1]], "fit": "no"})).is_err());
|
||||
}
|
||||
|
||||
|
||||
@@ -1583,8 +1583,9 @@ impl GestureTool {
|
||||
|
||||
/// The preview of a stroke being drawn: [`Self::freehand_params`], except that a stroke that
|
||||
/// redraws a selected path is shown as it is drawn, joined at its start to the point of the
|
||||
/// path nearest to it, with no fill, and leaves the path and the selection as they are: where
|
||||
/// the stroke ends is only known at the release, which redraws the path (`finish`).
|
||||
/// path nearest to it, with no fill, on top in any drawing mode, and leaves the path and the
|
||||
/// selection as they are: where the stroke ends is only known at the release, which redraws
|
||||
/// the path (`finish`).
|
||||
fn drawing_params(&self, cx: &ToolContext) -> Value {
|
||||
let mut v = self.freehand_params(cx, false);
|
||||
let Some((id, _)) = self.redraw else { return v };
|
||||
@@ -1593,7 +1594,7 @@ impl GestureTool {
|
||||
}
|
||||
v["fill"] = json!(false);
|
||||
v["keepSelected"] = json!(false);
|
||||
v["leaveSelection"] = json!(true);
|
||||
v["preview"] = json!(true);
|
||||
let on = self.points.first().and_then(|&p| cx.doc.node(id)?.path_data()?.nearest(p)).map(|n| n.3);
|
||||
if let (Some(on), Some(pts)) = (on, v["points"].as_array_mut()) {
|
||||
pts.insert(0, json!([on.x, on.y]));
|
||||
|
||||
@@ -885,7 +885,7 @@ fn pencil_previews_a_redraw_as_the_stroke_drawn_and_redraws_at_the_release() {
|
||||
let previews: Vec<&Value> = drawing.iter().flatten().filter_map(|a| if let Action::Preview(_, v) = a { Some(v) } else { None }).collect();
|
||||
assert!(!previews.is_empty(), "{acts:?}");
|
||||
for v in previews {
|
||||
assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["leaveSelection"] == true, "{v}");
|
||||
assert!(v.get("redraw").is_none() && v["fill"] == false && v["keepSelected"] == false && v["preview"] == true, "{v}");
|
||||
assert_eq!(v["points"][0], json!([350.0, 300.0]), "joined to the path where it starts: {v}");
|
||||
assert_eq!(v["points"][1], json!([350.0, 304.0]), "{v}");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user