📖 Companion book (in French): this code accompanies the chapter on lines in the plane of a French book on algorithms, which presents and analyzes this algorithm.
A C# implementation of the Voronoi cell of a site restricted to a rectangle — the zone served by an antenna, a fire station or a school: the points of an area of study R closer to the site than to any other. The cell is obtained by clipping R with perpendicular bisectors, the closest sites first, with a pruning that stops after about a dozen bisectors whatever the number of sites. Its two building blocks are the perpendicular bisector as a Cartesian line and the clipping of a convex polygon by a half-plane; on top of the cell come its area, the population it serves, and the whole diagram. An MSTest suite checks the cells against their definition, and a Windows Forms viewer draws the zone served by any site, replays the loop site by site and measures its cost.
As in the companion repositories sorting-algorithms, douglas-peucker and convex-hull, readability comes first: the code keeps the usual notations (S, R, Q, i, j, r, f, λ), each step is a method of its own, and the algorithm needs no square root, no normalization of a line and a single division per side cut.
The viewer on 80 antennas gathered around towns (seed 3), with the 20,000 inhabitants of the territory. The cell of the site s63 (in blue) has 6 vertices, an area of 11.35 km² and serves 626 inhabitants (in blue). The loop examined 30 bisectors out of 79 and stopped at s42: its bisector (dashed red), whose closest point to s63 is m, misses the disk of radius r (dotted) that contains the cell, and so do the bisectors of the 48 farther sites. The whole diagram is drawn in gray.
The Voronoi cell of a site S[i] among n sites S[0], …, S[n − 1] is the set of the points p at least as close to S[i] as to any other site. For each other site S[j], the points closer to S[i] form a half-plane bounded by the perpendicular bisector of [S[i] S[j]]: the cell restricted to the rectangle R is the intersection of R with these n − 1 half-planes, a convex polygon.
| Step | Method | Idea | Time |
|---|---|---|---|
| Perpendicular bisector | CartesianLine.PerpendicularBisector |
the line a x + b y + c = 0 with a = x_B − x_A, b = y_B − y_A, c = −(a (x_A + x_B) + b (y_A + y_B))/2; then f(p) = a x + b y + c = (‖p − A‖² − ‖p − B‖²)/2, so that f(p) ≤ 0 iff p is at least as close to A as to B | Θ(1) |
| Clipping by a half-plane | PolygonClipping.ClipConvexPolygon |
the vertices q_k with f(q_k) ≤ 0 are kept; on each side whose endpoints have values of strictly opposite signs, the crossing point q_k + λ(q_{k+1} − q_k), with λ = f_k/(f_k − f_{k+1}), is inserted | Θ(m) |
| Cell with pruning | VoronoiCellBuilder.Compute |
R is clipped by the bisectors of the other sites, sorted by increasing distance to S[i]; the loop stops at the first site S[j] with ‖S[j] − S[i]‖² > 4r², where r is the largest distance from S[i] to a vertex of the current cell | O(n log n + k m), Θ(n²) worst case |
| Cell without pruning | VoronoiCellBuilder.ComputeWithoutPruning |
the same clippings, by the n − 1 bisectors | Θ(n m) |
| Whole diagram | VoronoiCellBuilder.AllCells |
each cell computed independently, with the pruning | O(n² log n) in practice |
m is the number of vertices of the cell and k the number of bisectors examined.
Why the pruning is right. The disk centered on S[i] of radius r contains the current cell. The point of the bisector of [S[i] S[j]] closest to S[i] is the midpoint m of the segment, at the distance ‖S[j] − S[i]‖/2: if ‖S[j] − S[i]‖² > 4r², the bisector misses the disk and leaves the cell unchanged. The sites coming by increasing distance and the cell only shrinking, the bisectors of all the farther sites miss it too, and the loop can stop. On uniform sites it stops after about a dozen bisectors, so that the sort dominates; for a site surrounded by the others on a circle, it eliminates nothing and the cell grows to n − 1 vertices.
The cell answers the questions of the application:
- Zone served —
Computegives the polygon, counterclockwise, with its cost and, on demand, every iteration of the loop. - Area and perimeter —
Polygons.Area(shoelace formula) andPolygons.Perimeter. - Population —
Polygons.CountInsidecounts the inhabitants of a cell;VoronoiCellBuilder.CountServedcounts the same inhabitants without the cell, by looking for a site closer than S[i], with the argument of the pruning. - Nearest site —
VoronoiCellBuilder.NearestSitefinds the site that serves a point by examining every site, the question solved without the cells.
| Project | Content |
|---|---|
VoronoiCell.Core |
The perpendicular bisector, the clipping, the cell with and without pruning, the whole diagram, the area and the population of a cell, and site generators (class library) |
VoronoiCell.Tests |
MSTest suite: the 8 sample sites checked iteration by iteration and their whole diagram, special cases of the bisector and of the clipping, the definition of the cell on varied configurations, the same cell with and without pruning, cells covering R, population counted in two ways, cost |
VoronoiCell.Viewer |
Windows Forms application: generated or mouse-edited sites, cell of the chosen site with its area and its population, step-by-step mode, cost measured as n grows |
- A .NET SDK, 5.0 or later (tested with the .NET 10 SDK).
- The .NET 5.0 runtime to run the tests and the viewer: the .NET Runtime for the tests, the .NET Desktop Runtime for the viewer (both come with the .NET 5.0 SDK).
- Windows for the viewer. The library and the tests do not depend on Windows.
The projects target net5.0, which is out of support: the target is chosen on purpose, to stay consistent with the companion repositories, and the warning NETSDK1138 is silenced in Directory.Build.props.
Open VoronoiCell.sln in Visual Studio 2022 or later, or in JetBrains Rider; in Visual Studio Code, install the C# Dev Kit. Everything also works from the command line with the dotnet CLI.
git clone https://github.com/pothinjb/voronoi-cell.git
cd voronoi-cell
dotnet build VoronoiCell.sln
dotnet test VoronoiCell.Tests
dotnet run -c Release --project VoronoiCell.ViewerRun a single test class:
dotnet test VoronoiCell.Tests --filter "FullyQualifiedName~SampleSitesTests"Run the viewer in Release to measure the times: the timings below were measured in Release.
using System;
using VoronoiCell.Core;
Point2D[] S = Sites.Sample(); // 8 sites, s0 = (6;4)
Rectangle2D R = Sites.SampleRectangle; // [0;13] × [0;9]
// The cell of s0 in R: a convex polygon, counterclockwise
CellResult cell = VoronoiCellBuilder.Compute(S, 0, R);
// (8.289;5.553) (4.722;6.444) (3.333;3.667) (6;1) (8.667;3.667)
double area = cell.Area; // 17.714
int examined = cell.BisectorsExamined; // 6 bisectors out of n − 1 = 7
int stop = cell.StopSite; // 7: ‖s7 − s0‖² = 45 > 4r² = 36
double r2 = cell.RadiusSquared; // 9, reached at (6;1)
// The same cell without the pruning, by the 7 bisectors
CellResult all = VoronoiCellBuilder.ComputeWithoutPruning(S, 0, R); // the same polygon
// The two building blocks: the bisector, and the clipping by the half-plane f ≤ 0 on the side of s0
CartesianLine h = CartesianLine.PerpendicularBisector(S[0], S[1]); // (1, 4, -30.5): x + 4y − 30.5 = 0
Point2D[] Q = PolygonClipping.ClipConvexPolygon(R.Corners(), h); // (0;0) (13;0) (13;4.375) (0;7.625)
// The zone served by an antenna, and its population
Rectangle2D territory = Sites.Territory; // 40 km × 30 km
Point2D[] antennas = Sites.Towns(80, 3, territory);
Point2D[] people = Sites.Population(20000, 3, territory);
CellResult zone = VoronoiCellBuilder.Compute(antennas, 63, territory); // 6 vertices, 11.35 km²
int inside = Polygons.CountInside(zone.Polygon, people); // 626 inhabitants
int served = VoronoiCellBuilder.CountServed(antennas, 63, people); // 626 too, without the cell
// The loop, iteration by iteration
foreach (CellStep step in VoronoiCellBuilder.Compute(S, 0, R, recordSteps: true).Steps)
{
Console.WriteLine(step);
}The last loop prints:
s1: 17 ≤ 4r² = 296, 2 sides cut, 4 → 4 vertices
s2: 18 ≤ 4r² = 260, 2 sides cut, 4 → 5 vertices
s3: 18 ≤ 4r² = 260, 2 sides cut, 5 → 4 vertices
s4: 20 ≤ 4r² = 196.563, 2 sides cut, 4 → 4 vertices
s5: 26 ≤ 4r² = 72.08, 2 sides cut, 4 → 5 vertices
s6: 29 ≤ 4r² = 36, cell unchanged
s7: 45 > 4r² = 36, stop
The input sites are copied, never modified. Every public type and member carries XML documentation (cost, preconditions, conventions), so IntelliSense is the quickest way to explore the API.
Point2Dhas real coordinates (double): positions of antennas in kilometers, of inhabitants, vertices of a cell. It formats as(x;y). The coordinates of the sites and of the rectangle must be finite and bounded byVoronoiCellBuilder.MaxCoordinate= 10⁷⁵: beyond, the values f[k] or the squared distances could overflow.- The sites are sorted lexicographically on (‖S[j] − S[i]‖², j): at equal distance, the smallest index comes first, so that s2 precedes s3 in the sample (both at the squared distance 18).
CellResultgives the cell (Polygon, counterclockwise, empty if it does not meet R), the order of the sites (Order), the cost (SitesTested,BisectorsExamined,VertexEvaluations: the vertices scanned for r² and for the values f_k,EdgesCut: the divisions,MaxVertices), the site that stopped the loop (StopSite, −1 if every site was examined) and the disk of the final cell (RadiusSquared,FarthestVertex). WithrecordSteps,Stepslists the iterations (CellStep: site, squared distance, r², bisector, sides cut, cell before and after, outcome).- The outcome of an iteration is
Clippedif the bisector cuts the cell,Unchangedif every f_k is ≤ 0 (no side cut, the same number of vertices: the case of s6 in the sample),Stopif the test ‖S[j] − S[i]‖² > 4r² ends the loop. PolygonClippingkeeps the vertices in the order of the polygon and returns at most m + 1 of them. Only the ratio of f_k and f_{k+1} matters: the line needs no normalization, and (a, b, c) and (4a, 4b, 4c) give the same points, bit for bit.Polygons.CountInsidelocates each inhabitant in a convex polygon by the signs of the cross products, after a bounding-box test.VoronoiCellBuilder.CountServedcounts the same inhabitants without the cell, by looking for a site closer than S[i] among the sorted sites, with the argument of the pruning: if ‖S[j] − S[i]‖ > 2‖p − S[i]‖, neither S[j] nor the farther sites are closer to p than S[i]. The two counts check each other.Sitesprovides the 8 sample sites and configurations that illustrate the application or its limits: antennas spread uniformly over a territory of 40 km × 30 km, antennas gathered around towns, a regular network (jittered grid), a site surrounded on a circle (the worst case), and a population of 20,000 inhabitants (75 % in 8 towns, 25 % in the countryside).
- A single site: its cell is R, without any bisector.
- A site outside R: its cell may still meet R, or be empty. Once the cell is empty, the largest distance r is no longer defined, and the loop stops with an empty cell (
StopSite= −1,Area= 0). - A site equal to S[i] comes first in the sort (distance 0), gives the bisector (0, 0, 0) and leaves the cell unchanged: two equal sites have the same cell.
- Collinear sites: the cells are bands between parallel bisectors.
ClipConvexPolygoncopies once a vertex that lies exactly on the line, without inserting a crossing point; it returns the polygon unchanged for a half-plane that contains it or for the line (0, 0, 0), and an empty polygon for a half-plane that misses it.- A
nullcollection throwsArgumentNullException; an index outside [0; n − 1], a rectangle with x0 ≥ x1 or y0 ≥ y1, or a coordinate that is infinite, NaN or beyondMaxCoordinatethrowsArgumentOutOfRangeException. ComputeWithoutPruningclips by the n − 1 bisectors in the same order, without the stopping test; the tests check that it returns the same cell.- For the drawing, the bisector of the site that stops the loop is computed and recorded in
CellStep.Bisector, although the algorithm does not need it; likewise, r² is recorded without pruning when the steps are recorded.
- Sample sites. The tests check every value on
Sites.Sample:- the squared distances to s0: 17, 18, 18, 20, 26, 29 and 45;
- the successive values of r²: 74, 65, 65, 3145/64, 901/50, then 9 for s6 and s7;
- after s5, a cell of five vertices, (315/38; 211/38), (85/18; 58/9), (10/3; 11/3), (6; 1) and (26/3; 11/3), of area 24233/1368 ≈ 17.71;
- r² = 9 given by (6;1), hence 4r² = 36: s6 (29 ≤ 36) leaves the cell unchanged and s7 (45 > 36) stops the loop;
- the bisector of s0 and s7 crosses R from (7.75;0) to (12.25;9), and its midpoint m = (9;2.5) is at √45/2 ≈ 3.35 > 3 from s0;
- the eight cells of the whole diagram cover exactly the 117 units of area of R.
- Number of sides. A cell has fewer than six sides on average, for any configuration in general position: on the diagram restricted to R, Euler's formula gives an average of 6 − (k + 2)/n sides, where k is the number of edges of the diagram that end on the boundary of R (k = 7 and 39/8 = 4.875 sides for the sample). On 200 cells of 1,000 or 10,000 uniform sites, the measured average is 5.93; on the samples of 40 cells of the table below, it ranges from 5.65 to 6.30.
- Precision. The cells of the whole diagram are computed independently: two neighboring cells do not share exactly their vertices. On the configurations of 500 sites of the tests, the sum of the areas differs from the area of R by less than 10⁻¹⁵ in relative value.
- Pruning. On uniform sites, the loop examines about a dozen bisectors on average and about thirty at most, whatever n from 1,000 to 256,000 (table below): the sort dominates. On the circle, the pruning eliminates nothing, the cell grows to n − 1 vertices and the cost is in Θ(n²).
In Release (Cost versus n in the viewer), on 40 random cells for each n:
| Uniform sites, n | bisectors examined (mean) | at most | vertices (mean) | sort | total |
|---|---|---|---|---|---|
| 1,000 | 12.5 | 24 | 5.65 | 0.13 ms | 0.14 ms |
| 16,000 | 13.4 | 30 | 5.78 | 2.9 ms | 3.0 ms |
| 256,000 | 12.7 | 24 | 6.30 | 58 ms | 60 ms |
| Circle, n | bisectors examined | vertices | vertices scanned / n² | time |
|---|---|---|---|---|
| 1,001 | 1,000 | 1,000 | 1.00 | 14 ms |
| 4,001 | 4,000 | 4,000 | 1.00 | 190 ms |
| 16,001 | 16,000 | 16,000 | 1.00 | 3.25 s |
On uniform sites, the sort of the n − 1 sites takes almost all the time: the dozen clippings that follow are negligible. On the circle, each iteration scans twice the vertices of the current cell (for r² and for the values f_k), whose number grows by one with each bisector: about n² vertices scanned in total.
- Sites: scenario, number of sites and seed. On the canvas, the left button selects a site, drags it (the cell follows live) or adds one elsewhere; a right click on a site removes it, a right drag pans the view, the wheel zooms and a right double click fits the view.
- Cell: with pruning or without pruning; index i of the site.
- Display: the rectangle R, the whole diagram in gray (up to 2,000 sites), the cell in blue, the disk of radius r dotted with its radius drawn to the farthest vertex, and the bisector of the site that stops the loop in dashed red with its point m closest to S[i]. Population shows the 20,000 inhabitants, those of the cell in blue. The labels s_j are written up to 60 sites.
- Step by step: replays the iterations of the loop (up to 5,000 sites). Each step shows the cell before the iteration, the part that the bisector removes (in light red), the bisector (red if it cuts the cell, green if the cell is unchanged, dashed red if the loop stops), the midpoint m and the disk, and rings the sites already processed. The results box details the disk, the test, the bisector and the clipping, and lists the iterations done so far.
- The results box gives the bisectors examined, the site that stopped the loop and its test, the vertices of the cell (up to 30), its area and its perimeter, the population counted with the cell and without it, the cost (sort alone, whole computation, vertices scanned, divisions, largest cell) and, for the whole diagram, the gap between the sum of the areas and the area of R.
- Cost versus n: measures the cost on uniform sites for n = 1,000 to 256,000, then on the circle for n = 1,001 to 16,001.
- Examples to try: in the sample, move s6 closer to s0 until its bisector cuts the cell; the scenario Site surrounded on a circle shows a pruning that eliminates nothing; a site moved outside R keeps a cell as long as it is the closest site to a part of R; Antennas around towns with the population, as in the screenshot.
VoronoiCell.sln
├── Directory.Build.props # settings shared by the projects (C# 9, net5.0 kept on purpose)
├── VoronoiCell.Core/ # class library
│ ├── Point2D.cs # point with real coordinates
│ ├── Rectangle2D.cs # area of study R and its corners
│ ├── CartesianLine.cs # line a x + b y + c = 0, perpendicular bisector
│ ├── PolygonClipping.cs # clipping of a convex polygon by a half-plane
│ ├── Polygons.cs # cross product, area, perimeter, farthest vertex, point in a convex polygon
│ ├── VoronoiCellBuilder.cs # cell with and without pruning, whole diagram, nearest site, population served
│ ├── CellResult.cs, CellStep.cs # the cell, its cost and the iterations of the loop
│ └── Sites.cs # sample, antennas, towns, regular network, circle, population
├── VoronoiCell.Tests/ # MSTest suite
└── VoronoiCell.Viewer/ # Windows Forms viewer
- Floating point — the coordinates are real numbers, without any tolerance ε: the cells of two neighboring sites, computed independently, may overlap or leave a thin gap between them, and an inhabitant lying exactly on their common edge may be counted in both or in neither. The coordinates are limited to 10⁷⁵ in absolute value, otherwise
ArgumentOutOfRangeExceptionis thrown. - Worst case — when the sites surround S[i] on a circle, the pruning eliminates nothing and the cost is in Θ(n²); this is a property of the algorithm, not of the implementation.
- Whole diagram —
AllCellscomputes the n cells independently, in O(n² log n) because of the n sorts: Fortune's sweep line or the dual Delaunay triangulation build the whole diagram in O(n log n). - Rectangle only — the area of study is a rectangle with sides parallel to the axes; any convex polygon would do as the initial cell, but the API does not accept one.
- Viewer — Windows only; the whole diagram up to 2,000 sites, the step-by-step mode up to 5,000.
Issues and pull requests are welcome — bug fixes, new algorithms (Fortune's sweep line, Delaunay triangulation, power diagrams), more tests or better visualizations.
- Comments, XML documentation, test messages and user interface texts are in English.
- Keep the usual notations: short names (
S,R,Q,i,j,r2,f,lambda…), as in the rest of the code. - Keep the computations simple: squared distances rather than distances, no normalization of the lines, a single division per side cut.
- Document every public type and member with XML comments (summary, cost, preconditions).
- Run
dotnet test VoronoiCell.Testsbefore opening a pull request.
- G. Voronoi, "Nouvelles applications des paramètres continus à la théorie des formes quadratiques. Deuxième mémoire : recherches sur les parallélloèdres primitifs", Journal für die reine und angewandte Mathematik 134, 1908, pp. 198–287.
- I. E. Sutherland, G. W. Hodgman, "Reentrant polygon clipping", Communications of the ACM 17(1), 1974, pp. 32–42 — the clipping by the successive sides of a convex window.
- S. Fortune, "A sweepline algorithm for Voronoi diagrams", Algorithmica 2, 1987, pp. 153–174.
- F. Aurenhammer, "Voronoi diagrams — a survey of a fundamental geometric data structure", ACM Computing Surveys 23(3), 1991, pp. 345–405.
- A. Okabe, B. Boots, K. Sugihara, S. N. Chiu, Spatial Tessellations: Concepts and Applications of Voronoi Diagrams, 2nd ed., Wiley, 2000.
- M. de Berg, O. Cheong, M. van Kreveld, M. Overmars, Computational Geometry: Algorithms and Applications, 3rd ed., Springer, 2008 — chapter 7, Voronoi diagrams.
- Voronoi diagram and Sutherland–Hodgman algorithm on Wikipedia.
Released under the MIT License.
