diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index f683ca53de..4764af7cf0 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,15 +1,27 @@ # Local linesweeper 0.5.0 copy -This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and no -file changed. `.cargo_vcs_info.json` names the commit it was packaged from, +This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the +changes listed under Local changes. `.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 and `SOURCE.json` 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 hash here (`sha256`). `upstream_repository` is -null because no public repository this copy can name holds `upstream_revision`. `local_patches` is -empty. +Every file here except this one, `SOURCE.json` and the files under Local changes 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 +hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name +holds `upstream_revision`. `local_patches` describes each local change. + +## Local changes + +| Change | Code comment label | Touches | Tests | +|---|---|---|---| +| `SegmentOrder::position` finds a segment by binary search over a key on each sweep-line entry | `Craft patch (sweep position)` | `src/sweep/sweep_line.rs` | `position_after_edits`, `position_after_repeated_insertion`, `position_after_insertion_next_to_the_extreme_keys`, `position_after_moving_a_contour_continuation`, `position_on_a_wide_sweep_line` | +| `ComparisonCache` skips the curve comparison for segments whose horizontal bounds are far apart | `Craft patch (far-apart comparison)` | `src/order.rs`, `src/curve/mod.rs` | `far_apart_order`, `far_apart_curves_compare_like_the_full_comparison`, `far_apart_steep_curves_never_reverse`, `far_apart_steep_curves_skip_the_full_comparison` | +| `Metrics::entries` holds two entries inline, as a `SmallVec` | `Craft patch (inline metrics)` | `src/curve/mod.rs` | `cargo check --example curve_metrics` | + +Every change here updates this table and `SOURCE.json` in the same commit. To take a new linesweeper +release, unpack the crates.io package, carry these changes over, regenerate `SOURCE.json`, and run the +tests below. `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 9c71e51add..073ea37d45 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -7,7 +7,11 @@ "upstream_repository": null, "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", - "local_patches": [], + "local_patches": [ + "`SegmentOrder::position` finds a segment by binary search over a key on each sweep-line entry instead of scanning the line. The order of the line and the index returned do not change.", + "`ComparisonCache` skips the curve comparison for two segments whose horizontal bounds are more than four times the larger of the tolerance and the accuracy apart, and records one order for all the heights they share. The full comparison can report part of such a pair as `Ish`, and this result does not. This result's `metrics` holds one entry at depth zero.", + "`Metrics::entries` is a `SmallVec<[MetricsEntry; 2]>` instead of a `Vec`." + ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, { "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" }, @@ -32,14 +36,14 @@ { "path": "proptest-regressions/topology.txt", "source_sha256": "49ff0b5b370f082984276d5312f03b1fc96ef0dd218f9efd7b084b11abbb9d19", "source_git_blob": null, "sha256": "49ff0b5b370f082984276d5312f03b1fc96ef0dd218f9efd7b084b11abbb9d19" }, { "path": "src/arbitrary.rs", "source_sha256": "9c3753a40cfea2528a546295d39e0513537db5a3411a931fccea063873d95750", "source_git_blob": null, "sha256": "9c3753a40cfea2528a546295d39e0513537db5a3411a931fccea063873d95750" }, { "path": "src/curve/line.rs", "source_sha256": "07aebead4b0050410a3f9f28b66062b6016c115df58e2b2669470263cd352f3e", "source_git_blob": null, "sha256": "07aebead4b0050410a3f9f28b66062b6016c115df58e2b2669470263cd352f3e" }, - { "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2" }, + { "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "815aafe3b4bfb518fb05298374ced58a7c86349f47bc65506c5d64c25997c81d" }, { "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" }, { "path": "src/geom.rs", "source_sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08", "source_git_blob": null, "sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08" }, { "path": "src/lib.rs", "source_sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6", "source_git_blob": null, "sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6" }, { "path": "src/num.rs", "source_sha256": "39ff85da50c500ce91cf6dea81aedc0dcca1db5e7d0506696dde2da118e93a2a", "source_git_blob": null, "sha256": "39ff85da50c500ce91cf6dea81aedc0dcca1db5e7d0506696dde2da118e93a2a" }, - { "path": "src/order.rs", "source_sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596", "source_git_blob": null, "sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596" }, + { "path": "src/order.rs", "source_sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596", "source_git_blob": null, "sha256": "8d2393e43000543c4ac3d47c2615e16733106af78ac67708ebf6941a039b9cdc" }, { "path": "src/perturbation.rs", "source_sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5", "source_git_blob": null, "sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5" }, { "path": "src/position.rs", "source_sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0", "source_git_blob": null, "sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0" }, { "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc" }, @@ -62,7 +66,7 @@ { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square.snap", "source_sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77", "source_git_blob": null, "sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" }, - { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3" }, + { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "eeade258c65bee0e12621f0df0b422bb65fba721638e3aaab4b08945bd2ad33c" }, { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" }, { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" }, { "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" }, diff --git a/vendor/linesweeper/src/curve/mod.rs b/vendor/linesweeper/src/curve/mod.rs index f602308573..b56ff002cd 100644 --- a/vendor/linesweeper/src/curve/mod.rs +++ b/vendor/linesweeper/src/curve/mod.rs @@ -32,8 +32,9 @@ impl CurveOrderEntry { /// depth by y-interval. #[derive(Clone, Debug, PartialEq, Default)] pub struct Metrics { + // Craft patch (inline metrics): a `SmallVec` replaces the package's `Vec`. /// Each interval records a single recursion depth measurement. - pub entries: Vec, + pub entries: SmallVec<[MetricsEntry; 2]>, } /// A single observability entry. @@ -139,6 +140,14 @@ impl CurveOrder { } } + // Craft patch (far-apart comparison). + /// A curve order with the same order at all heights between `start` and `end`. + pub(crate) fn constant(start: f64, end: f64, order: Order) -> Self { + let mut ret = CurveOrder::new(start); + ret.push(end, order, MetricsStatus::default()); + ret + } + fn push(&mut self, end: f64, order: Order, status: MetricsStatus) { self.metrics.entries.push(MetricsEntry::new(end, status)); if let Some(last) = self.cmps.last_mut() { diff --git a/vendor/linesweeper/src/order.rs b/vendor/linesweeper/src/order.rs index b421bd885f..78ce53db51 100644 --- a/vendor/linesweeper/src/order.rs +++ b/vendor/linesweeper/src/order.rs @@ -3,8 +3,8 @@ use rustc_hash::FxHashMap; use crate::{ - SegIdx, Segments, - curve::{self, CurveOrder}, + SegIdx, Segment, Segments, + curve::{self, CurveOrder, Order}, }; /// A cache for curve comparisons, so that each pair of curves needs to be compared at most once. @@ -79,18 +79,7 @@ impl ComparisonCache { if let (Some(l0), Some(l1)) = (segi.as_kurbo_line(), segj.as_kurbo_line()) { curve::line::intersect_lines(l0, l1, self.tolerance) } else { - let c0 = segi.to_kurbo_cubic(); - let c0_div = segments.horiz_decomp(i); - let c1 = segj.to_kurbo_cubic(); - let c1_div = segments.horiz_decomp(j); - curve::intersect_cubics_with_precomputed_decomp( - c0, - c0_div, - c1, - c1_div, - self.accuracy, - self.tolerance, - ) + compare_curves(segments, i, j, self.accuracy, self.tolerance) }; debug_assert_eq!( forward.iter().last().unwrap().1, @@ -104,11 +93,309 @@ impl ComparisonCache { } } +// Craft patch (far-apart comparison): compares two segments, at least one of +// which is not a line. A pair that is far apart skips the full comparison. +fn compare_curves( + segments: &Segments, + i: SegIdx, + j: SegIdx, + accuracy: f64, + tolerance: f64, +) -> CurveOrder { + let margin = far_apart_margin(tolerance, accuracy); + let Some(ret) = order_if_far_apart(&segments[i], &segments[j], margin) else { + return full_comparison(segments, i, j, accuracy, tolerance); + }; + + // The full comparison can split the heights of a far-apart pair and report + // some of them as `Ish`. It covers the same heights and never finds the + // opposite order. + #[cfg(any(test, feature = "slow-asserts"))] + { + let far: Vec<_> = ret.iter().collect(); + let full: Vec<_> = full_comparison(segments, i, j, accuracy, tolerance) + .iter() + .collect(); + assert_eq!(far[0].0, full[0].0); + assert_eq!(far[0].1, full[full.len() - 1].1); + assert!(full.iter().all(|entry| entry.2 != far[0].2.flip())); + } + + ret +} + +// Craft patch (far-apart comparison). +fn full_comparison( + segments: &Segments, + i: SegIdx, + j: SegIdx, + accuracy: f64, + tolerance: f64, +) -> CurveOrder { + curve::intersect_cubics_with_precomputed_decomp( + segments[i].to_kurbo_cubic(), + segments.horiz_decomp(i), + segments[j].to_kurbo_cubic(), + segments.horiz_decomp(j), + accuracy, + tolerance, + ) +} + +// Craft patch (far-apart comparison). +fn far_apart_margin(tolerance: f64, accuracy: f64) -> f64 { + 4.0 * tolerance.max(accuracy) +} + +// Craft patch (far-apart comparison): the order of two segments whose horizontal +// bounds are more than `margin` apart, and which overlap vertically. Control points +// bound each segment, so the segments keep this order at every height they share. +// +// The full comparison does not always give this answer. Its quadratic approximation +// has a large error on a steep curve, and it can report part of such a pair as `Ish`. +fn order_if_far_apart(segi: &Segment, segj: &Segment, margin: f64) -> Option { + let order = if segi.max_x() + margin < segj.min_x() { + Order::Left + } else if segj.max_x() + margin < segi.min_x() { + Order::Right + } else { + return None; + }; + let start = segi.start().y.max(segj.start().y); + let end = segi.end().y.min(segj.end().y); + (start <= end).then(|| CurveOrder::constant(start, end, order)) +} + #[cfg(test)] mod tests { + use kurbo::BezPath; + use proptest::prelude::*; + use crate::{SegIdx, Segments, curve::Order}; - use super::ComparisonCache; + use super::{ComparisonCache, far_apart_margin, full_comparison, order_if_far_apart}; + + // Two closed paths with curves that bulge toward each other. The control points of + // the left curve reach `bulge` and those of the right curve start `gap` after that. + fn facing_curves(height: f64, bulge: f64, gap: f64) -> Segments { + let (left, right) = (0.0, bulge + gap); + let mut a = BezPath::new(); + a.move_to((left, 0.0)); + a.curve_to( + (bulge, height / 3.0), + (bulge, 2.0 * height / 3.0), + (left, height), + ); + a.line_to((left - 1.0, height / 2.0)); + a.close_path(); + + let mut b = BezPath::new(); + b.move_to((right + bulge, 0.0)); + b.curve_to( + (right, height / 3.0), + (right, 2.0 * height / 3.0), + (right + bulge, height), + ); + b.line_to((right + bulge + 1.0, height / 2.0)); + b.close_path(); + + let mut segments = Segments::default(); + segments.add_bez_path(&a).unwrap(); + segments.add_bez_path(&b).unwrap(); + segments + } + + // A closed path with a y-monotone cubic from `(x0, 0)` to `(x3, height)`. Its other + // control points are at the heights `a * height` and `b * height`. + fn steep_curve(xs: [f64; 4], a: f64, b: f64, height: f64) -> BezPath { + let mut path = BezPath::new(); + path.move_to((xs[0], 0.0)); + path.curve_to((xs[1], a * height), (xs[2], b * height), (xs[3], height)); + path.close_path(); + path + } + + fn intervals(order: &crate::curve::CurveOrder) -> Vec<(f64, f64, Order)> { + order.iter().collect() + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(2_000))] + + // Steep S-shaped and asymmetric curves, with heights that include the + // tolerance. Every pair goes through `compare_curves`, which checks in test + // builds that the full comparison covers the same heights and never finds the + // opposite order. The full comparison finds `Ish` in only some of these pairs. + #[test] + fn far_apart_steep_curves_never_reverse( + (tolerance, accuracy) in prop_oneof![ + Just((0.1f64, 0.05f64)), + Just((0.4, 0.05)), + Just((1e-6, 5e-7)), + ], + height in prop_oneof![Just(1.0f64), 1.0f64..4.0, 4.0f64..100.0], + widths in (-1.0f64..3.0, -1.0f64..3.0), + shapes in (0usize..3, 0usize..3), + x_controls in (0.0f64..1.0, 0.0f64..1.0, 0.0f64..1.0, 0.0f64..1.0), + y_controls in (0.0f64..0.5, 0.5f64..1.0, 0.0f64..0.5, 0.5f64..1.0), + gap in 1.0001f64..1.5, + swap: bool, + ) { + let height = height * tolerance; + let shape = |index: usize, x: f64, width: f64, controls: (f64, f64)| match index { + 0 => [x, x + width, x, x + width], + 1 => [x + width, x, x + width, x], + _ => [x, x + width * controls.0, x + width * controls.1, x + width], + }; + let w0 = tolerance * 10f64.powf(widths.0); + let w1 = tolerance * 10f64.powf(widths.1); + let right = w0 + gap * far_apart_margin(tolerance, accuracy); + let mut a = steep_curve( + shape(shapes.0, 0.0, w0, (x_controls.0, x_controls.1)), + y_controls.0, + y_controls.1, + height, + ); + let mut b = steep_curve( + shape(shapes.1, right, w1, (x_controls.2, x_controls.3)), + y_controls.2, + y_controls.3, + height, + ); + if swap { + std::mem::swap(&mut a, &mut b); + } + let mut segments = Segments::default(); + segments.add_bez_path(&a).unwrap(); + segments.add_bez_path(&b).unwrap(); + + let mut cmp = ComparisonCache::new(tolerance, accuracy); + for i in segments.indices() { + for j in segments.indices() { + if i != j { + cmp.compare_segments(&segments, i, j); + } + } + } + } + } + + proptest! { + // Every pair goes through `compare_curves`. The quadratic approximation of + // these curves has no error to speak of, so the full comparison gives a pair + // beyond the margin the same single order. The gaps include the margin of each + // tolerance and accuracy below. + #[test] + fn far_apart_curves_compare_like_the_full_comparison( + height in 0.001f64..10.0, + bulge in prop_oneof![Just(0.001f64), 0.001f64..0.5, 0.5f64..5.0], + gap in prop_oneof![ + 0.0f64..0.2, + 0.39f64..0.41, + 1.59f64..1.61, + 3.99f64..4.01, + 1.0f64..100.0, + ], + ) { + let segments = facing_curves(height, bulge, gap); + let eps = 0.1; + for (tolerance, accuracy) in [(eps, eps / 2.0), (4.0 * eps, eps / 2.0), (eps, 10.0 * eps)] { + let mut cmp = ComparisonCache::new(tolerance, accuracy); + for i in segments.indices() { + for j in segments.indices() { + if i != j { + let compared = intervals(cmp.compare_segments(&segments, i, j)); + let margin = far_apart_margin(tolerance, accuracy); + if order_if_far_apart(&segments[i], &segments[j], margin).is_some() { + let full = full_comparison(&segments, i, j, accuracy, tolerance); + prop_assert_eq!(compared, intervals(&full)); + } + } + } + } + } + } + } + + // The full comparison reports part of this pair as `Ish`, so a far-apart answer + // shows that `compare_curves` did not use it. + #[test] + fn far_apart_steep_curves_skip_the_full_comparison() { + let height = 1.7356316808658495e-6; + let a = steep_curve( + [ + 0.0, + 2.487438508389841e-5, + 7.989789511893805e-5, + 2.5251761348508994e-4, + ], + 4.1143632201699014e-7 / height, + 1.3944624441448228e-6 / height, + height, + ); + let b = steep_curve( + [ + 2.5693176647313107e-4, + 2.7157585226714214e-4, + 2.9262618025363465e-4, + 4.220260171548132e-4, + ], + 1.1589752235482678e-6 / height, + 1.6934571328972848e-6 / height, + height, + ); + let mut segments = Segments::default(); + segments.add_bez_path(&a).unwrap(); + let curve_b = SegIdx(segments.len()); + segments.add_bez_path(&b).unwrap(); + let (tolerance, accuracy) = (1e-6, 5e-7); + + let full = full_comparison(&segments, SegIdx(0), curve_b, accuracy, tolerance); + assert!(intervals(&full).iter().any(|entry| entry.2 == Order::Ish)); + + let mut cmp = ComparisonCache::new(tolerance, accuracy); + assert_eq!( + intervals(cmp.compare_segments(&segments, SegIdx(0), curve_b)), + vec![(0.0, height, Order::Left)] + ); + } + + #[test] + fn far_apart_order() { + let mut segments = Segments::default(); + segments.add_points([(0.0, 0.0), (1.0, 2.0)]); + segments.add_points([(2.0, 1.0), (3.0, 3.0)]); + segments.add_points([(1.5, 2.0), (1.5, 4.0)]); + segments.add_points([(9.0, 3.0), (9.0, 4.0)]); + let (a, b, c, d) = ( + &segments[SegIdx(0)], + &segments[SegIdx(1)], + &segments[SegIdx(2)], + &segments[SegIdx(3)], + ); + let intervals = + |o: Option| o.map(|o| o.iter().collect::>()); + + // The horizontal gap between `a` and `b` is 1. + assert_eq!( + intervals(order_if_far_apart(a, b, 0.8)), + Some(vec![(1.0, 2.0, Order::Left)]) + ); + assert_eq!( + intervals(order_if_far_apart(b, a, 0.8)), + Some(vec![(1.0, 2.0, Order::Right)]) + ); + assert_eq!(intervals(order_if_far_apart(a, b, 1.0)), None); + + // `a` and `c` meet only at the height 2. + assert_eq!( + intervals(order_if_far_apart(a, c, 0.4)), + Some(vec![(2.0, 2.0, Order::Left)]) + ); + + // `a` and `d` have no height in common. + assert_eq!(intervals(order_if_far_apart(a, d, 0.4)), None); + } #[test] fn slop_regression() { diff --git a/vendor/linesweeper/src/sweep/sweep_line.rs b/vendor/linesweeper/src/sweep/sweep_line.rs index b4b1883e29..047df5d645 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -12,7 +12,7 @@ use crate::{ geom::Segment, num::CheapOrderedFloat, order::ComparisonCache, - segments::{SegIdx, Segments}, + segments::{SegIdx, SegVec, Segments}, treevec::TreeVec, }; @@ -142,6 +142,10 @@ pub(crate) struct SegmentOrderEntry { /// /// If this is `Some`, both `enter` and `exit` will be true. old_seg: Option, + // Craft patch (sweep position). + /// Keys strictly increase along the sweep line. See [`SegmentOrder::keys`]. + #[cfg_attr(test, serde(skip))] + key: u64, } impl std::fmt::Debug for SegmentOrderEntry { @@ -168,6 +172,7 @@ impl SegmentOrderEntry { in_changed_interval: false, old_idx: None, old_seg: None, + key: 0, } } @@ -202,6 +207,15 @@ impl SegmentOrderEntry { #[derive(Clone, Default)] pub(crate) struct SegmentOrder { pub(crate) segs: TreeVec, + // Craft patch (sweep position). + /// For each segment, the key of the entry that last held it, or zero if no + /// entry has held it. Entries are sorted by key, so this finds a segment on + /// a wide sweep line by binary search. + /// + /// Removing an entry leaves its keys here, and `position` ignores any key + /// whose entry no longer holds the segment. + #[cfg_attr(test, serde(skip))] + keys: SegVec, } impl std::fmt::Debug for SegmentOrder { @@ -211,6 +225,14 @@ impl std::fmt::Debug for SegmentOrder { } impl SegmentOrder { + // Craft patch (sweep position). + fn new(num_segments: usize) -> Self { + Self { + segs: TreeVec::new(), + keys: SegVec::with_size(num_segments), + } + } + fn seg(&self, i: usize) -> SegIdx { self.segs[i].seg } @@ -367,7 +389,7 @@ impl<'segs> Sweeper<'segs> { let events = EventQueue::default(); Sweeper { eps, - line: SegmentOrder::default(), + line: SegmentOrder::new(segments.len()), correctness, y: events.next_y(segments).unwrap_or(f64::INFINITY), events, @@ -600,7 +622,7 @@ impl<'segs> Sweeper<'segs> { } fn insert(&mut self, pos: usize, seg: SegmentOrderEntry) { - self.line.segs.insert(pos, seg); + self.line.insert(pos, seg); self.intersection_scan_right(pos, WhichTouch::Mid); self.intersection_scan_left(pos, WhichTouch::Mid); } @@ -711,6 +733,8 @@ impl<'segs> Sweeper<'segs> { let x1 = seg.max_x(); self.line.segs[pos].old_seg = Some(self.line.segs[pos].seg); self.line.segs[pos].seg = seg_idx; + // Craft patch (sweep position). + self.line.keys[seg_idx] = self.line.segs[pos].key; self.line.segs[pos].enter = true; self.line.segs[pos].exit = true; self.line.segs[pos].lower_bound = x0.min(x1) - self.eps; @@ -813,7 +837,7 @@ impl<'segs> Sweeper<'segs> { // larger `y` than our current `y` (if not, it would // violate the cyclic order property). let which = WhichTouch::Late; - self.line.segs.insert(insertion_pos, seg); + self.line.insert(insertion_pos, seg); self.intersection_scan_right(insertion_pos, which); self.intersection_scan_left(insertion_pos, which); } @@ -1348,10 +1372,112 @@ impl SegmentOrder { // // Returns an index pointing to a `SegmentOrderEntry` for which // `seg_idx` is either the `seg` or the `old_seg`. + // + // Craft patch (sweep position): a binary search over the keys replaces + // the package's linear scan. fn position(&self, seg_idx: SegIdx) -> Option { - self.segs - .iter() - .position(|x| x.seg == seg_idx || x.old_seg == Some(seg_idx)) + let key = self.keys[seg_idx]; + let pos = self.segs.partition_point(|entry| entry.key < key); + let ret = self + .segs + .get(pos) + .is_some_and(|x| x.seg == seg_idx || x.old_seg == Some(seg_idx)) + .then_some(pos); + + #[cfg(any(test, feature = "slow-asserts"))] + assert_eq!( + ret, + self.segs + .iter() + .position(|x| x.seg == seg_idx || x.old_seg == Some(seg_idx)) + ); + + ret + } + + // Craft patch (sweep position): inserts an entry at the given index, + // assigning it a key that keeps the keys sorted. + fn insert(&mut self, pos: usize, mut entry: SegmentOrderEntry) { + let (mut before, mut after) = self.neighbor_keys(pos); + if after - before < 2 { + self.spread_keys(pos); + (before, after) = self.neighbor_keys(pos); + } + entry.key = before + (after - before) / 2; + self.keys[entry.seg] = entry.key; + if let Some(old_seg) = entry.old_seg { + self.keys[old_seg] = entry.key; + } + self.segs.insert(pos, entry); + } + + // Craft patch (sweep position): the keys of the entries on either side of + // the given index, or zero and `u64::MAX` at the ends of the sweep line. No entry has either of those + // keys, so there is always a key to give an entry inserted at either end. + fn neighbor_keys(&self, pos: usize) -> (u64, u64) { + let before = pos.checked_sub(1).map_or(0, |i| self.segs[i].key); + let after = self.segs.get(pos).map_or(u64::MAX, |entry| entry.key); + (before, after) + } + + // Craft patch (sweep position): makes space for inserting an entry at the + // given index, by evenly spacing the keys around it. + // + // This follows the tag-range relabeling of Bender et al., "Two Simplified + // Algorithms for Maintaining Order in a List" (ESA 2002): take the smallest + // aligned power-of-two range of keys around the index that is sparse enough, + // and spread out the keys inside it. The amortized number of keys changed by + // an insertion is logarithmic in the length of the sweep line. + fn spread_keys(&mut self, pos: usize) { + // How quickly the allowed density falls as the range grows. Each doubling + // of the range allows `2.0 / OVERFLOW` times as many entries, so a range + // of `2^bits` keys holds up to `(2.0 / OVERFLOW)^bits` of them. + const OVERFLOW: f64 = 1.4; + + let len = self.segs.len(); + let center = self.segs[pos.min(len - 1)].key; + let mut start = pos; + let mut end = pos; + let mut max_entries = 1.0; + for bits in 1..u64::BITS { + let range_len = 1u64 << bits; + let first = center & !(range_len - 1); + let last = first + (range_len - 1); + while start > 0 && self.segs[start - 1].key >= first { + start -= 1; + } + while end < len && self.segs[end].key <= last { + end += 1; + } + + max_entries *= 2.0 / OVERFLOW; + let count = (end - start) as u64; + let step = range_len / (count + 1); + // A step of 3 leaves a gap of at least 2 after the last key, even if + // the range ends at `u64::MAX`. + if count as f64 <= max_entries && step >= 3 { + self.assign_keys(start..end, first, step); + return; + } + } + + // Even the largest range is too dense for its limit, which takes about + // 6 * 10^9 entries. The whole key space still has room for all of them. + self.assign_keys(0..len, 0, u64::MAX / (len as u64 + 1)); + } + + // Craft patch (sweep position): gives the entries in a range of indices the + // keys `first + step`, `first + 2 * step`, and so on. + fn assign_keys(&mut self, range: std::ops::Range, first: u64, step: u64) { + let mut key = first; + for entry in self.segs.range_mut(range) { + key += step; + entry.key = key; + self.keys[entry.seg] = key; + if let Some(old_seg) = entry.old_seg { + self.keys[old_seg] = key; + } + } } } @@ -1588,6 +1714,7 @@ impl<'segs> SweepLine<'_, '_, 'segs> { in_changed_interval: false, old_idx: None, old_seg: None, + key: 0, }; let buffers = &mut self.bufs; @@ -1831,6 +1958,7 @@ mod tests { segs: (0..xs.len()) .map(|i| SegmentOrderEntry::new(SegIdx(i), &segs, eps)) .collect(), + ..Default::default() }; let mut cmp = ComparisonCache::new(eps, eps / 2.0); @@ -1883,6 +2011,7 @@ mod tests { segs: (0..(xs.len() - 1)) .map(|i| SegmentOrderEntry::new(SegIdx(i), &segs, eps)) .collect(), + ..Default::default() }; let mut comparer = ComparisonCache::new(eps, eps / 2.0); let idx = line.insertion_idx(y, &segs, new_idx, &mut comparer); @@ -1949,6 +2078,167 @@ mod tests { }); } + fn check_positions(line: &SegmentOrder, num_segs: usize) { + let keys: Vec<_> = line.segs.iter().map(|entry| entry.key).collect(); + assert!(keys.is_sorted_by(|a, b| a < b)); + assert!(keys.iter().all(|key| 0 < *key && *key < u64::MAX)); + + // `position` compares its answer with a linear scan. + for seg in (0..num_segs).map(SegIdx) { + line.position(seg); + } + } + + #[derive(Clone, Debug)] + enum LineEdit { + Insert(prop::sample::Index), + InsertRepeatedly(prop::sample::Index, usize), + Remove(prop::sample::Index), + Move(prop::sample::Index, prop::sample::Index), + ContinueContour(prop::sample::Index), + } + + fn line_edit() -> impl Strategy { + let idx = any::; + prop_oneof![ + idx().prop_map(LineEdit::Insert), + (idx(), 0usize..100).prop_map(|(at, n)| LineEdit::InsertRepeatedly(at, n)), + idx().prop_map(LineEdit::Remove), + (idx(), idx()).prop_map(|(from, to)| LineEdit::Move(from, to)), + idx().prop_map(LineEdit::ContinueContour), + ] + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(64))] + + // Applies the same kinds of edits as `Sweeper`, in any order. + #[test] + fn position_after_edits(edits in prop::collection::vec(line_edit(), 0..20)) { + let num_segs = 2000; + let segs = mk_segs(&vec![(0.0, 0.0); num_segs]); + let eps = 0.01; + + let mut line = SegmentOrder::new(num_segs); + let mut next_seg = 0; + let mut new_entry = || { + next_seg += 1; + SegmentOrderEntry::new(SegIdx(next_seg - 1), &segs, eps) + }; + for edit in edits { + let len = line.segs.len(); + match edit { + LineEdit::Insert(at) => line.insert(at.index(len + 1), new_entry()), + LineEdit::InsertRepeatedly(at, n) => { + let at = at.index(len + 1); + for _ in 0..n { + line.insert(at, new_entry()); + } + } + LineEdit::Remove(at) if len > 0 => { + line.segs.remove(at.index(len)); + } + LineEdit::Move(from, to) if len > 0 => { + let entry = line.segs.remove(from.index(len)); + line.insert(to.index(len), entry); + } + LineEdit::ContinueContour(at) if len > 0 => { + let pos = at.index(len); + let new_seg = new_entry().seg; + line.segs[pos].old_seg = Some(line.segs[pos].seg); + line.segs[pos].seg = new_seg; + line.keys[new_seg] = line.segs[pos].key; + } + _ => {} + } + check_positions(&line, 10); + } + check_positions(&line, next_seg); + } + } + + #[test] + fn position_after_repeated_insertion() { + let num_segs = 2000; + let segs = mk_segs(&vec![(0.0, 0.0); num_segs]); + let eps = 0.01; + let entry = |i| SegmentOrderEntry::new(SegIdx(i), &segs, eps); + + for insertion_pos in [ + // Always at the start of the line. + |_| 0, + // Always at the end of the line. + |i| i, + // Always in the same gap in the middle of the line. + |i: usize| i.min(1), + // Alternating on both sides of the most recent entry. + |i: usize| i.div_ceil(2), + ] { + let mut line = SegmentOrder::new(num_segs); + for i in 0..num_segs { + line.insert(insertion_pos(i), entry(i)); + } + check_positions(&line, num_segs); + } + } + + #[test] + fn position_after_insertion_next_to_the_extreme_keys() { + let segs = mk_segs(&[(0.0, 0.0); 2]); + let eps = 0.01; + for (key, pos) in [(u64::MAX - 1, 1), (1, 0)] { + let mut line = SegmentOrder::new(2); + line.insert(0, SegmentOrderEntry::new(SegIdx(0), &segs, eps)); + line.segs[0].key = key; + line.keys[SegIdx(0)] = key; + + line.insert(pos, SegmentOrderEntry::new(SegIdx(1), &segs, eps)); + check_positions(&line, 2); + } + } + + #[test] + fn position_after_moving_a_contour_continuation() { + let segs = mk_segs(&[(0.0, 0.0); 3]); + let eps = 0.01; + let mut line = SegmentOrder::new(3); + line.insert(0, SegmentOrderEntry::new(SegIdx(0), &segs, eps)); + line.insert(1, SegmentOrderEntry::new(SegIdx(1), &segs, eps)); + + line.segs[0].old_seg = Some(SegIdx(0)); + line.segs[0].seg = SegIdx(2); + line.keys[SegIdx(2)] = line.segs[0].key; + + let entry = line.segs.remove(0); + line.insert(1, entry); + assert_eq!(line.position(SegIdx(0)), Some(1)); + assert_eq!(line.position(SegIdx(2)), Some(1)); + } + + #[test] + fn position_on_a_wide_sweep_line() { + // Two overlapping sawtooths. About 160 of their segments are on the sweep + // line at one height, more than fit in a `TreeVec` node, and each kink, + // exit and crossing looks up a position. + let mut path = BezPath::new(); + for offset in [0.0, 0.25] { + path.move_to((offset, 0.0)); + for i in 0..40 { + let i_f = i as f64; + let height = 10.0 + (i_f * 0.618).fract(); + path.line_to((offset + i_f + 0.3, 5.0 + (i_f * 0.5).fract())); + path.line_to((offset + i_f + 0.5, height)); + path.line_to((offset + i_f + 0.8, 5.0 + (i_f * 0.25).fract())); + path.line_to((offset + i_f + 1.0, (i_f * 0.755).fract())); + } + path.close_path(); + } + + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + crate::sweep::sweep(&segs, 1e-6, |_, _| {}); + } + fn p(x: f64, y: f64) -> Point { Point::new(x, y) }