mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 22:33:08 +00:00
Path Precision Tools: a path that ends on a curve still divides it after the curve is cut
The crossing search took a crossing only where the straight pieces it splits two curves into actually cross. A line trimmed at a curve ends where that search found the crossing, up to about 0.0001 pt off the curve. Once the curve was cut as well, its segments were split differently, the line's end could fall just short of them, and the end no longer counted as a place on the curve. Trim at Crossings then removed the curve past that line, to the next crossing or the whole path. An open end of a path that lies within 0.001 pt of another path now meets it at the nearest point there, at any angle. Corners of a path and closed paths keep the exact test, and paths that lie along each other still don't cross. Trim at Crossings and its hover, Add Points at Crossings (with and without cut) and the Join tool's trim and join of crossing paths use this search. The params text of Trim at Crossings and Add Points at Crossings and docs/mcp.md say so.
This commit is contained in:
@@ -34,9 +34,19 @@ fn flat(c: &CubicBez) -> bool {
|
||||
off(c.p1) <= FLAT && off(c.p2) <= FLAT
|
||||
}
|
||||
|
||||
/// Where the chords of `a` and `b` cross: (s, u) along each, or `None` when they don't (parallel
|
||||
/// ones never do).
|
||||
fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> {
|
||||
/// Which ends of a segment are open ends of its path: (start, end).
|
||||
type Open = (bool, bool);
|
||||
|
||||
/// The open ends of segment `s` of `sp`.
|
||||
fn open_ends(sp: &SubPath, s: usize) -> Open {
|
||||
(!sp.closed && s == 0, !sp.closed && s + 1 == sp.segment_count())
|
||||
}
|
||||
|
||||
/// Where the straight pieces `a` and `b` cross: (t on `a`, t on `b`), or `None` when their chords
|
||||
/// don't cross (parallel ones never do, so paths lying along each other don't cross). An end in
|
||||
/// `open_a` or `open_b` (start, end) that lies within [`SAME`] of the other piece meets it at the
|
||||
/// point of that piece nearest it, at any angle.
|
||||
fn pieces_cross(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open) -> Option<(f64, f64)> {
|
||||
let (da, db) = (a.p3 - a.p0, b.p3 - b.p0);
|
||||
let den = da.cross(db);
|
||||
if den.abs() <= 1e-12 * da.hypot() * db.hypot() || den == 0.0 {
|
||||
@@ -45,12 +55,28 @@ fn chords_cross(a: &CubicBez, b: &CubicBez) -> Option<(f64, f64)> {
|
||||
let w = b.p0 - a.p0;
|
||||
let (s, u) = (w.cross(db) / den, w.cross(da) / den);
|
||||
let within = |v: f64| (-1e-9..=1.0 + 1e-9).contains(&v);
|
||||
(within(s) && within(u)).then(|| (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0)))
|
||||
if within(s) && within(u) {
|
||||
// The pieces are straight but their parameters needn't run evenly along them.
|
||||
let (s, u) = (s.clamp(0.0, 1.0), u.clamp(0.0, 1.0));
|
||||
return Some((a.nearest(a.p0.lerp(a.p3, s), 1e-9).t, b.nearest(b.p0.lerp(b.p3, u), 1e-9).t));
|
||||
}
|
||||
let ends_a = [(open_a.0, 0.0, a.p0), (open_a.1, 1.0, a.p3)].into_iter().filter(|e| e.0).map(|(_, ta, p)| {
|
||||
let n = b.nearest(p, 1e-9);
|
||||
((ta, n.t), n.distance_sq)
|
||||
});
|
||||
let ends_b = [(open_b.0, 0.0, b.p0), (open_b.1, 1.0, b.p3)].into_iter().filter(|e| e.0).map(|(_, tb, p)| {
|
||||
let n = a.nearest(p, 1e-9);
|
||||
((n.t, tb), n.distance_sq)
|
||||
});
|
||||
ends_a.chain(ends_b).filter(|e| e.1 < SAME * SAME).min_by(|x, y| x.1.total_cmp(&y.1)).map(|e| e.0)
|
||||
}
|
||||
|
||||
/// Where segments `a` and `b` cross: (t on `a`, t on `b`) pairs, halving both while their control
|
||||
/// boxes meet until each piece is straight. `None` once `budget` steps are spent.
|
||||
fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<Vec<(f64, f64)>> {
|
||||
/// boxes meet until each piece is straight. `None` once `budget` steps are spent. `open_a` and
|
||||
/// `open_b` are the segments' ends that are open ends of their paths (start, end): such an end
|
||||
/// within [`SAME`] of the other segment meets it there, as a path cut where another crosses it
|
||||
/// ends a little off that path.
|
||||
fn segment_crossings(a: &CubicBez, b: &CubicBez, open_a: Open, open_b: Open, budget: &mut usize) -> Option<Vec<(f64, f64)>> {
|
||||
let mut stack = vec![(0.0, 1.0, 0.0, 1.0, 0u32)];
|
||||
let mut found: Vec<(f64, f64)> = vec![];
|
||||
while let Some((a0, a1, b0, b1, depth)) = stack.pop() {
|
||||
@@ -60,10 +86,9 @@ fn segment_crossings(a: &CubicBez, b: &CubicBez, budget: &mut usize) -> Option<V
|
||||
continue;
|
||||
}
|
||||
if (flat(&ca) && flat(&cb)) || depth >= MAX_DEPTH {
|
||||
if let Some((s, u)) = chords_cross(&ca, &cb) {
|
||||
// The pieces are straight but their parameters needn't run evenly along them.
|
||||
let x = ca.p0.lerp(ca.p3, s);
|
||||
let (ta, tb) = (ca.nearest(x, 1e-9).t, cb.nearest(cb.p0.lerp(cb.p3, u), 1e-9).t);
|
||||
// Only a piece's ends that are the segment's open ends reach past it.
|
||||
let (oa, ob) = ((open_a.0 && a0 == 0.0, open_a.1 && a1 == 1.0), (open_b.0 && b0 == 0.0, open_b.1 && b1 == 1.0));
|
||||
if let Some((ta, tb)) = pieces_cross(&ca, &cb, oa, ob) {
|
||||
found.push((a0 + ta * (a1 - a0), b0 + tb * (b1 - b0)));
|
||||
}
|
||||
continue;
|
||||
@@ -152,18 +177,21 @@ fn shared_anchors(sp: &SubPath, with_length: &[usize], i: usize, j: usize) -> Ve
|
||||
|
||||
/// Where segments `a` and `b` cross, without the places at the anchors in `shared`: two segments that
|
||||
/// meet at an anchor don't cross there, but they can cross again elsewhere.
|
||||
fn crossings_apart(a: &CubicBez, b: &CubicBez, shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> {
|
||||
let mut found = segment_crossings(a, b, budget)?;
|
||||
fn crossings_apart(a: (&CubicBez, Open), b: (&CubicBez, Open), shared: &[Point], budget: &mut usize) -> Option<Vec<(f64, f64)>> {
|
||||
let ((a, open_a), (b, open_b)) = (a, b);
|
||||
let mut found = segment_crossings(a, b, open_a, open_b, budget)?;
|
||||
found.retain(|(ta, _)| !shared.iter().any(|p| a.eval(*ta).distance(*p) < SAME));
|
||||
Some(found)
|
||||
}
|
||||
|
||||
/// Where `paths` cross one another (and, with `self_crossings`, where each crosses itself, a segment
|
||||
/// that loops over itself included): for each path, the places on it, in order. Segments that meet
|
||||
/// at an anchor they share don't count as crossing there. `None` past [`MAX_CROSSING_SEGMENTS`]
|
||||
/// segments or when the curves are too tangled to sort out, or when a coordinate isn't finite.
|
||||
/// at an anchor they share don't count as crossing there, and an open end of a path that lies
|
||||
/// within 0.001 pt of another path (or of itself) meets it there; paths that lie along each other
|
||||
/// don't cross. `None` past [`MAX_CROSSING_SEGMENTS`] segments or when the curves are too tangled
|
||||
/// to sort out, or when a coordinate isn't finite.
|
||||
pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Place>>> {
|
||||
let mut segs: Vec<(usize, usize, usize, CubicBez, Rect)> = vec![];
|
||||
let mut segs: Vec<(usize, usize, usize, CubicBez, Rect, Open)> = vec![];
|
||||
for (k, path) in paths.iter().enumerate() {
|
||||
for (si, sp) in path.subpaths.iter().enumerate() {
|
||||
for s in 0..sp.segment_count() {
|
||||
@@ -171,7 +199,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
|
||||
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
segs.push((k, si, s, c, control_box(&c)));
|
||||
segs.push((k, si, s, c, control_box(&c), open_ends(sp, s)));
|
||||
if segs.len() > MAX_CROSSING_SEGMENTS {
|
||||
return None;
|
||||
}
|
||||
@@ -181,11 +209,11 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
|
||||
let with_length: Vec<Vec<Vec<usize>>> = paths.iter().map(|p| p.subpaths.iter().map(with_length_from).collect()).collect();
|
||||
let mut out: Vec<Vec<Place>> = vec![vec![]; paths.len()];
|
||||
let mut budget = MAX_STEPS;
|
||||
for (i, (ka, sa, ia, ca, ra)) in segs.iter().enumerate() {
|
||||
for (i, (ka, sa, ia, ca, ra, oa)) in segs.iter().enumerate() {
|
||||
if self_crossings && let Some((s, t)) = self_crossing(ca) {
|
||||
out.get_mut(*ka)?.extend([(*sa, *ia, s), (*sa, *ia, t)]);
|
||||
}
|
||||
for (kb, sb, ib, cb, rb) in segs.iter().skip(i + 1) {
|
||||
for (kb, sb, ib, cb, rb, ob) in segs.iter().skip(i + 1) {
|
||||
if (ka == kb && !self_crossings) || !ra.inflate(SAME, SAME).overlaps(*rb) {
|
||||
continue;
|
||||
}
|
||||
@@ -193,7 +221,7 @@ pub fn crossings(paths: &[&PathData], self_crossings: bool) -> Option<Vec<Vec<Pl
|
||||
(Some(sp), Some(w)) if ka == kb && sa == sb => shared_anchors(sp, w, *ia, *ib),
|
||||
_ => vec![],
|
||||
};
|
||||
for (ta, tb) in crossings_apart(ca, cb, &shared, &mut budget)? {
|
||||
for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, &mut budget)? {
|
||||
out.get_mut(*ka)?.push((*sa, *ia, ta));
|
||||
out.get_mut(*kb)?.push((*sb, *ib, tb));
|
||||
}
|
||||
@@ -248,41 +276,43 @@ impl Work {
|
||||
}
|
||||
|
||||
/// Where `others` cross `path`, and where `path` crosses itself (a segment that loops over itself
|
||||
/// included): the places on `path`, in order, within the work of [`Work::default`].
|
||||
/// included): the places on `path`, in order, within the work of [`Work::default`]. An open end of
|
||||
/// a path that lies within 0.001 pt of another meets it there, as [`crossings_on_within`] says.
|
||||
pub fn crossings_on(path: &PathData, others: &[&PathData]) -> Option<Vec<Place>> {
|
||||
crossings_on_within(path, others, &mut Work::default())
|
||||
}
|
||||
|
||||
/// [`crossings_on`], drawing on `work`. Only the segments of `others` whose control boxes meet the
|
||||
/// box of `path` are compared with it, so the paths far from it cost one box test per segment.
|
||||
/// Segments of `path` that meet at an anchor they share don't count as crossing there, and a
|
||||
/// segment of `others` with a coordinate that isn't finite is left out. `None` when `path` has more
|
||||
/// than [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than
|
||||
/// Segments of `path` that meet at an anchor they share don't count as crossing there, an open end
|
||||
/// of a path that lies within 0.001 pt of another meets it there, and a segment of `others` with a
|
||||
/// coordinate that isn't finite is left out. `None` when `path` has more than
|
||||
/// [`MAX_CROSSING_SEGMENTS`] segments or a coordinate that isn't finite, when more than
|
||||
/// [`MAX_CROSSED_BY_SEGMENTS`] segments of `others` lie in its box, when the pairs of segments to
|
||||
/// look at are more than `work` has left, or when the curves are too tangled to sort out in the
|
||||
/// steps it has left.
|
||||
pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Work) -> Option<Vec<Place>> {
|
||||
let mut own: Vec<(usize, usize, CubicBez, Rect)> = vec![];
|
||||
let mut own: Vec<(usize, usize, CubicBez, Rect, Open)> = vec![];
|
||||
for (si, sp) in path.subpaths.iter().enumerate() {
|
||||
for s in 0..sp.segment_count() {
|
||||
let c = sp.segment(s);
|
||||
if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
own.push((si, s, c, control_box(&c)));
|
||||
own.push((si, s, c, control_box(&c), open_ends(sp, s)));
|
||||
if own.len() > MAX_CROSSING_SEGMENTS {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(reach) = own.iter().map(|o| o.3).reduce(|a, b| a.union(b)).map(|r| r.inflate(SAME, SAME)) else { return Some(vec![]) };
|
||||
let mut near: Vec<(CubicBez, Rect)> = vec![];
|
||||
let mut near: Vec<(CubicBez, Rect, Open)> = vec![];
|
||||
for sp in others.iter().flat_map(|p| &p.subpaths) {
|
||||
for s in 0..sp.segment_count() {
|
||||
let c = sp.segment(s);
|
||||
let r = control_box(&c);
|
||||
if [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.x.is_finite() && p.y.is_finite()) && reach.overlaps(r) {
|
||||
near.push((c, r));
|
||||
near.push((c, r, open_ends(sp, s)));
|
||||
if near.len() > MAX_CROSSED_BY_SEGMENTS {
|
||||
return None;
|
||||
}
|
||||
@@ -293,17 +323,17 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor
|
||||
let with_length: Vec<Vec<usize>> = path.subpaths.iter().map(with_length_from).collect();
|
||||
let mut out: Vec<Place> = vec![];
|
||||
let budget = &mut work.steps;
|
||||
for (i, (sa, ia, ca, ra)) in own.iter().enumerate() {
|
||||
for (i, (sa, ia, ca, ra, oa)) in own.iter().enumerate() {
|
||||
let ra = ra.inflate(SAME, SAME);
|
||||
if let Some((s, t)) = self_crossing(ca) {
|
||||
out.extend([(*sa, *ia, s), (*sa, *ia, t)]);
|
||||
}
|
||||
for (cb, rb) in &near {
|
||||
for (cb, rb, ob) in &near {
|
||||
if ra.overlaps(*rb) {
|
||||
out.extend(segment_crossings(ca, cb, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta)));
|
||||
out.extend(segment_crossings(ca, cb, *oa, *ob, budget)?.into_iter().map(|(ta, _)| (*sa, *ia, ta)));
|
||||
}
|
||||
}
|
||||
for (sb, ib, cb, rb) in own.iter().skip(i + 1) {
|
||||
for (sb, ib, cb, rb, ob) in own.iter().skip(i + 1) {
|
||||
if !ra.overlaps(*rb) {
|
||||
continue;
|
||||
}
|
||||
@@ -311,7 +341,7 @@ pub fn crossings_on_within(path: &PathData, others: &[&PathData], work: &mut Wor
|
||||
(Some(sp), Some(w)) if sa == sb => shared_anchors(sp, w, *ia, *ib),
|
||||
_ => vec![],
|
||||
};
|
||||
for (ta, tb) in crossings_apart(ca, cb, &shared, budget)? {
|
||||
for (ta, tb) in crossings_apart((ca, *oa), (cb, *ob), &shared, budget)? {
|
||||
out.push((*sa, *ia, ta));
|
||||
out.push((*sb, *ib, tb));
|
||||
}
|
||||
|
||||
@@ -689,3 +689,58 @@ fn a_slice_of_a_curve_keeps_its_shape_and_the_anchors_it_runs_through() {
|
||||
assert!(slice(&circle, (2.0, 1.0)).anchors.is_empty());
|
||||
assert!(slice(&circle, (f64::NAN, 1.0)).anchors.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_end_a_hair_off_another_path_still_meets_it() {
|
||||
// A bow from (0, 0) to (100, 100), and where a line across at y = 50 crosses it.
|
||||
let bow = PathData::single(SubPath::new(
|
||||
vec![Anchor { h_out: pt(0.0, 55.0), ..Anchor::corner(pt(0.0, 0.0)) }, Anchor { h_in: pt(45.0, 100.0), ..Anchor::corner(pt(100.0, 100.0)) }],
|
||||
false,
|
||||
));
|
||||
let across = PathData::single(line(&[(-50.0, 50.0), (150.0, 50.0)], false));
|
||||
let at = crossings_on(&across, &[&bow]).unwrap();
|
||||
assert_eq!(at.len(), 1);
|
||||
let p = across.subpaths[0].segment(0).eval(at[0].2);
|
||||
// A line ending 0.00005 pt short of the bow, or past it, as a line cut where the bow crosses it
|
||||
// can: the bow is crossed there, on both searches.
|
||||
let on_bow = |l: &PathData| crossings_on(&bow, &[l]).unwrap().iter().map(|q| bow.subpaths[0].segment(q.1).eval(q.2)).collect::<Vec<_>>();
|
||||
for off in [-5e-5, 5e-5] {
|
||||
let stub = PathData::single(line(&[(-50.0, 50.0), (p.x + off, 50.0)], false));
|
||||
let found = on_bow(&stub);
|
||||
assert!(found.len() == 1 && found[0].distance(p) < 1e-3, "{off}: {found:?}");
|
||||
let both = crossings(&[&stub, &bow], false).unwrap();
|
||||
assert_eq!((both[0].len(), both[1].len()), (1, 1), "{off}: {both:?}");
|
||||
}
|
||||
// 0.01 pt short is not on it.
|
||||
assert!(on_bow(&PathData::single(line(&[(-50.0, 50.0), (p.x - 0.01, 50.0)], false))).is_empty());
|
||||
// The bow's own open end 0.00005 pt short of an upright meets it there.
|
||||
let upright = PathData::single(line(&[(100.00005, 50.0), (100.00005, 150.0)], false));
|
||||
let found = crossings_on(&upright, &[&bow]).unwrap();
|
||||
assert!(found.len() == 1 && near(upright.subpaths[0].segment(0).eval(found[0].2).y, 100.0, 1e-3), "{found:?}");
|
||||
// Two ends that each stop 0.0009 pt short of a corner lie 0.0013 pt apart: they don't meet.
|
||||
let flat = PathData::single(line(&[(0.0, 0.0), (99.9991, 0.0)], false));
|
||||
let post = PathData::single(line(&[(100.0, 0.0009), (100.0, 50.0)], false));
|
||||
assert!(crossings_on(&flat, &[&post]).unwrap().is_empty() && crossings_on(&post, &[&flat]).unwrap().is_empty());
|
||||
// Two ends that each stop 0.0004 pt short of a corner lie 0.0006 pt apart: they meet.
|
||||
let flat = PathData::single(line(&[(0.0, 0.0), (99.9996, 0.0)], false));
|
||||
let post = PathData::single(line(&[(100.0, 0.0004), (100.0, 50.0)], false));
|
||||
assert_eq!((crossings_on(&flat, &[&post]).unwrap().len(), crossings_on(&post, &[&flat]).unwrap().len()), (1, 1));
|
||||
// A level line that crosses a quarter circle near its top, where the two meet at under 3
|
||||
// degrees, cut 0.0015 pt short along its length: its end lies under 0.0001 pt from the arc and
|
||||
// meets it there.
|
||||
use kurbo::ParamCurveNearest;
|
||||
let arc = PathData::single(quarter());
|
||||
let level = PathData::single(line(&[(50.0, 99.9), (-50.0, 99.9)], false));
|
||||
let at = crossings_on(&level, &[&arc]).unwrap();
|
||||
assert_eq!(at.len(), 1);
|
||||
let end = level.subpaths[0].segment(0).eval(at[0].2) + Vec2::new(0.0015, 0.0);
|
||||
assert!(arc.subpaths[0].segment(0).nearest(end, 1e-12).distance_sq.sqrt() < 1e-4);
|
||||
let stub = PathData::single(line(&[(50.0, 99.9), (end.x, end.y)], false));
|
||||
let found = crossings_on(&arc, &[&stub]).unwrap();
|
||||
assert!(found.len() == 1 && arc.subpaths[0].segment(0).eval(found[0].2).distance(end) < 1e-3, "{found:?}");
|
||||
assert_eq!(crossings(&[&stub, &arc], false).unwrap().iter().map(Vec::len).collect::<Vec<_>>(), [1, 1]);
|
||||
// A corner of a closed path as near a line is not an open end: it doesn't reach the line.
|
||||
let wedge = PathData::single(line(&[(180.0, 0.0), (220.0, 0.0), (200.0, 49.99995)], true));
|
||||
let floor = PathData::single(line(&[(150.0, 50.0), (250.0, 50.0)], false));
|
||||
assert!(crossings_on(&floor, &[&wedge]).unwrap().is_empty() && crossings_on(&wedge, &[&floor]).unwrap().is_empty());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user