{ } JustinGeoSci

Coverages

Polygonal coverages and noded line work: exact validation, simplification that keeps a coverage a coverage, and union and polygonization that construct nothing.

Coverage validation

A polygonal coverage is a set of polygons in which every ring is simple, no two interiors meet, and every shared stretch of boundary is made of identical edges, so adjacent polygons share their vertices bit for bit. Gaps between polygons are allowed. The functions here and on the rest of this page are in geometres::ops.

Every operation on this page works on input that is already exactly noded: adjacent polygons share their vertices, and lines meet only at shared endpoints. That is why every output coordinate is an input coordinate: nothing is intersected, rounded or moved. Operations that node general input first construct coordinates, and so are not in this crate.

coverage_validate

pub fn coverage_validate(polys: &[Polygon]) -> Vec<CoverageIssue>

coverage_validate returns every reason polys is not a valid polygonal coverage, sorted; the list is empty when it is one. Every decision is exact: overlaps by relate, edge identity by coordinate equality, and collinearity and vertex-on-edge by orient2d on stored coordinates. Candidate pairs come from a box index with no false negatives.

use geometres::ops::{CoverageIssue, coverage_validate};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let rect = |x0: f64, y0: f64, x1: f64, y1: f64| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
        Coord2d::new(x0, y0), Coord2d::new(x1, y0), Coord2d::new(x1, y1), Coord2d::new(x0, y1),
    ])).unwrap()).unwrap()
};

// Two unit squares sharing the edge x = 1: a valid coverage.
assert!(coverage_validate(&[rect(0.0, 0.0, 1.0, 1.0), rect(1.0, 0.0, 2.0, 1.0)]).is_empty());

// Overlapping squares.
let issues = coverage_validate(&[rect(0.0, 0.0, 1.0, 1.0), rect(0.5, 0.0, 1.5, 1.0)]);
assert!(issues.contains(&CoverageIssue::Overlap { a: 0, b: 1 }));

// A square beside a taller rectangle: they touch along x = 1, but the
// rectangle's edge (1, 2)-(1, 0) does not match the square's edge (1, 0)-(1, 1).
let issues = coverage_validate(&[rect(0.0, 0.0, 1.0, 1.0), rect(1.0, 0.0, 2.0, 2.0)]);
assert!(issues.iter().any(|i| matches!(i, CoverageIssue::UnmatchedEdge { .. })));

coverage_validate_with_gap

pub fn coverage_validate_with_gap(polys: &[Polygon], width: f64) -> Result<Vec<CoverageIssue>, GeometryError>

coverage_validate_with_gap reports what coverage_validate reports, plus a NarrowGap for every pair of boundary edges of different polygons that lie within width of each other (distance ≤ width), are not the same edge, and do not touch. This finds gaps narrower than the width, including gaps separating disjoint coverage regions and narrow gores. width = 0 reports no gap, since a distance of zero means the edges touch.

“This gap is narrower than width” is never decided in f64. The edges do not touch, so their distance is attained at an endpoint of one of them, and each endpoint-to-segment comparison is arithmetica’s exact predicate. Candidates come from each edge’s box grown by width and rounded outward, which can only add candidates for the exact test to reject.

Errors: GeometryError::InvalidTolerance if width is negative or not finite.

use geometres::GeometryError;
use geometres::ops::{CoverageIssue, coverage_validate_with_gap};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let rect = |x0: f64, x1: f64| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
        Coord2d::new(x0, 0.0), Coord2d::new(x1, 0.0), Coord2d::new(x1, 1.0), Coord2d::new(x0, 1.0),
    ])).unwrap()).unwrap()
};
// A gap of exactly 0.25 between x = 1 and x = 1.25.
let polys = [rect(0.0, 1.0), rect(1.25, 2.25)];

// Distance <= width, decided exactly: a gap of exactly the width is reported.
let at = coverage_validate_with_gap(&polys, 0.25).unwrap();
assert!(at.iter().any(|i| matches!(i, CoverageIssue::NarrowGap { .. })));
assert!(coverage_validate_with_gap(&polys, 0.2).unwrap().is_empty());

assert!(matches!(
    coverage_validate_with_gap(&polys, -1.0),
    Err(GeometryError::InvalidTolerance { .. })
));

CoverageIssue

pub enum CoverageIssue

CoverageIssue names one reason a set of polygons is not a valid coverage. Its indices refer to the input slice: polygon, other, a and b are positions in it, ring is 0 for the exterior and 1.. for the holes in order, and edge is the edge starting at that ring’s vertex edge. The enum is #[non_exhaustive] and implements Ord; the validators return their issues sorted.

Variant Meaning
NonSimpleRing { polygon, ring } A ring touches or crosses itself, decided by the exact self-contact test. Polygon constructors do not check simplicity, and a coverage of non-simple polygons has no well-defined shared boundary.
Overlap { a, b } The interiors of polygons a and b meet (a < b), decided by the exact relate. Duplicate polygons, a polygon crossing into another, and one inside another’s interior all show here.
UnmatchedEdge { polygon, ring, edge, other } An edge meets polygon other’s boundary somewhere other than along an identical edge or at its own endpoints: it overlaps one of other’s edges collinearly without having the same two endpoints, or a vertex of other lies in its interior. The coverage is not noded there.
NarrowGap { polygon, ring, edge, other, other_ring, .. } Two boundary edges of different polygons lie within the gap width of each other, are not the same edge, and do not touch. Reported only by coverage_validate_with_gap. The first edge is the one earlier in (polygon, ring, edge) order; the remaining field is the second edge’s index in its ring.
use geometres::ops::{CoverageIssue, coverage_validate};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let square = Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
    Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0), Coord2d::new(1.0, 1.0), Coord2d::new(0.0, 1.0),
])).unwrap()).unwrap();

// A duplicate polygon is an overlap, naming both positions in the input.
let issues = coverage_validate(&[square.clone(), square]);
assert_eq!(issues.first(), Some(&CoverageIssue::Overlap { a: 0, b: 1 }));

Coverage simplification

Coverage simplification is Visvalingam–Whyatt simplification of a polygonal coverage that keeps it a coverage. The method follows JTS’s CoverageSimplifier (Martin Davis), which simplifies the boundaries of the polygons in a coverage while preserving the original coverage topology, by a topology-preserving Visvalingam–Whyatt on the coverage’s edges, keeping node points unchanged.

For a valid coverage, the result is one polygon per input polygon, in input order, such that:

  1. Every output vertex is an input vertex, bit for bit. Vertices are only removed.
  2. Every shared edge is simplified once, and both polygons that share it use the same result, so neighbors still match vertex for vertex.
  3. No edge crosses, touches or jumps over another that it did not before: every removal is decided by the exact checks of simplify_preserve_topology.
  4. Every node is kept, and no polygon disappears: every ring keeps at least three vertices.
  5. The result is a valid coverage, checked exactly by coverage_validate; a result that fails is refused, never returned.

A node is a ring vertex where three or more distinct segments of the coverage meet, or where the ring passes from one sharing to another (from a shared stretch to the coverage’s outer boundary, or from one neighbor to another). Each ring is cut at its nodes into edges, and two pieces are the same edge when their vertex sequences are equal by exact coordinate equality, in either direction. Which vertex to remove is chosen by simplify_vw’s f64 effective areas; whether the removal is allowed is decided exactly against every other current segment of the whole coverage.

The threshold is an area, with simplify_vw’s units and semantics. JTS’s CoverageSimplifier takes a distance tolerance documented as the square root of the area tolerance, so a JTS tolerance t corresponds to a threshold of t * t here.

coverage_simplify

pub fn coverage_simplify(polys: &[Polygon], threshold: f64) -> Result<Vec<Polygon>, GeometryError>

coverage_simplify simplifies every edge of the coverage, shared and outer, once each, and returns one polygon per input polygon in input order. Every polygon is built by Polygon::new, and the result is checked by coverage_validate. By the argument in the module documentation both always pass; a failure would be a defect in the crate, and is refused rather than returned.

Errors:

  • GeometryError::InvalidTolerance for a negative or non-finite threshold.
  • GeometryError::InvalidCoverage with the first issue coverage_validate finds, if polys is not a valid coverage.
  • GeometryError::TooManyEntries for more than u32::MAX − 1 ring vertices.
  • GeometryError::Unvouched with UnvouchedReason::NotACoverage, or a constructor’s error, if the closing checks fail, which is not expected.
use geometres::ops::{coverage_simplify, coverage_validate};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let poly = |v: &[(f64, f64)]| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(
        v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect(),
    )).unwrap()).unwrap()
};
// Two squares sharing a slightly bent edge through (1.01, 0.5).
let left = poly(&[(0.0, 0.0), (1.0, 0.0), (1.01, 0.5), (1.0, 1.0), (0.0, 1.0)]);
let right = poly(&[(1.0, 0.0), (2.0, 0.0), (2.0, 1.0), (1.0, 1.0), (1.01, 0.5)]);

// The bend's effective area is 0.5 * 1 * 0.01 = 0.005, below the threshold.
let out = coverage_simplify(&[left, right], 0.01).unwrap();
assert_eq!(out[0].exterior().num_vertices(), 4);
assert_eq!(out[1].exterior().num_vertices(), 4);
// Both polygons dropped the same vertex, so they still form a coverage.
assert!(coverage_validate(&out).is_empty());

coverage_simplify_inner

pub fn coverage_simplify_inner(polys: &[Polygon], threshold: f64) -> Result<Vec<Polygon>, GeometryError>

coverage_simplify_inner simplifies only the shared edges. Every edge on the coverage’s outer boundary (used by one polygon) is left unchanged, byte for byte, so the result fits exactly inside the original coverage’s outline. It corresponds to JTS’s simplifyInner.

Errors: as coverage_simplify.

use geometres::ops::{coverage_simplify, coverage_simplify_inner};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let poly = |v: &[(f64, f64)]| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(
        v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect(),
    )).unwrap()).unwrap()
};
// As above, but the left square's outer edge x = 0 is also bent, at (-0.01, 0.5).
let left = poly(&[(0.0, 0.0), (1.0, 0.0), (1.01, 0.5), (1.0, 1.0), (0.0, 1.0), (-0.01, 0.5)]);
let right = poly(&[(1.0, 0.0), (2.0, 0.0), (2.0, 1.0), (1.0, 1.0), (1.01, 0.5)]);
let polys = [left, right];

// Every edge simplified: both bends go.
assert_eq!(coverage_simplify(&polys, 0.01).unwrap()[0].exterior().num_vertices(), 4);

// Shared edges only: the inner bend goes, the outer one stays.
let inner = coverage_simplify_inner(&polys, 0.01).unwrap();
let ext = inner[0].exterior().coords().as_slice();
assert_eq!(ext.len(), 5);
assert!(ext.contains(&Coord2d::new(-0.01, 0.5)));
assert!(!ext.contains(&Coord2d::new(1.01, 0.5)));

Union and polygonization

Union of a valid coverage and polygonization of noded line work both trace faces from edges that are already exactly noded, so every output vertex is an input vertex and nothing is constructed. Faces are traced with the face on the left of each directed edge, classified by the certified sign of their area (counterclockwise is an exterior, clockwise a hole), and holes are assigned to the innermost exterior that contains them by exact ring placement, never by comparing approximate areas.

Tracing adds one numerical primitive: the order of the edges leaving a vertex, counterclockwise from the +x direction. Each direction is placed in the upper or lower half-turn by the signs of its coordinate differences, which are the signs of the exact differences, and within one half-turn the order is the exact predicate orient2d. No angle is computed.

coverage_union

pub fn coverage_union(polys: &[Polygon]) -> Result<MultiPolygon, GeometryError>

coverage_union computes the union of a valid coverage by removing shared edges. It takes no overlay and no intersection, and adds no vertex. In a valid coverage an edge shared by two polygons appears exactly twice, in opposite directions, and lies inside the union, so it is dropped; an edge appearing once is on the union’s boundary. The boundary edges are traced into rings, and the result is built through Polygon::new and MultiPolygon::new.

Collinear vertices left on a dissolved boundary are kept: removing them would be simplification, and every output vertex is an input vertex, bit for bit.

Errors:

  • GeometryError::InvalidCoverage carrying the first issue coverage_validate finds, if the input is not a valid coverage. General input needs a constructive union.
  • GeometryError::NonFiniteResult if a ring of the union has a signed area beyond the range of f64. Every input polygon has a finite area, but their union can exceed it (coordinates near 1e154 and beyond).
use geometres::GeometryError;
use geometres::ops::{CoverageIssue, area, coverage_union};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};

let rect = |x0: f64, x1: f64| {
    Polygon::new_simple(LinearRing::new(CoordSeq::new(vec![
        Coord2d::new(x0, 0.0), Coord2d::new(x1, 0.0), Coord2d::new(x1, 1.0), Coord2d::new(x0, 1.0),
    ])).unwrap()).unwrap()
};

// Two unit squares sharing the edge x = 1 dissolve into one 2 x 1 rectangle.
let union = coverage_union(&[rect(0.0, 1.0), rect(1.0, 2.0)]).unwrap();
assert_eq!(union.num_polygons(), 1);
let p = &union.polygons()[0];
assert_eq!(area(p), 2.0);
// (1, 0) and (1, 1) are kept: six vertices, not four.
assert_eq!(p.exterior().num_vertices(), 6);

// Overlapping input is not a coverage, and is refused rather than unioned.
assert!(matches!(
    coverage_union(&[rect(0.0, 1.0), rect(0.5, 1.5)]),
    Err(GeometryError::InvalidCoverage { first: CoverageIssue::Overlap { a: 0, b: 1 } })
));

polygonize_noded

pub fn polygonize_noded(lines: &impl Relatable) -> Result<Polygonized, GeometryError>

polygonize_noded returns the faces of the noded line work of lines, as polygons, with their by-products: dangles, cut edges and invalid rings. The line work is every segment of every line and ring in lines (points are ignored); identical segments, in either direction, are one edge, and every vertex is a node.

The line work must be noded: two segments may meet only at an endpoint of both, with no crossing, no collinear overlap, and no endpoint in the interior of another segment. That is checked exactly before anything is traced.

Dangles are removed repeatedly, then cut edges (edges whose two sides trace the same face), and the remaining faces are traced. A face’s outer loop is its exterior; the loops of components nested inside it are its holes. The faces of a nested component are output as well: a hole and the island in it are both faces. Every output coordinate is an input coordinate.

Errors: GeometryError::NotNoded, naming the first offending pair of segments, if the line work is not noded. General input must be noded first by a constructive operation.

use geometres::GeometryError;
use geometres::ops::polygonize_noded;
use geometres::types::{Coord2d, CoordSeq, LineString, MultiLineString};

let line = |v: &[(f64, f64)]| {
    LineString::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
// The outline of a 2 x 1 rectangle, a divider at x = 1, and a spur off a corner.
let work = MultiLineString::new(vec![
    line(&[(0.0, 0.0), (1.0, 0.0), (2.0, 0.0), (2.0, 1.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]),
    line(&[(1.0, 0.0), (1.0, 1.0)]),
    line(&[(2.0, 1.0), (3.0, 2.0)]),
]);
let out = polygonize_noded(&work).unwrap();
assert_eq!(out.polygons.len(), 2); // the two unit squares
assert_eq!(out.dangles.num_line_strings(), 1); // the spur
assert!(out.cut_edges.is_empty());

// Two crossing segments are not noded: their crossing point is not a vertex.
let crossing = MultiLineString::new(vec![line(&[(0.0, 0.0), (2.0, 2.0)]), line(&[(0.0, 2.0), (2.0, 0.0)])]);
assert!(matches!(polygonize_noded(&crossing), Err(GeometryError::NotNoded { .. })));

Polygonized

pub struct Polygonized { pub polygons: Vec<Polygon>, pub dangles: MultiLineString, pub cut_edges: MultiLineString, pub invalid_rings: MultiLineString }

Polygonized is what polygonize_noded returns: the faces of a noded line arrangement, and the line work that bounds no face. It is #[non_exhaustive].

Field Contents
polygons The bounded faces, each with the rings of the components nested in it as holes. Faces are interior-disjoint but may share edges, so they are a Vec<Polygon> rather than a MultiPolygon. Sorted by exterior vertex sequence.
dangles Edges with a free end, removed repeatedly until none is left, merged into maximal chains.
cut_edges Edges with the same face on both sides (bridges), merged into maximal chains.
invalid_rings Closed rings that cannot form a valid polygon, as closed lines. Every traced loop of noded input is accepted by Polygon::new except one whose signed area is beyond the range of f64 (coordinates near 1e154 and beyond). Such a loop is reported here rather than dropped.
use geometres::ops::polygonize_noded;
use geometres::types::{Coord2d, CoordSeq, LineString, MultiLineString};

let line = |v: &[(f64, f64)]| {
    LineString::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
// Two unit squares joined by a bridge from (1, 0.5) to (2, 0.5).
let work = MultiLineString::new(vec![
    line(&[(0.0, 0.0), (1.0, 0.0), (1.0, 0.5), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]),
    line(&[(2.0, 0.0), (3.0, 0.0), (3.0, 1.0), (2.0, 1.0), (2.0, 0.5), (2.0, 0.0)]),
    line(&[(1.0, 0.5), (2.0, 0.5)]),
]);
let out = polygonize_noded(&work).unwrap();
assert_eq!(out.polygons.len(), 2);
assert_eq!(out.cut_edges.num_line_strings(), 1); // the bridge
assert!(out.dangles.is_empty());
assert!(out.invalid_rings.is_empty());