Convex hulls and polygon booleans
| Problem | Find the smallest convex polygon or polyhedron containing a set of points, and combine polygons by intersection, union and difference |
| Devised by | Ronald Graham (1972) and Andrew (1979), planar hulls; C. Bradford Barber, David Dobkin and Hannu Huhdanpaa (1996), Quickhull; Günther Greiner and Kai Hormann (1998), polygon clipping |
| Accuracy | Hull vertex sets identical to Qhull’s, volumes and areas within ; boolean areas within of Shapely’s (see the chapter overview) |
| Cost | Planar hull ; Quickhull typical, worst case; booleans for polygons of and vertices |
| Read first | Geometric types: points, vectors, shapes and shared tables |
| API | convex_hull_2d, polygon_area_2d, convex_polygon_contains_2d, convex_hull_3d, Hull3D (vertices, volume, surface_area, contains), polygon_boolean, BooleanOperation, point_in_polygon |
Overview
The convex hull of a point set is the smallest convex set containing it: in the plane, the shape a rubber band takes around nails at the points. It gives a fast first test for collision and containment, the extreme points of data, bounding shapes for meshes, and appears inside other algorithms (the Delaunay triangulation is a convex hull one dimension up). In the plane the library uses Andrew’s monotone chain; in space, Quickhull.
Boolean operations combine two polygons into their intersection, union or difference. They are the core of computer-aided design, map overlay in geographic information systems, and clipping in graphics. The library uses the Greiner–Hormann algorithm, which walks around both outlines and switches from one to the other at each crossing.
Where it is used
Convex hulls and polygon operations are workhorses of computational geometry.
- Collision detection and games. A convex hull is a cheap bounding shape for testing whether objects touch.
- Robotics and path planning. Obstacles are enlarged and combined by polygon unions.
- GIS and CAD. Intersecting, subtracting or merging land parcels, building footprints and parts are polygon boolean operations.
- Statistics and image analysis. The hull of a point cloud outlines a cluster or an object’s extent.
History
Ronald Graham (1972) gave the first planar hull, sorting points by angle around an interior point, for a Bell Labs problem with thousands of points. A. M. Andrew (1979) simplified it to sorting by and building the lower and upper chains separately. In three dimensions Franco Preparata and S. J. Hong (1977) gave a divide-and-conquer algorithm. Barber, Dobkin and Huhdanpaa’s Quickhull (1996) is the basis of Qhull, used by SciPy, MATLAB and R. Polygon clipping began with Sutherland and Hodgman (1974) for convex clip windows. Weiler and Atherton (1977) handled general polygons, and Greiner and Hormann (1998) gave the simple linked-list version used here.
The idea
The monotone chain
Sort the points by , then . Walk left to right building the lower chain. Before adding each point, remove the last chain point while the last two chain points and the new one make a clockwise or straight turn: such a point cannot be on the lower boundary. A right-to-left walk builds the upper chain the same way, and together they are the hull, counter-clockwise. The turn test is the sign of the cross product . Removing straight turns too leaves points in the middle of hull edges out.
Quickhull in three dimensions
Start with a tetrahedron of four extreme points. Each face keeps an outside set: the remaining points above its plane, each assigned to one face. Points above no face are inside and are discarded. Repeatedly take a face with a non-empty outside set and its farthest point, the apex. The apex is certainly a hull vertex. The faces it can see form a connected cap. Their boundary, the horizon, is found by a search across shared edges from the starting face. The cap is replaced by a cone of new faces from the horizon to the apex, and the cap’s outside points are shared out among the new faces. When no face has outside points, the remaining faces are the hull.
Figure 24.5. Hulls.
Points far inside are discarded early, so on typical data most of the work is the first few passes. The worst case is every point on the hull, such as points on a sphere, and even that is fast:
Table 24.3. Convex hull times in two and three dimensions.
| points | 2D, Gaussian | 3D, Gaussian | 3D, all on a sphere |
|---|---|---|---|
| 1000 | 54 µs (11 vertices) | 94 µs (70 faces) | 1.7 ms (1996 faces) |
| 10000 | 459 µs (11 vertices) | 317 µs (76 faces) | 19.0 ms (19996 faces) |
| 100000 | 5.1 ms (15 vertices) | 2.7 ms (124 faces) | 251.7 ms (199996 faces) |
Inserting points in input order and rebuilding a map of every face edge for each one is slow: 10 000 points on a sphere took 46 s. Quickhull, which takes the farthest point first, is far faster and also keeps points that lie on a face or an edge of the hull from becoming vertices. A grid gives its 8 corners, where the naive insertion kept 32.
The Greiner–Hormann algorithm
- Find every crossing of an edge of polygon A with an edge of polygon B, and insert it into both vertex lists, linked to its twin.
- Walking around A, the crossings alternate between entries into B and exits from it. Whether the first is an entry depends on whether A’s first vertex is inside B, decided by the even–odd ray test.
- Trace the result: start at an unvisited crossing and follow its polygon, forwards from an entry and backwards from an exit, to the next crossing; jump to the twin and continue on the other polygon, until back at the start. That traces the intersection. Swapping the entry and exit labels on both polygons gives the union, and on A alone gives A minus B.
If a vertex lies exactly on the other polygon’s boundary, or two edges overlap, the entry/exit labels become ambiguous. The library then moves the clip polygon by a random relative and retries, so results are exact up to that tolerance. If the outlines never cross, the answer follows from whether one contains the other.
Figure 24.6. Polygon booleans.
Results are counter-clockwise outer boundaries and clockwise holes, so signed areas add up to the true area. A union can enclose a hole, as here.
Algorithm
Convex hull in the plane (monotone chain).
- Sort the points by , then .
- Lower chain. For each point in order: while the chain has at least two points and the last two together with the new point do not make a counter-clockwise turn, remove the last point of the chain; then append the new point.
- Upper chain. Do the same through the points in reverse order.
- Join the two chains, omitting the endpoint each shares with the other.
The sort costs and the two walks , since each point is appended once and removed at most once.
Convex hull in space (quickhull).
- Initial tetrahedron. Choose four extreme points that are not coplanar.
- Outside sets. Assign each remaining point to one face that it lies above; discard the points that lie above no face, which are inside.
- Take a face with a non-empty outside set, and its farthest point, the apex.
- Visible cap. Starting from that face, search across shared edges for all the faces the apex lies above. The edges between a visible and an invisible face form the horizon.
- Replace. Delete the visible faces. Create a new face from each horizon edge to the apex. Reassign the outside points of the deleted faces among the new faces, discarding those now inside.
- Repeat from step 3 until no face has outside points.
Polygon boolean operations (Greiner-Hormann), on polygons A and B.
- Crossings. Test every edge of A against every edge of B. Insert each crossing point into both vertex lists, in order along its edge, and link the two copies.
- Labels. Decide by the even-odd test whether the first vertex of A is inside B. Walking round A, label the crossings alternately as entries and exits, starting accordingly. Do the same for B with respect to A. Reverse the labels as the operation requires: neither for the intersection, both for the union, and those of A alone for A minus B.
- Trace. While an unvisited crossing remains: start a new loop there. Follow the current polygon, forwards from an entry and backwards from an exit, adding vertices to the loop, until the next crossing; jump to its copy on the other polygon; continue until the loop returns to its start.
- Orient. A loop nested inside an odd number of other loops is a hole, and is made clockwise; the others are outer boundaries, counter-clockwise.
If no crossings are found, the result follows from whether one polygon contains the other.
Implementation
// Quickhull: add the point farthest above this face, which is certainly a hull vertex.
let apex = *slots[k].outside.iter().max_by(|&&a, &&b| height(&slots[k], a).total_cmp(&height(&slots[k], b))).unwrap();
// The faces it sees form a connected cap around face k: find them across shared edges.
let mut visible = vec![k];
let mut seen = std::collections::HashSet::from([k]);
let mut horizon: Vec<(usize, usize)> = Vec::new();
let mut i = 0;
while i < visible.len() {
let f = slots[visible[i]].vertices;
for j in 0..3 {
let (a, b) = (f[j], f[(j + 1) % 3]);
let across = owner[&(b, a)];
if seen.contains(&across) {
continue;
}
if height(&slots[across], apex) > eps {
seen.insert(across);
visible.push(across);
} else {
horizon.push((a, b));
}
}
i += 1;
}
// Remove the cap, keeping its outside points to hand on to the new faces.
let mut orphans = Vec::new();
for &v in &visible {
let f = &mut slots[v];
f.alive = false;
orphans.append(&mut f.outside);
for j in 0..3 {
owner.remove(&(f.vertices[j], f.vertices[(j + 1) % 3]));
}
}
// Cone the horizon to the apex, skipping any edge that rounding has left inconsistent
// (its face across was removed after all).
let first_new = slots.len();
for (a, b) in horizon {
if owner.contains_key(&(a, b)) || !owner.contains_key(&(b, a)) {
continue;
}
let vertices = [a, b, apex];
let (normal, offset) = plane(&vertices);
for j in 0..3 {
owner.insert((vertices[j], vertices[(j + 1) % 3]), slots.len());
}
slots.push(Face { vertices, normal, offset, outside: Vec::new(), alive: true });
}
for p in orphans.into_iter().filter(|&p| p != apex) {
if let Some(f) = (first_new..slots.len()).find(|&f| height(&slots[f], p) > eps) {
slots[f].outside.push(p);
}
}
pending.extend(first_new..slots.len());
convex_hull_2dreturns counter-clockwise indices from the lexicographically smallest point, without duplicates or points in the middle of edges.convex_hull_3dreturnsNonefor fewer than four points or coplanar input; its faces wind counter-clockwise seen from outside.polygon_booleantakes simple polygons in either orientation.
In practice
//! Convex hulls in two and three dimensions, and boolean operations on polygons.
use lib_jsl_geometry::algorithms::{BooleanOperation, convex_hull_2d, convex_hull_3d, polygon_area_2d, polygon_boolean, polygon_signed_area};
fn main() {
let points = [[0.0, 0.0], [2.0, 0.5], [4.0, 0.0], [3.0, 2.0], [4.0, 4.0], [2.0, 3.0], [0.0, 4.0], [1.0, 2.0], [2.0, 2.0]];
let hull = convex_hull_2d(&points);
println!("2D hull {:?}, area {}", hull, polygon_area_2d(&points, &hull));
// The unit cube's corners plus its centre and a point in a face.
let mut cube: Vec<[f64; 3]> = (0..8).map(|i| [(i & 1) as f64, (i >> 1 & 1) as f64, (i >> 2 & 1) as f64]).collect();
cube.extend([[0.5, 0.5, 0.5], [0.5, 0.5, 1.0]]);
let h = convex_hull_3d(&cube).unwrap();
println!("3D hull: {} faces, vertices {:?}, volume {}, area {}", h.faces.len(), h.vertices(), h.volume(&cube), h.surface_area(&cube));
println!("contains (0.2, 0.9, 0.5): {}", h.contains(&cube, [0.2, 0.9, 0.5], 1e-12));
let square = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]];
let diamond = [[1.0, -0.5], [2.5, 1.0], [1.0, 2.5], [-0.5, 1.0]];
for op in [BooleanOperation::Intersection, BooleanOperation::Union, BooleanOperation::Difference] {
let pieces = polygon_boolean(&square, &diamond, op);
let area: f64 = pieces.iter().map(|p| polygon_signed_area(p)).sum();
println!("{op:?}: {} piece(s), area {area:.4}", pieces.len());
}
}
2D hull [0, 2, 4, 6], area 16
3D hull: 12 faces, vertices [0, 1, 2, 3, 4, 5, 6, 7], volume 0.9999999999999999, area 6
contains (0.2, 0.9, 0.5): true
Intersection: 1 piece(s), area 3.5000
Union: 1 piece(s), area 5.0000
Difference: 4 piece(s), area 0.5000
The cube’s centre and the point in its top face are not hull vertices, and the square minus the diamond leaves four corner triangles.
Strengths
- Hulls agreeing with Qhull, and a 3D hull fast even when every point is on it.
- Boolean operations on concave polygons, with several pieces and holes.
Weaknesses
- No hulls in more than three dimensions, and no Delaunay triangulation in 3D.
- Booleans take simple polygons only (no self-intersections, no polygons with holes as input), and resolve degeneracies by perturbation rather than exactly.
Exercises
- Show that the monotone chain’s turn test removes exactly the points that are not lower-hull vertices.
- Prove that the point farthest above a hull face is a vertex of the final hull.
- Show that the faces visible from a point outside a convex polyhedron form a connected set bounded by a single cycle of edges.
- Find a set of points in the plane on which any comparison-based hull algorithm needs time. (Reduce sorting to it.)
- Work out the entry/exit rules for union and difference from those for intersection.
Hints and answers
- In the monotone chain scan, a point is popped if the last two points and it make a clockwise (or collinear) turn, i.e. it lies on or inside the line through its neighbours; only points on the lower hull stay.
- The farthest point above a face has the largest signed distance from the face plane; a plane parallel to the face through this point supports the whole point set, so it is a hull vertex.
- The visible faces form a connected set (they are the faces seen from a point, a topological disc on the sphere-like surface), so its boundary is a single closed curve of edges.
- Map sorting to hulls: given numbers , lift them to the points on a parabola; all are hull vertices, and the hull lists them in sorted order, so the hull takes .
- With each region’s edges tagged inside or outside the other polygon, intersection keeps edges inside both; union keeps edges outside both; difference keeps edges of outside and edges of inside (reversed).
Further reading
- A. M. Andrew, “Another efficient algorithm for convex hulls in two dimensions”, Information Processing Letters 9 (1979) 216–219.
- C. B. Barber, D. P. Dobkin and H. Huhdanpaa, “The Quickhull algorithm for convex hulls”, ACM Transactions on Mathematical Software 22 (1996) 469–483.
- G. Greiner and K. Hormann, “Efficient clipping of arbitrary polygons”, ACM Transactions on Graphics 17 (1998) 71–83.
- J. O’Rourke, Computational Geometry in C, 2nd ed., Cambridge University Press, 1998, chapters 3 and 4.