mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 02:36:54 +01:00
Merge #720 (fix/linesweeper-comparison-cache-unbounded) into integration/linesweeper
This commit is contained in:
commit
eba2cf9de4
7 files changed
+314
-14
No files matched your search
@@ -325,6 +325,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
|
||||
|
||||
Vendored
+5
@@ -263,6 +263,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
|
||||
@@ -339,6 +343,7 @@ Every change here updates this table and `SOURCE.json` in the same commit.
|
||||
| `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. |
|
||||
| `src/order.rs`, `src/sweep/sweep_line.rs`, `src/position.rs` | `ComparisonCache` stores one `CurveOrder` per pair of segments instead of one for each direction, and flips it when the pair is looked up in the other order. `ComparisonCache::evict_ended` drops the pairs in which a segment ends above a given height, once the cache has doubled since its last scan. `Sweeper` calls it on both of its caches each time the sweep line moves down, and `compute_positions` calls it each time it takes the next height from its queue. Both caches used to keep every pair the sweep compared until the sweep ended, so a sweep of a 2,001-point star polygon held 4,001,998 cached orders (1,463 MiB). Code comments label the changes `Craft patch (comparison cache size)`. The `one_order_per_pair` and `reversed_lookup_flips_the_stored_order` tests check the stored and flipped orders, `ended_pairs_leave_the_comparison_cache` checks that a sweep of a tall band keeps fewer than a tenth of the pairs, and `evicting_comparisons_keeps_the_sweep_lines` and `evicting_comparisons_keeps_the_correct_positions` check that the sweep lines, output events and positions do not change. |
|
||||
|
||||
`omitted_files` lists the 43 files of the package left out here, with their hashes:
|
||||
|
||||
|
||||
Vendored
+6
@@ -69,6 +69,7 @@
|
||||
"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."
|
||||
"In `src/order.rs`, `ComparisonCache` stores one `CurveOrder` per pair of segments and flips it for a lookup in the other order, and `ComparisonCache::evict_ended` drops the pairs in which a segment ends above a given height once the cache has doubled since its last scan; `Sweeper::advance` in `src/sweep/sweep_line.rs` and `compute_positions` in `src/position.rs` call it, so the comparison caches no longer keep every compared pair until the sweep ends."
|
||||
],
|
||||
"files": [
|
||||
{ "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" },
|
||||
@@ -159,6 +160,9 @@
|
||||
{ "path": "src/perturbation.rs", "source_sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5", "source_git_blob": null, "sha256": "86c27289a9e447a7a1022d3a5c35cf85490555a8904f28bc90a479dcbd49d4ca" },
|
||||
{ "path": "src/position.rs", "source_sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0", "source_git_blob": null, "sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0" },
|
||||
{ "path": "src/position.rs", "source_sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0", "source_git_blob": null, "sha256": "37686f512c4f4ded9fcbd19e8a736f1462ad2e883a65d88d32a7c441d512dc30" },
|
||||
{ "path": "src/order.rs", "source_sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596", "source_git_blob": null, "sha256": "11253aa656c5d2af3067b9a55f0e8f56e5107dd6befa9eeccc5d109123957fb9" },
|
||||
{ "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": "6a436972dfbf73f2fae8eeebf3d8a9d217c8980339b05a1d7e3fb74a5c8c1571" },
|
||||
{ "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc" },
|
||||
{ "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "33997b8afe11f5b3d1846b69db4533af7242121176ba7dff3b7525799a4e17e1" },
|
||||
{ "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "74478b647c0243a18bf0e34af28735544754b42445910cd4145aa1c31826d24d" },
|
||||
@@ -219,6 +223,8 @@
|
||||
{ "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "c520c286f7bb896546beb312ec114f7f8019a5af0094c1ab149fa36dc36f96b8" },
|
||||
{ "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "8e901d5cb80f2b920db1c5be85fdd31d6a31ca4b71191aea930a17a90ede1a35" },
|
||||
{ "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "701a53d627f3ef2ccde552fb1d35fb445ef51dba356fcce0e9f9f091bf71f66f" },
|
||||
{ "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "d99a5da5d623de525ef38aeb420c7e5a230c9a4306642b85fb6b93203ff6ba88" },
|
||||
{ "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "edba8f797d8d35026d9ff70de85f0ce151191af341234cbff91927064fce4985" },
|
||||
{ "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" },
|
||||
{ "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "5dfbff54f25438ddb800f4136af5c7ef1d6d2a3a626ea5311dacefd884c5c9e8" },
|
||||
{ "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" },
|
||||
|
||||
Vendored
+121
-13
@@ -14,7 +14,14 @@ use crate::{
|
||||
/// starts again with that arena.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ComparisonCache {
|
||||
inner: FxHashMap<(SegIdx, SegIdx), (CurveOrder, CurveOrder)>,
|
||||
// Craft patch (comparison cache size): each pair stores the order of its
|
||||
// lower-indexed segment relative to the other. A lookup in the other
|
||||
// direction flips it into `flipped`.
|
||||
inner: FxHashMap<(SegIdx, SegIdx), CurveOrder>,
|
||||
flipped: Option<CurveOrder>,
|
||||
// Craft patch (comparison cache size): `evict_ended` scans the cache once
|
||||
// it holds this many pairs.
|
||||
next_purge: usize,
|
||||
accuracy: f64,
|
||||
tolerance: f64,
|
||||
// Craft patch (work limit): the number of calls to `compare_segments`,
|
||||
@@ -24,6 +31,10 @@ pub struct ComparisonCache {
|
||||
arena: Option<u64>,
|
||||
}
|
||||
|
||||
// Craft patch (comparison cache size): the smallest cache that `evict_ended`
|
||||
// scans. Unit tests use a small value so that the sweep tests evict.
|
||||
const MIN_PURGE: usize = if cfg!(test) { 8 } else { 4096 };
|
||||
|
||||
impl ComparisonCache {
|
||||
/// Creates a new comparison cache.
|
||||
///
|
||||
@@ -36,6 +47,8 @@ impl ComparisonCache {
|
||||
pub fn new(tolerance: f64, accuracy: f64) -> Self {
|
||||
ComparisonCache {
|
||||
inner: FxHashMap::default(),
|
||||
flipped: None,
|
||||
next_purge: MIN_PURGE,
|
||||
accuracy,
|
||||
tolerance,
|
||||
calls: 0,
|
||||
@@ -54,6 +67,8 @@ impl ComparisonCache {
|
||||
pub fn new_without_y_slop(tolerance: f64, accuracy: f64) -> Self {
|
||||
ComparisonCache {
|
||||
inner: FxHashMap::default(),
|
||||
flipped: None,
|
||||
next_purge: MIN_PURGE,
|
||||
accuracy,
|
||||
tolerance,
|
||||
calls: 0,
|
||||
@@ -89,14 +104,8 @@ impl ComparisonCache {
|
||||
(j, i, true)
|
||||
};
|
||||
|
||||
match self.inner.entry((i, j)) {
|
||||
Entry::Occupied(o) => {
|
||||
if flipped {
|
||||
&mut o.into_mut().1
|
||||
} else {
|
||||
&mut o.into_mut().0
|
||||
}
|
||||
}
|
||||
let stored = match self.inner.entry((i, j)) {
|
||||
Entry::Occupied(o) => o.into_mut(),
|
||||
Entry::Vacant(v) => {
|
||||
let segi = &segments[i];
|
||||
let segj = &segments[j];
|
||||
@@ -117,12 +126,43 @@ impl ComparisonCache {
|
||||
forward.iter().last().unwrap().1,
|
||||
segi.end().y.min(segj.end().y)
|
||||
);
|
||||
let reverse = forward.flip();
|
||||
let v = v.insert((forward, reverse));
|
||||
if flipped { &mut v.1 } else { &mut v.0 }
|
||||
v.insert(forward)
|
||||
}
|
||||
};
|
||||
if flipped {
|
||||
self.flipped.insert(stored.flip())
|
||||
} else {
|
||||
stored
|
||||
}
|
||||
}
|
||||
|
||||
// Craft patch (comparison cache size): removes the pairs in which a
|
||||
// segment ends above `y`. Callers pass heights that never decrease, so
|
||||
// such a pair is not compared again; if it were, the comparison would be
|
||||
// computed again with the same result. The cache is scanned only after it
|
||||
// has doubled since the last scan, so the scans take time proportional to
|
||||
// the number of comparisons.
|
||||
pub(crate) fn evict_ended(&mut self, segments: &Segments, y: f64) {
|
||||
if self.inner.len() < self.next_purge {
|
||||
return;
|
||||
}
|
||||
self.inner
|
||||
.retain(|(i, j), _| segments[*i].end().y >= y && segments[*j].end().y >= y);
|
||||
if self.inner.len() * 4 < self.inner.capacity() {
|
||||
self.inner.shrink_to_fit();
|
||||
}
|
||||
self.next_purge = self.inner.len().saturating_mul(2).max(MIN_PURGE);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cached_pairs(&self) -> usize {
|
||||
self.inner.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn never_evict(&mut self) {
|
||||
self.next_purge = usize::MAX;
|
||||
}
|
||||
}
|
||||
|
||||
// Craft patch (far-apart comparison): compares two segments, at least one of
|
||||
@@ -203,7 +243,10 @@ mod tests {
|
||||
use kurbo::BezPath;
|
||||
use proptest::prelude::*;
|
||||
|
||||
use crate::{SegIdx, Segments, curve::Order};
|
||||
use crate::{
|
||||
SegIdx, Segments,
|
||||
curve::{CurveOrder, Order},
|
||||
};
|
||||
|
||||
use super::{ComparisonCache, far_apart_margin, full_comparison, order_if_far_apart};
|
||||
|
||||
@@ -519,4 +562,69 @@ mod tests {
|
||||
cmp_cache.compare_segments(&segments, SegIdx(1), SegIdx(2));
|
||||
assert_eq!(cmp_cache.inner.len(), 2);
|
||||
}
|
||||
|
||||
// Two cubics that cross each other twice, and a vertical line that
|
||||
// crosses both.
|
||||
fn crossing_segments() -> Segments {
|
||||
let mut segments = Segments::default();
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.curve_to((3.0, 1.0), (-3.0, 2.0), (0.0, 3.0));
|
||||
segments.add_non_closed_bez_path(&path).unwrap();
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.5, 0.0));
|
||||
path.curve_to((-2.5, 1.0), (3.5, 2.0), (0.5, 3.0));
|
||||
segments.add_non_closed_bez_path(&path).unwrap();
|
||||
segments.add_points([(0.2, -0.5), (0.3, 3.5)]);
|
||||
segments
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_order_per_pair() {
|
||||
let segments = crossing_segments();
|
||||
let mut cmp_cache = ComparisonCache::new(0.1, 0.05);
|
||||
for i in segments.indices() {
|
||||
for j in segments.indices() {
|
||||
if i != j {
|
||||
cmp_cache.compare_segments(&segments, i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
let n = segments.len();
|
||||
assert_eq!(cmp_cache.inner.len(), n * (n - 1) / 2);
|
||||
for stored in cmp_cache.inner.values() {
|
||||
assert_eq!(
|
||||
std::mem::size_of_val(stored),
|
||||
std::mem::size_of::<CurveOrder>()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reversed_lookup_flips_the_stored_order() {
|
||||
let segments = crossing_segments();
|
||||
let mut forward_first = ComparisonCache::new(0.1, 0.05);
|
||||
let mut reverse_first = ComparisonCache::new(0.1, 0.05);
|
||||
let entries = |order: &CurveOrder| order.iter().collect::<Vec<_>>();
|
||||
for i in segments.indices() {
|
||||
for j in segments.indices() {
|
||||
if i.0 >= j.0 {
|
||||
continue;
|
||||
}
|
||||
let reverse_before = entries(reverse_first.compare_segments(&segments, j, i));
|
||||
let forward = forward_first.compare_segments(&segments, i, j).clone();
|
||||
let reverse_after = forward_first.compare_segments(&segments, j, i).clone();
|
||||
let forward_again = entries(forward_first.compare_segments(&segments, i, j));
|
||||
let flipped: Vec<_> = entries(&forward)
|
||||
.into_iter()
|
||||
.map(|(y0, y1, order)| (y0, y1, order.flip()))
|
||||
.collect();
|
||||
|
||||
assert_eq!(entries(&reverse_after), flipped);
|
||||
assert_eq!(reverse_before, flipped);
|
||||
assert_eq!(forward_again, entries(&forward));
|
||||
assert_eq!(reverse_after.metrics, forward.metrics);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+4
@@ -398,6 +398,10 @@ pub(crate) fn compute_positions(
|
||||
if last_y[entry.idx] > y0 {
|
||||
continue;
|
||||
}
|
||||
// Craft patch (comparison cache size): the heights popped from the
|
||||
// queue never decrease, and every neighbor compared from here on
|
||||
// extends below `y0`.
|
||||
cmp.evict_ended(segs, y0);
|
||||
|
||||
let mut y1 = endpoints[entry.idx.second_half()].y;
|
||||
let mut west_scan = vec![entry.idx];
|
||||
|
||||
+108
@@ -646,6 +646,12 @@ impl<'segs> Sweeper<'segs> {
|
||||
self.line.segs.remove(idx);
|
||||
}
|
||||
self.y = y;
|
||||
// Craft patch (comparison cache size): the sweep line holds no
|
||||
// segment that ends above `y`, so their cached pairs are dropped.
|
||||
self.comparisons.get_mut().evict_ended(self.segments, y);
|
||||
self.conservative_comparisons
|
||||
.get_mut()
|
||||
.evict_ended(self.segments, y);
|
||||
self.segs_needing_positions.clear();
|
||||
self.horizontals.clear();
|
||||
self.touch_scans.clear();
|
||||
@@ -3080,6 +3086,108 @@ mod tests {
|
||||
assert!(work <= limit + 2, "{work} units of work");
|
||||
}
|
||||
|
||||
// A tall closed band whose sides zigzag: each segment shares heights with
|
||||
// only a few others.
|
||||
fn zigzag_band(rows: usize) -> Segments {
|
||||
let left = (0..=rows).map(|k| p((k % 2) as f64, k as f64));
|
||||
let right = (0..=rows).rev().map(|k| p(10.0 + (k % 2) as f64, k as f64));
|
||||
let mut segs = Segments::default();
|
||||
segs.add_closed_polyline(left.chain(right));
|
||||
segs
|
||||
}
|
||||
|
||||
// A star polygon in which every edge crosses every edge it does not share a
|
||||
// vertex with.
|
||||
fn star(points: usize) -> Segments {
|
||||
let step = (points - 1) / 2;
|
||||
let mut segs = Segments::default();
|
||||
segs.add_closed_polyline((0..points).map(|k| {
|
||||
let angle = std::f64::consts::TAU * ((k * step) % points) as f64 / points as f64 + 0.1;
|
||||
p(1000.0 * angle.cos(), 1000.0 * angle.sin())
|
||||
}));
|
||||
segs
|
||||
}
|
||||
|
||||
// Two wavy closed paths of cubics that cross each other many times.
|
||||
fn wavy_cubics() -> Segments {
|
||||
let mut segs = Segments::default();
|
||||
for offset in [0.0, 0.7] {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((offset, 0.0));
|
||||
for k in 0..40 {
|
||||
let y = 4.0 * k as f64;
|
||||
let x = offset + (k % 3) as f64 * 0.5;
|
||||
path.curve_to(
|
||||
(offset + 3.0, y + 1.0),
|
||||
(offset - 3.0, y + 3.0),
|
||||
(x, y + 4.0),
|
||||
);
|
||||
}
|
||||
path.line_to((offset + 5.0, 160.0));
|
||||
path.line_to((offset + 5.0, 0.0));
|
||||
path.close_path();
|
||||
segs.add_bez_path(&path).unwrap();
|
||||
}
|
||||
segs
|
||||
}
|
||||
|
||||
// Runs a sweep and records every sweep line, its changed intervals and its
|
||||
// output events. Also returns the largest number of pairs the comparison
|
||||
// caches held after a step.
|
||||
fn sweep_record(segs: &Segments, eps: f64, evict: bool) -> (Vec<String>, usize) {
|
||||
let mut record = Vec::new();
|
||||
let mut most_pairs = 0;
|
||||
let mut sweeper = Sweeper::new(segs, eps);
|
||||
if !evict {
|
||||
sweeper.comparisons.get_mut().never_evict();
|
||||
sweeper.conservative_comparisons.get_mut().never_evict();
|
||||
}
|
||||
let mut line_bufs = SweepLineBuffers::default();
|
||||
let mut range_bufs = crate::sweep::SweepLineRangeBuffers::default();
|
||||
while let Some(mut line) = sweeper.next_line(&mut line_bufs) {
|
||||
record.push(format!(
|
||||
"{} {:?} {:?}",
|
||||
line.y(),
|
||||
line.state.line,
|
||||
line.state.changed_intervals
|
||||
));
|
||||
while let Some(mut range) = line.next_range(&mut range_bufs, segs) {
|
||||
while let Some(events) = range.events() {
|
||||
record.extend(events.into_iter().map(|ev| format!("{ev:?}")));
|
||||
}
|
||||
}
|
||||
most_pairs = most_pairs.max(
|
||||
line.state.comparisons.borrow().cached_pairs()
|
||||
+ line.state.conservative_comparisons.borrow().cached_pairs(),
|
||||
);
|
||||
}
|
||||
(record, most_pairs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ended_pairs_leave_the_comparison_cache() {
|
||||
let segs = zigzag_band(400);
|
||||
let (_, kept) = sweep_record(&segs, 0.1, false);
|
||||
let (_, evicted) = sweep_record(&segs, 0.1, true);
|
||||
assert!(kept >= 400, "{kept}");
|
||||
assert!(evicted * 10 < kept, "{evicted} {kept}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evicting_comparisons_keeps_the_sweep_lines() {
|
||||
for (segs, eps) in [
|
||||
(zigzag_band(400), 0.1),
|
||||
(star(31), 1e-6),
|
||||
(star(31), 1.0),
|
||||
(wavy_cubics(), 0.01),
|
||||
(wavy_cubics(), 0.25),
|
||||
] {
|
||||
let (kept, _) = sweep_record(&segs, eps, false);
|
||||
let (evicted, _) = sweep_record(&segs, eps, true);
|
||||
assert!(kept == evicted);
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn perturbation_test_f64(perturbations in prop::collection::vec(perturbation(f64_perturbation(0.1)), 1..5)) {
|
||||
|
||||
Vendored
+67
-1
@@ -2615,7 +2615,7 @@ mod tests {
|
||||
},
|
||||
};
|
||||
|
||||
use super::{Affine, Contour, ContourIdx, Contours, OneOfTwo, Topology};
|
||||
use super::{Affine, Contour, ContourIdx, Contours, Correctness, HalfOutputSegVec, OneOfTwo, Topology};
|
||||
|
||||
fn p(x: f64, y: f64) -> Point {
|
||||
Point::new(x, y)
|
||||
@@ -3524,6 +3524,72 @@ mod tests {
|
||||
//check_intersections(&top);
|
||||
}
|
||||
|
||||
// A column of shapes, each made of two closed paths whose wavy cubic sides
|
||||
// cross each other twice.
|
||||
fn wavy_column(rows: usize) -> BezPath {
|
||||
let mut path = BezPath::new();
|
||||
for k in 0..rows {
|
||||
let y = 10.0 * k as f64;
|
||||
for offset in [0.0, 0.7] {
|
||||
path.move_to((offset, y));
|
||||
path.curve_to(
|
||||
(offset + 3.0, y + 2.0),
|
||||
(offset - 3.0, y + 6.0),
|
||||
(offset, y + 8.0),
|
||||
);
|
||||
path.line_to((offset + 2.0, y + 8.0));
|
||||
path.line_to((offset + 2.0, y));
|
||||
path.close_path();
|
||||
}
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
// The positions that `compute_positions_correct` computes, with a cache
|
||||
// that drops ended pairs or one that keeps every pair.
|
||||
fn correct_positions(top: &Topology<i32>, evict: bool) -> (String, usize) {
|
||||
let mut cmp = ComparisonCache::new(top.eps, top.eps / 2.0);
|
||||
if !evict {
|
||||
cmp.never_evict();
|
||||
}
|
||||
let mut endpoints = HalfOutputSegVec::with_size(top.orig_seg.len());
|
||||
for idx in top.orig_seg.indices() {
|
||||
endpoints[idx.first_half()] = top.points[top.point_idx[idx.first_half()]].to_kurbo();
|
||||
endpoints[idx.second_half()] = top.points[top.point_idx[idx.second_half()]].to_kurbo();
|
||||
}
|
||||
let out = crate::position::compute_positions(
|
||||
&top.segments,
|
||||
&top.orig_seg,
|
||||
&mut cmp,
|
||||
&endpoints,
|
||||
&top.build_scan_line_orders(),
|
||||
top.eps / 4.0,
|
||||
);
|
||||
(format!("{out:?}"), cmp.cached_pairs())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evicting_comparisons_keeps_the_correct_positions() {
|
||||
let path = wavy_column(200);
|
||||
for eps in [0.01, 0.25] {
|
||||
let top = Topology::<i32>::from_paths_with_correctness(
|
||||
[(&path, ())],
|
||||
eps,
|
||||
Correctness::ReallyCorrect,
|
||||
)
|
||||
.unwrap();
|
||||
let (kept, kept_pairs) = correct_positions(&top, false);
|
||||
let (evicted, evicted_pairs) = correct_positions(&top, true);
|
||||
assert!(kept == evicted);
|
||||
assert_eq!(format!("{:?}", top.compute_positions()), evicted);
|
||||
assert!(kept_pairs >= 400, "{kept_pairs}");
|
||||
assert!(
|
||||
evicted_pairs * 10 < kept_pairs,
|
||||
"{evicted_pairs} {kept_pairs}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn perturbation_test_f64(perturbations in prop::collection::vec(perturbation(f64_perturbation(0.1)), 1..5)) {
|
||||
|
||||
Reference in new issue
Block a user