mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-22 18:34:42 +01:00
Merge pull request #7256 from dotCooCoo/fix/blob-brush-preview-bounded
Blob Brush and Eraser: the drag outline does a bounded amount of work per frame
This commit is contained in:
5 files changed
+943
-24
No files matched your search
@@ -23,6 +23,8 @@
|
||||
//! pointer, even if Alt is released during the drag. Shift on each drag or release constrains that
|
||||
//! line to 45° steps from the canvas axes.
|
||||
|
||||
mod area;
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -31,9 +33,10 @@ use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, ParamCurve, PathData, PathSeg, Point, Rect, Vec2, shapes};
|
||||
use vectorcraft_pathops as po;
|
||||
|
||||
use super::{FEEDBACK, blob_area, blob_tip, eraser_area, eraser_tip, points_json, polyline};
|
||||
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};
|
||||
|
||||
/// 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.
|
||||
@@ -166,6 +169,15 @@ pub struct GestureTool {
|
||||
/// Where the Blob Brush's or the Eraser's tip outline shows: the pointer over the canvas,
|
||||
/// unless Cmd/Ctrl lends a selection tool or Alt the Smooth tool.
|
||||
tip_at: Option<Point>,
|
||||
/// A pen pressed less than fully at a point of the stroke whose pressure is kept.
|
||||
light: bool,
|
||||
/// The length of the stroke, in points.
|
||||
length: f64,
|
||||
/// The outline of the area a Blob Brush or Eraser drag covers, as far as it is built
|
||||
/// ([`AreaPreview`]).
|
||||
area: Cell<Option<AreaPreview>>,
|
||||
/// The last [`Tool::overlays`] left part of that outline for later calls.
|
||||
area_pending: Cell<bool>,
|
||||
/// The band the smoothing drag has shown so far ([`GestureTool::smooth_band`]).
|
||||
band: Cell<Option<SmoothBand>>,
|
||||
/// The band last shown does not cover the whole drag yet; the next call adds to it.
|
||||
@@ -824,6 +836,10 @@ impl GestureTool {
|
||||
snap: DrawSnap::default(),
|
||||
pressed: Point::ZERO,
|
||||
tip_at: None,
|
||||
light: false,
|
||||
length: 0.0,
|
||||
area: Cell::new(None),
|
||||
area_pending: Cell::new(false),
|
||||
band: Cell::new(None),
|
||||
band_pending: Cell::new(false),
|
||||
}
|
||||
@@ -871,9 +887,13 @@ impl GestureTool {
|
||||
|
||||
/// Add a stroke sample, with the pen's pressure, tilt and rotation of the event `ev` there.
|
||||
fn push(&mut self, p: Point, ev: &PointerEvent) {
|
||||
if let Some(last) = self.points.last() {
|
||||
self.length += last.distance(p);
|
||||
}
|
||||
self.points.push(p);
|
||||
if self.id == "paintbrush" || (self.varies_size() && self.size_pressure) {
|
||||
self.pressures.push(ev.pressure);
|
||||
self.light |= ev.pressure < 1.0;
|
||||
}
|
||||
if self.id == "paintbrush" {
|
||||
self.poses.push(ev.pen.map(PenPose::sanitized));
|
||||
@@ -961,6 +981,10 @@ impl GestureTool {
|
||||
self.poses.clear();
|
||||
self.previewed = 0;
|
||||
self.shift_line = None;
|
||||
self.light = false;
|
||||
self.length = 0.0;
|
||||
self.area.set(None);
|
||||
self.area_pending.set(false);
|
||||
self.band.set(None);
|
||||
self.band_pending.set(false);
|
||||
}
|
||||
@@ -1022,7 +1046,7 @@ impl GestureTool {
|
||||
/// Pressure, when a pen pressed less than fully anywhere along it (a stroke without pressure
|
||||
/// keeps its Size).
|
||||
fn size_pressures(&self) -> Option<&[f32]> {
|
||||
let pressed = self.pressures.len() == self.points.len() && self.pressures.iter().any(|p| *p < 1.0);
|
||||
let pressed = self.pressures.len() == self.points.len() && self.light;
|
||||
(self.varies_size() && self.size_pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice())
|
||||
}
|
||||
|
||||
@@ -1388,10 +1412,10 @@ impl Tool for GestureTool {
|
||||
fn wants_samples(&self) -> bool {
|
||||
matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser")
|
||||
}
|
||||
/// A smoothing drag's band outlined again after a zoom change reaches the whole drag over
|
||||
/// several frames.
|
||||
/// The outline of a long Blob Brush or Eraser drag, and a smoothing drag's band outlined again
|
||||
/// after a zoom change, reach the whole drag over several frames.
|
||||
fn overlays_pending(&self) -> bool {
|
||||
self.band_pending.get()
|
||||
self.area_pending.get() || self.band_pending.get()
|
||||
}
|
||||
/// `[` and `]` are the Blob Brush's and the Eraser's: their size (#1661).
|
||||
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
|
||||
@@ -1443,6 +1467,7 @@ impl Tool for GestureTool {
|
||||
if began { stale.into_iter().chain([Action::Commit]).collect() } else { vec![] }
|
||||
}
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
self.area_pending.set(false);
|
||||
self.band_pending.set(false);
|
||||
let mut o = self.snap.guides().to_vec();
|
||||
// A path being drawn shows itself, except with the Pencil's Live preview off.
|
||||
@@ -1467,24 +1492,24 @@ impl Tool for GestureTool {
|
||||
// A tip that is not round shows the outline of the area it covers, each step of the drag
|
||||
// as wide as the pen pressed there with Size set to Pressure. So does a round Blob Brush
|
||||
// tip: a line as wide as the brush would end square, where the stroke it adds is round at
|
||||
// both ends (#4343).
|
||||
// both ends (#4343). The outline is built a bounded amount per call ([`AreaPreview`]).
|
||||
if matches!(self.id, "eraser" | "blobBrush") && (self.roundness < 100.0 || self.id == "blobBrush") && !self.smoothing {
|
||||
let area = |pts: &[Point], size| {
|
||||
if self.id == "blobBrush" {
|
||||
blob_area(pts, size, self.angle, self.roundness)
|
||||
} else {
|
||||
eraser_area(pts, size, self.angle, self.roundness)
|
||||
}
|
||||
let pressures = self.size_pressures();
|
||||
let key = AreaKey {
|
||||
blob: self.id == "blobBrush",
|
||||
size: self.size,
|
||||
variation: self.size_variation,
|
||||
angle: self.angle,
|
||||
roundness: self.roundness,
|
||||
pressure: pressures.is_some(),
|
||||
};
|
||||
if let Some(pressures) = self.size_pressures() {
|
||||
for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) {
|
||||
let pressure = f64::from(p[0] + p[1]) / 2.0;
|
||||
let size = super::pressure_size(self.size, self.size_variation, pressure);
|
||||
o.push(Overlay::Path { path: area(seg, size).to_bezpath(), color, width: 1.0, dashed: false });
|
||||
}
|
||||
} else {
|
||||
o.push(Overlay::Path { path: area(&self.points, self.size).to_bezpath(), color, width: 1.0, dashed: false });
|
||||
let mut area = self.area.take().filter(|a| a.fits(key, &self.points)).unwrap_or_else(|| AreaPreview::new(key, self.points[0]));
|
||||
area.step(&self.points, pressures);
|
||||
for path in area.paths(&self.points) {
|
||||
o.push(Overlay::Path { path, color, width: 1.0, dashed: false });
|
||||
}
|
||||
self.area_pending.set(area.pending(&self.points));
|
||||
self.area.set(Some(area));
|
||||
} else if let Some(pressures) = self.size_pressures() {
|
||||
// With Size set to Pressure, each step of the drag shows as wide as the pen pressed there.
|
||||
for (seg, p) in self.points.windows(2).zip(pressures.windows(2)) {
|
||||
@@ -1497,7 +1522,7 @@ impl Tool for GestureTool {
|
||||
}
|
||||
if cx.measurement_labels && self.id == "blobBrush" && !self.smoothing {
|
||||
let last = self.points[self.points.len() - 1];
|
||||
let length = self.points.windows(2).map(|w| w[0].distance(w[1])).sum();
|
||||
let length = self.length;
|
||||
o.push(Overlay::Measure { p: last + vectorcraft_geom::Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("L: {}", cx.len(length)) });
|
||||
}
|
||||
// Over the stroke's footprint, which reaches the tip's edge at the pointer.
|
||||
|
||||
@@ -0,0 +1,645 @@
|
||||
//! The outline a Blob Brush or Eraser drag shows while it is dragged: the boundary of the area its
|
||||
//! tip covers, built a bounded amount at a time.
|
||||
//!
|
||||
//! The drag is cut into pieces of up to [`PIECE_SEGMENTS`] segments (one segment each when the
|
||||
//! Size varies with pressure). A call outlines again, in the space where the tip is round, only the
|
||||
//! pieces it added segments to. A piece's outline then loses the parts that lie inside the area
|
||||
//! of another piece, found through a grid of squares that lists the segments near each square, so
|
||||
//! the pieces show as one outline. One call takes at most [`POINTS_PER_CALL`] new points and does at most
|
||||
//! [`WORK_PER_CALL`] units of work, plus the one step it was in; what is left waits for the next
|
||||
//! call ([`AreaPreview::pending`]). Until then a piece shows the outline it last finished, and the
|
||||
//! points not yet taken show as a thin line. The settled pieces show as paths of up to
|
||||
//! [`BLOCK_PIECES`] pieces each, and a call joins again only the paths whose pieces changed, at
|
||||
//! most [`JOIN_PIECES_PER_CALL`] pieces' worth. The grid holds at most [`LISTINGS`] listings.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
|
||||
use vectorcraft_geom::{Affine, BezPath, Line, ParamCurve, PathData, PathEl, PathSeg, Point, SubPath};
|
||||
use vectorcraft_pathops as po;
|
||||
use vectorcraft_pathops::{Cap, Join};
|
||||
|
||||
use super::super::{MIN_BRUSH_SIZE, blob_tip, eraser_tip, pressure_size};
|
||||
|
||||
/// The most segments of a drag that one piece of its outline holds, when the Size does not vary
|
||||
/// with pressure (a piece then holds one segment).
|
||||
pub(super) const PIECE_SEGMENTS: usize = 32;
|
||||
/// The most points of a drag one call takes.
|
||||
pub(super) const POINTS_PER_CALL: usize = 256;
|
||||
/// The most work one call does: one unit for each square of the grid a segment is listed in, and
|
||||
/// for each segment of the drag a piece of an outline is checked against. A call stops before the
|
||||
/// next point or the next segment of an outline once it has done this much.
|
||||
pub(super) const WORK_PER_CALL: usize = 200_000;
|
||||
/// The most segments one square of the grid lists. A segment past them is not listed there, and
|
||||
/// the outlines inside its area there still show.
|
||||
const SQUARE_SEGMENTS: usize = 128;
|
||||
/// The most points, half a square apart, at which a segment of the drag is listed in the squares
|
||||
/// around them. A longer segment is kept in a short list of its own ([`WIDE_SEGMENTS`]).
|
||||
pub(super) const SEGMENT_SAMPLES: usize = 32;
|
||||
/// The most listings all squares of the grid hold together: past them a segment is listed in no
|
||||
/// square, and the outlines inside its area still show.
|
||||
pub(super) const LISTINGS: usize = 4_000_000;
|
||||
/// The most squares, along a side of an outline, whose segments the side is checked against; a
|
||||
/// longer side is checked against the squares at its ends.
|
||||
const SIDE_SQUARES: usize = 128;
|
||||
/// The most pieces one joined path of the outline holds.
|
||||
pub(super) const BLOCK_PIECES: usize = 64;
|
||||
/// The most pieces one call joins into those paths; the others show the path last joined.
|
||||
pub(super) const JOIN_PIECES_PER_CALL: usize = 2048;
|
||||
/// The most segments the list of long segments holds; the outlines inside the area of a long
|
||||
/// segment past them still show.
|
||||
const WIDE_SEGMENTS: usize = 256;
|
||||
/// The most points along a long segment at which the pieces near it are looked for.
|
||||
const WIDE_SAMPLES: usize = 128;
|
||||
/// The most points the thin line over the points not yet taken has.
|
||||
const GUIDE_POINTS: usize = 256;
|
||||
/// The most pieces a curve of an outline is checked in, each at its middle.
|
||||
const CURVE_PIECES: usize = 32;
|
||||
/// How far inside another piece's area, as a share of its radius, a piece of an outline must be
|
||||
/// to be left out: an outline along the edge of another area still shows.
|
||||
const INSIDE: f64 = 5e-3;
|
||||
|
||||
/// What the outline depends on besides the drag's points: a change starts it again.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
pub(super) struct AreaKey {
|
||||
/// The Blob Brush's tip (else the Eraser's).
|
||||
pub blob: bool,
|
||||
pub size: f64,
|
||||
pub variation: f64,
|
||||
pub angle: f64,
|
||||
pub roundness: f64,
|
||||
/// Each segment is as wide as the pen pressed there.
|
||||
pub pressure: bool,
|
||||
}
|
||||
|
||||
/// The work of the last call.
|
||||
#[derive(Clone, Copy, Default, Debug)]
|
||||
pub(super) struct AreaWork {
|
||||
/// Points taken.
|
||||
pub points: usize,
|
||||
/// Points of the drag outlined.
|
||||
pub outlined: usize,
|
||||
/// Units of work ([`WORK_PER_CALL`]).
|
||||
pub work: usize,
|
||||
/// Pieces joined into the paths shown ([`JOIN_PIECES_PER_CALL`]).
|
||||
pub joined: usize,
|
||||
}
|
||||
|
||||
/// The joined outline of up to [`BLOCK_PIECES`] settled pieces.
|
||||
#[derive(Default)]
|
||||
struct Block {
|
||||
path: BezPath,
|
||||
/// A piece in it changed since `path` was joined.
|
||||
stale: bool,
|
||||
}
|
||||
|
||||
/// A piece of the drag: segments `from..to` (segment `j` joins points `j` and `j + 1`).
|
||||
struct Piece {
|
||||
from: usize,
|
||||
to: usize,
|
||||
/// Its outline where the tip is round, segment by segment: the segment, whether it starts a
|
||||
/// contour and whether it ends a closed one.
|
||||
outline: Vec<(PathSeg, bool, bool)>,
|
||||
/// The part of its outline that shows, on the page.
|
||||
shown: BezPath,
|
||||
}
|
||||
|
||||
/// A piece whose outline is being checked, up to segment `at` of it.
|
||||
struct Check {
|
||||
piece: usize,
|
||||
at: usize,
|
||||
out: BezPath,
|
||||
pen: Option<Point>,
|
||||
/// Every segment of the current contour shows whole.
|
||||
whole: bool,
|
||||
}
|
||||
|
||||
pub(super) struct AreaPreview {
|
||||
key: AreaKey,
|
||||
first: Point,
|
||||
squash: Affine,
|
||||
stretch: Affine,
|
||||
/// The side of the grid's squares, where the tip is round.
|
||||
side: f64,
|
||||
/// The points taken, where the tip is round.
|
||||
sq: Vec<Point>,
|
||||
/// The last point taken, on the page.
|
||||
last: Point,
|
||||
/// The tip's radius along each segment, where the tip is round.
|
||||
radius: Vec<f64>,
|
||||
pieces: Vec<Piece>,
|
||||
squares: HashMap<(i64, i64), Vec<u32>>,
|
||||
/// How many listings the squares hold ([`LISTINGS`]).
|
||||
listed: usize,
|
||||
wide: Vec<usize>,
|
||||
/// The pieces whose outline is to be checked again.
|
||||
dirty: BTreeSet<usize>,
|
||||
check: Option<Check>,
|
||||
/// The outlines that show of every piece but a growing last one, joined [`BLOCK_PIECES`] at a
|
||||
/// time.
|
||||
blocks: Vec<Block>,
|
||||
pub work: AreaWork,
|
||||
}
|
||||
|
||||
impl AreaPreview {
|
||||
/// The outline of a drag that starts at `first`.
|
||||
pub(super) fn new(key: AreaKey, first: Point) -> Self {
|
||||
let stretch = if key.blob { blob_tip(key.angle, key.roundness) } else { eraser_tip(key.angle, key.roundness) };
|
||||
let widest = if key.pressure { pressure_size(key.size, key.variation, 1.0) } else { key.size };
|
||||
Self {
|
||||
key,
|
||||
first,
|
||||
squash: stretch.inverse(),
|
||||
stretch,
|
||||
side: widest.max(MIN_BRUSH_SIZE),
|
||||
sq: vec![],
|
||||
last: first,
|
||||
radius: vec![],
|
||||
pieces: vec![],
|
||||
squares: HashMap::new(),
|
||||
listed: 0,
|
||||
wide: vec![],
|
||||
dirty: BTreeSet::new(),
|
||||
check: None,
|
||||
blocks: vec![],
|
||||
work: AreaWork::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is this the outline of the drag `pts` with `key`: the same start, and the points it took
|
||||
/// still the drag's?
|
||||
pub(super) fn fits(&self, key: AreaKey, pts: &[Point]) -> bool {
|
||||
self.key == key
|
||||
&& pts.first() == Some(&self.first)
|
||||
&& self.sq.len() <= pts.len()
|
||||
&& self.sq.len().checked_sub(1).and_then(|i| pts.get(i)) == Some(&self.last)
|
||||
}
|
||||
|
||||
/// Is part of the drag `pts` not shown yet as it should be?
|
||||
pub(super) fn pending(&self, pts: &[Point]) -> bool {
|
||||
self.sq.len() < pts.len() || !self.dirty.is_empty() || self.check.is_some() || self.blocks.iter().any(|b| b.stale)
|
||||
}
|
||||
|
||||
/// How many listings the grid's squares hold.
|
||||
#[cfg(test)]
|
||||
pub(super) fn listed(&self) -> usize {
|
||||
self.listed
|
||||
}
|
||||
|
||||
/// Mark the joined path that holds settled piece `k` to be joined again.
|
||||
fn mark(&mut self, k: usize) {
|
||||
let b = k / BLOCK_PIECES;
|
||||
if self.blocks.len() <= b {
|
||||
self.blocks.resize_with(b + 1, Block::default);
|
||||
}
|
||||
self.blocks[b].stale = true;
|
||||
}
|
||||
|
||||
/// Take the points of the drag `pts` added since the last call and check outlines, within this
|
||||
/// call's limits. `pressures` holds the pen pressure at each point when the Size varies with it.
|
||||
pub(super) fn step(&mut self, pts: &[Point], pressures: Option<&[f32]>) {
|
||||
self.work = AreaWork::default();
|
||||
let mut changed = BTreeSet::new();
|
||||
while self.sq.len() < pts.len() && self.work.points < POINTS_PER_CALL && self.work.work < WORK_PER_CALL {
|
||||
let i = self.sq.len();
|
||||
self.sq.push(self.squash * pts[i]);
|
||||
self.last = pts[i];
|
||||
self.work.points += 1;
|
||||
let Some(j) = i.checked_sub(1) else { continue };
|
||||
let size = match pressures.filter(|_| self.key.pressure).and_then(|f| f.get(j..=i)) {
|
||||
Some(f) => pressure_size(self.key.size, self.key.variation, f64::from(f[0] + f[1]) / 2.0),
|
||||
None => self.key.size,
|
||||
};
|
||||
self.radius.push(size / 2.0);
|
||||
if self.key.pressure || self.pieces.last().is_none_or(|p| p.to - p.from >= PIECE_SEGMENTS) {
|
||||
self.pieces.push(Piece { from: j, to: j, outline: vec![], shown: BezPath::new() });
|
||||
}
|
||||
let k = self.pieces.len() - 1;
|
||||
self.pieces[k].to = j + 1;
|
||||
changed.insert(k);
|
||||
self.list(j, k);
|
||||
}
|
||||
for k in changed {
|
||||
self.outline_piece(k);
|
||||
}
|
||||
self.check_some();
|
||||
}
|
||||
|
||||
/// The paths to show: the settled pieces' outlines, joined [`BLOCK_PIECES`] at a time, the
|
||||
/// growing last piece's and a thin line over the points of `pts` not taken yet. The joined
|
||||
/// paths with a changed piece are joined again, newest first, at most
|
||||
/// [`JOIN_PIECES_PER_CALL`] pieces a call; the others show the path last joined.
|
||||
pub(super) fn paths(&mut self, pts: &[Point]) -> Vec<BezPath> {
|
||||
let settled = self.settled_count();
|
||||
for b in (0..self.blocks.len()).rev() {
|
||||
if self.work.joined >= JOIN_PIECES_PER_CALL {
|
||||
break;
|
||||
}
|
||||
if !self.blocks[b].stale {
|
||||
continue;
|
||||
}
|
||||
let pieces = self.pieces.get(b * BLOCK_PIECES..settled.min((b + 1) * BLOCK_PIECES)).unwrap_or_default();
|
||||
let mut joined = BezPath::new();
|
||||
for p in pieces {
|
||||
joined.extend(p.shown.elements().iter().copied());
|
||||
}
|
||||
self.work.joined += pieces.len();
|
||||
self.blocks[b] = Block { path: joined, stale: false };
|
||||
}
|
||||
let mut out: Vec<BezPath> = self.blocks.iter().filter(|b| !b.path.elements().is_empty()).map(|b| b.path.clone()).collect();
|
||||
if let Some(p) = self.pieces.get(settled).filter(|p| !p.shown.elements().is_empty()) {
|
||||
out.push(p.shown.clone());
|
||||
}
|
||||
if let Some(rest) = pts.get(self.sq.len()..).filter(|r| !r.is_empty()) {
|
||||
let stride = rest.len().div_ceil(GUIDE_POINTS).max(1);
|
||||
let mut guide = BezPath::new();
|
||||
guide.move_to(self.last);
|
||||
for p in rest.iter().skip(stride - 1).step_by(stride) {
|
||||
guide.line_to(*p);
|
||||
}
|
||||
if let Some(&end) = rest.last().filter(|_| (rest.len() % stride) != 0) {
|
||||
guide.line_to(end);
|
||||
}
|
||||
out.push(guide);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How many pieces no longer grow: all of them but a last one with room for more segments.
|
||||
fn settled_count(&self) -> usize {
|
||||
let growing = !self.key.pressure && self.pieces.last().is_some_and(|p| p.to - p.from < PIECE_SEGMENTS);
|
||||
self.pieces.len() - usize::from(growing)
|
||||
}
|
||||
|
||||
/// The piece that holds segment `j`.
|
||||
fn piece_of(&self, j: usize) -> usize {
|
||||
if self.key.pressure { j } else { j / PIECE_SEGMENTS }
|
||||
}
|
||||
|
||||
/// The square of the grid that holds `p`; `None` far outside any document.
|
||||
fn square(&self, p: Point) -> Option<(i64, i64)> {
|
||||
let (x, y) = ((p.x / self.side).floor(), (p.y / self.side).floor());
|
||||
(x.abs() < 1e15 && y.abs() < 1e15).then_some((x as i64, y as i64))
|
||||
}
|
||||
|
||||
/// The squares around points half a square apart along the segment from `a` to `b`: every
|
||||
/// square holding a point within half a square of it. `None` past `samples` points.
|
||||
fn squares_along(&self, a: Point, b: Point, samples: usize) -> Option<Vec<(i64, i64)>> {
|
||||
let n = (a.distance(b) / (0.5 * self.side)).ceil().max(1.0);
|
||||
if !n.is_finite() || n > samples as f64 {
|
||||
return None;
|
||||
}
|
||||
let mut keys = vec![];
|
||||
for k in 0..=(n as usize) {
|
||||
let (x, y) = self.square(a.lerp(b, k as f64 / n))?;
|
||||
for dy in -1..=1 {
|
||||
for dx in -1..=1 {
|
||||
keys.push((x + dx, y + dy));
|
||||
}
|
||||
}
|
||||
}
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
Some(keys)
|
||||
}
|
||||
|
||||
/// List segment `j` of piece `k` in the squares its area reaches, and mark the other pieces
|
||||
/// whose outline its area can reach to be checked again.
|
||||
fn list(&mut self, j: usize, k: usize) {
|
||||
let (a, b, r) = (self.sq[j], self.sq[j + 1], self.radius[j]);
|
||||
let mut near = vec![];
|
||||
match self.squares_along(a, b, SEGMENT_SAMPLES) {
|
||||
Some(keys) => {
|
||||
for key in keys {
|
||||
self.work.work += 1;
|
||||
if self.listed >= LISTINGS {
|
||||
near.extend(self.squares.get(&key).into_iter().flatten().map(|m| *m as usize));
|
||||
continue;
|
||||
}
|
||||
let listed = self.squares.entry(key).or_default();
|
||||
near.extend(listed.iter().map(|m| *m as usize));
|
||||
if listed.len() < SQUARE_SEGMENTS {
|
||||
listed.push(j as u32);
|
||||
self.listed += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// The pieces near points along it, at most WIDE_SAMPLES of them.
|
||||
let n = (a.distance(b) / (0.5 * self.side)).ceil().clamp(1.0, WIDE_SAMPLES as f64);
|
||||
for s in 0..=(n as usize) {
|
||||
let Some((x, y)) = self.square(a.lerp(b, s as f64 / n)) else { continue };
|
||||
for dy in -1..=1 {
|
||||
for dx in -1..=1 {
|
||||
self.work.work += 1;
|
||||
near.extend(self.squares.get(&(x + dx, y + dy)).into_iter().flatten().map(|m| *m as usize));
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.wide.len() < WIDE_SEGMENTS {
|
||||
self.wide.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
near.extend(self.wide.iter().copied().filter(|m| *m != j));
|
||||
near.sort_unstable();
|
||||
near.dedup();
|
||||
for m in near {
|
||||
self.work.work += 1;
|
||||
let q = self.piece_of(m);
|
||||
if q != k && !self.dirty.contains(&q) && segment_distance(a, b, self.sq[m], self.sq[m + 1]) < r + self.radius[m] {
|
||||
self.dirty.insert(q);
|
||||
if self.check.as_ref().is_some_and(|c| c.piece == q) {
|
||||
self.check = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Outline piece `k` again, and mark it to be checked.
|
||||
fn outline_piece(&mut self, k: usize) {
|
||||
let settled = self.settled_count();
|
||||
let Some(p) = self.pieces.get(k) else { return };
|
||||
let pts = &self.sq[p.from..=p.to];
|
||||
let width = 2.0 * self.radius[p.from];
|
||||
self.work.outlined += pts.len();
|
||||
let area = po::outline_stroke(&PathData::single(SubPath::polyline(pts, false)), width, Cap::Round, Join::Round, 4.0).to_bezpath();
|
||||
let outline = segments(&area);
|
||||
let shown = self.stretch * area;
|
||||
if let Some(p) = self.pieces.get_mut(k) {
|
||||
p.outline = outline;
|
||||
p.shown = shown;
|
||||
}
|
||||
if self.check.as_ref().is_some_and(|c| c.piece == k) {
|
||||
self.check = None;
|
||||
}
|
||||
self.dirty.insert(k);
|
||||
if k < settled {
|
||||
self.mark(k);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the outlines of the pieces marked, newest first, one segment of an outline at a
|
||||
/// time, until this call's work is done.
|
||||
fn check_some(&mut self) {
|
||||
while self.work.work < WORK_PER_CALL {
|
||||
let mut c = match self.check.take() {
|
||||
Some(c) => c,
|
||||
None => match self.dirty.pop_last() {
|
||||
Some(piece) => Check { piece, at: 0, out: BezPath::new(), pen: None, whole: true },
|
||||
None => break,
|
||||
},
|
||||
};
|
||||
let Some(p) = self.pieces.get(c.piece) else { continue };
|
||||
let Some(&(seg, starts, closes)) = p.outline.get(c.at) else {
|
||||
// The whole outline is checked.
|
||||
let settled = self.settled_count();
|
||||
let shown = self.stretch * std::mem::take(&mut c.out);
|
||||
if let Some(p) = self.pieces.get_mut(c.piece) {
|
||||
p.shown = shown;
|
||||
}
|
||||
if c.piece < settled {
|
||||
self.mark(c.piece);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let own = p.from..p.to;
|
||||
if starts {
|
||||
c.pen = None;
|
||||
c.whole = true;
|
||||
}
|
||||
let runs = self.visible(seg, own);
|
||||
if !matches!(runs[..], [(a, b)] if a == 0.0 && b == 1.0) {
|
||||
c.whole = false;
|
||||
}
|
||||
for (a, b) in runs {
|
||||
push_seg(&mut c.out, &mut c.pen, if a == 0.0 && b == 1.0 { seg } else { seg.subsegment(a..b) });
|
||||
}
|
||||
if closes && c.whole {
|
||||
c.out.close_path();
|
||||
c.pen = None;
|
||||
}
|
||||
c.at += 1;
|
||||
self.check = Some(c);
|
||||
}
|
||||
}
|
||||
|
||||
/// The segments of the drag, but `own`, whose area can hold a point of the squares `keys`.
|
||||
fn candidates(&mut self, keys: impl IntoIterator<Item = (i64, i64)>, own: &std::ops::Range<usize>) -> Vec<usize> {
|
||||
let mut out: Vec<usize> = self.wide.clone();
|
||||
for key in keys {
|
||||
out.extend(self.squares.get(&key).into_iter().flatten().map(|m| *m as usize));
|
||||
}
|
||||
self.work.work += out.len();
|
||||
out.retain(|m| !own.contains(m));
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
/// The stretches of `seg` (from and to, 0 at its start, 1 at its end) that lie inside no area
|
||||
/// of a segment of the drag but `own`.
|
||||
fn visible(&mut self, seg: PathSeg, own: std::ops::Range<usize>) -> Vec<(f64, f64)> {
|
||||
let inside = |s: &Self, q: Point, m: usize| distance_to_segment(q, s.sq[m], s.sq[m + 1]) < s.radius[m] * (1.0 - INSIDE);
|
||||
match seg {
|
||||
PathSeg::Line(line) => {
|
||||
let len = line.p0.distance(line.p1);
|
||||
let n = (len / self.side).ceil().max(1.0);
|
||||
let keys: Vec<(i64, i64)> = if !n.is_finite() || n > SIDE_SQUARES as f64 {
|
||||
// A very long side: the squares at its ends.
|
||||
[line.p0, line.p1].into_iter().filter_map(|p| self.square(p)).collect()
|
||||
} else {
|
||||
let mut keys = vec![];
|
||||
for i in 0..(n as usize) {
|
||||
let (p, q) = (line.p0.lerp(line.p1, i as f64 / n), line.p0.lerp(line.p1, (i + 1) as f64 / n));
|
||||
let (Some(lo), Some(hi)) =
|
||||
(self.square(Point::new(p.x.min(q.x), p.y.min(q.y))), self.square(Point::new(p.x.max(q.x), p.y.max(q.y))))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for y in lo.1..=hi.1 {
|
||||
for x in lo.0..=hi.0 {
|
||||
keys.push((x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
keys
|
||||
};
|
||||
let near = self.candidates(keys, &own);
|
||||
let spans = near.iter().filter_map(|&m| capsule_span(line, self.sq[m], self.sq[m + 1], self.radius[m] * (1.0 - INSIDE))).collect();
|
||||
gaps(&merge_spans(spans))
|
||||
}
|
||||
_ => {
|
||||
let reach: f64 = match seg {
|
||||
PathSeg::Quad(q) => q.p0.distance(q.p1) + q.p1.distance(q.p2),
|
||||
PathSeg::Cubic(c) => c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3),
|
||||
PathSeg::Line(l) => l.p0.distance(l.p1),
|
||||
};
|
||||
let n = (reach / (0.025 * self.side)).ceil().clamp(1.0, CURVE_PIECES as f64) as usize;
|
||||
let mut shows = vec![];
|
||||
for i in 0..n {
|
||||
let mid = seg.eval((i as f64 + 0.5) / n as f64);
|
||||
let near = self.candidates(self.square(mid), &own);
|
||||
shows.push(!near.iter().any(|&m| inside(self, mid, m)));
|
||||
}
|
||||
let mut runs: Vec<(f64, f64)> = vec![];
|
||||
for (i, show) in shows.into_iter().enumerate() {
|
||||
if !show {
|
||||
continue;
|
||||
}
|
||||
let (a, b) = (i as f64 / n as f64, (i + 1) as f64 / n as f64);
|
||||
match runs.last_mut() {
|
||||
Some(last) if last.1 == a => last.1 = b,
|
||||
_ => runs.push((a, b)),
|
||||
}
|
||||
}
|
||||
runs
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The segments of `path`: each with whether it starts a contour and whether it ends a closed one.
|
||||
fn segments(path: &BezPath) -> Vec<(PathSeg, bool, bool)> {
|
||||
let mut out: Vec<(PathSeg, bool, bool)> = vec![];
|
||||
let (mut start, mut pen, mut first) = (Point::ZERO, Point::ZERO, true);
|
||||
for el in path.elements() {
|
||||
let seg = match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
(start, pen, first) = (p, p, true);
|
||||
continue;
|
||||
}
|
||||
PathEl::LineTo(p) => PathSeg::Line(Line::new(pen, p)),
|
||||
PathEl::QuadTo(p1, p2) => PathSeg::Quad(vectorcraft_geom::kurbo::QuadBez::new(pen, p1, p2)),
|
||||
PathEl::CurveTo(p1, p2, p3) => PathSeg::Cubic(vectorcraft_geom::CubicBez::new(pen, p1, p2, p3)),
|
||||
PathEl::ClosePath => {
|
||||
if pen != start {
|
||||
out.push((PathSeg::Line(Line::new(pen, start)), first, false));
|
||||
first = false;
|
||||
}
|
||||
if !first && let Some(last) = out.last_mut() {
|
||||
last.2 = true;
|
||||
}
|
||||
pen = start;
|
||||
first = true;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
out.push((seg, first, false));
|
||||
first = false;
|
||||
pen = seg.end();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Add `seg` to `out`, starting a new subpath unless it starts at `pen`, where the last one ended.
|
||||
fn push_seg(out: &mut BezPath, pen: &mut Option<Point>, seg: PathSeg) {
|
||||
let a = seg.start();
|
||||
if *pen != Some(a) {
|
||||
out.move_to(a);
|
||||
}
|
||||
match seg {
|
||||
PathSeg::Line(l) => out.line_to(l.p1),
|
||||
PathSeg::Quad(q) => out.quad_to(q.p1, q.p2),
|
||||
PathSeg::Cubic(c) => out.curve_to(c.p1, c.p2, c.p3),
|
||||
}
|
||||
*pen = Some(seg.end());
|
||||
}
|
||||
|
||||
/// How far `q` is from the segment from `a` to `b`.
|
||||
fn distance_to_segment(q: Point, a: Point, b: Point) -> f64 {
|
||||
let d = b - a;
|
||||
let t = if d.hypot2() > 0.0 { ((q - a).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
q.distance(a + d * t)
|
||||
}
|
||||
|
||||
/// How far the segment from `a` to `b` is from the segment from `c` to `d`.
|
||||
fn segment_distance(a: Point, b: Point, c: Point, d: Point) -> f64 {
|
||||
let side = |p: Point, q: Point, s: Point| (q - p).cross(s - p);
|
||||
if side(a, b, c) * side(a, b, d) < 0.0 && side(c, d, a) * side(c, d, b) < 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
distance_to_segment(a, c, d).min(distance_to_segment(b, c, d)).min(distance_to_segment(c, a, b)).min(distance_to_segment(d, a, b))
|
||||
}
|
||||
|
||||
/// The stretch of `line`, as from and to along it (0 at its start, 1 at its end, and beyond), that
|
||||
/// lies within `rad` of the segment from `a` to `b`; `None` when no point of the line does.
|
||||
fn capsule_span(line: Line, a: Point, b: Point, rad: f64) -> Option<(f64, f64)> {
|
||||
let (p, d) = (line.p0, line.p1 - line.p0);
|
||||
let dd = d.hypot2();
|
||||
if dd <= 0.0 || rad.is_nan() || rad <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);
|
||||
// The round ends.
|
||||
for c in [a, b] {
|
||||
let f = p - c;
|
||||
let (half_b, k) = (d.dot(f), f.hypot2() - rad * rad);
|
||||
let disc = half_b * half_b - dd * k;
|
||||
if disc >= 0.0 {
|
||||
let root = disc.sqrt();
|
||||
lo = lo.min((-half_b - root) / dd);
|
||||
hi = hi.max((-half_b + root) / dd);
|
||||
}
|
||||
}
|
||||
// The part between them: along the segment from 0 to its length, and across it within `rad`.
|
||||
let e = b - a;
|
||||
let len = e.hypot();
|
||||
if len > 0.0 {
|
||||
let u = e / len;
|
||||
let n = vectorcraft_geom::Vec2::new(-u.y, u.x);
|
||||
let (mut s0, mut s1) = (f64::NEG_INFINITY, f64::INFINITY);
|
||||
for (at, rate, min, max) in [((p - a).dot(u), d.dot(u), 0.0, len), ((p - a).dot(n), d.dot(n), -rad, rad)] {
|
||||
if rate == 0.0 {
|
||||
if at < min || at > max {
|
||||
s1 = f64::NEG_INFINITY;
|
||||
}
|
||||
} else {
|
||||
let (x, y) = ((min - at) / rate, (max - at) / rate);
|
||||
s0 = s0.max(x.min(y));
|
||||
s1 = s1.min(x.max(y));
|
||||
}
|
||||
}
|
||||
if s0 <= s1 {
|
||||
lo = lo.min(s0);
|
||||
hi = hi.max(s1);
|
||||
}
|
||||
}
|
||||
(lo < hi).then_some((lo, hi))
|
||||
}
|
||||
|
||||
/// `spans` sorted and joined where they overlap.
|
||||
fn merge_spans(mut spans: Vec<(f64, f64)>) -> Vec<(f64, f64)> {
|
||||
spans.sort_by(|x, y| x.0.total_cmp(&y.0));
|
||||
let mut out: Vec<(f64, f64)> = Vec::with_capacity(spans.len());
|
||||
for (a, b) in spans {
|
||||
match out.last_mut() {
|
||||
Some(last) if a <= last.1 => last.1 = last.1.max(b),
|
||||
_ => out.push((a, b)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The stretches of 0 to 1 that none of `spans` (from [`merge_spans`]) holds.
|
||||
fn gaps(spans: &[(f64, f64)]) -> Vec<(f64, f64)> {
|
||||
let mut out = vec![];
|
||||
let mut at = 0.0;
|
||||
for &(a, b) in spans {
|
||||
if b <= at {
|
||||
continue;
|
||||
}
|
||||
if a >= 1.0 {
|
||||
break;
|
||||
}
|
||||
if a > at {
|
||||
out.push((at, a));
|
||||
}
|
||||
at = b;
|
||||
}
|
||||
if at < 1.0 {
|
||||
out.push((at, 1.0));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -2171,6 +2171,254 @@ fn the_blob_brush_sends_its_tip_and_shows_the_area_it_covers() {
|
||||
assert!(vectorcraft_geom::Shape::bounding_box(path).height() < 0.1, "{o:?}");
|
||||
}
|
||||
|
||||
/// A drag of `n` points (2 to 10 pt apart) that circles round and crosses itself many times,
|
||||
/// pressed at `pressure(i)` at point `i`, left down.
|
||||
fn long_area_drag(t: &mut GestureTool, cx: &ToolContext, n: usize, pressure: impl Fn(usize) -> f32) {
|
||||
for i in 0..n {
|
||||
let s = i 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());
|
||||
let kind = if i == 0 { PointerKind::Down } else { PointerKind::Drag };
|
||||
t.pointer(cx, &PointerEvent { pressure: pressure(i), ..PointerEvent::new(kind, x, y) });
|
||||
}
|
||||
assert_eq!(t.points.len(), n, "every point is a sample");
|
||||
}
|
||||
|
||||
/// The work the last `overlays` did on the area's outline, and whether it left some for later.
|
||||
fn area_work(t: &GestureTool) -> (area::AreaWork, bool) {
|
||||
let Some(a) = t.area.take() else { panic!("no outline") };
|
||||
let w = (a.work, a.pending(&t.points));
|
||||
t.area.set(Some(a));
|
||||
assert_eq!(w.1, t.overlays_pending());
|
||||
w
|
||||
}
|
||||
|
||||
/// The most work one `overlays` call can do past [`area::WORK_PER_CALL`]: the one step it is in
|
||||
/// when it reaches it: a segment of the drag listed in, or checked near, up to 129 × 9 squares of
|
||||
/// up to 128 segments each, and those segments checked once each.
|
||||
const AREA_STEP: usize = 2 * (129 * 9 * 129 + 256);
|
||||
|
||||
/// Call `overlays` until the outline covers the whole drag, checking each call's work; the
|
||||
/// number of calls it took.
|
||||
fn drain_area(t: &GestureTool, cx: &ToolContext) -> usize {
|
||||
let mut calls = 0;
|
||||
loop {
|
||||
t.overlays(cx);
|
||||
calls += 1;
|
||||
let (w, pending) = area_work(t);
|
||||
assert!(w.points <= area::POINTS_PER_CALL, "{w:?}");
|
||||
assert!(w.outlined <= 2 * area::POINTS_PER_CALL + 2 * (area::PIECE_SEGMENTS + 1), "{w:?}");
|
||||
assert!(w.work <= area::WORK_PER_CALL + AREA_STEP, "{w:?}");
|
||||
assert!(w.joined <= area::JOIN_PIECES_PER_CALL + area::BLOCK_PIECES, "{w:?}");
|
||||
if !pending {
|
||||
return calls;
|
||||
}
|
||||
assert!(calls < 10_000, "the outline never covers the drag");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Blob Brush's and the Eraser's outline of a long drag does a bounded amount of work per
|
||||
/// frame: each call takes at most `POINTS_PER_CALL` new points, outlines a bounded number of them
|
||||
/// and checks outlines for a bounded amount of work, leaving the rest for later calls
|
||||
/// (`overlays_pending`), which finish it with the pointer still. A call after that does nothing
|
||||
/// until the drag moves, and then only the new step's work. The release sends the whole stroke.
|
||||
#[test]
|
||||
fn the_blob_brush_and_the_eraser_outline_a_long_drag_a_bounded_amount_per_frame() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
|
||||
for (id, angle, roundness, pressure) in [
|
||||
("blobBrush", 0.0, 100.0, false),
|
||||
("blobBrush", 30.0, 40.0, false),
|
||||
("eraser", -60.0, 30.0, false),
|
||||
("blobBrush", 0.0, 100.0, true),
|
||||
("eraser", 45.0, 50.0, true),
|
||||
] {
|
||||
let mut t = GestureTool::new(id);
|
||||
t.set_option("size", &json!(10));
|
||||
t.set_option("angle", &json!(angle));
|
||||
t.set_option("roundness", &json!(roundness));
|
||||
if pressure {
|
||||
t.set_option("sizeMode", &json!("pressure"));
|
||||
t.set_option("sizeVariation", &json!(4));
|
||||
}
|
||||
long_area_drag(&mut t, &cx, 3000, |i| if pressure { 0.3 + 0.6 * ((i % 50) as f32 / 50.0) } else { 1.0 });
|
||||
let calls = drain_area(&t, &cx);
|
||||
assert!(calls > 1, "{id}: a 3,000-point drag takes several frames");
|
||||
// Nothing new: nothing to do, at any zoom (the outline is in document space).
|
||||
for zoom in [1.0, 4.0] {
|
||||
t.overlays(&ToolContext { zoom, ..cx });
|
||||
let (w, pending) = area_work(&t);
|
||||
assert_eq!((w.points, w.outlined, w.work, w.joined, pending), (0, 0, 0, 0, false), "{id}");
|
||||
}
|
||||
// One step more: one point, its piece outlined again, and the outlines near it checked.
|
||||
t.pointer(&cx, &PointerEvent { pressure: if pressure { 0.5 } else { 1.0 }, ..PointerEvent::new(PointerKind::Drag, 520.0, 300.0) });
|
||||
t.overlays(&cx);
|
||||
let (w, _) = area_work(&t);
|
||||
assert_eq!(w.points, 1, "{id}");
|
||||
assert!(w.outlined <= area::PIECE_SEGMENTS + 1, "{id}: {w:?}");
|
||||
if pressure {
|
||||
// 3,000 one-segment pieces: only the joined paths near the step are joined again.
|
||||
assert!(w.joined <= 8 * area::BLOCK_PIECES, "{id}: {w:?}");
|
||||
}
|
||||
drain_area(&t, &cx);
|
||||
let want = t.stroke_json();
|
||||
let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 520.0, 300.0));
|
||||
let Some(Action::Exec(_, v)) = acts.first() else { panic!("{acts:?}") };
|
||||
assert_eq!(v["points"], want, "{id}: the release sends every point");
|
||||
assert_eq!(v["points"].as_array().map(Vec::len), Some(3001), "{id}");
|
||||
assert!(t.area.take().is_none() && !t.overlays_pending(), "{id}: the release drops the outline");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every flattened point of the paths `o` (the outline shown).
|
||||
fn shown_points(o: &[Overlay]) -> Vec<(Point, Point)> {
|
||||
let mut lines = vec![];
|
||||
for o in o {
|
||||
let Overlay::Path { path, .. } = o else { continue };
|
||||
let mut pen = Point::ZERO;
|
||||
let mut start = Point::ZERO;
|
||||
vectorcraft_geom::kurbo::flatten(path.elements().iter().copied(), 0.01, |el| match el {
|
||||
vectorcraft_geom::PathEl::MoveTo(p) => (pen, start) = (p, p),
|
||||
vectorcraft_geom::PathEl::LineTo(p) => {
|
||||
lines.push((pen, p));
|
||||
pen = p;
|
||||
}
|
||||
vectorcraft_geom::PathEl::ClosePath => {
|
||||
lines.push((pen, start));
|
||||
pen = start;
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn distance_to_line(q: Point, (a, b): (Point, Point)) -> f64 {
|
||||
let d = b - a;
|
||||
let t = if d.hypot2() > 0.0 { ((q - a).dot(d) / d.hypot2()).clamp(0.0, 1.0) } else { 0.0 };
|
||||
q.distance(a + d * t)
|
||||
}
|
||||
|
||||
/// Once a long drag's outline is finished it is the outline of the whole area its tip covers, as
|
||||
/// `blob_area` and `eraser_area` give it: no line inside the area (where pieces of the drag
|
||||
/// overlap or it crosses itself), and no gap along its edge.
|
||||
#[test]
|
||||
fn the_outline_of_a_long_drag_is_the_edge_of_the_whole_area() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
|
||||
for (id, angle, roundness) in [("blobBrush", 0.0, 100.0), ("eraser", 30.0, 40.0)] {
|
||||
let mut t = GestureTool::new(id);
|
||||
t.set_option("size", &json!(12));
|
||||
t.set_option("angle", &json!(angle));
|
||||
t.set_option("roundness", &json!(roundness));
|
||||
long_area_drag(&mut t, &cx, 700, |_| 1.0);
|
||||
drain_area(&t, &cx);
|
||||
let shown = shown_points(&t.overlays(&cx));
|
||||
let tip = if id == "blobBrush" { blob_tip(angle, roundness) } else { eraser_tip(angle, roundness) };
|
||||
let squash = tip.inverse();
|
||||
let round: Vec<Point> = t.points.iter().map(|p| squash * *p).collect();
|
||||
// Nothing shows inside the area: every point shown is about the tip's radius from the drag.
|
||||
for &(a, _) in &shown {
|
||||
let q = squash * a;
|
||||
let inner = round.windows(2).map(|w| distance_to_line(q, (w[0], w[1]))).fold(f64::INFINITY, f64::min);
|
||||
assert!(inner > 6.0 * 0.9, "{id}: a line {inner} from the drag, inside the area, at {a:?}");
|
||||
}
|
||||
// The whole edge shows.
|
||||
let exact = if id == "blobBrush" {
|
||||
super::super::blob_area(&t.points, 12.0, angle, roundness)
|
||||
} else {
|
||||
super::super::eraser_area(&t.points, 12.0, angle, roundness)
|
||||
};
|
||||
let edge = shown_points(&[Overlay::Path { path: exact.to_bezpath(), color: FEEDBACK, width: 1.0, dashed: false }]);
|
||||
for &(a, _) in &edge {
|
||||
let gap = shown.iter().map(|l| distance_to_line(a, *l)).fold(f64::INFINITY, f64::min);
|
||||
assert!(gap < 0.6, "{id}: the edge at {a:?} is {gap} from the outline shown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A drag with a very long step (a jump of 20,000 pt with a 1 pt tip) still finishes its outline
|
||||
/// a bounded amount at a time, and the outline reaches both ends of the jump.
|
||||
#[test]
|
||||
fn a_long_jump_in_a_blob_brush_drag_is_outlined_a_bounded_amount_at_a_time() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
|
||||
let mut t = GestureTool::new("blobBrush");
|
||||
t.set_option("size", &json!(1));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
|
||||
for i in 1..400 {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, f64::from(i) * 2.0, 0.0));
|
||||
}
|
||||
// Over and back across the first steps, then out 20,000 pt and back over the same line.
|
||||
for x in [20_000.0, 400.0, 20_000.0, 10.0] {
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, 0.3));
|
||||
}
|
||||
drain_area(&t, &cx);
|
||||
let o = t.overlays(&cx);
|
||||
let b = o
|
||||
.iter()
|
||||
.filter_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::Shape::bounding_box(path)) } else { None })
|
||||
.reduce(|a, b| a.union(b));
|
||||
let Some(b) = b else { panic!("{o:?}") };
|
||||
assert!((b.x0 + 0.5).abs() < 0.01 && (b.x1 - 20_000.5).abs() < 0.01, "{b:?}");
|
||||
}
|
||||
|
||||
/// A drag of many long steps (60 times the tip's size) lists each step in a bounded number of the
|
||||
/// grid's squares, so the grid does not grow with the steps' length.
|
||||
#[test]
|
||||
fn long_steps_of_a_drag_are_listed_in_a_bounded_number_of_squares() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
|
||||
let mut t = GestureTool::new("eraser");
|
||||
t.set_option("size", &json!(1));
|
||||
t.set_option("roundness", &json!(50));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
|
||||
for i in 1..=2000 {
|
||||
let x = if i % 2 == 0 { 0.0 } else { 60.0 };
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, f64::from(i) * 0.05));
|
||||
}
|
||||
assert_eq!(t.points.len(), 2001);
|
||||
drain_area(&t, &cx);
|
||||
let Some(a) = t.area.take() else { panic!("no outline") };
|
||||
assert!(a.listed() <= 2000 * 3 * (32 + 1) && a.listed() <= area::LISTINGS, "{}", a.listed());
|
||||
}
|
||||
|
||||
/// Escape, the release and leaving the tool drop the outline built so far; the next drag starts
|
||||
/// a new one, and its length label counts that drag alone.
|
||||
#[test]
|
||||
fn escape_and_leaving_the_tool_drop_the_drag_outline() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = ToolContext { measurement_labels: true, ..cx(&d, &s, &p) };
|
||||
for id in ["blobBrush", "eraser"] {
|
||||
let mut t = GestureTool::new(id);
|
||||
t.set_option("roundness", &json!(50));
|
||||
long_area_drag(&mut t, &cx, 1000, |_| 1.0);
|
||||
t.overlays(&cx);
|
||||
assert!(t.overlays_pending(), "{id}: a 1,000-point drag takes more than one frame");
|
||||
t.key(&cx, ToolKey::Escape, Mods::default());
|
||||
assert!(t.area.take().is_none() && !t.overlays_pending(), "{id}: Escape drops it");
|
||||
long_area_drag(&mut t, &cx, 1000, |_| 1.0);
|
||||
t.overlays(&cx);
|
||||
t.deactivate(&cx);
|
||||
assert!(t.area.take().is_none() && !t.overlays_pending(), "{id}: leaving the tool drops it");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 50.0, 150.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0));
|
||||
let o = t.overlays(&cx);
|
||||
let want = format!("L: {}", cx.len(100.0));
|
||||
assert_eq!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &want)), id == "blobBrush", "{id}: {o:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4977: the Blob Brush and the Eraser show their tip at the pointer before a press and while
|
||||
/// painting: its outline at its size, angle and roundness, a black line on a white halo, following
|
||||
/// `[` / `]` and Tool Options at once. It goes when the hover ends, with precise cursors (Caps
|
||||
|
||||
@@ -136,9 +136,9 @@ pub trait Tool: Send {
|
||||
fn overlays(&self, _cx: &ToolContext) -> Vec<Overlay> {
|
||||
vec![]
|
||||
}
|
||||
/// Did the last [`Tool::overlays`] leave part of its overlays for later calls (the band of a
|
||||
/// long smoothing drag, outlined again after a zoom change)? The host then draws again on the
|
||||
/// next frame, even when the pointer holds still.
|
||||
/// Did the last [`Tool::overlays`] leave part of its overlays for later calls (the outline of a
|
||||
/// long Blob Brush or Eraser drag, the band of a long smoothing drag outlined again after a
|
||||
/// zoom change)? The host then draws again on the next frame, even when the pointer holds still.
|
||||
fn overlays_pending(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -1063,6 +1063,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
Alt-drag with the Knife cuts in a straight line, and Shift+Alt-drag cuts at 45° or 90°, as [Cut objects using the Knife and Scissors tools](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) describe. Alt counts only when held at the press; the dashed line runs from the press point to the pointer, stays straight after Alt is let go, and release sends `path.knife` with those two points. Alt pressed after the press leaves the cut freehand. Shift+Alt keeps the endpoint at 45° steps from the horizontal and vertical, whatever the Constrain Angle.
|
||||
With Smart Guides on, a straight Knife cut snaps to anchor points and paths: [Cut objects using the Knife and Scissors tools](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/cut-objects.html) describes the Knife snapping to anchor points and paths while Smart Guides are on. Its ends snap as the ends of the Pencil's straight line do, to anchor points and path segments of art that is shown: the press, and the release of an Alt-drag. Shift+Alt steps 45° from the snapped press, and its release stays on that step. With Smart Guides off, or with Snap to Pixel or Snap to Grid on, the cut is not snapped. The dashed line and `path.knife` use the snapped points.
|
||||
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`).
|
||||
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. With Size set to Pressure the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`).
|
||||
- **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