Skip to main content

lib_jsl_geometry/algorithms/
voronoi.rs

1//! Voronoi diagrams of 2D point sets, as the dual of the Delaunay triangulation.
2//!
3//! See the book entry [Delaunay triangulations and Voronoi diagrams](https://jwkunz.github.io/lib_jsl/book/geometry/delaunay-voronoi.html#voronoi-diagrams).
4
5use crate::algorithms::delaunay_triangulation::{Triangulation, delaunay_triangulation};
6use std::collections::BTreeSet;
7
8/// A Voronoi diagram clipped to a bounding box: the cell of each site is the convex polygon of
9/// box points closer to that site than to any other.
10#[derive(Debug, Clone)]
11
12pub struct VoronoiDiagram {
13    /// Counter-clockwise cell polygons, one per input site (empty for duplicate or non-finite
14    /// sites, which have no cell of their own).
15    pub cells: Vec<Vec<[f64; 2]>>,
16    /// The Delaunay triangulation it was built from.
17    pub triangulation: Triangulation,
18    /// The Voronoi vertices: circumcentres of the Delaunay triangles (possibly outside the box).
19    pub vertices: Vec<[f64; 2]>,
20}
21
22/// Clips a convex polygon to the half-plane `{x : (x − m)·d ≤ 0}`.
23fn clip(polygon: &[[f64; 2]], m: [f64; 2], d: [f64; 2]) -> Vec<[f64; 2]> {
24    let side = |p: [f64; 2]| (p[0] - m[0]) * d[0] + (p[1] - m[1]) * d[1];
25    let mut out = Vec::with_capacity(polygon.len() + 1);
26    for k in 0..polygon.len() {
27        let (a, b) = (polygon[k], polygon[(k + 1) % polygon.len()]);
28        let (sa, sb) = (side(a), side(b));
29        if sa <= 0.0 {
30            out.push(a);
31        }
32        if (sa < 0.0 && sb > 0.0) || (sa > 0.0 && sb < 0.0) {
33            let t = sa / (sa - sb);
34            out.push([a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]);
35        }
36    }
37    out
38}
39
40/// The Voronoi diagram of `sites` within the box `[lo, hi]`. Each cell is the box clipped by the
41/// perpendicular bisectors to the site's Delaunay neighbours, which are exactly the sites whose
42/// cells it shares an edge with. Returns `None` when the sites cannot be triangulated (fewer than
43/// three distinct points, or all collinear).
44pub fn voronoi_diagram(sites: &[[f64; 2]], lo: [f64; 2], hi: [f64; 2]) -> Option<VoronoiDiagram> {
45    let triangulation = delaunay_triangulation(sites)?;
46    let mut neighbours: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); sites.len()];
47    for (a, b) in triangulation.edges() {
48        neighbours[a].insert(b);
49        neighbours[b].insert(a);
50    }
51    let bounding = vec![lo, [hi[0], lo[1]], hi, [lo[0], hi[1]]];
52    let cells = (0..sites.len())
53        .map(|i| {
54            if neighbours[i].is_empty() {
55                return Vec::new();
56            }
57            neighbours[i].iter().fold(bounding.clone(), |cell, &j| {
58                let (s, t) = (sites[i], sites[j]);
59                clip(&cell, [(s[0] + t[0]) / 2.0, (s[1] + t[1]) / 2.0], [t[0] - s[0], t[1] - s[1]])
60            })
61        })
62        .collect();
63    let vertices = (0..triangulation.triangles.len()).map(|t| triangulation.circumcenter(sites, t)).collect();
64    Some(VoronoiDiagram { cells, triangulation, vertices })
65}
66
67/// The area of a simple polygon (positive for counter-clockwise order).
68pub fn polygon_signed_area(polygon: &[[f64; 2]]) -> f64 {
69    (0..polygon.len()).map(|k| { let (a, b) = (polygon[k], polygon[(k + 1) % polygon.len()]); a[0] * b[1] - b[0] * a[1] }).sum::<f64>() / 2.0
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    fn lcg(seed: u64) -> impl FnMut() -> f64 {
77        let mut s = seed;
78        move || {
79            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
80            (s >> 11) as f64 / (1u64 << 53) as f64
81        }
82    }
83
84    #[test]
85    fn cells_tile_the_box_and_contain_their_nearest_points() {
86        let mut r = lcg(3);
87        let sites: Vec<[f64; 2]> = (0..60).map(|_| [r() * 4.0, r() * 2.0]).collect();
88        let v = voronoi_diagram(&sites, [0.0, 0.0], [4.0, 2.0]).unwrap();
89        let total: f64 = v.cells.iter().map(|c| polygon_signed_area(c)).sum();
90        assert!((total - 8.0).abs() < 1e-9, "{total}");
91        assert!(v.cells.iter().all(|c| polygon_signed_area(c) > 0.0));
92        // Random probes: the nearest site's cell contains the probe (convex point-in-polygon).
93        for _ in 0..500 {
94            let p = [r() * 4.0, r() * 2.0];
95            let nearest = (0..sites.len()).min_by(|&a, &b| {
96                let d = |s: [f64; 2]| (s[0] - p[0]).powi(2) + (s[1] - p[1]).powi(2);
97                d(sites[a]).total_cmp(&d(sites[b]))
98            }).unwrap();
99            let cell = &v.cells[nearest];
100            let inside = (0..cell.len()).all(|k| {
101                let (a, b) = (cell[k], cell[(k + 1) % cell.len()]);
102                (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) >= -1e-12
103            });
104            assert!(inside);
105        }
106    }
107
108    #[test]
109    fn a_regular_grid_has_square_cells() {
110        let sites: Vec<[f64; 2]> = (0..4).flat_map(|i| (0..4).map(move |j| [i as f64 + 0.5, j as f64 + 0.5])).collect();
111        let v = voronoi_diagram(&sites, [0.0, 0.0], [4.0, 4.0]).unwrap();
112        assert!(v.cells.iter().all(|c| (polygon_signed_area(c) - 1.0).abs() < 1e-9));
113        assert!(voronoi_diagram(&[[0.0, 0.0], [1.0, 1.0]], [0.0, 0.0], [1.0, 1.0]).is_none());
114    }
115}