Skip to content
Merged
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
114 changes: 102 additions & 12 deletions crates/analysis/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ mod repair_geometry;
mod tabulate_area;
mod texture_shading;

use geo::{Contains, ConvexHull, CoordsIter, InteriorPoint, Intersects, MultiPolygon, Orient, Relate, orient::Direction};
use geo::{
Contains, ConvexHull, CoordsIter, InteriorPoint, Intersects, MultiPolygon, Orient, Relate, indexed::PreparedGeometry, orient::Direction,
};
use rustgis_data::overlay::{Overlay as _, union_all};
use rustgis_data::raster::{Crs, Transformer};
use rustgis_data::{Coord, Dataset, Feature, Field, FieldType, Geometry, GeometryType, Measure, Value};
Expand Down Expand Up @@ -2224,12 +2226,22 @@ fn largest_geometry_bytes(ds: &Dataset, rows: &[usize]) -> Result<usize, String>
Ok(largest)
}

/// Prepare only when enough masks will reuse the input geometry's segment index.
const PREPARE_ERASE_MASKS: usize = 32;
/// Limit the size of a single input's prepared graph, including on the browser.
const PREPARE_ERASE_COORDS: std::ops::RangeInclusive<usize> = 128..=16_384;
/// Budget space for the projected validity check, R-tree, cached edges and graph clone per vertex.
const PREPARE_ERASE_BYTES_PER_COORD: usize = 256;
/// The work a vertex allows the validity check before preparing: one that needs more isn't prepared.
const PREPARE_ERASE_CHECK_WORK: u64 = 256;

/// Peak per-feature overlay storage, estimated from the masks it may actually meet: converted
/// and dissolved input, the masks' union and output. Overlapping masks can each retain the
/// entire input as an inside piece, so cuts budget another input copy per candidate mask.
/// Four input copies allow conversion, dissolve, intermediate and output; three mask copies
/// allow the union, boolean-operation work and output. The index's candidate references can
/// exceed the number of zones before deduplication.
/// allow the union, boolean-operation work and output. Erase and Update budget one prepared
/// graph when a polygon meets enough masks. Its coordinate cap allows for growth during dissolve.
/// The index's candidate references can exceed the number of zones before deduplication.
/// Like Clip's estimate this sizes coordinate storage, not a worst-case bound on edge crossings.
fn overlay_scratch(ds: &Dataset, rows: &[usize], zones: &[Zone], near: (&ExtentIndex, &AtPoles), inside: bool) -> Result<usize, String> {
crate::control::begin(rows.len().saturating_add(zones.len()));
Expand All @@ -2247,7 +2259,12 @@ fn overlay_scratch(ds: &Dataset, rows: &[usize], zones: &[Zone], near: (&ExtentI
let hits = meeting(g, &g.extent(), zones, near);
let masks = hits.iter().filter_map(|&i| sizes.get(i)).fold(0usize, |n, &b| n.saturating_add(b));
let copies = if inside { hits.len().saturating_add(4) } else { 4 };
largest = largest.max(coord_bytes(g).saturating_mul(copies).saturating_add(masks.saturating_mul(3)));
let prepared = if !inside && hits.len() >= PREPARE_ERASE_MASKS && matches!(g, Geometry::Polygon(_)) {
*PREPARE_ERASE_COORDS.end() * PREPARE_ERASE_BYTES_PER_COORD
} else {
0
};
largest = largest.max(coord_bytes(g).saturating_mul(copies).saturating_add(masks.saturating_mul(3)).saturating_add(prepared));
}
crate::control::advance(1);
}
Expand Down Expand Up @@ -2791,6 +2808,28 @@ fn rest_outside(g: &Geometry, whole: &Geometry, hit: &[&Zone]) -> Option<Geometr
}
}

/// The unsnapped overlap test used to select erase masks, excluding boundary-only touches.
fn polygon_zone_cuts(zone: &Zone, whole: &impl Relate<f64>) -> bool {
let m = zone.poly.relate(whole);
m.is_intersects() && !m.is_touches()
}

/// Keep the same DE-9IM test, preparing the dissolved input once for a large set of candidates.
/// Check validity in the run's plane before caching self-noding results. A bounded check keeps
/// complicated or invalid polygons on the existing path and limits the graph we have to hold.
fn polygon_zone_hits<'a>(near: Vec<&'a Zone>, whole: &geo::Geometry<f64>, polygons: &MultiPolygon<f64>) -> Vec<&'a Zone> {
let coords = polygons.coords_count();
if near.len() >= PREPARE_ERASE_MASKS
&& PREPARE_ERASE_COORDS.contains(&coords)
&& crate::validity::check(Some(&in_plane(polygons)), coords as u64 * PREPARE_ERASE_CHECK_WORK).problems.is_empty()
{
let prepared = PreparedGeometry::from(whole);
near.into_iter().filter(|z| polygon_zone_cuts(z, &prepared)).collect()
} else {
near.into_iter().filter(|z| polygon_zone_cuts(z, whole)).collect()
}
}

/// A feature's part outside every zone, as [`part`] gives it, for tools that keep only that
/// (Erase, Update): it is cut once, by the zones that cut it (that zone itself, so its edges stay
/// exactly where they are, or their union), without [`cut`]'s part in each zone. Only zones whose
Expand All @@ -2811,15 +2850,12 @@ fn outside(g: &Geometry, zones: &[Zone], index: (&ExtentIndex, &AtPoles)) -> Opt
// The zones that cut it: a polygon is cut by those it overlaps, a line or point by those it
// meets (an edge counts as inside, and a point at a pole meets a zone reaching it). Each is
// tested on its own, before any union.
let cuts = |z: &&Zone| match g {
Geometry::Polygon(_) => {
let m = z.poly.relate(&geo_g);
m.is_intersects() && !m.is_touches()
}
Geometry::Point(_) | Geometry::MultiPoint(_) => meet_at_a_pole(poles(&ext), poles(&z.ext)) || z.poly.intersects(&geo_g),
Geometry::Line(_) => z.poly.intersects(&geo_g),
let hit = if let geo::Geometry::MultiPolygon(polygons) = &geo_g {
polygon_zone_hits(near, &geo_g, polygons)
} else {
let points = matches!(g, Geometry::Point(_) | Geometry::MultiPoint(_));
near.into_iter().filter(|z| (points && meet_at_a_pole(poles(&ext), poles(&z.ext))) || z.poly.intersects(&geo_g)).collect()
};
let hit: Vec<&Zone> = near.into_iter().filter(cuts).collect();
rest_outside(g, &whole, &hit)
}

Expand Down Expand Up @@ -15256,6 +15292,60 @@ mod tests {
assert!((rest.unsigned_area() - want.unsigned_area()).abs() < 1e-6 * want.unsigned_area(), "{rest:?}");
}

/// A complex feature can have thousands of bounding-box matches without any cuts.
/// Rebuilding its segment index for each mask makes this finish too slowly.
#[test]
fn erase_finishes_with_many_masks_outside_a_complex_feature() {
let ring = (0..=8192)
.map(|i| {
let angle = (i % 8192) as f64 * std::f64::consts::TAU / 8192.0;
Coord::new(angle.cos(), angle.sin())
})
.collect();
let g = Geometry::Polygon(vec![vec![ring]]);
let mut input = Dataset::new("input", GeometryType::Polygon, vec![]);
input.push(Some(g.clone()), vec![]);
let mut zones = Dataset::new("zones", GeometryType::Polygon, vec![]);
for _ in 0..4096 {
zones.push(Some(sq(0.85, 0.85, 0.1)), vec![]);
}
let m = Map(HashMap::from([("input".into(), input), ("zones".into(), zones)]));
let out = layer(finishes(move || crate::run("erase", &m, &serde_json::json!({"input": "input", "erase": "zones"})).unwrap()));
assert_eq!(out.features.len(), 1);
assert_eq!(out.features.geometry(0), Some(&g));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// The masks picked for a prepared feature are the ones picked for it unprepared: ones that cut it,
/// touch it along an edge or at a corner, cover it, or lie in its hole, in order.
#[test]
fn a_prepared_feature_is_cut_by_the_same_masks() {
let ring = |r: f64| {
(0..=256)
.map(|i| (f64::from(i % 256) * std::f64::consts::TAU / 256.0).sin_cos())
.map(|(y, x)| Coord::new(x * r, y * r))
.collect::<Vec<_>>()
};
let whole = to_multipolygon(&Geometry::Polygon(vec![vec![ring(1.0), ring(0.3).into_iter().rev().collect()]])).unwrap();
let mut zones: Vec<Geometry> = (0..64).map(|i| sq(0.85, 0.85 + f64::from(i) * 1e-4, 0.1)).collect();
zones.extend([
sq(0.5, 0.0, 0.2),
sq(1.0, 0.0, 0.5),
sq(0.9, -0.2, 0.4),
sq(-2.0, -2.0, 4.0),
sq(-0.1, -0.1, 0.2),
sq(-0.1, 0.9, 0.2),
]);
let side: Vec<Coord> = ring(1.0)[..2].to_vec();
zones.push(Geometry::Polygon(vec![vec![vec![side[0], Coord::new(1.5, 0.0), side[1], side[0]]]]));
let zones: Vec<Zone> = zones.iter().map(|g| Zone { row: 0, ext: g.extent(), poly: to_multipolygon(g).unwrap() }).collect();
let geo_whole = geo::Geometry::MultiPolygon(whole.clone());
let at = |hits: Vec<&Zone>| hits.iter().map(|h| zones.iter().position(|z| std::ptr::eq(z, *h)).unwrap()).collect::<Vec<_>>();
let picked = at(polygon_zone_hits(zones.iter().collect(), &geo_whole, &whole));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test can't tell whether the prepared branch ran. polygon_zone_hits falls back to the unprepared predicate when the mask count, coordinate range or validity gate fails, and the assertions still pass. The earlier thread (all masks missing) is addressed, but this is a separate gap: nothing checks the preconditions that select the prepared path.

Suggest asserting them here, before the call, so the comparison is known to exercise the prepared branch:

  • assert!(zones.len() >= PREPARE_ERASE_MASKS);
  • assert!(PREPARE_ERASE_COORDS.contains(&whole.coords_count()));
  • assert!(crate::validity::check(Some(&in_plane(&whole)), u64::MAX).problems.is_empty());

If the gate is ever changed so the prepared path is skipped, these fail instead of the comparison passing trivially.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test doesn't say by itself which path ran, but it was checked to be the prepared one: with that path made to answer nothing, the test fails with an empty list against [64, 66, 67, 69]. Making it say so in the test is left for the release quality pass.

let unprepared = at(zones.iter().filter(|z| polygon_zone_cuts(z, &geo_whole)).collect());
assert_eq!(picked, unprepared);
assert_eq!(picked, [64, 66, 67, 69]);
}

#[test]
fn update_replaces_the_covered_part_with_the_update_polygons() {
let mut m = parcels_and_zones();
Expand Down
Loading