mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 15:26:50 +00:00
Merge pull request #8002 from dotCooCoo/fix/tool-overlays-long-drag-copies
Tool overlays: long drags keep their line in shared pieces instead of rebuilding it every frame
This commit is contained in:
@@ -30,9 +30,11 @@
|
||||
//! line to 45° steps from the canvas axes.
|
||||
|
||||
mod area;
|
||||
mod line;
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{Calligraphic, Variation};
|
||||
@@ -44,6 +46,7 @@ use super::{FEEDBACK, blob_area, blob_tip, eraser_tip, points_json, polyline};
|
||||
use crate::guides::DrawSnap;
|
||||
use crate::{Action, Cursor, Mods, Overlay, PenPose, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
use area::{AreaKey, AreaPreview};
|
||||
use line::LinePreview;
|
||||
|
||||
/// How far from its drag the Smooth tool smooths, in screen pixels. Alt smoothing with the
|
||||
/// Pencil, Paintbrush or Blob Brush uses the same radius.
|
||||
@@ -217,6 +220,8 @@ pub struct GestureTool {
|
||||
band: Cell<Option<SmoothBand>>,
|
||||
/// The band last shown does not cover the whole drag yet; the next call adds to it.
|
||||
band_pending: Cell<bool>,
|
||||
/// The pieces of a long drag's line shown so far ([`LinePreview`]).
|
||||
line: Cell<Option<LinePreview>>,
|
||||
}
|
||||
|
||||
/// The band a smoothing drag smooths, for the drag's first `used` points at `radius`, kept as its
|
||||
@@ -239,8 +244,8 @@ struct SmoothBand {
|
||||
dirty_long: BTreeSet<usize>,
|
||||
/// The band changed since `shown` was made.
|
||||
changed: bool,
|
||||
/// The outline last finished.
|
||||
shown: Option<BezPath>,
|
||||
/// The outline last finished, shared with the overlays that show it until it is made again.
|
||||
shown: Option<Arc<BezPath>>,
|
||||
/// The work done on long segments in the current call ([`BAND_WORK_PER_CALL`]).
|
||||
work: usize,
|
||||
}
|
||||
@@ -496,7 +501,7 @@ impl SmoothBand {
|
||||
/// The band's outline: the last one finished. While the band has changed since, the parts it
|
||||
/// changed are made again, until [`BAND_WORK_PER_CALL`] is spent in the call; when all are
|
||||
/// made, the outline is joined from them ([`SmoothBand::make_outline`]).
|
||||
fn outline(&mut self) -> Option<BezPath> {
|
||||
fn outline(&mut self) -> Option<Arc<BezPath>> {
|
||||
while self.changed {
|
||||
if !self.dirty_tiles.is_empty() || !self.dirty_long.is_empty() {
|
||||
if self.work >= BAND_WORK_PER_CALL {
|
||||
@@ -516,7 +521,7 @@ impl SmoothBand {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self.shown = Some(self.make_outline());
|
||||
self.shown = Some(Arc::new(self.make_outline()));
|
||||
self.changed = false;
|
||||
}
|
||||
}
|
||||
@@ -903,6 +908,7 @@ impl GestureTool {
|
||||
area_pending: Cell::new(false),
|
||||
band: Cell::new(None),
|
||||
band_pending: Cell::new(false),
|
||||
line: Cell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1154,6 +1160,7 @@ impl GestureTool {
|
||||
self.area_pending.set(false);
|
||||
self.band.set(None);
|
||||
self.band_pending.set(false);
|
||||
self.line.set(None);
|
||||
}
|
||||
|
||||
/// The outline of the band a smoothing drag smooths: every point within `radius` of the drag,
|
||||
@@ -1166,8 +1173,9 @@ impl GestureTool {
|
||||
/// outside the squares, and one whose outlines cannot be combined adds nothing. Either way the
|
||||
/// band goes on past it. The work on such long segments stops for the call once
|
||||
/// [`BAND_WORK_PER_CALL`] is spent, and the drag is added to the band only once the outline of
|
||||
/// what it holds is finished.
|
||||
fn smooth_band(&self, radius: f64) -> Option<BezPath> {
|
||||
/// what it holds is finished. The outline is the same shared path from one call to the next
|
||||
/// until the band changes.
|
||||
fn smooth_band(&self, radius: f64) -> Option<Arc<BezPath>> {
|
||||
let pts = &self.points;
|
||||
let &first = pts.first()?;
|
||||
let mut b = self
|
||||
@@ -1845,7 +1853,7 @@ impl Tool for GestureTool {
|
||||
&& has_selected_smooth_path(cx)
|
||||
&& let Some(path) = self.smooth_band(cx.tol(SMOOTH_RADIUS))
|
||||
{
|
||||
o.push(Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: true });
|
||||
o.push(Overlay::SharedPath { path, color: FEEDBACK, width: 1.0, dash: Some(0.0) });
|
||||
}
|
||||
// A Blob Brush drag that smooths shows the Smooth tool's thin line.
|
||||
let width = match self.id {
|
||||
@@ -1878,17 +1886,34 @@ impl Tool for GestureTool {
|
||||
let sized = |[angle, roundness, size]: [f64; 3]| [angle, roundness, if size_varies { size } else { self.size }];
|
||||
area.step(&self.points, &|i| sized(self.tip_of_point(i)), &|j| sized(self.tip_between(j)));
|
||||
let paths = area.paths(&self.points);
|
||||
o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0 }));
|
||||
o.extend(paths.settled.into_iter().map(|path| Overlay::SharedPath { path, color, width: 1.0, dash: None }));
|
||||
o.extend(paths.live.into_iter().map(|path| Overlay::Path { path, color, width: 1.0, dashed: false }));
|
||||
self.area_pending.set(area.pending(&self.points));
|
||||
self.area.set(Some(area));
|
||||
} else if size_varies {
|
||||
// With Size on a mode that follows the pen, each step of the drag shows as wide as the
|
||||
// tip the pen gives at its ends.
|
||||
for (j, seg) in self.points.windows(2).enumerate() {
|
||||
let width = (self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom;
|
||||
o.push(Overlay::Path { path: polyline(seg), color, width: width as f32, dashed: false });
|
||||
// tip the pen gives at its ends. A long drag's steps are kept from call to call
|
||||
// ([`LinePreview::segments`]).
|
||||
let width_of = |j: usize| ((self.tip_of_point(j)[2] + self.tip_of_point(j + 1)[2]) / 2.0 * cx.zoom) as f32;
|
||||
if self.points.len() > line::PIECE_SEGMENTS + 1 {
|
||||
let mut kept = self.line.take().unwrap_or_default();
|
||||
for (j, path) in kept.segments(&self.points).into_iter().enumerate() {
|
||||
o.push(Overlay::SharedPath { path, color, width: width_of(j), dash: None });
|
||||
}
|
||||
self.line.set(Some(kept));
|
||||
} else {
|
||||
for (j, seg) in self.points.windows(2).enumerate() {
|
||||
o.push(Overlay::Path { path: polyline(seg), color, width: width_of(j), dashed: false });
|
||||
}
|
||||
}
|
||||
} else if self.points.len() > line::PIECE_SEGMENTS + 1 {
|
||||
// A long drag's line shows in pieces kept from call to call ([`LinePreview::pieces`]).
|
||||
let mut kept = self.line.take().unwrap_or_default();
|
||||
let dashed = self.id == "knife";
|
||||
for piece in kept.pieces(&self.points) {
|
||||
o.push(Overlay::SharedPath { path: piece.path, color, width, dash: dashed.then_some(piece.along) });
|
||||
}
|
||||
self.line.set(Some(kept));
|
||||
} else {
|
||||
o.push(Overlay::Path { path: polyline(&self.points), color, width, dashed: self.id == "knife" });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
//! The line a drag shows while it is dragged where it does not show the area its tip covers (a
|
||||
//! round Eraser tip, the Knife, the Pencil with Live preview off, a smoothing drag), kept in
|
||||
//! pieces that later calls return again unchanged.
|
||||
//!
|
||||
//! A drag of more than [`PIECE_SEGMENTS`] segments is cut into pieces of that many segments. A
|
||||
//! piece ends halfway along the segment after its last point, where the next piece starts, so that
|
||||
//! a wide line turns at a piece's last point as one line does and no part of the line is drawn
|
||||
//! twice. A piece the drag has gone past is built once and returned again as the
|
||||
//! same shared path; only the last piece is built again, and only when the drag changed it. With
|
||||
//! Size on a mode that follows the pen each segment shows at its own width, so each segment is
|
||||
//! kept as its own path, and only a segment whose ends moved is built again.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_geom::{BezPath, Point};
|
||||
|
||||
use super::super::polyline;
|
||||
|
||||
/// The segments of a drag from the first point of one piece of its line to the first point of the
|
||||
/// next.
|
||||
pub(super) const PIECE_SEGMENTS: usize = 64;
|
||||
|
||||
/// A piece of the line along the drag's points `from` to `to`: from point `from`, or halfway to the
|
||||
/// point after it in a piece other than the first, and up to point `to`, or halfway to it in a
|
||||
/// piece the drag has gone past.
|
||||
struct Piece {
|
||||
path: Arc<BezPath>,
|
||||
from: usize,
|
||||
to: usize,
|
||||
/// The drag's point `to` when the piece was built.
|
||||
end: Point,
|
||||
/// The length of the line before the piece's first point.
|
||||
along: f64,
|
||||
/// The length of the piece.
|
||||
length: f64,
|
||||
}
|
||||
|
||||
/// A piece of the line to show ([`LinePreview::pieces`]).
|
||||
pub(super) struct LinePiece {
|
||||
/// The same shared path as in the call before while the piece did not change.
|
||||
pub path: Arc<BezPath>,
|
||||
/// The length of the line before the piece, where a dashed line's pattern goes on.
|
||||
pub along: f64,
|
||||
}
|
||||
|
||||
/// The pieces of a long drag's line, as far as they are built.
|
||||
#[derive(Default)]
|
||||
pub(super) struct LinePreview {
|
||||
/// The pieces the drag has gone past, in order.
|
||||
settled: Vec<Piece>,
|
||||
/// The last piece, up to the drag's last point.
|
||||
last: Option<Piece>,
|
||||
/// Each segment of the drag as its own path, with the points it runs between.
|
||||
segments: Vec<(Point, Point, Arc<BezPath>)>,
|
||||
/// The points copied into new paths by the last call.
|
||||
built: usize,
|
||||
}
|
||||
|
||||
impl LinePreview {
|
||||
/// The points copied into new paths by the last call.
|
||||
#[cfg(test)]
|
||||
pub(super) fn built(&self) -> usize {
|
||||
self.built
|
||||
}
|
||||
|
||||
/// The pieces of the line through `pts`: the pieces kept from the call before while the drag
|
||||
/// still runs through their points, and new ones for the rest.
|
||||
pub(super) fn pieces(&mut self, pts: &[Point]) -> Vec<LinePiece> {
|
||||
self.built = 0;
|
||||
// The drag no longer runs through the points of a kept piece (another drag, or a drag
|
||||
// made again from its press).
|
||||
let runs_through = |p: &Piece| pts.get(p.to) == Some(&p.end) && p.path.elements().first().and_then(|e| e.end_point()) == start(pts, p.from);
|
||||
if let Some(k) = self.settled.iter().position(|p| !runs_through(p)) {
|
||||
self.settled.truncate(k);
|
||||
self.last = None;
|
||||
}
|
||||
// A piece settles once the drag has gone past its last point, which can still move. It
|
||||
// then ends halfway along the segment after that point, so it is built again.
|
||||
loop {
|
||||
let from = self.settled.len() * PIECE_SEGMENTS;
|
||||
let to = from + PIECE_SEGMENTS + 1;
|
||||
if to + 1 >= pts.len() {
|
||||
break;
|
||||
}
|
||||
let along = self.along_next();
|
||||
let piece = self.build(pts, from, to, true, along);
|
||||
self.settled.push(piece);
|
||||
}
|
||||
let from = self.settled.len() * PIECE_SEGMENTS;
|
||||
let to = pts.len().saturating_sub(1);
|
||||
if to > from {
|
||||
let along = self.along_next();
|
||||
// The last piece's points other than its last can change only with its last one, or
|
||||
// with the drag's length.
|
||||
let kept =
|
||||
self.last.take().filter(|p| p.from == from && p.to == to && run(pts, from, to, false).is_some_and(|run| same_points(&p.path, run)));
|
||||
self.last = Some(match kept {
|
||||
Some(p) => p,
|
||||
None => self.build(pts, from, to, false, along),
|
||||
});
|
||||
} else {
|
||||
self.last = None;
|
||||
}
|
||||
self.settled.iter().chain(&self.last).map(|p| LinePiece { path: Arc::clone(&p.path), along: p.along }).collect()
|
||||
}
|
||||
|
||||
/// Each segment of the line through `pts` as its own path: the same shared path as in the
|
||||
/// call before while the segment's ends did not move.
|
||||
pub(super) fn segments(&mut self, pts: &[Point]) -> Vec<Arc<BezPath>> {
|
||||
self.built = 0;
|
||||
let n = pts.len().saturating_sub(1);
|
||||
self.segments.truncate(n);
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for (j, w) in pts.windows(2).enumerate() {
|
||||
match self.segments.get(j) {
|
||||
Some((a, b, path)) if *a == w[0] && *b == w[1] => out.push(Arc::clone(path)),
|
||||
_ => {
|
||||
let path = Arc::new(polyline(w));
|
||||
self.built += 2;
|
||||
match self.segments.get_mut(j) {
|
||||
Some(kept) => *kept = (w[0], w[1], Arc::clone(&path)),
|
||||
None => self.segments.push((w[0], w[1], Arc::clone(&path))),
|
||||
}
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The length of the line before the piece after the settled ones.
|
||||
fn along_next(&self) -> f64 {
|
||||
self.settled.last().map_or(0.0, |p| p.along + p.length)
|
||||
}
|
||||
|
||||
/// The piece along the points `from` to `to` of `pts` ([`run`]), `along` the line.
|
||||
fn build(&mut self, pts: &[Point], from: usize, to: usize, settled: bool, along: f64) -> Piece {
|
||||
let points: Vec<Point> = run(pts, from, to, settled).map(Iterator::collect).unwrap_or_default();
|
||||
self.built += points.len();
|
||||
let length = points.windows(2).map(|w| w[0].distance(w[1])).sum();
|
||||
Piece { path: Arc::new(polyline(&points)), from, to, end: pts.get(to).copied().unwrap_or_default(), along, length }
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a piece from the point `from` of `pts` starts: at the point in the first piece, else
|
||||
/// halfway to the point after it, where the piece before ends.
|
||||
fn start(pts: &[Point], from: usize) -> Option<Point> {
|
||||
if from == 0 { pts.first().copied() } else { Some(pts.get(from)?.midpoint(*pts.get(from + 1)?)) }
|
||||
}
|
||||
|
||||
/// The points of the piece along the points `from` to `to` of `pts`: from its [`start`], through
|
||||
/// the points after `from`, to point `to`, or, in a piece the drag has gone past (`settled`), to
|
||||
/// halfway between the point before `to` and point `to`.
|
||||
fn run(pts: &[Point], from: usize, to: usize, settled: bool) -> Option<impl Iterator<Item = Point> + '_> {
|
||||
let first = start(pts, from)?;
|
||||
let inner = pts.get(from + 1..if settled { to } else { to + 1 })?;
|
||||
let last = if settled { Some(pts.get(to.checked_sub(1)?)?.midpoint(*pts.get(to)?)) } else { None };
|
||||
Some(std::iter::once(first).chain(inner.iter().copied()).chain(last))
|
||||
}
|
||||
|
||||
/// Does `path` run through exactly the points `pts`?
|
||||
fn same_points(path: &BezPath, mut pts: impl Iterator<Item = Point>) -> bool {
|
||||
path.elements().iter().all(|e| e.end_point().is_some() && e.end_point() == pts.next()) && pts.next().is_none()
|
||||
}
|
||||
@@ -1195,7 +1195,14 @@ fn pencil_alt_smooths_within_the_smooth_tools_radius() {
|
||||
|
||||
/// The dashed paths among the overlays.
|
||||
fn bands(t: &GestureTool, cx: &ToolContext) -> Vec<vectorcraft_geom::BezPath> {
|
||||
t.overlays(cx).into_iter().filter_map(|o| if let Overlay::Path { path, dashed: true, .. } = o { Some(path) } else { None }).collect()
|
||||
t.overlays(cx)
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
Overlay::Path { path, dashed: true, .. } => Some(path),
|
||||
Overlay::SharedPath { path, dash: Some(_), .. } => Some((*path).clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How far `q` is from the polyline through `pts`.
|
||||
@@ -1344,6 +1351,12 @@ fn smoothing_band_follows_a_long_drag() {
|
||||
assert_eq!(frames, (n - 1).div_ceil(BAND_STEP * BAND_STEPS_PER_CALL), "frames for {n} points");
|
||||
check_band(&t, &cx, cx.tol(12.0));
|
||||
assert!(!t.overlays_pending());
|
||||
// Once finished, the band shows as the same shared path each frame.
|
||||
let band_of = |t: &GestureTool| {
|
||||
t.overlays(&cx).into_iter().find_map(|o| if let Overlay::SharedPath { path, dash: Some(_), .. } = o { Some(path) } else { None })
|
||||
};
|
||||
let (a, b) = (band_of(&t), band_of(&t));
|
||||
assert!(a.zip(b).is_some_and(|(a, b)| std::sync::Arc::ptr_eq(&a, &b)), "the band is not made again");
|
||||
let last = pts[pts.len() - 1];
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Up, last.x, last.y));
|
||||
// The next drag shows only its own band.
|
||||
@@ -1623,7 +1636,7 @@ fn smoothing_drag_shows_no_band_without_a_path_it_smooths() {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 300.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 400.0, 300.0));
|
||||
let o = t.overlays(&cx);
|
||||
assert!(!o.iter().any(|o| matches!(o, Overlay::Path { dashed: true, .. })), "{o:?}");
|
||||
assert!(bands(&t, &cx).is_empty(), "{o:?}");
|
||||
}
|
||||
|
||||
/// An Alt smoothing drag uses the Smooth tool's Fidelity for Pencil, Paintbrush and Blob Brush.
|
||||
@@ -2500,7 +2513,7 @@ fn the_blob_brush_sends_its_tip_and_shows_the_area_it_covers() {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0).with_mods(alt));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0).with_mods(alt));
|
||||
let o = t.overlays(&cx);
|
||||
let [Overlay::Path { dashed: true, .. }, Overlay::Path { path, width, dashed: false, .. }] = &o[..] else { panic!("{o:?}") };
|
||||
let [Overlay::SharedPath { dash: Some(_), .. }, Overlay::Path { path, width, dashed: false, .. }] = &o[..] else { panic!("{o:?}") };
|
||||
assert_eq!(*width, 1.0);
|
||||
assert!(vectorcraft_geom::Shape::bounding_box(path).height() < 0.1, "{o:?}");
|
||||
}
|
||||
@@ -2660,6 +2673,112 @@ fn the_settled_outline_of_a_long_drag_is_the_same_shared_path_each_frame() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The points the last `overlays` call copied into new paths for a drag's line.
|
||||
fn line_built(t: &GestureTool) -> usize {
|
||||
let line = t.line.take();
|
||||
let built = line.as_ref().map_or(0, |l| l.built());
|
||||
t.line.set(line);
|
||||
built
|
||||
}
|
||||
|
||||
/// The points of piece `k` of the line of a drag through `pts`. A piece other than the first starts
|
||||
/// halfway along the segment after its first point, and a piece other than the last (`settled`)
|
||||
/// ends halfway along the segment after its last point, where the next piece starts.
|
||||
fn piece_points(pts: &[Point], k: usize, settled: bool) -> Vec<Point> {
|
||||
let from = k * line::PIECE_SEGMENTS;
|
||||
let to = if settled { from + line::PIECE_SEGMENTS } else { pts.len() - 1 };
|
||||
let mut want = vec![if k == 0 { pts[0] } else { pts[from].midpoint(pts[from + 1]) }];
|
||||
want.extend_from_slice(&pts[from + 1..=to]);
|
||||
if settled {
|
||||
want.push(pts[to].midpoint(pts[to + 1]));
|
||||
}
|
||||
want
|
||||
}
|
||||
|
||||
/// The line of a long round Eraser, Knife, Path Eraser or Pencil (Live preview off) drag shows in
|
||||
/// pieces, and the steps of a round Eraser drag whose Size follows the pen each as its own path.
|
||||
/// They come back from one call to the next, at any zoom, as the same shared paths, which the host
|
||||
/// draws again without building them again; the call copies no point into a new path. A step of
|
||||
/// the drag builds again only the last piece, or adds one step. The pieces run through every point
|
||||
/// of the drag, each from where the one before ends, halfway along a segment, so no part of the
|
||||
/// line is drawn twice, and the Knife's dashes go on from one piece to the next.
|
||||
#[test]
|
||||
fn the_line_of_a_long_drag_is_the_same_shared_pieces_each_frame() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let mut s = Selection::default();
|
||||
s.set([id]);
|
||||
let p = paint();
|
||||
let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
|
||||
let shared = |o: &[Overlay]| -> Vec<(std::sync::Arc<BezPath>, f32, Option<f64>)> {
|
||||
o.iter()
|
||||
.filter_map(
|
||||
|o| if let Overlay::SharedPath { path, width, dash, .. } = o { Some((std::sync::Arc::clone(path), *width, *dash)) } else { None },
|
||||
)
|
||||
.collect()
|
||||
};
|
||||
let points_of = |p: &BezPath| -> Vec<Point> { p.elements().iter().filter_map(|e| e.end_point()).collect() };
|
||||
let n = 3000;
|
||||
for (id, pressure) in [("eraser", false), ("knife", false), ("pathEraser", false), ("pencil", false), ("eraser", true)] {
|
||||
let mut t = GestureTool::new(id);
|
||||
t.set_option("size", &json!(10));
|
||||
t.set_option("livePreview", &json!(false));
|
||||
if pressure {
|
||||
t.set_option("sizeMode", &json!("pressure"));
|
||||
t.set_option("sizeVariation", &json!(4));
|
||||
}
|
||||
long_area_drag(&mut t, &cx, n, |i| if pressure { 0.3 + 0.6 * ((i % 50) as f32 / 50.0) } else { 1.0 });
|
||||
let first = shared(&t.overlays(&cx));
|
||||
assert!(t.overlays(&cx).iter().all(|o| !matches!(o, Overlay::Path { .. })), "{id}: no path of the drag is built for the call alone");
|
||||
if pressure {
|
||||
assert_eq!(first.len(), n - 1, "{id}: a path for each step");
|
||||
for (j, (path, _, dash)) in first.iter().enumerate() {
|
||||
assert_eq!(points_of(path), t.points[j..=j + 1], "{id}: step {j}");
|
||||
assert_eq!(*dash, None);
|
||||
}
|
||||
} else {
|
||||
assert!(first.len() > 1, "{id}: {} pieces", first.len());
|
||||
let mut along = 0.0;
|
||||
for (k, (path, width, dash)) in first.iter().enumerate() {
|
||||
let got = points_of(path);
|
||||
assert_eq!(got, piece_points(&t.points, k, k + 1 < first.len()), "{id}: piece {k}");
|
||||
assert_eq!(*width, if id == "eraser" { 10.0 } else { 1.0 }, "{id}");
|
||||
match dash {
|
||||
Some(at) => assert!(id == "knife" && (at - along).abs() < 1e-6, "{id}: piece {k} dashes from {at}, not {along}"),
|
||||
None => assert_ne!(id, "knife"),
|
||||
}
|
||||
along += got.windows(2).map(|w| w[0].distance(w[1])).sum::<f64>();
|
||||
}
|
||||
assert_eq!(first.len() - 1, (n - 3) / line::PIECE_SEGMENTS, "{id}: the last piece holds the points no settled piece holds");
|
||||
}
|
||||
for zoom in [1.0, 4.0, 1.0] {
|
||||
let again = shared(&t.overlays(&ToolContext { zoom, ..cx }));
|
||||
assert_eq!(line_built(&t), 0, "{id}: at zoom {zoom}, no point is copied into a new path");
|
||||
assert_eq!(again.len(), first.len(), "{id}");
|
||||
assert!(
|
||||
again.iter().zip(&first).all(|(a, b)| std::sync::Arc::ptr_eq(&a.0, &b.0)),
|
||||
"{id}: at zoom {zoom}, every path is the one shown before"
|
||||
);
|
||||
}
|
||||
// One step more along the drag.
|
||||
let s = n as f64;
|
||||
let r = 150.0 + 100.0 * (s * 0.0071).sin();
|
||||
let (x, y) = (300.0 + r * (s * 0.04).cos(), 300.0 + r * (s * 0.04).sin());
|
||||
t.pointer(&cx, &PointerEvent { pressure: 0.5, ..PointerEvent::new(PointerKind::Drag, x, y) });
|
||||
let after = shared(&t.overlays(&cx));
|
||||
let built = line_built(&t);
|
||||
let kept = after.iter().filter(|a| first.iter().any(|f| std::sync::Arc::ptr_eq(&a.0, &f.0))).count();
|
||||
if pressure {
|
||||
assert_eq!((built, after.len(), kept), (2, n, n - 1), "{id}: one step added");
|
||||
} else {
|
||||
assert!(built <= line::PIECE_SEGMENTS + 2, "{id}: {built} points copied");
|
||||
assert_eq!(kept, first.len() - 1, "{id}: only the last piece is built again");
|
||||
}
|
||||
let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y));
|
||||
assert!(!acts.is_empty(), "{id}: the release still acts");
|
||||
assert!(t.line.take().is_none(), "{id}: the release drops the pieces");
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline a Blob Brush or Eraser drag shows does not change what its release sends: the same
|
||||
/// drag sends the same command whether or not its outline was drawn along the way.
|
||||
#[test]
|
||||
|
||||
@@ -73,10 +73,13 @@ pub enum Overlay {
|
||||
SelectionMarquee { rect: Rect, enclosed: bool, pointer: Point },
|
||||
/// A path preview (e.g. pen rubber band) in a colour (RGB).
|
||||
Path { path: BezPath, color: [u8; 3], width: f32, dashed: bool },
|
||||
/// A solid path preview that later calls return again, as the same shared `path`, for as long
|
||||
/// as it does not change (the settled outline of a long Blob Brush or Eraser drag). The host
|
||||
/// can keep what it built to draw it while `path` is the same allocation.
|
||||
SharedPath { path: std::sync::Arc<BezPath>, color: [u8; 3], width: f32 },
|
||||
/// A path preview that later calls return again, as the same shared `path`, for as long as it
|
||||
/// does not change (the settled outline of a long Blob Brush or Eraser drag, the pieces of a long
|
||||
/// drag's line). The host can keep what it built to draw it while `path` is the same allocation.
|
||||
/// With `dash`, it is dashed as a dashed [`Overlay::Path`] is, from `dash` document units along
|
||||
/// the dash pattern: the pieces of one line, each starting where the one before it ends, dash
|
||||
/// as the whole line does.
|
||||
SharedPath { path: std::sync::Arc<BezPath>, color: [u8; 3], width: f32, dash: Option<f64> },
|
||||
/// A line segment (smart guide, handle line).
|
||||
Line { a: Point, b: Point, color: [u8; 3], dashed: bool },
|
||||
/// An anchor square: filled = selected.
|
||||
|
||||
@@ -395,20 +395,76 @@ struct SharedKey {
|
||||
/// The painter's clip: the lines of the path outside it have no triangles in the mesh.
|
||||
clip: egui::Rect,
|
||||
stroke: Stroke,
|
||||
/// Where the dash pattern starts along the path, in document units, when it is dashed.
|
||||
dash: Option<f64>,
|
||||
pixels_per_point: f32,
|
||||
tessellation: TessellationOptions,
|
||||
}
|
||||
|
||||
/// The length of a dash of a dashed overlay, in screen pixels.
|
||||
const DASH: f32 = 4.0;
|
||||
/// The length of the gap after each dash of a dashed overlay, in screen pixels.
|
||||
const GAP: f32 = 3.0;
|
||||
|
||||
/// Add to `out` the dashes of `line` drawn with `s`, [`DASH`] pixels drawn and [`GAP`] left out,
|
||||
/// with the pattern started `from` pixels along it: from 0, the dashes [`Shape::dashed_line`] gives.
|
||||
pub(super) fn dashes_from(line: &[Pos2], s: Stroke, from: f64, out: &mut Vec<Shape>) {
|
||||
let period = f64::from(DASH + GAP);
|
||||
let phase = from.rem_euclid(period);
|
||||
let phase = if phase.is_finite() { phase as f32 } else { 0.0 };
|
||||
if line.len() < 2 {
|
||||
return;
|
||||
}
|
||||
if phase >= DASH {
|
||||
Shape::dashed_line_many_with_offset(line, s, &[DASH], &[GAP], DASH + GAP - phase, out);
|
||||
return;
|
||||
}
|
||||
// The pattern starts within a dash: the rest of that dash is drawn, then the pattern goes on
|
||||
// after its gap.
|
||||
let mut left = DASH - phase;
|
||||
for (i, w) in line.windows(2).enumerate() {
|
||||
let len = (w[1] - w[0]).length();
|
||||
if len >= left {
|
||||
let cut = w[0] + (w[1] - w[0]) * (left / len);
|
||||
let mut dash = line[..=i].to_vec();
|
||||
dash.push(cut);
|
||||
segments(&dash, s, out);
|
||||
let mut rest = vec![cut];
|
||||
rest.extend_from_slice(&line[i + 1..]);
|
||||
Shape::dashed_line_many_with_offset(&rest, s, &[DASH], &[GAP], GAP, out);
|
||||
return;
|
||||
}
|
||||
left -= len;
|
||||
}
|
||||
segments(line, s, out);
|
||||
}
|
||||
|
||||
/// Add to `out` each line of `line` that has a length as its own [`Shape::LineSegment`], as
|
||||
/// [`Shape::dashed_line`] draws a dash.
|
||||
fn segments(line: &[Pos2], s: Stroke, out: &mut Vec<Shape>) {
|
||||
out.extend(line.windows(2).filter(|w| w[0] != w[1]).map(|w| Shape::line_segment([w[0], w[1]], s)));
|
||||
}
|
||||
|
||||
impl SharedPaths {
|
||||
/// The mesh that draws `path` with `s` at the view `xf` with the painter `p`: the one kept in
|
||||
/// this frame or in `last` (the last frame's) when it was built for the same, else a new one.
|
||||
/// It is kept for the next frame.
|
||||
fn mesh(&mut self, last: &mut HashMap<usize, SharedMesh>, path: &Arc<BezPath>, xf: &Xf, s: Stroke, p: &egui::Painter) -> Arc<Mesh> {
|
||||
/// The mesh that draws `path` with `s`, dashed from `dash` document units along the pattern
|
||||
/// when that is set, at the view `xf` with the painter `p`: the one kept in this frame or in
|
||||
/// `last` (the last frame's) when it was built for the same, else a new one. It is kept for
|
||||
/// the next frame.
|
||||
fn mesh(
|
||||
&mut self,
|
||||
last: &mut HashMap<usize, SharedMesh>,
|
||||
path: &Arc<BezPath>,
|
||||
xf: &Xf,
|
||||
s: Stroke,
|
||||
dash: Option<f64>,
|
||||
p: &egui::Painter,
|
||||
) -> Arc<Mesh> {
|
||||
let ctx = p.ctx();
|
||||
let key = SharedKey {
|
||||
view: xf.affine().as_coeffs(),
|
||||
clip: p.clip_rect(),
|
||||
stroke: s,
|
||||
dash,
|
||||
pixels_per_point: ctx.pixels_per_point(),
|
||||
tessellation: ctx.tessellation_options(|o| *o),
|
||||
};
|
||||
@@ -425,7 +481,16 @@ impl SharedPaths {
|
||||
tessellator.set_clip_rect(key.clip);
|
||||
let mut mesh = Mesh::default();
|
||||
for line in to_screen_path(path, xf) {
|
||||
tessellator.tessellate_shape(Shape::line(line, s), &mut mesh);
|
||||
match dash {
|
||||
Some(from) => {
|
||||
let mut dashes = vec![];
|
||||
dashes_from(&line, s, from * xf.zoom, &mut dashes);
|
||||
for d in dashes {
|
||||
tessellator.tessellate_shape(d, &mut mesh);
|
||||
}
|
||||
}
|
||||
None => tessellator.tessellate_shape(Shape::line(line, s), &mut mesh),
|
||||
}
|
||||
}
|
||||
SharedMesh { path: Arc::clone(path), key, mesh: Arc::new(mesh) }
|
||||
}
|
||||
@@ -476,8 +541,8 @@ pub(super) fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t:
|
||||
stroke_path(p, path, xf, s);
|
||||
}
|
||||
}
|
||||
Overlay::SharedPath { path, color, width } => {
|
||||
let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), p);
|
||||
Overlay::SharedPath { path, color, width, dash } => {
|
||||
let mesh = shared.mesh(&mut last, path, xf, Stroke::new(*width, c32(*color)), *dash, p);
|
||||
if !mesh.is_empty() {
|
||||
p.add(Shape::mesh(mesh));
|
||||
}
|
||||
|
||||
@@ -99,7 +99,8 @@ fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() {
|
||||
path.line_to((250.0, 160.0));
|
||||
let a = std::sync::Arc::new(path.clone());
|
||||
let b = std::sync::Arc::new(path.clone());
|
||||
let shared_of = |p: &std::sync::Arc<BezPath>| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0 };
|
||||
let shared_of =
|
||||
|p: &std::sync::Arc<BezPath>| Overlay::SharedPath { path: std::sync::Arc::clone(p), color: [0x80, 0x80, 0x80], width: 1.0, dash: None };
|
||||
let first = one(frame(&[shared_of(&a)], 1.0, &mut shared));
|
||||
assert!(!first.vertices.is_empty());
|
||||
let again = one(frame(&[shared_of(&a)], 1.0, &mut shared));
|
||||
@@ -143,6 +144,71 @@ fn a_shared_tool_path_is_drawn_with_the_mesh_kept_while_it_and_the_view_stay() {
|
||||
half.line_to((5100.0, 5000.0));
|
||||
let half = one(frame(&[shared_of(&std::sync::Arc::new(half))], 1.0, &mut shared));
|
||||
assert_eq!(*half, *first, "the subpath off the canvas adds no triangles");
|
||||
// A dashed shared path keeps its mesh too, and the place its dashes start is part of it.
|
||||
let dashed_of = |p: &std::sync::Arc<BezPath>, dash: f64| Overlay::SharedPath {
|
||||
path: std::sync::Arc::clone(p),
|
||||
color: [0x80, 0x80, 0x80],
|
||||
width: 1.0,
|
||||
dash: Some(dash),
|
||||
};
|
||||
let dashed = one(frame(&[dashed_of(&a, 0.0)], 1.0, &mut shared));
|
||||
assert!(!dashed.vertices.is_empty() && *dashed != *first, "the dashes leave out parts of the line");
|
||||
assert!(std::sync::Arc::ptr_eq(&dashed, &one(frame(&[dashed_of(&a, 0.0)], 1.0, &mut shared))));
|
||||
let moved = one(frame(&[dashed_of(&a, 2.0)], 1.0, &mut shared));
|
||||
assert!(!std::sync::Arc::ptr_eq(&dashed, &moved) && *dashed != *moved, "dashes that start elsewhere build a new mesh");
|
||||
}
|
||||
|
||||
/// A line drawn dashed in pieces, each piece's dashes starting as far along the pattern as the
|
||||
/// pieces before it are long, shows the dashes the whole line shows dashed in one go, whether a
|
||||
/// piece starts within a dash or within a gap, and a pattern started at 0 gives the dashes of
|
||||
/// [`Shape::dashed_line`].
|
||||
#[test]
|
||||
fn a_line_dashed_in_pieces_dashes_as_the_whole_line_does() {
|
||||
// The stretches of x that dashes along the x axis cover, with touching ones joined.
|
||||
let covered = |shapes: &[Shape]| -> Vec<(f32, f32)> {
|
||||
let mut spans: Vec<(f32, f32)> = shapes
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let xs: Vec<f32> = match s {
|
||||
Shape::LineSegment { points, .. } => points.iter().map(|p| p.x).collect(),
|
||||
Shape::Path(p) => p.points.iter().map(|p| p.x).collect(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
(xs.iter().copied().fold(f32::MAX, f32::min), xs.iter().copied().fold(f32::MIN, f32::max))
|
||||
})
|
||||
.collect();
|
||||
spans.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut joined: Vec<(f32, f32)> = vec![];
|
||||
for (a, b) in spans {
|
||||
match joined.last_mut() {
|
||||
Some(last) if a - last.1 < 1e-3 => last.1 = last.1.max(b),
|
||||
_ => joined.push((a, b)),
|
||||
}
|
||||
}
|
||||
joined
|
||||
};
|
||||
let s = Stroke::new(1.0, Color32::WHITE);
|
||||
let along = |xs: &[f32]| -> Vec<Pos2> { xs.iter().map(|&x| pos2(x, 10.0)).collect() };
|
||||
let whole = along(&[0.0, 30.0, 61.5, 100.0]);
|
||||
let mut one_go = vec![];
|
||||
overlays::dashes_from(&whole, s, 0.0, &mut one_go);
|
||||
assert_eq!(covered(&one_go), covered(&Shape::dashed_line(&whole, s, 4.0, 3.0)));
|
||||
// Cuts at 50 (within a dash: 50 is 1 past the dash that starts at 49) and at 75 (within a gap).
|
||||
let mut pieces = vec![];
|
||||
overlays::dashes_from(&along(&[0.0, 30.0, 50.0]), s, 0.0, &mut pieces);
|
||||
overlays::dashes_from(&along(&[50.0, 61.5, 75.0]), s, 50.0, &mut pieces);
|
||||
overlays::dashes_from(&along(&[75.0, 100.0]), s, 75.0, &mut pieces);
|
||||
let (want, got) = (covered(&one_go), covered(&pieces));
|
||||
assert_eq!(want.len(), got.len(), "{want:?} {got:?}");
|
||||
assert!(want.iter().zip(&got).all(|(w, g)| (w.0 - g.0).abs() < 1e-3 && (w.1 - g.1).abs() < 1e-3), "{want:?} {got:?}");
|
||||
// Every dash is drawn as line segments with a length, as `Shape::dashed_line` draws them: the
|
||||
// cut first dash, a dash cut on a vertex (at 4) and a line shorter than the rest of a dash too.
|
||||
let mut ends = vec![];
|
||||
overlays::dashes_from(&along(&[0.0, 4.0, 10.0]), s, 0.0, &mut ends);
|
||||
overlays::dashes_from(&along(&[0.0, 1.0, 2.0]), s, 1.0, &mut ends);
|
||||
for shape in one_go.iter().chain(&pieces).chain(&ends) {
|
||||
assert!(matches!(shape, Shape::LineSegment { points: [a, b], .. } if a != b), "{shape:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1203,7 +1203,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`).
|
||||
Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations).
|
||||
The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`).
|
||||
The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The outline of a drag with a round Eraser tip is drawn whole each frame.
|
||||
The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame.
|
||||
- **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag).
|
||||
A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`).
|
||||
Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing).
|
||||
|
||||
Reference in New Issue
Block a user