Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 115 additions & 18 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2312,10 +2312,11 @@ impl MaskCache {
}

/// [`clip`] on `threads` threads (by the number of items in each step, and the memory each
/// takes, when `None`): the masks are unioned, and each input feature clipped, on their own
/// takes, when `None`): the masks are made ready ([`keeps_its_edges`], or a union), and each input
/// feature clipped, on their own
/// (#1252), in batches of [`CLIP_BATCH`] features a thread, and the rows come back in input
/// order, as on one thread. A thread's work in progress takes about twice the largest mask's
/// coordinates while the masks are unioned, then twice the largest input feature's, a list of
/// coordinates while the masks are made ready, and what checking one takes, then twice the largest input feature's, a list of
/// the masks (or the index's references to them), and the larger of the largest mask and the
/// largest size of the masks one feature meets, together (found for each batch first, standing
/// for their union); as many threads run as fit, at that much work each, in half the scratch
Expand All @@ -2340,21 +2341,22 @@ fn clip_on(inp: &dyn Inputs, p: &Json, threads: Option<usize>, cache_bytes: Opti
rows.iter().filter_map(|&r| ds.features.get(r)?.geometry.as_ref()).map(coord_bytes).max().unwrap_or(0)
};
let largest_mask = largest(clip_ds, &mask_rows);
// Each mask is a union: Cancel is looked at, and progress counted, before each. A thread
// holds a mask's polygons and their union.
// Each mask is checked, and unioned unless it is valid: Cancel is looked at, and progress counted,
// before each. A thread holds a mask's polygons and their union, or what checking one takes.
crate::control::begin(mask_rows.len());
let made = crate::parallel::try_map_on(
&mask_rows,
threads_for(mask_rows.len(), largest_mask.saturating_mul(2)),
threads_for(mask_rows.len(), largest_mask.saturating_mul(2).saturating_add(edges_check_bytes(largest_mask))),
|| (),
|_, _, &r| {
let Some(m) = clip_ds.features.get(r).and_then(|f| f.geometry.as_ref()).and_then(polygon_of) else {
return Ok::<_, String>(ClipMask::NoPolygon);
};
let ext = merc_extent(&m);
// Union even one polygon: collapsed rings have no filled area. Keep the original
// bounds too: rounding an edge must not hide a line the boolean overlay clips to it.
let mask = union_all(m.0.iter());
// A valid mask keeps its edges. Any other is unioned, even one polygon: collapsed rings have no
// filled area. Keep the original bounds too: rounding an edge must not hide a line the boolean
// overlay clips to it.
let mask = if keeps_its_edges(&m) { m.orient(Direction::Default) } else { union_all(m.0.iter()) };
let ext = ext.union(&merc_extent(&mask));
Ok(if mask.0.is_empty() { ClipMask::NoArea } else { ClipMask::Mask(mask, ext) })
},
Expand Down Expand Up @@ -2580,20 +2582,38 @@ fn outside_each(
}

/// An overlay polygon: its row in the overlay layer, its extent and its polygons in the analysis
/// plane, oriented for the overlay, its parts unioned when it has several (as Clip's mask is).
/// plane, oriented for the overlay, its parts unioned when it has several that aren't valid as they are.
struct Zone {
row: usize,
ext: Extent,
poly: MultiPolygon<f64>,
}

/// A feature's polygons as a mask for the overlay: parts of one feature may overlap, which the
/// overlay can't take as they are, so several are unioned; one polygon is only oriented, so its
/// edges stay exactly where they are.
/// Polygons as a mask for the overlay: they may overlap, which the overlay can't take as they are, so
/// several are unioned; one polygon is only oriented, so its edges stay exactly where they are.
fn mask_of(poly: MultiPolygon<f64>) -> MultiPolygon<f64> {
if poly.0.len() > 1 { union_all(poly.0.iter()) } else { poly.orient(Direction::Default) }
}

/// One feature's polygons as a zone: as [`mask_of`] gives them, but for several that are valid together,
/// which keep their edges too ([`keeps_its_edges`]).
fn zone_of(poly: MultiPolygon<f64>) -> MultiPolygon<f64> {
if poly.0.len() > 1 && keeps_its_edges(&poly) { poly.orient(Direction::Default) } else { mask_of(poly) }
}

/// Whether the overlay can take a mask's polygons as they are: valid, and few enough to look at
/// ([`KEEP_WHOLE_COORDS`]). A union would round them to a grid of its own, apart from a neighbour's, and
/// leave a gap along an edge they share.
fn keeps_its_edges(m: &MultiPolygon<f64>) -> bool {
m.coords_count() <= KEEP_WHOLE_COORDS && crate::validity::check(Some(&in_plane(m)), crate::validity::MAX_WORK).problems.is_empty()
}

/// What [`keeps_its_edges`] holds at most while it looks at a feature of `largest` bytes of coordinates:
/// a copy in the plane (16 bytes a coordinate) and the check's state (about 100).
fn edges_check_bytes(largest: usize) -> usize {
largest.min(KEEP_WHOLE_COORDS * std::mem::size_of::<Coord>()).saturating_mul(8)
}

/// How an overlay tool uses its overlay polygons, for [`overlay_zones_on`].
#[derive(Clone, Copy, PartialEq, Eq)]
enum ZoneUse {
Expand Down Expand Up @@ -2639,7 +2659,10 @@ fn overlay_zones_on<'a>(
return Err(format!("'{}' is not a polygon layer", ov.name));
}
let zone_rows = each_once(rows(inp, p, k, ov));
let threads = geometry_threads(zone_rows.len(), threads, || Ok(largest_geometry_bytes(ov, &zone_rows)?.saturating_mul(2)))?;
let threads = geometry_threads(zone_rows.len(), threads, || {
let largest = largest_geometry_bytes(ov, &zone_rows)?;
Ok(largest.saturating_mul(2).saturating_add(edges_check_bytes(largest)))
})?;
let made = crate::parallel::try_map_on(
&zone_rows,
threads,
Expand All @@ -2648,7 +2671,7 @@ fn overlay_zones_on<'a>(
let Some((g, poly)) = ov.features.get(row).and_then(|f| f.geometry.as_ref()).and_then(|g| Some((g, polygon_of(g)?))) else {
return Ok::<_, String>(ZoneMade::NoPolygon);
};
let poly = mask_of(poly);
let poly = zone_of(poly);
if poly.0.is_empty() && use_ != ZoneUse::AsIs {
return Ok(ZoneMade::NoArea);
}
Expand Down Expand Up @@ -14500,12 +14523,16 @@ mod tests {
.filter_map(|r| masks.features[*r].geometry.as_ref().and_then(to_multipolygon))
.collect();
let whole = union_all(polys.iter().flat_map(|m| m.0.iter()));
let as_they_are = MultiPolygon::new(polys.iter().flat_map(|m| m.0.clone()).collect());
let features = &inp.0.0["features"];
let expected: Vec<_> = rows(&inp, &p, "input", features)
.into_iter()
.filter_map(|r| {
let f = &features.features[r];
let g = part(&dissolved(f.geometry.as_ref()?), &whole, true)?;
let g = f.geometry.as_ref()?;
// A point on a mask's edge is in it, where the union's grid can move the edge off it.
let mask = if matches!(g, Geometry::Point(_) | Geometry::MultiPoint(_)) { &as_they_are } else { &whole };
let g = part(&dissolved(g), mask, true)?;
Some((f.attrs.clone(), g))
})
.collect();
Expand Down Expand Up @@ -14808,7 +14835,7 @@ mod tests {
for y in [-1e-12, -0.01] {
lines.push(Some(Geometry::Line(vec![vec![Coord::new(0.1, y), Coord::new(0.9, y)]])), vec![]);
}
let whole = union_all(to_multipolygon(masks.features[0].geometry.as_ref().unwrap()).unwrap().0.iter());
let whole = to_multipolygon(masks.features[0].geometry.as_ref().unwrap()).unwrap();
let expected: Vec<_> = lines.features.iter().filter_map(|f| part(f.geometry.as_ref().unwrap(), &whole, true)).collect();
// The integer overlay snaps the near line onto the edge, but leaves the far line out.
assert_eq!(expected.len(), 1);
Expand Down Expand Up @@ -16109,7 +16136,68 @@ mod tests {
}
}

/// A shared diagonal becomes a small positive-area overlap when the mask is normalized.
/// Masks that share an edge leave no gap along it: a triangle over one comes out in one part (#2573).
#[test]
fn clip_leaves_no_gap_between_masks_that_share_an_edge() {
let poly = |pts: &[(f64, f64)]| Geometry::Polygon(vec![vec![pts.iter().map(|&(x, y)| Coord::new(x, y)).collect()]]);
for (feature, one, other) in [
(
poly(&[(43.0, 72.28125), (43.2109375, 72.0), (43.0, 72.0), (43.0, 72.28125)]),
poly(&[(43.046875, 72.421875), (43.046875, 72.140625), (42.8359375, 72.140625), (43.046875, 72.421875)]),
poly(&[(42.8359375, 72.140625), (43.375, 72.140625), (42.8359375, 71.859375), (42.8359375, 72.140625)]),
),
(
poly(&[(-99.5, 33.5), (-99.0, 33.5), (-99.0, 34.0), (-99.5, 33.5)]),
poly(&[(-99.75, 33.71875), (-99.25, 33.71875), (-99.25, 34.21875), (-99.75, 33.71875)]),
poly(&[(-99.25, 34.21875), (-99.25, 33.28125), (-98.75, 34.21875), (-99.25, 34.21875)]),
),
] {
let mut input = Dataset::new("input", GeometryType::Polygon, vec![]);
input.push(Some(feature), vec![]);
let mut masks = Dataset::new("masks", GeometryType::Polygon, vec![]);
masks.push(Some(one), vec![]);
masks.push(Some(other), vec![]);
let m = Map(HashMap::from([("input".into(), input), ("masks".into(), masks)]));
let out = layer(crate::run("clip", &m, &serde_json::json!({"input": "input", "clip": "masks"})).unwrap());
let Some(Geometry::Polygon(parts)) = &out.features[0].geometry else { panic!("a polygon") };
assert_eq!(parts.len(), 1, "{parts:?}");
}
}

/// Zones of several parts that share an edge leave no gap along it either: nothing of a feature
/// across it is left when both are erased (#2573). 644 of 3,000 such pairs left some when each was
/// unioned first.
#[test]
fn zones_of_several_parts_that_share_an_edge_leave_no_gap() {
let mut seed = 11_u64;
let mut rnd = |lo: f64, hi: f64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
lo + (hi - lo) * ((seed >> 11) as f64 / (1u64 << 53) as f64)
};
for round in 0..100 {
let (x, y, dx, dy) = (rnd(-170.0, 170.0), rnd(-70.0, 70.0), rnd(0.01, 0.3), rnd(-0.1, 0.1));
let (a, b) = (Coord::new(x, y), Coord::new(x + dx, y + dy));
// Above the edge and below it, each with a part far from it.
let mut zone = |side: f64| {
let Geometry::Polygon(far) = sq(x + side * rnd(1.0, 3.0), y + side * rnd(1.0, 3.0), 0.1) else { panic!("a polygon") };
let tip = Coord::new(x + rnd(0.0, dx), y + side * 0.5);
Geometry::Polygon([vec![vec![vec![a, b, tip, a]]], far].concat())
};
let mut zones = Dataset::new("zones", GeometryType::Polygon, vec![]);
zones.push(Some(zone(1.0)), vec![]);
zones.push(Some(zone(-1.0)), vec![]);
let w = dx.min(0.05) / 8.0;
let mut input = Dataset::new("input", GeometryType::Polygon, vec![]);
input.push(Some(sq(x + dx / 2.0 - w / 2.0, y + dy / 2.0 - w / 2.0, w)), vec![]);
let m = Map(HashMap::from([("input".into(), input), ("zones".into(), zones)]));
let out = layer(crate::run("erase", &m, &serde_json::json!({"input": "input", "erase": "zones"})).unwrap());
assert_eq!(out.features.len(), 0, "round {round}: {:?}", out.features.geometry(0));
}
}

/// A sliver of an overlap along a diagonal is kept and said; a diagonal only shared is no overlap.
/// Count kept features once, across workers, without changing their geometry; an ordinary
/// partial clip needs no notice.
#[test]
Expand All @@ -16119,7 +16207,16 @@ mod tests {
let (x, y, d) = (-89.7, 35.05, 0.01);
let tract = poly(&[(x, y), (x + d, y + d), (x - d, y + d), (x, y)]);
let town = poly(&[(x, y), (x + d, y + d), (x + 6.0 * d, y - 0.3 * d), (x, y)]);
let mask = union_all(to_multipolygon(&town).unwrap().0.iter());
let mut touching = Dataset::new("touching", GeometryType::Polygon, vec![]);
touching.push(Some(tract.clone()), vec![]);
let mut beside = Dataset::new("beside", GeometryType::Polygon, vec![]);
beside.push(Some(town), vec![]);
let m = Map(HashMap::from([("touching".into(), touching), ("beside".into(), beside)]));
let r = clip_on(&m, &serde_json::json!({"input": "touching", "clip": "beside"}), Some(1), None).unwrap();
assert_eq!(r.messages, ["Clip: 0 features kept"]);
let e = 2e-9;
let town = poly(&[(x - e, y), (x + d - e, y + d), (x + 6.0 * d, y - 0.3 * d), (x - e, y)]);
let mask = to_multipolygon(&town).unwrap().orient(Direction::Default);
// The old part path keeps this sliver: exactly-zero checks miss it. Keep its coordinates
// bit for bit, and count the two output features rather than dropped boundary contacts.
let expected = part(&tract, &mask, true).unwrap();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"seed": "13714318419105429329",
"index": 614,
"known": "gap between rounded clip masks",
"case": {"a":[{"type":"Polygon","coordinates":[[[-25.01953125,42.0],[-25.0,41.9833984375],[-25.0,42.0],[-25.01953125,42.0]]]}],"b":[{"type":"Polygon","coordinates":[[[-25.029296875,41.9931640625],[-25.009765625,41.9931640625],[-25.009765625,42.009765625],[-25.029296875,41.9931640625]]]},{"type":"Polygon","coordinates":[[[-25.009765625,42.009765625],[-25.009765625,41.9736328125],[-24.990234375,42.009765625],[-25.009765625,42.009765625]]]}],"tools":["clip"]}
}
Loading