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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,23 @@ allow-panic-in-tests = true
# A thread count follows the user's setting (`rustgis_data::threads`), and a thread the system
# refuses costs speed or ends one job with an error, never the app: `std::thread::spawn` panics
# then, so use `std::thread::Builder` and handle its error (AGENTS.md › Use the threads).
#
# Geo's boolean operations run on an overlay engine that can loop forever on valid polygons:
# `rustgis_data::overlay` has the same operations without it.
disallowed-methods = [
{ path = "geo::algorithm::bool_ops::unary_union", reason = "it can hang on valid polygons: `rustgis_data::overlay::union_all`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::boolean_op", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::boolean_op_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::intersection", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::intersection_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::union", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::union_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::difference", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::difference_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::xor", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::xor_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::clip", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "geo::algorithm::bool_ops::BooleanOps::clip_with_fill_rule", reason = "it can hang on valid polygons: `rustgis_data::overlay::Overlay`" },
{ path = "rustgis_geom::haversine_m", reason = "the sphere; the Earth measures with `wgs84_distance_m`" },
{ path = "rustgis_geom::geodesic_length_m", reason = "the sphere; the Earth measures with `wgs84_length_m`" },
{ path = "rustgis_geom::geodesic_ring_perimeter_m", reason = "the sphere; the Earth measures with `wgs84_ring_perimeter_area_m2`" },
Expand Down
3 changes: 0 additions & 3 deletions crates/analysis/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@ workspace = true
rustgis-geom = { workspace = true }
rustgis-data = { workspace = true }
geo = { workspace = true }
# Not 9.2.0: of 8,674 random groups it wrote invalid polygons for 5 (one of valid input), and 9.2.1
# for none.
i_overlay9 = { package = "i_overlay", version = "9.2.1" }
# FFTs for texture shading (#3146): pure Rust, MIT or Apache-2.0, builds for wasm32.
rustfft = "6.4"
a5 = { workspace = true }
Expand Down
12 changes: 12 additions & 0 deletions crates/analysis/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,18 @@ fn gc(c: Coord) -> GC<f64> {
GC { x: m.x, y: m.y }
}

/// Whether a geometry is a polygon with a coordinate that isn't finite, in its own coordinates or in
/// the run's plane. Its own are asked first: an infinite latitude is a pole once in the plane, where only a longitude
/// far past any on the globe stops being finite.
pub fn polygon_not_finite(g: &Geometry) -> bool {
matches!(g, Geometry::Polygon(polys) if polys.iter().flatten().flatten().any(not_finite))
}

/// [`polygon_not_finite`] of one coordinate.
pub(crate) fn not_finite(c: &Coord) -> bool {
!c.is_finite() || (c.x.abs() > 1e290 && !to_plane(*c).is_finite())
}

fn back(c: &GC<f64>) -> Coord {
from_plane(Coord::new(c.x, c.y))
}
Expand Down
6 changes: 3 additions & 3 deletions crates/analysis/src/geodesic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@
//! ([`crate::convert::own_length`]), as distances are in a projected system.

use geo::{
BooleanOps, Buffer, Contains, Coord as GC, CoordsIter, LineString, MultiLineString, MultiPolygon, Orient, Point, Polygon,
Buffer, Contains, Coord as GC, CoordsIter, LineString, MultiLineString, MultiPolygon, Orient, Point, Polygon,
algorithm::buffer::{BufferStyle, LineCap, LineJoin},
orient::Direction,
};
use rustgis_data::overlay::Overlay as _;
use rustgis_data::{Coord, Geometry};
use rustgis_geom::{Aeqd, geodesic_interpolate, haversine_m, lonlat_to_plane, plane_to_lonlat, spherical_centre};

Expand Down Expand Up @@ -567,8 +568,7 @@ fn union(pieces: Vec<MultiPolygon<f64>>) -> MultiPolygon<f64> {
if pieces.len() == 1 {
return pieces.into_iter().next().unwrap_or_else(|| MultiPolygon::new(vec![]));
}
let oriented: Vec<Polygon<f64>> = pieces.iter().flat_map(|m| m.0.iter()).map(|p| p.orient(Direction::Default)).collect();
geo::unary_union(oriented.iter())
rustgis_data::overlay::union_all(pieces.iter().flat_map(|m| m.0.iter()))
}

fn to_geometry(mp: &MultiPolygon<f64>) -> Option<Geometry> {
Expand Down
49 changes: 19 additions & 30 deletions crates/analysis/src/repair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
//! around (non-zero winding: both lobes of a bowtie count, and the direction a ring is wound in
//! doesn't matter); a part is its exterior ring's area less the union of its holes' areas, so a
//! hole outside its exterior ring disappears and holes that overlap merge; and the feature is
//! the union of its parts, so parts that overlap merge. geo's boolean overlay (i_overlay) does
//! the union of its parts, so parts that overlap merge. the boolean overlay does
//! the arithmetic on an integer grid, which moves coordinates a little ([`grid_step`],
//! [`GRID_STEPS_MOVED`]), and writes each piece of a split interior as a part of its own. A hole
//! or part narrower than a step of that grid in any direction (up to √2 steps across a diagonal,
Expand All @@ -29,15 +29,16 @@
//! of the browser before it runs. Natively a panic is caught, and the feature is left as it was.

use crate::validity::{self, At, Checked, Code, Limit, Problem, Room};
use geo::algorithm::bool_ops::{BooleanOps, FillRule, OpType};
use geo::orient::{Direction, Orient};
use geo::{Area, Euclidean, Length};
pub(crate) use rustgis_data::overlay::grid_step;
use rustgis_data::overlay::{FillRule, OpType, Overlay};
use rustgis_data::{Coord, Geometry};

/// Work per vertex the overlay takes in or makes, against the same bound as a check
/// ([`validity::MAX_WORK`]): at 25, up to 2 million vertices a feature, as Buffer allows.
const OVERLAY_COST: u64 = 25;
/// The memory the overlay holds per vertex, as estimated: geo's and i_overlay's copies of the
/// The memory the overlay holds per vertex, as estimated: our and i_overlay's copies of the
/// rings in floats and on the grid, their segments and sort, the overlay's graph and its output.
const OVERLAY_BYTES: u64 = 160;
/// How far a coordinate may move through the overlays of one repair, in steps of the grid: a
Expand Down Expand Up @@ -426,24 +427,6 @@ fn polygon(
)
}

/// The step of the integer grid i_overlay rounds the points `pts` to: it takes half the larger
/// side of their extent, `h`, to about 2^29 grid units (2^(29 - round(log2 h)) units a unit of
/// the coordinates). `None` when there is no such grid: an extent that is empty, not finite, or
/// so large or so small that the scale or the step isn't a finite number.
pub(crate) fn grid_step(pts: impl Iterator<Item = (f64, f64)>) -> Option<f64> {
let (mut lo_x, mut lo_y, mut hi_x, mut hi_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for (x, y) in pts {
(lo_x, lo_y, hi_x, hi_y) = (lo_x.min(x), lo_y.min(y), hi_x.max(x), hi_y.max(y));
}
let half = (hi_x - lo_x).max(hi_y - lo_y) * 0.5;
if !(half.is_finite() && half > 0.0) {
return None;
}
let e = 29.0 - half.log2().round();
let (scale, step) = (e.exp2(), (-e).exp2());
(scale.is_normal() && step.is_normal()).then_some(step)
}

/// The step of the grid the overlay rounds `rings` to ([`grid_step`]); an error when there is
/// none, and the overlay can't run on them.
fn on_grid<'a>(rings: impl Iterator<Item = &'a geo::LineString<f64>>) -> Result<f64, Kept> {
Expand Down Expand Up @@ -613,8 +596,7 @@ fn ring_area(ring: &[Coord], at: (usize, usize), crossing: &[(usize, usize)], ro
// A simple ring: its area as it is, wound as the overlay expects.
return Ok(geo::MultiPolygon::new(vec![poly.orient(Direction::Default)]));
}
on_grid(std::iter::once(poly.exterior()))?;
Ok(poly.boolean_op_with_fill_rule(&geo::MultiPolygon::new(vec![]), OpType::Union, FillRule::NonZero))
combine(&poly, &geo::MultiPolygon::new(vec![]), OpType::Union, FillRule::NonZero)
}

/// The rebuild under [`Rule::EvenOdd`] of `parts` (closed rings, each with 3 distinct points or
Expand Down Expand Up @@ -686,7 +668,7 @@ fn by_parity(parts: &[Vec<Vec<Coord>>], crossing: &[(usize, usize)], room: Room)
let mut pieces: Vec<geo::Polygon<f64>> = room.vec(shell.0.len().saturating_add(cut.0.len())).map_err(kept_for)?;
pieces.extend(shell.0);
pieces.extend(cut.0);
geo::MultiPolygon::new(pieces).boolean_op_with_fill_rule(&empty, OpType::Union, FillRule::EvenOdd)
combine(&geo::MultiPolygon::new(pieces), &empty, OpType::Union, FillRule::EvenOdd)?
};
if part.0.is_empty() {
no_area += 1;
Expand All @@ -712,7 +694,7 @@ fn by_parity(parts: &[Vec<Vec<Coord>>], crossing: &[(usize, usize)], room: Room)
let given = all.len();
let each: f64 = all.iter().map(Area::unsigned_area).sum();
let length: f64 = rings_of(&all).map(|r| Euclidean.length(r)).sum();
let combined = geo::MultiPolygon::new(all).boolean_op_with_fill_rule(&empty, OpType::Union, FillRule::EvenOdd);
let combined = combine(&geo::MultiPolygon::new(all), &empty, OpType::Union, FillRule::EvenOdd)?;
if combined.0.len() < given || each - combined.unsigned_area() > length * step {
found.push(Code::PartsOverlap);
}
Expand All @@ -723,19 +705,26 @@ fn by_parity(parts: &[Vec<Vec<Coord>>], crossing: &[(usize, usize)], room: Room)
Ok(Rebuilt { polys: polygons(&combined, room).map_err(kept_for)?, no_area, narrow, found, duplicates })
}

/// `op` of `a` and `b`; an error when there is no grid ([`grid_step`]) for their coordinates, since a
/// panic in the overlay can't be caught in the browser.
fn combine(a: &impl Overlay, b: &impl Overlay, op: OpType, fill: FillRule) -> Result<geo::MultiPolygon<f64>, Kept> {
on_grid(rings_of(a.polygons()).chain(rings_of(b.polygons())))?;
Ok(a.boolean_op_with_fill_rule(b, op, fill))
}

/// What the checks don't tell of the holes of a part with a ring crossing itself, which they
/// can't relate to the rest: [`Code::HoleOutsideShell`] when some of `cut`, its holes' areas, lies
/// outside `shell`, its exterior ring's, and [`Code::RingsIntersect`] when holes overlap or touch
/// along a line, which their union tells by making fewer polygons than it was given.
fn unrelated_hole_codes(shell: &geo::MultiPolygon<f64>, cut: &geo::MultiPolygon<f64>, found: &mut Found) {
if !found.contains(&Code::HoleOutsideShell) && !cut.boolean_op_with_fill_rule(shell, OpType::Difference, FillRule::NonZero).0.is_empty()
if !found.contains(&Code::HoleOutsideShell)
&& combine(cut, shell, OpType::Difference, FillRule::NonZero).is_ok_and(|outside| !outside.0.is_empty())
{
found.push(Code::HoleOutsideShell);
}
if cut.0.len() > 1
&& !found.contains(&Code::RingsIntersect)
&& on_grid(rings_of(&cut.0)).is_ok()
&& cut.boolean_op_with_fill_rule(&geo::MultiPolygon::new(vec![]), OpType::Union, FillRule::NonZero).0.len() < cut.0.len()
&& combine(cut, &geo::MultiPolygon::new(vec![]), OpType::Union, FillRule::NonZero).is_ok_and(|merged| merged.0.len() < cut.0.len())
{
found.push(Code::RingsIntersect);
}
Expand Down Expand Up @@ -1031,7 +1020,7 @@ fn by_area(parts: &[Vec<Vec<Coord>>], crossing: &[(usize, usize)], room: Room) -
if !related {
unrelated_hole_codes(&shell, &cut, &mut found);
}
shell.boolean_op_with_fill_rule(&cut, OpType::Difference, FillRule::NonZero)
combine(&shell, &cut, OpType::Difference, FillRule::NonZero)?
};
if part.0.is_empty() {
no_area += 1;
Expand All @@ -1048,7 +1037,7 @@ fn by_area(parts: &[Vec<Vec<Coord>>], crossing: &[(usize, usize)], room: Room) -
}
let all = geo::MultiPolygon::new(all);
let merged = if parts.len() > 1 && all.0.len() > 1 {
let merged = all.boolean_op_with_fill_rule(&empty, OpType::Union, FillRule::NonZero);
let merged = combine(&all, &empty, OpType::Union, FillRule::NonZero)?;
if merged.0.len() < all.0.len() {
found.push(Code::PartsOverlap);
}
Expand Down
4 changes: 2 additions & 2 deletions crates/analysis/src/selection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
//! Only the selection outline is normalized. Candidate geometries are borrowed, and their
//! non-finite separators are treated as breaks rather than passed to `geo`.

use geo::algorithm::bool_ops::{BooleanOps, FillRule};
use geo::line_intersection::line_intersection;
use geo::{Coord as GeoCoord, Intersects, Line, LineString, MultiPolygon, Point, Polygon};
use rustgis_data::overlay::{FillRule, OpType, Overlay as _};
use rustgis_data::{Geometry, geometry::ring_contains};
use rustgis_geom::{Coord, Extent};

Expand Down Expand Up @@ -88,7 +88,7 @@ impl PolygonMask {
}
boundary.truncate(write);
let raw = Polygon::new(LineString::new(local_ring), vec![]);
let filled = raw.union_with_fill_rule(&MultiPolygon::<f64>::new(vec![]), FillRule::EvenOdd);
let filled = raw.boolean_op_with_fill_rule(&MultiPolygon::<f64>::new(vec![]), OpType::Union, FillRule::EvenOdd);
if filled.0.is_empty() {
return Err("Selection outline has no filled area.".into());
}
Expand Down
3 changes: 2 additions & 1 deletion crates/analysis/src/sketch_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,8 @@ fn geo_polygon(rings: &[Vec<Coord>]) -> Option<geo::Polygon<f64>> {

/// The area two polygons share, in square metres (0 when their boxes don't meet).
fn shared_area(a: &geo::Polygon<f64>, b: &geo::Polygon<f64>) -> f64 {
use geo::{Area, BooleanOps, BoundingRect, Intersects};
use geo::{Area, BoundingRect, Intersects};
use rustgis_data::overlay::Overlay as _;
match (a.bounding_rect(), b.bounding_rect()) {
(Some(x), Some(y)) if x.intersects(&y) => a.intersection(b).unsigned_area(),
_ => 0.0,
Expand Down
Loading
Loading