Merge #719 (fix/linesweeper-near-parallel-leaf-count) into integration/linesweeper

This commit is contained in:
dotCooCoo committed 2026-11-09 14:07:24 -08:00
commit 92f57d1479
4 files changed
+313

No files matched your search

+3
View File
@@ -322,6 +322,9 @@ vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for proven
vendor/linesweeper with its upstream license files and one local patch. Its manifest names Joe Neeman
as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
vendor/linesweeper with its upstream license files and one local patch. Its manifest names Joe Neeman
as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
change and the files left out.
Platform lifecycle source provenance
+5
View File
@@ -259,6 +259,10 @@ local patches listed below. `.cargo_vcs_info.json` names the commit it was packa
`824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest
names, which is archived; its README says development moved off GitHub.
local patches listed below. `.cargo_vcs_info.json` names the commit it was packaged from,
`824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest
names, which is archived; its README says development moved off GitHub.
Every file here except this one, `SOURCE.json` and the patched files below is byte for byte the file
in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download
(`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the
@@ -334,6 +338,7 @@ Every change here updates this table and `SOURCE.json` in the same commit.
| `src/segments.rs`, `src/sweep/sweep_line.rs`, `src/topology.rs` | The `Topology` constructors and `Sweeper::new_with_correctness` replace an `eps` that is NaN, infinite, not positive, or below `64 * f64::EPSILON` times the largest coordinate magnitude (and at least 64 times the spacing of subnormal floats) with that value, the scale `binary_op` uses. Before, an infinite `eps` made a lens of two arcs vanish, and an `eps` below one ulp of the coordinates (0 included, or 1e-10 at 1.5e8) overflowed the stack and aborted the process. |
| `src/curve/mod.rs` | `intersect_cubics` and `intersect_cubics_with_precomputed_decomp` raise a positive `ish_tolerance` below `4 * f64::EPSILON` times the two curves' largest x coordinate magnitude (two to four ulps of it, and at least four times the spacing of subnormal floats) to that value, and a positive `sure_tolerance` below half of it to half of it. Below that, rounding made the comparison report the wrong order. `intersect_cubics_rec` returns close (`Ish`) for an interval whose midpoint rounds to one of its ends instead of splitting it again, which repeated the same call until the stack overflowed. The `ish_tolerance_below_float_spacing` test covers both. `raised_tolerance_keeps_far_curves_apart`, `raised_tolerance_ignores_large_y` and `raised_tolerance_keeps_subnormal_curves_apart` check that lines 1.0 apart at x = 1e15, lines 1.0 apart at y = 2e15, and lines at x = 1e-310 and 2e-310 stay ordered. |
| `src/position.rs` | `approximate` stops halving an interval whose midpoint rounds to one of its ends. Before, it could return the interval's start, and the loop in `compute_positions_correct` then made no progress. The `approx_stops_at_one_float` test covers it. |
| `src/curve/mod.rs` | `intersect_cubics_rec` calls the new `order_from_control_points` after cutting both cubics to their shared y-range. It bounds the x gap between the two pieces by the smallest and largest control point x gap, widened by the largest control point y gap times a bound on `\|dx/dy\|` from the control polygon (`max_slope`). When that range stays more than `ish_tolerance` on one side of zero, the whole range gets `Left` or `Right` and the comparison does not recurse. Before, two nearly parallel cubics split their shared y-range into about `(height / ish_tolerance)^(1/3)` pieces even when they stayed more than `ish_tolerance` apart: a tall S-shaped cubic and a copy moved 10 * `ish_tolerance` sideways took 4,096 recursion leaves at height 1e6 and 16,384 at height 1e8; now each takes one. The `near_parallel_cubics_are_ordered_without_recursing` test counts the entries for that pair, `control_point_order_is_sound` checks every order the control points give against sampled gaps, and `control_point_order_keeps_band_contours` checks that the contours of a tall wavy band and a moved copy do not change. |
`omitted_files` lists the 43 files of the package left out here, with their hashes:
+2
View File
@@ -68,6 +68,7 @@
"`ComparisonCache` in `src/order.rs` holds the comparisons of one `Segments` arena. `compare_segments` reads the arena's number, which `src/segments.rs` gives each arena and each clone, and drops the cached comparisons when the number differs from the one they were made with. Before, a cache given a second arena returned the first arena's order for the same pair of indices."
"In `src/curve/mod.rs`, `fit_quadratic` multiplies the heights by the power of two that brings the largest to between 2 and 4 when one of them has a magnitude above 2^500 and scales the coefficients back, and `QuadraticApprox::from_cubic` multiplies by the `y^2` coefficient first when a product of two y coefficients is not finite, so curves taller than about 1.3e154 no longer give NaN coefficients or error bounds that make curve comparisons, and `binary_op`, return a wrong order without an error. The quadratic sign checks of curve comparisons report an unknown (or close) order for a quadratic with a NaN or infinite coefficient. In `src/curve/line.rs`, `intersect_lines` scales the x coordinates and the tolerance by 1/16 when one of them is above 2^1019 and works with half of each height for lines more than `f64::MAX` tall, so coordinates near `f64::MAX` no longer give a wrong order. In `src/geom.rs`, `Segment::at_y` and `Segment::to_kurbo_cubic` give finite results for a straight segment more than `f64::MAX` long on either axis. `src/curve/mod.rs`, `src/curve/line.rs`, `src/geom.rs` and `src/lib.rs` add tests for it."
"In `src/lib.rs`, `src/segments.rs`, `src/sweep/sweep_line.rs` and `src/topology.rs`, `binary_op_with_eps` returns the new `Error::InvalidEps` for an `eps` that is NaN, infinite, zero or negative, and the `Topology` constructors and `Sweeper::new_with_correctness` replace an `eps` that is NaN, infinite, not positive, or below `64 * f64::EPSILON` times the largest coordinate magnitude (and at least 64 times the spacing of subnormal floats) with that value, so a bad `eps` no longer gives a wrong region, a hang or a stack overflow. In `src/curve/mod.rs`, `intersect_cubics` and `intersect_cubics_with_precomputed_decomp` raise a positive `ish_tolerance` below `4 * f64::EPSILON` times the curves' largest x coordinate magnitude (and at least four times the spacing of subnormal floats) to that value and a positive `sure_tolerance` below half of it to half of it, and `intersect_cubics_rec` returns `Ish` for an interval whose midpoint rounds to one of its ends instead of recursing on it again. In `src/position.rs`, `approximate` stops halving such an interval, so `compute_positions_correct` always advances."
"In `src/curve/mod.rs`, `intersect_cubics_rec` calls the new `order_from_control_points` after cutting both cubics to the shared y-range and before building quadratic approximations. It takes the smallest and largest gap between matching control point x coordinates and widens that range by the largest control point y gap times a bound on `|dx/dy|` from the control polygon (`max_slope`); when the widened range stays more than `ish_tolerance` on one side of zero it records `Left` or `Right` for the whole range and does not recurse. Before the change, a tall S-shaped cubic and a copy moved 10 * `ish_tolerance` sideways took 4,096 recursion leaves at height 1e6 and 16,384 at height 1e8; now each takes one. `curve::test::near_parallel_cubics_are_ordered_without_recursing`, `curve::test::control_point_order_is_sound` and `curve::test::control_point_order_keeps_band_contours` cover it."
],
"files": [
{ "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" },
@@ -119,6 +120,7 @@
{ "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "f992312ad44b74336a18c992cbabff0bb8a42bd759bc4bee778586b44f2dfe1d" },
{ "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "7bbc99e120d3af0af93df9b6f2fde4da7b5075fef7588f8bf3c4807c007e9d76" },
{ "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "cbc6f444153525e7da85473466434b07826c75d0500773a0aa3cf068c5225d09" },
{ "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "d34845883ebcd1ca8e89b29594bd26270c8d40eaff2c438f27108204e4cace4f" },
{ "path": "src/curve/split_quad.rs", "source_sha256": "b8aae4ce7c16fa623724f667e1058130a9c7eed693b5b01e8b9e16632b8ec45f", "source_git_blob": null, "sha256": "b8aae4ce7c16fa623724f667e1058130a9c7eed693b5b01e8b9e16632b8ec45f" },
{ "path": "src/curve/transverse.rs", "source_sha256": "be9c695531f4cb0fe73af13e78040b51b9476c193d84562e701aadd07b3fd06e", "source_git_blob": null, "sha256": "be9c695531f4cb0fe73af13e78040b51b9476c193d84562e701aadd07b3fd06e" },
{ "path": "src/generators.rs", "source_sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef", "source_git_blob": null, "sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef" },
+303
View File
@@ -1393,6 +1393,79 @@ fn float_spacing(max_coord: f64) -> f64 {
(max_coord * f64::EPSILON).max(MIN_SPACING)
}
// Craft patch (control point order): two y-subsegments that stay more than
// `ish_tolerance` apart get one order from their control points without
// recursing. At parameter t the gap `x1(t) - x0(t)` lies between the smallest
// and largest control point x gaps, and `|y1(t) - y0(t)|` is at most the
// largest control point y gap `dy`. At one height y = y0(t0) = y1(t1), the gap
// `x1(t1) - x0(t0)` differs from `x1(t1) - x0(t1)` by at most `slope * dy`,
// where `slope` bounds `|dx/dy|` on c0 (and symmetrically for c1). When `dy`
// is zero both curves reach each height at the same t, so no slope is needed.
fn order_from_control_points(c0: CubicBez, c1: CubicBez, ish_tolerance: f64) -> Option<Order> {
let gaps = [
c1.p0.x - c0.p0.x,
c1.p1.x - c0.p1.x,
c1.p2.x - c0.p2.x,
c1.p3.x - c0.p3.x,
];
if !gaps.iter().all(|g| g.is_finite()) {
return None;
}
let min_gap = gaps.iter().copied().fold(f64::INFINITY, f64::min);
let max_gap = gaps.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let dy = (c1.p0.y - c0.p0.y)
.abs()
.max((c1.p1.y - c0.p1.y).abs())
.max((c1.p2.y - c0.p2.y).abs())
.max((c1.p3.y - c0.p3.y).abs());
let slack = if dy == 0.0 {
0.0
} else {
dy * max_slope(c0).min(max_slope(c1))
};
if !slack.is_finite() {
return None;
}
if min_gap - slack > ish_tolerance {
Some(Order::Left)
} else if max_gap + slack < -ish_tolerance {
Some(Order::Right)
} else {
None
}
}
// Craft patch (control point order): an upper bound on `|dx/dy|` along `c`,
// or infinity unless every leg of the control polygon rises in y. The
// derivative is a positive combination of the legs, so the largest leg ratio
// bounds it.
fn max_slope(c: CubicBez) -> f64 {
let mut ret = 0.0f64;
for (a, b) in [(c.p0, c.p1), (c.p1, c.p2), (c.p2, c.p3)] {
let dy = b.y - a.y;
if dy.is_nan() || dy <= 0.0 {
return f64::INFINITY;
}
ret = ret.max((b.x - a.x).abs() / dy);
}
ret
}
#[cfg(test)]
thread_local! {
static SKIP_CONTROL_POINT_ORDER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(not(test))]
fn control_point_order_enabled() -> bool {
true
}
#[cfg(test)]
fn control_point_order_enabled() -> bool {
!SKIP_CONTROL_POINT_ORDER.with(std::cell::Cell::get)
}
#[derive(Clone, Debug)]
struct CubicParams {
c: CubicBez,
@@ -1438,6 +1511,12 @@ fn intersect_cubics_rec(
out.push(y1, order, status);
return;
}
if control_point_order_enabled()
&& let Some(order) = order_from_control_points(c0, c1, ish_tolerance)
{
out.push(y1, order, status);
return;
}
// If the y coordinates are very off-center, the quadratic coefficients become
// large and cause instability. So we re-center and then compensate afterwards.
@@ -2375,6 +2454,230 @@ mod test {
}
}
fn shifted(c: CubicBez, dx: f64, dy: f64) -> CubicBez {
let v = Vec2::new(dx, dy);
CubicBez::new(c.p0 + v, c.p1 + v, c.p2 + v, c.p3 + v)
}
fn without_control_point_order<T>(f: impl FnOnce() -> T) -> T {
SKIP_CONTROL_POINT_ORDER.with(|s| s.set(true));
let ret = f();
SKIP_CONTROL_POINT_ORDER.with(|s| s.set(false));
ret
}
// Craft patch (control point order) test: a tall S-shaped cubic and a copy
// moved 10 * ish_tolerance sideways are ordered in one step. Without the
// patch the recursion splits the range into thousands of pieces.
#[test]
fn near_parallel_cubics_are_ordered_without_recursing() {
let s = 1e6;
let ish = 1e-6;
let c0 = CubicBez::new((0.0, 0.0), (s, s / 3.0), (-s, 2.0 * s / 3.0), (0.0, s));
for (dx, dy, order) in [
(10.0 * ish, 0.0, Order::Left),
(10.0 * ish, 0.5 * ish, Order::Left),
(-10.0 * ish, 0.0, Order::Right),
(-10.0 * ish, 0.5 * ish, Order::Right),
] {
let c1 = shifted(c0, dx, dy);
let cmp = intersect_cubics(c0, c1, ish / 2.0, ish);
let y0 = c1.p0.y;
assert_eq!(cmp.iter().collect::<Vec<_>>(), vec![(y0, s, order)]);
assert!(
cmp.metrics.entries.len() <= 4,
"{} entries for ({dx}, {dy})",
cmp.metrics.entries.len()
);
}
}
// Craft patch (control point order) test: whenever the control points of
// two y-subsegments give an order, the subsegments are more than
// `sure_tolerance` apart in that order at sample heights, and a curve and
// a copy moved 10 * ish_tolerance or more sideways get the same
// `CurveOrder` as without the patch.
#[test]
fn control_point_order_is_sound() {
// Returns how many subsegment pairs the control points ordered.
fn check(c0: CubicBez, c1: CubicBez, sure: f64, ish: f64) -> usize {
let y0 = c0.p0.y.max(c1.p0.y);
let y1 = c0.p3.y.min(c1.p3.y);
let mut ordered = 0;
for parts in [1u32, 3, 16] {
for j in 0..parts {
let a = y0 + (y1 - y0) * f64::from(j) / f64::from(parts);
let b = if j + 1 == parts {
y1
} else {
y0 + (y1 - y0) * f64::from(j + 1) / f64::from(parts)
};
if a >= b {
continue;
}
let s0 = y_subsegment(c0, a, b);
let s1 = y_subsegment(c1, a, b);
let Some(order) = order_from_control_points(s0, s1, ish) else {
continue;
};
ordered += 1;
for i in 0..=8 {
let y = (a + (b - a) * f64::from(i) / 8.0).min(b);
let gap = solve_x_for_y(s1, y) - solve_x_for_y(s0, y);
match order {
Order::Left => assert!(gap > sure, "{s0:?} {s1:?} {y} {gap}"),
Order::Right => assert!(gap < -sure, "{s0:?} {s1:?} {y} {gap}"),
Order::Ish => panic!("control points gave Ish for {s0:?} {s1:?}"),
}
}
}
}
ordered
}
let sure = 1e-4;
let ish = 1e-3;
let curves = [
CubicBez::new((0.0, 0.0), (1.0, 0.3), (-1.0, 0.7), (0.0, 1.0)),
CubicBez::new((-1.0, 0.0), (0.5, 0.6), (0.5, 0.4), (-1.0, 1.0)),
CubicBez::new((0.0, 0.0), (30.0, 0.01), (60.0, 0.02), (90.0, 1.0)),
CubicBez::new((90.0, 0.0), (60.0, 0.98), (30.0, 0.99), (0.0, 1.0)),
CubicBez::new((0.0, 0.0), (0.0, 1.0 / 3.0), (0.0, 2.0 / 3.0), (0.0, 1.0)),
];
let mut ordered = 0;
for (i0, c0) in curves.into_iter().enumerate() {
for (i1, c1) in curves.into_iter().enumerate() {
for k in [-1000.0, -10.0, -2.0, -1.0, 0.0, 1.0, 2.0, 10.0, 1000.0] {
for dy in [0.0, 0.25 * ish, 0.25] {
let c1 = shifted(c1, k * ish, dy);
ordered += check(c0, c1, sure, ish);
if i0 != i1 || k.abs() < 10.0 || dy >= ish {
continue;
}
let with = intersect_cubics(c0, c1, sure, ish)
.iter()
.collect::<Vec<_>>();
if i0 == 2 || i0 == 3 {
// Almost horizontal: the recursion can report Ish
// near an end, and a sideways copy is now ordered
// over the whole range.
if dy == 0.0 {
let order = if k > 0.0 { Order::Left } else { Order::Right };
assert_eq!(with, vec![(0.0, 1.0, order)], "{c0:?} {c1:?}");
}
} else {
let without = without_control_point_order(|| {
intersect_cubics(c0, c1, sure, ish)
.iter()
.collect::<Vec<_>>()
});
assert_eq!(with, without, "{c0:?} {c1:?}");
}
}
}
}
}
assert!(
ordered > 100,
"{ordered} hand-built subsegment pairs ordered"
);
// Generated pairs, from a fixed sequence of bytes: a curve and either
// another curve or a copy of it moved sideways and up.
let mut state = 0x9e37_79b9_7f4a_7c15_u64;
let mut bytes = vec![0u8; 256];
let mut compared = 0;
let mut ordered = 0;
for n in 0..2000 {
for b in &mut bytes {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
*b = state as u8;
}
let mut u = arbitrary::Unstructured::new(&bytes);
let Ok(c0) = crate::arbitrary::monotonic_bezier(&mut u) else {
continue;
};
for (sure, ish) in [(1e-3, 1e-2), (0.25, 1.0), (100.0, 1000.0)] {
let c1 = if n % 2 == 0 {
let Ok(c1) = crate::arbitrary::another_monotonic_bezier(&mut u, &c0) else {
continue;
};
c1
} else {
let k = f64::from(u.int_in_range(-40..=40).unwrap_or(20));
let dy = f64::from(u.int_in_range(0..=8).unwrap_or(0)) * 0.125 * ish;
shifted(c0, k * ish, dy)
};
if c1.p0.y >= c1.p3.y || c0.p0.y.max(c1.p0.y) >= c0.p3.y.min(c1.p3.y) {
continue;
}
ordered += check(c0, c1, sure, ish);
compared += 1;
}
}
assert!(compared > 3000, "{compared} generated comparisons");
assert!(
ordered > 1000,
"{ordered} generated subsegment pairs ordered"
);
}
// Craft patch (control point order) test: the contours of a tall wavy band
// and a copy moved 10 * eps sideways are the same with and without the
// patch.
#[test]
fn control_point_order_keeps_band_contours() {
let (n, l) = (50, 1e6);
let eps = 1e-6;
let amp = l * 0.05;
let lam = l / 3.0;
let width = l * 0.1;
let x = |y: f64| amp * (std::f64::consts::TAU * y / lam).sin();
let dx =
|y: f64| amp * std::f64::consts::TAU / lam * (std::f64::consts::TAU * y / lam).cos();
let h = l / f64::from(n);
let mut band = kurbo::BezPath::new();
band.move_to((x(0.0), 0.0));
for i in 0..n {
let (y0, y1) = (f64::from(i) * h, f64::from(i + 1) * h);
band.curve_to(
(x(y0) + dx(y0) * h / 3.0, y0 + h / 3.0),
(x(y1) - dx(y1) * h / 3.0, y1 - h / 3.0),
(x(y1), y1),
);
}
band.line_to((x(l) + width, l));
for i in (0..n).rev() {
let (y0, y1) = (f64::from(i) * h, f64::from(i + 1) * h);
band.curve_to(
(x(y1) + width - dx(y1) * h / 3.0, y1 - h / 3.0),
(x(y0) + width + dx(y0) * h / 3.0, y0 + h / 3.0),
(x(y0) + width, y0),
);
}
band.close_path();
for (kx, ky) in [(10.0, 0.0), (10.0, 1.0), (-10.0, 0.3)] {
let mut both = band.clone();
let mut copy = band.clone();
copy.apply_affine(kurbo::Affine::translate((kx * eps, ky * eps)));
both.extend(copy.iter());
let contours = || {
let top = crate::topology::Topology::<i32>::from_path(&both, eps).unwrap();
top.contours(|w| *w != 0)
.contours()
.map(|c| c.path.clone())
.collect::<Vec<_>>()
};
let with = contours();
let without = without_control_point_order(contours);
assert!(!with.is_empty());
assert_eq!(with, without, "copy moved by ({kx}, {ky}) * eps");
}
}
#[test]
fn quad_approximation() {
let c = CubicBez {