kika 0.7.1

Robust 2D kernel for Rust: exact predicates, Delaunay triangulation, constrained Delaunay triangulation, and simple-polygon triangulation, with adaptive/exact fallback arithmetic. No CMake, no Boost, no GMP/MPFR, WASM-ready.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
//! Voronoi diagram topology and geometry: the dual of a
//! [`Triangulation2`].
//!
//! ADR-007 (0.5.0) built the internal data model, the [`voronoi2`]
//! constructor, an internal validator, the public query API (`cells`,
//! `vertices`, `edges`, and the accessors on each), and the ordered
//! `cell_edges` boundary walk -- topology only, no coordinates. ADR-009
//! (0.7.0) adds the geometry layer on top: [`Voronoi2::vertex_point`]
//! (circumcenters) and [`Voronoi2::edge_geometry`] (segments/rays). See
//! `docs/adr/ADR-007-voronoi-diagram-topology.md` and
//! `docs/adr/ADR-009-voronoi-geometry.md` for the full design and
//! correctness arguments this module implements.

use super::delaunay2::Triangulation2;
use super::ids::{EdgeId, FaceId, VertexId};
use crate::predicates::{Orientation, Sign, circumcenter, incircle, orient2d};
use crate::primitives::{Point2, Vector2};

/// A Voronoi cell, identified with the [`VertexId`] of the Delaunay site
/// it surrounds -- a true bijection, so no separate cell table is kept.
///
/// Valid only for the [`Voronoi2`] that produced it -- comparing or
/// indexing with a handle from a different `Voronoi2` is not checked and
/// will silently look up the wrong element or panic (same convention as
/// [`VertexId`]'s own cross-triangulation caveat).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VoronoiCellId(pub(super) VertexId);

/// A Voronoi vertex: the dual of one connected group of Delaunay faces
/// merged by cocircularity (§"Cocircular tie-break normalization",
/// ADR-007). Usually one face, but every face in a cocircular cluster
/// (e.g. all faces of a triangulated square) shares a single
/// `VoronoiVertexId`, since they share a single true circumcenter.
///
/// See [`VoronoiCellId`]'s doc comment for the cross-`Voronoi2` caveat.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VoronoiVertexId(pub(super) u32);

/// A Voronoi edge: the dual of a Delaunay edge whose two sides fall in
/// different face groups (an excluded same-group Delaunay edge is a
/// spurious artifact of the input triangulation's tie-break, not a real
/// Voronoi edge -- see [`voronoi2`]).
///
/// See [`VoronoiCellId`]'s doc comment for the cross-`Voronoi2` caveat.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VoronoiEdgeId(pub(super) u32);

/// Whether a [`VoronoiEdge`] is a finite segment between two Voronoi
/// vertices, or an infinite ray from one Voronoi vertex out to infinity.
///
/// `#[non_exhaustive]`: closed only for the current problem scope (≥3
/// non-collinear sites). Degenerate inputs (0-2 sites, or all sites
/// collinear) will need a future `Line`-shaped variant this crate doesn't
/// yet support, unlike e.g. [`Sign`], which is mathematically complete
/// forever.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VoronoiEdgeKind {
    /// A finite segment between two Voronoi vertices.
    Bounded {
        /// The segment's two endpoints.
        vertices: [VoronoiVertexId; 2],
    },
    /// An infinite ray from `finite_vertex` out to infinity, dual to a
    /// convex-hull edge of the Delaunay triangulation.
    Unbounded {
        /// The ray's single finite endpoint.
        finite_vertex: VoronoiVertexId,
    },
}

/// One edge of a Voronoi diagram: the two cells it separates, its shape
/// (bounded segment or unbounded ray), and the Delaunay edge it is dual
/// to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct VoronoiEdge {
    /// The two cells (sites) this edge separates.
    pub cells: [VoronoiCellId; 2],
    /// The dual Delaunay edge, kept as provenance/debugging metadata --
    /// not needed to interpret `cells`/`kind`, which are self-sufficient.
    pub source_edge: EdgeId,
    /// Whether this edge is a finite segment or an infinite ray.
    pub kind: VoronoiEdgeKind,
}

/// Why [`Voronoi2::vertex_point`]/[`Voronoi2::edge_geometry`] couldn't
/// produce a coordinate (ADR-009).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VoronoiGeometryError {
    /// The true circumcenter is not representable as a finite [`Point2`]
    /// -- either the defining face is exactly collinear (no circumcircle
    /// exists at all; not expected to be reachable from a valid
    /// [`Triangulation2`], checked rather than trusted), or the face is
    /// thin enough that its true, finite, well-defined circumradius
    /// overflows `f64`'s representable range. Never a `NaN`/`Infinity`
    /// leaking into a `Point2`.
    NonFiniteCircumcenter,
    /// An internal topology invariant this method depends on didn't hold
    /// -- e.g. a `VoronoiVertexId`'s face group was empty, or an
    /// `Unbounded` edge's source Delaunay edge had no incident face.
    /// Never expected from a [`Voronoi2`] built by [`voronoi2`] (matching
    /// `docs/adr/ADR-008-point-location.md`'s posture:
    /// `validate_topology()` is a test-only diagnostic, never a
    /// construction-time gate a public method may assume) -- returned
    /// rather than panicking so a caller holding a
    /// hand-assembled/corrupted instance gets a typed error, not a crash.
    InvalidTopology,
}

/// The actual geometry of a [`VoronoiEdge`] (ADR-009): a bounded segment
/// between two Voronoi vertex coordinates, or an unbounded ray from one.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VoronoiEdgeGeometry {
    /// A finite segment between two Voronoi vertex coordinates.
    ///
    /// `start`/`end` carry no orientation meaning -- which one is
    /// `start` is incidental to internal Delaunay face-adjacency order
    /// (unlike `VoronoiEdgeId`/`VoronoiVertexId`, this pair is not
    /// canonically sorted). Treat the pair as unordered.
    Segment {
        /// One of the segment's two endpoints.
        start: Point2,
        /// The segment's other endpoint.
        end: Point2,
    },
    /// An infinite ray from `origin` in `direction`.
    Ray {
        /// The ray's single finite endpoint.
        origin: Point2,
        /// The ray's outward direction. **Not normalized** -- an
        /// unnormalized vector, each component a single correctly-rounded
        /// `f64` coordinate difference (not a fully exact one -- see
        /// `docs/adr/ADR-009-voronoi-geometry.md`'s "Determining the ray
        /// direction" section). This crate has no `sqrt`/normalize
        /// anywhere; a caller wanting a unit direction normalizes it
        /// themselves.
        direction: Vector2,
    },
}

/// A 2D Voronoi diagram: the dual of a [`Triangulation2`], owned by value
/// (no lifetime parameter), matching
/// [`super::ConstrainedTriangulation2`]'s precedent.
///
/// Topology (which cells/vertices/edges exist and how they connect) is
/// available unconditionally via the query API below. Geometry
/// (`vertex_point`/`edge_geometry`, ADR-009) is fallible and computed on
/// demand, not cached -- see those methods' own doc comments.
#[derive(Debug, Clone, PartialEq)]
pub struct Voronoi2 {
    delaunay: Triangulation2,
    /// Dense, indexed by `FaceId::raw()`: which Voronoi vertex (face
    /// group) each Delaunay face belongs to.
    face_group: Vec<VoronoiVertexId>,
    /// Dense, indexed by `VoronoiVertexId`'s inner `u32`: the inverse of
    /// `face_group`, each group's member faces (sorted by `FaceId::raw()`
    /// for this instance's own internal determinism).
    group_faces: Vec<Vec<FaceId>>,
    /// Dense, indexed by `VoronoiEdgeId`'s inner `u32`, in canonical
    /// (cell-pair-key-sorted) order.
    edges: Vec<VoronoiEdge>,
}

/// Union-find (disjoint-set) over Delaunay `FaceId`s, path-compressed
/// only -- no union-by-rank. Face counts here are small enough that this
/// is not a bottleneck, and performance tuning is explicitly out of scope
/// for this phase (ADR-007 Phase 7A).
struct UnionFind {
    parent: Vec<u32>,
}

impl UnionFind {
    fn new(n: usize) -> Self {
        UnionFind {
            parent: (0..n as u32).collect(),
        }
    }

    fn find(&mut self, x: u32) -> u32 {
        if self.parent[x as usize] != x {
            let root = self.find(self.parent[x as usize]);
            self.parent[x as usize] = root;
        }
        self.parent[x as usize]
    }

    fn union(&mut self, a: u32, b: u32) {
        let ra = self.find(a);
        let rb = self.find(b);
        if ra != rb {
            self.parent[ra as usize] = rb;
        }
    }
}

/// Every distinct `VertexId` among `faces`' vertices, sorted and
/// deduplicated -- the canonical key a face group is sorted and assigned
/// a dense [`VoronoiVertexId`] by (ADR-007 "Canonical dense ID
/// assignment").
fn group_key(delaunay: &Triangulation2, faces: &[FaceId]) -> Vec<u32> {
    let mut verts: Vec<u32> = faces
        .iter()
        .flat_map(|&f| delaunay.face_vertices(f))
        .map(VertexId::raw)
        .collect();
    verts.sort_unstable();
    verts.dedup();
    verts
}

/// The sorted pair of `VertexId::raw()` a [`VoronoiEdge`]'s `cells`
/// resolve to -- the canonical key a Voronoi edge is sorted and assigned
/// a dense [`VoronoiEdgeId`] by.
fn edge_key(cells: [VoronoiCellId; 2]) -> [u32; 2] {
    let mut k = [cells[0].0.raw(), cells[1].0.raw()];
    k.sort_unstable();
    k
}

/// A triangle's third vertex, given the other two (an edge it shares with
/// a neighboring face). Panics only if `face` doesn't actually have `u`
/// and `v` among its vertices -- which cannot happen for a `face`/`edge`
/// pair drawn from `delaunay.adjacent_faces(edge)`, an invariant
/// `Triangulation2` itself is responsible for and already validated by
/// (`TopologyError::AdjacencyMismatch`).
fn third_vertex(delaunay: &Triangulation2, face: FaceId, u: VertexId, v: VertexId) -> VertexId {
    delaunay
        .face_vertices(face)
        .into_iter()
        .find(|&w| w != u && w != v)
        .expect("a triangle's vertices must include a 3rd vertex besides its shared edge's two")
}

/// `pv - pu` as a [`Vector2`], guaranteed finite for any two finite,
/// distinct points -- unlike a plain `Point2 - Point2`, which can
/// overflow to a non-finite `Vector2` when `pu`/`pv` have opposite-sign,
/// near-`f64::MAX`-magnitude coordinates on some axis.
///
/// The plain difference is used whenever it doesn't overflow -- always
/// finite, always the correctly-rounded (often exact, by Sterbenz's
/// lemma) true difference, so this changes nothing for any coordinate
/// range this crate's own tests already exercise. The fallback only
/// triggers when a component difference overflows, which (for finite
/// operands) requires both `pu` and `pv` to already be within a small
/// factor of `f64::MAX` in magnitude with opposite signs on that axis --
/// meaning the *true* difference on the overflowing axis is itself
/// astronomically large, not a fine geometric detail close to `pu`/`pv`.
/// Rescaling both points by a fixed `2^-600` first (an exact
/// power-of-two multiply, then a single subtraction) brings that axis
/// back into finite range losing no meaningful precision -- but the
/// *other* axis, if its true difference happens to be extremely small
/// (e.g. `1e-300`), can underflow to exactly `0.0` under the same fixed
/// factor. Harmless in practice: that axis is negligible next to the
/// overflowing one regardless (the resulting direction is off by an
/// angle on the order of `1e-600` radians, far below any representable
/// or practically meaningful precision) -- but "no meaningful precision
/// lost" is a claim about the overflowing axis specifically, not both.
/// Never scaled back either way -- `outward_ray_direction`'s output has
/// no magnitude contract, only a side (via `orient2d`, computed
/// separately from the original, unscaled points) and non-zero-ness,
/// both preserved by any positive uniform rescale.
fn edge_vector(pu: Point2, pv: Point2) -> Vector2 {
    let dx = pv.x() - pu.x();
    let dy = pv.y() - pu.y();
    if dx.is_finite() && dy.is_finite() {
        return Vector2::new_unchecked(dx, dy);
    }
    let s = 2f64.powi(-600);
    Vector2::new_unchecked(pv.x() * s - pu.x() * s, pv.y() * s - pu.y() * s)
}

/// Builds the [`Voronoi2`] topology dual to `delaunay`.
///
/// Adjacent Delaunay faces whose shared edge is cocircular with both
/// opposite vertices (`incircle(..) == Sign::Zero`) are merged via
/// union-find into one Voronoi vertex, so an arbitrary Delaunay
/// tie-break among cocircular sites (`delaunay2`'s own documented
/// behavior) never leaks into the Voronoi topology as spurious extra
/// vertices/edges. Every dense ID (`VoronoiVertexId`, `VoronoiEdgeId`) is
/// assigned by sorting on a canonical key derived from site identity, not
/// from union-find root values or face-scan order, so two differently
/// triangulated-but-topologically-equal inputs produce identical (not
/// merely isomorphic) output. Always succeeds -- no fallible variant is
/// needed, since every input, including degenerate ones, has a
/// well-defined (possibly empty) dual.
///
/// # Examples
///
/// ```
/// use kika::{Point2, VoronoiEdgeKind, delaunay2, voronoi2};
///
/// let pts = [
///     Point2::new(0.0, 0.0).unwrap(),
///     Point2::new(4.0, 0.0).unwrap(),
///     Point2::new(0.0, 4.0).unwrap(),
/// ];
/// let voronoi = voronoi2(delaunay2(&pts));
///
/// // One cell per site, one Voronoi vertex (the triangle's circumcenter),
/// // and 3 unbounded rays -- no interior Delaunay edge to exclude.
/// assert_eq!(voronoi.cells().count(), 3);
/// assert_eq!(voronoi.vertices().count(), 1);
/// for edge in voronoi.edges() {
///     assert!(matches!(
///         voronoi.edge_kind(edge),
///         VoronoiEdgeKind::Unbounded { .. }
///     ));
/// }
/// ```
pub fn voronoi2(delaunay: Triangulation2) -> Voronoi2 {
    let n_faces = delaunay.faces().count();
    let mut uf = UnionFind::new(n_faces);
    let coord: Vec<_> = delaunay.vertices().map(|(_, p)| p).collect();

    for edge in delaunay.edges() {
        if let [Some(f1), Some(f2)] = delaunay.adjacent_faces(edge) {
            let (u, v) = delaunay.edge_vertices(edge);
            let a = third_vertex(&delaunay, f1, u, v);
            let b = third_vertex(&delaunay, f2, u, v);
            let cocircular = incircle(
                coord[u.raw() as usize],
                coord[v.raw() as usize],
                coord[a.raw() as usize],
                coord[b.raw() as usize],
            ) == Sign::Zero;
            if cocircular {
                uf.union(f1.raw(), f2.raw());
            }
        }
    }

    let mut by_root: std::collections::HashMap<u32, Vec<FaceId>> = std::collections::HashMap::new();
    for f in delaunay.faces() {
        by_root.entry(uf.find(f.raw())).or_default().push(f);
    }

    // Canonical order: sort groups by their site-identity key. Iteration
    // order over `by_root` (a HashMap) never leaks into the result --
    // only the *content* of each group's key determines its final
    // position.
    let mut keyed_groups: Vec<(Vec<u32>, Vec<FaceId>)> = by_root
        .into_values()
        .map(|mut faces| {
            faces.sort_unstable_by_key(|f| f.raw());
            (group_key(&delaunay, &faces), faces)
        })
        .collect();
    keyed_groups.sort_unstable_by(|a, b| a.0.cmp(&b.0));

    let mut face_group = vec![VoronoiVertexId(0); n_faces];
    let mut group_faces = Vec::with_capacity(keyed_groups.len());
    for (i, (_, faces)) in keyed_groups.into_iter().enumerate() {
        for &f in &faces {
            face_group[f.raw() as usize] = VoronoiVertexId(i as u32);
        }
        group_faces.push(faces);
    }

    let mut raw_edges: Vec<VoronoiEdge> = Vec::new();
    for edge in delaunay.edges() {
        let (u, v) = delaunay.edge_vertices(edge);
        let cells = [VoronoiCellId(u), VoronoiCellId(v)];
        match delaunay.adjacent_faces(edge) {
            [Some(f), None] | [None, Some(f)] => {
                raw_edges.push(VoronoiEdge {
                    cells,
                    source_edge: edge,
                    kind: VoronoiEdgeKind::Unbounded {
                        finite_vertex: face_group[f.raw() as usize],
                    },
                });
            }
            [Some(f1), Some(f2)] => {
                let g1 = face_group[f1.raw() as usize];
                let g2 = face_group[f2.raw() as usize];
                if g1 != g2 {
                    raw_edges.push(VoronoiEdge {
                        cells,
                        source_edge: edge,
                        kind: VoronoiEdgeKind::Bounded { vertices: [g1, g2] },
                    });
                }
                // else: both sides in the same cocircular group -- a
                // spurious artifact of the Delaunay tie-break, excluded.
            }
            [None, None] => unreachable!("a Triangulation2 edge always has at least one face"),
        }
    }

    raw_edges.sort_unstable_by_key(|e| edge_key(e.cells));

    Voronoi2 {
        delaunay,
        face_group,
        group_faces,
        edges: raw_edges,
    }
}

impl Voronoi2 {
    /// Every cell -- one per Delaunay site, a bijection with
    /// [`Triangulation2::vertices`].
    pub fn cells(&self) -> impl Iterator<Item = VoronoiCellId> + '_ {
        self.delaunay.vertices().map(|(v, _)| VoronoiCellId(v))
    }

    /// Every Voronoi vertex (one per cocircular-merged Delaunay face
    /// group).
    pub fn vertices(&self) -> impl Iterator<Item = VoronoiVertexId> + '_ {
        (0..self.group_faces.len()).map(|i| VoronoiVertexId(i as u32))
    }

    /// Every Voronoi edge.
    pub fn edges(&self) -> impl Iterator<Item = VoronoiEdgeId> + '_ {
        (0..self.edges.len()).map(|i| VoronoiEdgeId(i as u32))
    }

    /// The Delaunay site `cell` surrounds.
    pub fn cell_site(&self, cell: VoronoiCellId) -> VertexId {
        cell.0
    }

    /// Every cell adjacent to `cell` across a Voronoi edge -- the other
    /// endpoint of every edge incident to `cell` (an excluded,
    /// same-group Delaunay edge never contributes one, since it never
    /// became a `VoronoiEdge` at all).
    ///
    /// # Examples
    ///
    /// ```
    /// use kika::{Point2, delaunay2, voronoi2};
    ///
    /// let pts = [
    ///     Point2::new(0.0, 0.0).unwrap(),
    ///     Point2::new(4.0, 0.0).unwrap(),
    ///     Point2::new(4.0, 4.0).unwrap(),
    ///     Point2::new(0.0, 4.0).unwrap(),
    /// ];
    /// let voronoi = voronoi2(delaunay2(&pts));
    /// let cell = voronoi.cells().next().unwrap();
    ///
    /// // A square's corners are all hull vertices -- every cell is unbounded.
    /// assert!(voronoi.cell_is_unbounded(cell));
    /// // Each corner is Voronoi-adjacent to the 2 corners sharing a square
    /// // edge, not to the diagonally-opposite corner (that Delaunay edge
    /// // is cocircular with this one and was excluded).
    /// assert_eq!(voronoi.neighboring_cells(cell).count(), 2);
    /// ```
    pub fn neighboring_cells(
        &self,
        cell: VoronoiCellId,
    ) -> impl Iterator<Item = VoronoiCellId> + '_ {
        self.edges.iter().filter_map(move |e| {
            if e.cells[0] == cell {
                Some(e.cells[1])
            } else if e.cells[1] == cell {
                Some(e.cells[0])
            } else {
                None
            }
        })
    }

    /// `true` iff `cell` has at least one `Unbounded` edge -- equivalently,
    /// iff its site lies on the Delaunay triangulation's convex hull. A
    /// hull site always has a boundary Delaunay edge, and a boundary edge
    /// (only ever 1 incident face) can never be excluded as same-group,
    /// so this can never disagree with the hull-membership definition.
    pub fn cell_is_unbounded(&self, cell: VoronoiCellId) -> bool {
        self.edges.iter().any(|e| {
            (e.cells[0] == cell || e.cells[1] == cell)
                && matches!(e.kind, VoronoiEdgeKind::Unbounded { .. })
        })
    }

    /// `edge`'s two cells.
    pub fn edge_cells(&self, edge: VoronoiEdgeId) -> [VoronoiCellId; 2] {
        self.edges[edge.0 as usize].cells
    }

    /// `edge`'s shape: a finite segment between two Voronoi vertices, or
    /// an infinite ray from one.
    pub fn edge_kind(&self, edge: VoronoiEdgeId) -> &VoronoiEdgeKind {
        &self.edges[edge.0 as usize].kind
    }

    /// The Delaunay edge `edge` is dual to -- provenance/debugging
    /// metadata, not needed to interpret `edge`'s cells or kind.
    pub fn dual_delaunay_edge(&self, edge: VoronoiEdgeId) -> EdgeId {
        self.edges[edge.0 as usize].source_edge
    }

    /// Every Delaunay face merged into `vertex`'s group -- one face for
    /// an ordinary Voronoi vertex, more than one where cocircular faces
    /// were merged (ADR-007).
    pub fn vertex_delaunay_faces(&self, vertex: VoronoiVertexId) -> &[FaceId] {
        &self.group_faces[vertex.0 as usize]
    }

    /// `cell`'s boundary edges in counterclockwise order: a closed cycle
    /// for a bounded cell (interior site), or a linear sequence from one
    /// `Unbounded` ray to the other for an unbounded cell (hull site).
    ///
    /// Derived entirely from `Triangulation2::face_vertices`/
    /// `neighboring_faces` (the existing Delaunay face-adjacency
    /// structure, no new data model) plus the already-computed `edges`:
    /// walking the faces incident to `cell`'s site in a fixed rotational
    /// direction visits the same faces the geometric Voronoi cell
    /// boundary would, in order, and a step whose Delaunay edge was
    /// excluded as a same-cocircular-group artifact (§`voronoi2`) simply
    /// has no entry in `edges` to find -- which is exactly the signal to
    /// skip it and continue the walk across the merged group, no special
    /// casing needed. Cocircular merging cannot split a cell's walk into
    /// disconnected pieces of the same `VoronoiVertexId`: if two faces
    /// incident to `cell`'s site land in the same group, every face
    /// between them in the local rotation must too (their shared vertex
    /// plus both circles' defining triples force one common circle,
    /// which `voronoi2`'s exhaustive adjacent-pair testing always
    /// catches) -- so no `VoronoiVertexId` can appear from two separate,
    /// non-adjacent stretches of one cell's boundary.
    ///
    /// # Examples
    ///
    /// ```
    /// use kika::{Point2, delaunay2, voronoi2};
    ///
    /// let pts = [
    ///     Point2::new(0.0, 0.0).unwrap(),
    ///     Point2::new(4.0, 0.0).unwrap(),
    ///     Point2::new(0.0, 4.0).unwrap(),
    /// ];
    /// let voronoi = voronoi2(delaunay2(&pts));
    /// let cell = voronoi.cells().next().unwrap();
    ///
    /// // A single triangle's cell has exactly 2 unbounded rays -- no
    /// // interior edge to complete a cycle.
    /// assert_eq!(voronoi.cell_edges(cell).count(), 2);
    /// ```
    pub fn cell_edges(&self, cell: VoronoiCellId) -> impl Iterator<Item = VoronoiEdgeId> + '_ {
        let s = cell.0;
        let mut result = Vec::new();

        if let Some(f0) = self
            .delaunay
            .faces()
            .find(|&f| self.delaunay.face_vertices(f).contains(&s))
        {
            let i0 = self.local_index(f0, s);

            // Rotate backward from f0: either it returns to f0 itself
            // (s is fully surrounded -- a closed cycle), or it hits the
            // hull boundary (None), landing on the fan's true start.
            // Verified by hand for a degree-3 interior umbrella and a
            // 2-triangle hull fan (a square's corner) before writing
            // this -- the cycle case must restart the forward walk from
            // the *original* f0/i0, not wherever this loop's `face` ends
            // up, since the loop only exists to classify hull vs.
            // interior, not to locate a meaningful position on a cycle.
            // (An earlier draft used the loop's ending position for both
            // cases and silently dropped one step per cell on every
            // interior vertex -- caught by hand-tracing before it ever
            // reached a test.)
            let mut face = f0;
            let mut i = i0;
            let mut is_cycle = false;
            loop {
                let (_, next) = self.backward_step(face, i);
                match next {
                    None => break,
                    Some(nf) if nf == f0 => {
                        is_cycle = true;
                        break;
                    }
                    Some(nf) => {
                        face = nf;
                        i = self.local_index(nf, s);
                    }
                }
            }
            let (start_face, start_i) = if is_cycle { (f0, i0) } else { (face, i) };

            let mut face = start_face;
            let mut i = start_i;

            if !is_cycle {
                let (entry_other, _) = self.backward_step(face, i);
                if let Some(id) = self.edge_id_between(s, entry_other) {
                    result.push(id);
                }
            }

            loop {
                let (other, next) = self.forward_step(face, i);
                if let Some(id) = self.edge_id_between(s, other) {
                    result.push(id);
                }
                match next {
                    Some(nf) if is_cycle && nf == start_face => break,
                    Some(nf) => {
                        face = nf;
                        i = self.local_index(nf, s);
                    }
                    None => break,
                }
            }
        }

        result.into_iter()
    }

    /// The correctly-rounded coordinate of `vertex` -- the circumcenter of
    /// its merged Delaunay face group (ADR-009). `Err` only when the true
    /// circumcenter is not representable as a finite [`Point2`] (an
    /// extremely thin/near-degenerate defining face) -- never a panic,
    /// never a silently wrong large-magnitude coordinate.
    ///
    /// Recomputed on demand each call, not cached -- matches
    /// `neighboring_cells`/`cell_is_unbounded`'s existing "derive on
    /// demand, don't pre-index" precedent.
    ///
    /// For a cocircular-merged group (2+ faces), every member face shares
    /// exactly one true circumcenter (three non-collinear points determine
    /// a circle uniquely), so the correctly-rounded result is the same
    /// regardless of which member face computes it -- within this
    /// construction's verified-exact magnitude range. The member actually
    /// used is chosen by a canonical, site-identity-keyed rule (the
    /// lexicographically smallest sorted `VertexId` triple among the
    /// group's faces), not `FaceId`/scan order, so the choice stays
    /// deterministic and reproducible even below that range too. See
    /// `docs/adr/ADR-009-voronoi-geometry.md`.
    ///
    /// # Examples
    ///
    /// ```
    /// use kika::{Point2, delaunay2, voronoi2};
    ///
    /// let pts = [
    ///     Point2::new(0.0, 0.0).unwrap(),
    ///     Point2::new(4.0, 0.0).unwrap(),
    ///     Point2::new(0.0, 4.0).unwrap(),
    /// ];
    /// let voronoi = voronoi2(delaunay2(&pts));
    /// let vertex = voronoi.vertices().next().unwrap();
    ///
    /// // The right triangle's circumcenter is its hypotenuse's midpoint.
    /// let p = voronoi.vertex_point(vertex).unwrap();
    /// assert_eq!((p.x(), p.y()), (2.0, 2.0));
    /// ```
    pub fn vertex_point(&self, vertex: VoronoiVertexId) -> Result<Point2, VoronoiGeometryError> {
        let face = self.canonical_representative_face(vertex)?;
        let [a, b, c] = self.delaunay.face_vertices(face);
        let (pa, pb, pc) = (
            self.delaunay.vertex_point(a),
            self.delaunay.vertex_point(b),
            self.delaunay.vertex_point(c),
        );
        circumcenter(pa, pb, pc).ok_or(VoronoiGeometryError::NonFiniteCircumcenter)
    }

    /// The actual geometry of `edge`: a bounded segment between two
    /// Voronoi vertex coordinates, or a ray from one. `Err` propagates
    /// from [`Self::vertex_point`] on the endpoint(s) involved -- no
    /// partial `Segment` with one real and one non-representable endpoint.
    ///
    /// # Examples
    ///
    /// ```
    /// use kika::{Point2, VoronoiEdgeGeometry, delaunay2, voronoi2};
    ///
    /// let pts = [
    ///     Point2::new(0.0, 0.0).unwrap(),
    ///     Point2::new(4.0, 0.0).unwrap(),
    ///     Point2::new(0.0, 4.0).unwrap(),
    /// ];
    /// let voronoi = voronoi2(delaunay2(&pts));
    /// for edge in voronoi.edges() {
    ///     match voronoi.edge_geometry(edge).unwrap() {
    ///         VoronoiEdgeGeometry::Ray { origin, .. } => {
    ///             assert_eq!((origin.x(), origin.y()), (2.0, 2.0));
    ///         }
    ///         VoronoiEdgeGeometry::Segment { .. } => {
    ///             unreachable!("a single triangle's Voronoi diagram has no bounded edge")
    ///         }
    ///         // `VoronoiEdgeGeometry` is `#[non_exhaustive]`.
    ///         _ => unreachable!(),
    ///     }
    /// }
    /// ```
    pub fn edge_geometry(
        &self,
        edge: VoronoiEdgeId,
    ) -> Result<VoronoiEdgeGeometry, VoronoiGeometryError> {
        match self.edges[edge.0 as usize].kind {
            VoronoiEdgeKind::Bounded { vertices: [v0, v1] } => {
                let start = self.vertex_point(v0)?;
                let end = self.vertex_point(v1)?;
                Ok(VoronoiEdgeGeometry::Segment { start, end })
            }
            VoronoiEdgeKind::Unbounded { finite_vertex } => {
                let origin = self.vertex_point(finite_vertex)?;
                let source_edge = self.edges[edge.0 as usize].source_edge;
                let (u, v) = self.delaunay.edge_vertices(source_edge);
                let face = self
                    .delaunay
                    .adjacent_faces(source_edge)
                    .into_iter()
                    .flatten()
                    .next()
                    .ok_or(VoronoiGeometryError::InvalidTopology)?;
                let w = third_vertex(&self.delaunay, face, u, v);
                let direction = self.outward_ray_direction(u, v, w);
                Ok(VoronoiEdgeGeometry::Ray { origin, direction })
            }
        }
    }

    /// The canonical representative face for `vertex`'s group: the member
    /// face whose 3 vertices, sorted by `VertexId::raw()`, are
    /// lexicographically smallest -- a site-identity-keyed choice
    /// (ADR-007's own canonical-id discipline, applied one layer deeper:
    /// see `docs/adr/ADR-009-voronoi-geometry.md`'s "Canonical-per-group
    /// circumcenter"), not `FaceId`/scan order.
    ///
    /// `Err` only if `vertex`'s group is empty -- never true for a
    /// `Voronoi2` built by [`voronoi2`] (every `VoronoiVertexId` in range
    /// has at least one member face by construction), but not assumed:
    /// a hand-assembled/corrupted instance gets a typed error here
    /// rather than panicking.
    fn canonical_representative_face(
        &self,
        vertex: VoronoiVertexId,
    ) -> Result<FaceId, VoronoiGeometryError> {
        self.group_faces[vertex.0 as usize]
            .iter()
            .copied()
            .min_by_key(|&f| {
                let mut verts = self.delaunay.face_vertices(f).map(VertexId::raw);
                verts.sort_unstable();
                verts
            })
            .ok_or(VoronoiGeometryError::InvalidTopology)
    }

    /// The outward (away from `w`) perpendicular direction of Delaunay
    /// hull edge `(u, v)`, `w` being that edge's one incident face's third
    /// vertex. Each component of the edge vector is a single
    /// correctly-rounded `f64` coordinate difference (`Point2 - Point2`)
    /// -- or, in the rare case that difference overflows (see
    /// [`edge_vector`]), a uniformly-rescaled equivalent; the perpendicular
    /// rotation and `orient2d`-based sign selection introduce no further
    /// error. Finite and non-zero for any two distinct finite points --
    /// see `docs/adr/ADR-009-voronoi-geometry.md`'s "Determining the ray
    /// direction" section.
    fn outward_ray_direction(&self, u: VertexId, v: VertexId, w: VertexId) -> Vector2 {
        let pu = self.delaunay.vertex_point(u);
        let pv = self.delaunay.vertex_point(v);
        let pw = self.delaunay.vertex_point(w);

        let edge = edge_vector(pu, pv);
        let perp = Vector2::new_unchecked(-edge.y(), edge.x());

        // `perp` is `edge` rotated +90 deg, which always lies on
        // `orient2d(pu, pv, .)`'s CounterClockwise side of the line
        // through `pu`/`pv` -- a fact of the rotation itself
        // (cross(edge, perp) == edge.x^2 + edge.y^2 >= 0), true
        // regardless of `edge`'s magnitude. This lets us pick the side
        // without ever materializing a `pu + perp` candidate point, which
        // could overflow to a non-finite `Point2` for near-`f64::MAX`
        // input coordinates.
        if orient2d(pu, pv, pw) == Orientation::CounterClockwise {
            -perp
        } else {
            perp
        }
    }

    /// `v`'s index within `face`'s 3 vertices. Panics only if `face`
    /// isn't actually incident to `v` -- never true for any call site in
    /// this file, which only ever passes a `face` already known (by
    /// construction) to contain `v`.
    fn local_index(&self, face: FaceId, v: VertexId) -> usize {
        self.delaunay
            .face_vertices(face)
            .iter()
            .position(|&w| w == v)
            .expect("`face` must be incident to `v`")
    }

    /// One rotation step around `face_vertices(face)[i]`, crossing the
    /// edge to the *previous* CCW vertex -- verified against a concrete
    /// square (corner site, diagonal split into 2 CCW triangles) to
    /// trace true counterclockwise order, not assumed from the index
    /// arithmetic alone. Returns the edge's other endpoint and the
    /// neighboring face across it (`None` at the hull boundary).
    fn forward_step(&self, face: FaceId, i: usize) -> (VertexId, Option<FaceId>) {
        let other = self.delaunay.face_vertices(face)[(i + 2) % 3];
        let next = self.delaunay.neighboring_faces(face)[(i + 1) % 3];
        (other, next)
    }

    /// The reverse of [`Self::forward_step`]: crosses the edge to the
    /// *next* CCW vertex.
    fn backward_step(&self, face: FaceId, i: usize) -> (VertexId, Option<FaceId>) {
        let other = self.delaunay.face_vertices(face)[(i + 1) % 3];
        let next = self.delaunay.neighboring_faces(face)[(i + 2) % 3];
        (other, next)
    }

    /// The `VoronoiEdgeId` of the surviving edge between sites `a` and
    /// `b`, if any -- `None` means the Delaunay edge between them was
    /// excluded as a same-cocircular-group artifact (`voronoi2`), not
    /// that no such Delaunay edge exists.
    fn edge_id_between(&self, a: VertexId, b: VertexId) -> Option<VoronoiEdgeId> {
        let target = [VoronoiCellId(a), VoronoiCellId(b)];
        self.edges
            .iter()
            .position(|e| e.cells == target || e.cells == [target[1], target[0]])
            .map(|idx| VoronoiEdgeId(idx as u32))
    }
}

/// A structural invariant violated in a [`Voronoi2`], found by
/// `validate_voronoi_topology`. Mirrors
/// [`super::delaunay2::TopologyError`]'s role for `Triangulation2`:
/// `#[doc(hidden)]` `pub` so this crate's own `tests/`/`fuzz/` can reach
/// it without being a real, advertised public API commitment yet.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum VoronoiTopologyError {
    /// `face_group[face]` and `group_faces` don't agree with each other
    /// as inverses.
    FaceGroupNotInverse {
        /// The face whose group membership is inconsistent.
        face: FaceId,
    },
    /// `group_faces` (the `VoronoiVertexId` space) is not sorted by its
    /// canonical site-identity key at this position.
    GroupsNotCanonicallyOrdered {
        /// The index at which canonical order first breaks.
        at: usize,
    },
    /// `edges` (the `VoronoiEdgeId` space) is not sorted by its canonical
    /// cell-pair key at this position.
    EdgesNotCanonicallyOrdered {
        /// The index at which canonical order first breaks.
        at: usize,
    },
    /// A Delaunay edge that should contribute a Voronoi edge (a hull
    /// edge, or an interior edge between two different groups) has no
    /// corresponding entry in `edges`.
    MissingVoronoiEdge {
        /// The Delaunay edge with no dual entry.
        source_edge: EdgeId,
    },
    /// An entry in `edges` doesn't match what its `source_edge` and the
    /// current `face_group` table independently say it should be.
    EdgeMismatch {
        /// The Delaunay edge whose dual entry is wrong.
        source_edge: EdgeId,
    },
    /// A Voronoi edge's two `cells` are the same cell, not two distinct
    /// sites.
    NonDistinctEdgeCells {
        /// The offending edge.
        edge: VoronoiEdgeId,
    },
    /// A `Bounded` edge's two endpoint vertices are the same Voronoi
    /// vertex, not two distinct groups.
    NonDistinctBoundedVertices {
        /// The offending edge.
        edge: VoronoiEdgeId,
    },
    /// An `Unbounded` edge's dual Delaunay edge is not actually a
    /// convex-hull edge (recomputed from `delaunay.adjacent_faces`
    /// independently of `edges`' own cached `kind`).
    UnboundedEdgeNotHullDual {
        /// The offending edge.
        edge: VoronoiEdgeId,
    },
    /// The same Delaunay face appears more than once in one Voronoi
    /// vertex's face group.
    DuplicateFaceInGroup {
        /// The group with a duplicate entry.
        vertex: VoronoiVertexId,
        /// The duplicated face.
        face: FaceId,
    },
    /// A Voronoi edge doesn't appear in exactly 2 cells' `cell_edges()`
    /// sequences. This is a coverage check, not an ordering one: since
    /// `cell_edges` finds an edge via `edge_id_between(s, other)` -- a
    /// lookup keyed on `edges`' own `cells` pair -- any edge with
    /// `cells == [a, b]` is *found* by construction when walking `a` and
    /// when walking `b`, so a healthy walk always yields exactly 2 by
    /// that lookup alone. What this actually catches is a walk that
    /// *drops* a step it should have visited (leaving the edge under 2,
    /// possibly 0) -- it cannot detect two edges emitted in the wrong
    /// relative order, or a duplicate emission alongside a correct one.
    /// Order is verified by test (`cell_edges_interior_cell_is_...` and
    /// its hull-cell counterpart), not by this check.
    EdgeNotInExactlyTwoCellBoundaries {
        /// The offending edge.
        edge: VoronoiEdgeId,
        /// How many cells' boundaries it actually appeared in.
        count: usize,
    },
}

impl Voronoi2 {
    /// Checks every structural invariant `voronoi2` is supposed to
    /// establish: `face_group`/`group_faces` are mutual inverses with no
    /// duplicate face in any one group, both `group_faces` and `edges`
    /// are canonically (not incidentally) ordered, `edges` matches what
    /// independently recomputing each Delaunay edge's classification
    /// against `face_group` says it should be (which also covers "no
    /// same-component edge is ever exposed" -- a same-group interior
    /// edge's independently recomputed classification is `None`, so any
    /// entry for it at all is an `EdgeMismatch`), every edge's two cells
    /// are distinct, every `Bounded` edge's two vertices are distinct,
    /// and every `Unbounded` edge's dual is actually a hull edge.
    ///
    /// Two invariants ADR-007 also names have no corresponding check
    /// here. "Every site has exactly one cell" needs none:
    /// `VoronoiCellId` is a direct `VertexId` wrapper with no separate
    /// cell table to desync in the first place. "The neighboring-cells
    /// relation is symmetric" is asserted by a test instead (see
    /// `neighboring_and_unbounded_queries_on_the_mixed_fixture`), not a
    /// validator check: `neighboring_cells` derives its answer fresh from
    /// `edges`' own unordered `[cell_a, cell_b]` pairs on every call, so
    /// it reads symmetrically regardless of what `edges` contains -- the
    /// data shape admits no asymmetric entry to inject, the way the 4
    /// checks above can each be tested by directly corrupting a
    /// constructed `Voronoi2`'s private fields.
    ///
    /// Returns every violation found, not just the first.
    #[doc(hidden)]
    pub fn validate_voronoi_topology(&self) -> Vec<VoronoiTopologyError> {
        let mut errors = Vec::new();

        for (i, faces) in self.group_faces.iter().enumerate() {
            for &f in faces {
                if self.face_group[f.raw() as usize] != VoronoiVertexId(i as u32) {
                    errors.push(VoronoiTopologyError::FaceGroupNotInverse { face: f });
                }
            }
        }
        for f in self.delaunay.faces() {
            let g = self.face_group[f.raw() as usize];
            if !self.group_faces[g.0 as usize].contains(&f) {
                errors.push(VoronoiTopologyError::FaceGroupNotInverse { face: f });
            }
        }

        for (i, w) in self.group_faces.windows(2).enumerate() {
            let ka = group_key(&self.delaunay, &w[0]);
            let kb = group_key(&self.delaunay, &w[1]);
            if ka >= kb {
                errors.push(VoronoiTopologyError::GroupsNotCanonicallyOrdered { at: i + 1 });
            }
        }
        for (i, w) in self.edges.windows(2).enumerate() {
            if edge_key(w[0].cells) >= edge_key(w[1].cells) {
                errors.push(VoronoiTopologyError::EdgesNotCanonicallyOrdered { at: i + 1 });
            }
        }

        for source_edge in self.delaunay.edges() {
            let (u, v) = self.delaunay.edge_vertices(source_edge);
            let expected_cells = [VoronoiCellId(u), VoronoiCellId(v)];
            let expected_kind = match self.delaunay.adjacent_faces(source_edge) {
                [Some(f), None] | [None, Some(f)] => Some(VoronoiEdgeKind::Unbounded {
                    finite_vertex: self.face_group[f.raw() as usize],
                }),
                [Some(f1), Some(f2)] => {
                    let g1 = self.face_group[f1.raw() as usize];
                    let g2 = self.face_group[f2.raw() as usize];
                    if g1 != g2 {
                        Some(VoronoiEdgeKind::Bounded { vertices: [g1, g2] })
                    } else {
                        None
                    }
                }
                [None, None] => None,
            };

            let actual = self.edges.iter().find(|e| e.source_edge == source_edge);
            match (expected_kind, actual) {
                (None, Some(_)) => errors.push(VoronoiTopologyError::EdgeMismatch { source_edge }),
                (Some(_), None) => {
                    errors.push(VoronoiTopologyError::MissingVoronoiEdge { source_edge })
                }
                (Some(expected), Some(actual)) => {
                    if actual.cells != expected_cells || actual.kind != expected {
                        errors.push(VoronoiTopologyError::EdgeMismatch { source_edge });
                    }
                }
                (None, None) => {}
            }
        }

        for (i, faces) in self.group_faces.iter().enumerate() {
            let mut seen = std::collections::HashSet::new();
            for &f in faces {
                if !seen.insert(f) {
                    errors.push(VoronoiTopologyError::DuplicateFaceInGroup {
                        vertex: VoronoiVertexId(i as u32),
                        face: f,
                    });
                }
            }
        }

        for (i, e) in self.edges.iter().enumerate() {
            let edge = VoronoiEdgeId(i as u32);
            if e.cells[0] == e.cells[1] {
                errors.push(VoronoiTopologyError::NonDistinctEdgeCells { edge });
            }
            match e.kind {
                VoronoiEdgeKind::Bounded { vertices } => {
                    if vertices[0] == vertices[1] {
                        errors.push(VoronoiTopologyError::NonDistinctBoundedVertices { edge });
                    }
                }
                VoronoiEdgeKind::Unbounded { .. } => {
                    let is_hull_edge = matches!(
                        self.delaunay.adjacent_faces(e.source_edge),
                        [Some(_), None] | [None, Some(_)]
                    );
                    if !is_hull_edge {
                        errors.push(VoronoiTopologyError::UnboundedEdgeNotHullDual { edge });
                    }
                }
            }
        }

        // cell_edges()'s own coverage: every edge must be reachable from
        // exactly 2 cells' walks, catching a dropped step (see
        // EdgeNotInExactlyTwoCellBoundaries's doc comment for why this
        // is coverage, not ordering, verification). O(cells x average
        // degree), the first check here costing more than near-linear
        // -- fine for a validator, not something to call from a hot
        // path.
        let mut boundary_counts = vec![0usize; self.edges.len()];
        for cell in self.cells() {
            for edge in self.cell_edges(cell) {
                boundary_counts[edge.0 as usize] += 1;
            }
        }
        for (i, &count) in boundary_counts.iter().enumerate() {
            if count != 2 {
                errors.push(VoronoiTopologyError::EdgeNotInExactlyTwoCellBoundaries {
                    edge: VoronoiEdgeId(i as u32),
                    count,
                });
            }
        }

        errors
    }
}

#[cfg(test)]
mod tests {
    use super::super::delaunay2::{assemble_triangulation, delaunay2};
    use super::*;
    use crate::primitives::Point2;

    fn pt(x: f64, y: f64) -> Point2 {
        Point2::new(x, y).unwrap()
    }

    #[test]
    fn single_triangle_has_one_group_and_three_unbounded_edges() {
        let pts = vec![pt(0.0, 0.0), pt(1.0, 0.0), pt(0.0, 1.0)];
        let v = voronoi2(delaunay2(&pts));

        assert_eq!(v.group_faces.len(), 1);
        assert_eq!(v.edges.len(), 3);
        assert!(
            v.edges
                .iter()
                .all(|e| matches!(e.kind, VoronoiEdgeKind::Unbounded { .. }))
        );
        assert!(v.validate_voronoi_topology().is_empty());
    }

    #[test]
    fn axis_aligned_square_merges_both_faces_into_one_group() {
        // Exactly cocircular under exact incircle: any 3 corners' circle
        // passes exactly through the 4th, a pure algebraic identity for
        // a square -- not merely numerically close.
        let pts = vec![pt(0.0, 0.0), pt(2.0, 0.0), pt(2.0, 2.0), pt(0.0, 2.0)];
        let v = voronoi2(delaunay2(&pts));

        assert_eq!(
            v.group_faces.len(),
            1,
            "the diagonal split by delaunay2's tie-break must not leak as 2 Voronoi vertices"
        );
        assert_eq!(
            v.edges.len(),
            4,
            "the 4 hull edges are Unbounded; the interior diagonal is same-group and excluded"
        );
        assert!(
            v.edges
                .iter()
                .all(|e| matches!(e.kind, VoronoiEdgeKind::Unbounded { .. }))
        );
        assert!(v.validate_voronoi_topology().is_empty());
    }

    #[test]
    fn generic_position_random_points_pass_validation() {
        struct Xorshift64(u64);
        impl Xorshift64 {
            fn next_u64(&mut self) -> u64 {
                let mut x = self.0;
                x ^= x << 13;
                x ^= x >> 7;
                x ^= x << 17;
                self.0 = x;
                x
            }
            fn next_f64_in(&mut self, scale: f64) -> f64 {
                let bits = self.next_u64();
                let unit = (bits >> 11) as f64 * (1.0 / (1u64 << 53) as f64);
                (unit * 2.0 - 1.0) * scale
            }
        }

        let mut rng = Xorshift64(0x9e3779b97f4a7c15);
        let pts: Vec<Point2> = (0..60)
            .map(|_| pt(rng.next_f64_in(100.0), rng.next_f64_in(100.0)))
            .collect();
        let v = voronoi2(delaunay2(&pts));

        assert!(!v.group_faces.is_empty());
        assert_eq!(v.validate_voronoi_topology(), Vec::new());

        // cell_is_unbounded must agree with an independent recomputation
        // from the Delaunay hull, not just always be true -- every other
        // test in this file uses a fully-convex point set (every site on
        // the hull), so a 60-point generic-position cloud is the only
        // fixture that actually has interior sites to distinguish.
        let hull_sites: std::collections::HashSet<VertexId> = v
            .delaunay
            .boundary_edges()
            .flat_map(|e| {
                let (a, b) = v.delaunay.edge_vertices(e);
                [a, b]
            })
            .collect();
        let mut saw_interior_cell = false;
        for cell in v.cells() {
            let expected_unbounded = hull_sites.contains(&v.cell_site(cell));
            assert_eq!(v.cell_is_unbounded(cell), expected_unbounded);
            if !expected_unbounded {
                saw_interior_cell = true;
                assert!(
                    v.neighboring_cells(cell).count() >= 3,
                    "an interior Voronoi cell in generic position has at least 3 neighbors"
                );
            }
        }
        assert!(
            saw_interior_cell,
            "a 60-point generic-position cloud must have at least one interior site"
        );
    }

    // -- Canonical-topology normalization tests (ADR-007) --
    //
    // delaunay2() canonically sorts its input before insertion, so it is
    // a deterministic function of the input *set*, not order -- it can
    // never itself be coaxed into picking a different diagonal among
    // cocircular points. Different triangulations of the same cocircular
    // point set are instead built directly via assemble_triangulation,
    // using the exact same `pts` (and so the exact same VertexId
    // numbering) each time -- which lets the tests check that canonical
    // ID assignment makes differently-triangulated-but-topologically-
    // equal inputs produce *identical*, not merely isomorphic, output.

    /// 12 exact lattice points on the circle x^2+y^2=25, in CCW angular
    /// order -- small integers, so `incircle` is exactly (not just
    /// numerically) zero for any 4 of them.
    fn cocircular_lattice_points(n: usize) -> Vec<Point2> {
        const ALL: [(f64, f64); 12] = [
            (5.0, 0.0),
            (4.0, 3.0),
            (3.0, 4.0),
            (0.0, 5.0),
            (-3.0, 4.0),
            (-4.0, 3.0),
            (-5.0, 0.0),
            (-4.0, -3.0),
            (-3.0, -4.0),
            (0.0, -5.0),
            (3.0, -4.0),
            (4.0, -3.0),
        ];
        assert!(n <= ALL.len());
        ALL[..n].iter().map(|&(x, y)| pt(x, y)).collect()
    }

    /// Fans `n` CCW-ordered convex points (indices `0..n`) out from
    /// vertex `start`: triangles `(start, start+i, start+i+1)` for
    /// `i = 1..=n-2`, indices mod `n`. A different `start` picks a
    /// different, but equally valid, triangulation of the same point set.
    fn fan_from(n: usize, start: usize) -> Vec<[VertexId; 3]> {
        (1..n - 1)
            .map(|i| {
                let a = start % n;
                let b = (start + i) % n;
                let c = (start + i + 1) % n;
                [VertexId(a as u32), VertexId(b as u32), VertexId(c as u32)]
            })
            .collect()
    }

    /// A face group's canonical key (sorted-dedup site `VertexId`s),
    /// recomputed independently of any incidental group/scan order.
    fn group_site_set(v: &Voronoi2, g: VoronoiVertexId) -> Vec<u32> {
        group_key(&v.delaunay, &v.group_faces[g.0 as usize])
    }

    /// Every group's canonical key, in `VoronoiVertexId` order.
    fn canonical_groups(v: &Voronoi2) -> Vec<Vec<u32>> {
        v.group_faces
            .iter()
            .map(|faces| group_key(&v.delaunay, faces))
            .collect()
    }

    /// Every edge's canonical representation: the sorted site pair it
    /// separates, and its endpoint(s) translated from (per-instance)
    /// `VoronoiVertexId` to (instance-independent) site sets -- exactly
    /// the "cell-as-site, vertex-as-sorted-incident-site-set" comparison
    /// ADR-007 specifies, dropping the incidental `source_edge`/raw-id
    /// fields entirely.
    fn canonical_edges(v: &Voronoi2) -> Vec<(Vec<u32>, Vec<Vec<u32>>)> {
        let mut out: Vec<_> = v
            .edges
            .iter()
            .map(|e| {
                let cell_key = edge_key(e.cells).to_vec();
                let mut endpoints: Vec<Vec<u32>> = match e.kind {
                    VoronoiEdgeKind::Bounded { vertices } => {
                        vertices.iter().map(|&g| group_site_set(v, g)).collect()
                    }
                    VoronoiEdgeKind::Unbounded { finite_vertex } => {
                        vec![group_site_set(v, finite_vertex)]
                    }
                };
                endpoints.sort();
                (cell_key, endpoints)
            })
            .collect();
        out.sort();
        out
    }

    /// Asserts a fully cocircular convex `n`-gon collapses to exactly one
    /// Voronoi vertex with `n` Unbounded hull edges and no interior
    /// (Bounded) edges -- true regardless of which triangulation of it
    /// was fed in, since every pair of adjacent faces in any
    /// triangulation of mutually cocircular points tests cocircular.
    fn assert_single_cocircular_group(v: &Voronoi2, n_sites: usize) {
        assert_eq!(v.group_faces.len(), 1);
        assert_eq!(v.edges.len(), n_sites);
        assert!(
            v.edges
                .iter()
                .all(|e| matches!(e.kind, VoronoiEdgeKind::Unbounded { .. }))
        );
        assert!(v.validate_voronoi_topology().is_empty());
    }

    #[test]
    fn square_both_diagonals_produce_identical_canonical_topology() {
        let pts = vec![pt(0.0, 0.0), pt(2.0, 0.0), pt(2.0, 2.0), pt(0.0, 2.0)];

        let diagonal_a = voronoi2(assemble_triangulation(pts.clone(), fan_from(4, 0)));
        let diagonal_b = voronoi2(assemble_triangulation(pts, fan_from(4, 1)));

        assert_single_cocircular_group(&diagonal_a, 4);
        assert_single_cocircular_group(&diagonal_b, 4);
        assert_eq!(canonical_groups(&diagonal_a), canonical_groups(&diagonal_b));
        assert_eq!(canonical_edges(&diagonal_a), canonical_edges(&diagonal_b));
    }

    #[test]
    fn five_cocircular_points_multiple_fans_produce_identical_canonical_topology() {
        let pts = cocircular_lattice_points(5);

        let fan_0 = voronoi2(assemble_triangulation(pts.clone(), fan_from(5, 0)));
        let fan_2 = voronoi2(assemble_triangulation(pts, fan_from(5, 2)));

        assert_single_cocircular_group(&fan_0, 5);
        assert_single_cocircular_group(&fan_2, 5);
        assert_eq!(canonical_groups(&fan_0), canonical_groups(&fan_2));
        assert_eq!(canonical_edges(&fan_0), canonical_edges(&fan_2));
    }

    #[test]
    fn eight_cocircular_points_multiple_fans_produce_identical_canonical_topology() {
        let pts = cocircular_lattice_points(8);

        let fan_0 = voronoi2(assemble_triangulation(pts.clone(), fan_from(8, 0)));
        let fan_3 = voronoi2(assemble_triangulation(pts.clone(), fan_from(8, 3)));
        let fan_6 = voronoi2(assemble_triangulation(pts, fan_from(8, 6)));

        for v in [&fan_0, &fan_3, &fan_6] {
            assert_single_cocircular_group(v, 8);
        }
        assert_eq!(canonical_groups(&fan_0), canonical_groups(&fan_3));
        assert_eq!(canonical_groups(&fan_0), canonical_groups(&fan_6));
        assert_eq!(canonical_edges(&fan_0), canonical_edges(&fan_3));
        assert_eq!(canonical_edges(&fan_0), canonical_edges(&fan_6));
    }

    // -- Geometry (ADR-009): vertex_point/edge_geometry --

    #[test]
    fn vertex_point_matches_hand_computed_circumcenter() {
        let pts = vec![pt(0.0, 0.0), pt(4.0, 0.0), pt(0.0, 4.0)];
        let v = voronoi2(delaunay2(&pts));
        let vertex = v.vertices().next().unwrap();
        let p = v.vertex_point(vertex).unwrap();
        assert_eq!((p.x(), p.y()), (2.0, 2.0));
    }

    /// The central claim ADR-009's "Canonical-per-group circumcenter"
    /// section makes: every member face of a cocircular-merged group
    /// shares one true circumcenter (three non-collinear points determine
    /// a circle uniquely), so the correctly-rounded output is
    /// byte-identical regardless of which member face computes it. This
    /// bypasses `canonical_representative_face`'s own pick entirely,
    /// computing directly from *every* member face via the `pub(crate)`
    /// `circumcenter` construction, to test the underlying mathematical
    /// claim itself -- not just that the canonical-pick mechanism is
    /// deterministic (which would be a weaker, near-vacuous test).
    #[test]
    fn cocircular_group_circumcenter_identical_regardless_of_member_face() {
        let pts = cocircular_lattice_points(8);
        let v = voronoi2(assemble_triangulation(pts, fan_from(8, 0)));
        assert_eq!(v.group_faces.len(), 1, "all 8 points share one circle");

        let faces = &v.group_faces[0];
        assert!(
            faces.len() >= 3,
            "expected a genuinely multi-face cocircular group"
        );

        let results: Vec<Point2> = faces
            .iter()
            .map(|&f| {
                let [a, b, c] = v.delaunay.face_vertices(f);
                circumcenter(
                    v.delaunay.vertex_point(a),
                    v.delaunay.vertex_point(b),
                    v.delaunay.vertex_point(c),
                )
                .expect("a fan triangle of cocircular points is never collinear")
            })
            .collect();

        let first = results[0];
        for &r in &results[1..] {
            assert_eq!(
                (r.x(), r.y()),
                (first.x(), first.y()),
                "circumcenter must be identical regardless of which member face computed it"
            );
        }
    }

    /// The thin-triangle overflow case (`docs/adr/ADR-009-voronoi-geometry.md`)
    /// must surface as a typed `Err` through the *public* API, not just
    /// from the internal `circumcenter` construction directly -- confirms
    /// `vertex_point`/`edge_geometry` propagate it correctly rather than
    /// unwrapping/panicking.
    #[test]
    fn thin_triangle_vertex_point_and_edge_geometry_return_err_not_panic() {
        // See `predicates::constructions::circumcenter`'s own
        // `thin_triangle_overflow_returns_none_not_a_panic` for why this
        // specific L/h pair (comfortably above the exact-product
        // representability floor, confirmed a genuine non-degenerate
        // triangle) rather than a subnormal-scale one.
        let l = 1e75;
        let h = 1e-170;
        let pts = vec![pt(0.0, 0.0), pt(l, 0.0), pt(l / 2.0, h)];
        let v = voronoi2(delaunay2(&pts));
        let vertex = v.vertices().next().unwrap();
        assert_eq!(
            v.vertex_point(vertex),
            Err(VoronoiGeometryError::NonFiniteCircumcenter)
        );
        for edge in v.edges() {
            assert_eq!(
                v.edge_geometry(edge),
                Err(VoronoiGeometryError::NonFiniteCircumcenter)
            );
        }
    }

    /// `canonical_representative_face`/`vertex_point`: an internal
    /// topology invariant this crate's own construction always
    /// maintains (`group_faces[i]` never empty, since a `VoronoiVertexId`
    /// is only ever assigned for a group with >= 1 member face) --
    /// checked rather than trusted, per `docs/adr/ADR-008-point-location.md`'s
    /// posture. Deliberately corrupted here (not reachable via any public
    /// constructor) to confirm `Err(InvalidTopology)`, not a panic.
    #[test]
    fn empty_face_group_is_a_typed_error_not_a_panic() {
        let pts = vec![pt(0.0, 0.0), pt(4.0, 0.0), pt(0.0, 4.0)];
        let mut broken = voronoi2(delaunay2(&pts));
        let vertex = broken.vertices().next().unwrap();
        broken.group_faces[vertex.0 as usize].clear();

        assert_eq!(
            broken.vertex_point(vertex),
            Err(VoronoiGeometryError::InvalidTopology)
        );
        // Propagates through `edge_geometry` too, not just `vertex_point`
        // directly -- every edge of a single triangle references this
        // one (now-broken) vertex, whether `Unbounded` (via
        // `finite_vertex`) or (not present in this single-triangle
        // fixture, but structurally the same call) `Bounded`.
        for edge in broken.edges() {
            assert_eq!(
                broken.edge_geometry(edge),
                Err(VoronoiGeometryError::InvalidTopology)
            );
        }
    }

    /// `edge_geometry`'s `Unbounded` branch also has an internal-topology
    /// `.ok_or(InvalidTopology)` guard (an `Unbounded` edge's source
    /// Delaunay edge must have exactly 1 incident face). Unlike the
    /// empty-face-group case above, this invariant is enforced by
    /// `Triangulation2`'s own construction, and `Triangulation2`'s fields
    /// are private to a sibling module (`delaunay2`, not a descendant of
    /// `voronoi`) -- so reaching it needs `Triangulation2`'s own
    /// `#[cfg(test)] clear_adjacent_faces_for_test`, added specifically
    /// for this test (see its doc comment in `delaunay2.rs`), rather than
    /// a `Voronoi2`-field mutation like `group_faces` above.
    #[test]
    fn unbounded_edge_missing_incident_face_is_a_typed_error_not_a_panic() {
        let pts = vec![pt(0.0, 0.0), pt(4.0, 0.0), pt(0.0, 4.0)];
        let mut broken = voronoi2(delaunay2(&pts));
        let edge = broken
            .edges()
            .find(|&e| matches!(broken.edge_kind(e), VoronoiEdgeKind::Unbounded { .. }))
            .expect("a single triangle's Voronoi diagram has 3 Unbounded hull edges");
        let source_edge = broken.dual_delaunay_edge(edge);
        broken.delaunay.clear_adjacent_faces_for_test(source_edge);

        assert_eq!(
            broken.edge_geometry(edge),
            Err(VoronoiGeometryError::InvalidTopology)
        );
    }

    /// `edge_geometry`'s `Segment` case: both endpoints of a genuine
    /// interior (`Bounded`) Voronoi edge must match `vertex_point`'s own
    /// output for those same two vertices exactly.
    #[test]
    fn edge_geometry_segment_endpoints_match_vertex_point() {
        // 4 generic-position points guaranteed to produce at least one
        // interior (Bounded) edge: a square's diagonal split, perturbed
        // off cocircularity so the diagonal survives as a real edge
        // rather than being excluded as a same-group artifact.
        let pts = vec![
            pt(0.0, 0.0),
            pt(4.0, 0.0),
            pt(4.0, 4.0),
            pt(0.0, 4.1), // perturbed: not exactly cocircular with the other 3
        ];
        let v = voronoi2(delaunay2(&pts));
        let mut saw_bounded = false;
        for edge in v.edges() {
            if let VoronoiEdgeKind::Bounded { vertices } = *v.edge_kind(edge) {
                saw_bounded = true;
                let expected_start = v.vertex_point(vertices[0]).unwrap();
                let expected_end = v.vertex_point(vertices[1]).unwrap();
                match v.edge_geometry(edge).unwrap() {
                    VoronoiEdgeGeometry::Segment { start, end } => {
                        assert_eq!(
                            (start.x(), start.y()),
                            (expected_start.x(), expected_start.y())
                        );
                        assert_eq!((end.x(), end.y()), (expected_end.x(), expected_end.y()));
                    }
                    VoronoiEdgeGeometry::Ray { .. } => panic!("Bounded edge produced a Ray"),
                }
            }
        }
        assert!(
            saw_bounded,
            "expected at least one Bounded edge in this fixture"
        );
    }

    /// `edge_geometry`'s `Ray` case: `direction` must point to the
    /// opposite side of the boundary Delaunay edge `(u, w)` from that
    /// edge's incident face's third vertex -- an exact `orient2d`-based
    /// check independently re-derived here (not just re-running the
    /// implementation's own side-test), and `origin` must match
    /// `vertex_point`.
    #[test]
    fn edge_geometry_ray_points_away_from_third_vertex() {
        let pts = vec![pt(0.0, 0.0), pt(4.0, 0.0), pt(0.0, 4.0)];
        let v = voronoi2(delaunay2(&pts));

        for edge in v.edges() {
            let VoronoiEdgeKind::Unbounded { finite_vertex } = *v.edge_kind(edge) else {
                continue;
            };
            let expected_origin = v.vertex_point(finite_vertex).unwrap();
            let source_edge = v.dual_delaunay_edge(edge);
            let (u, w) = v.delaunay.edge_vertices(source_edge);
            let face = v
                .delaunay
                .adjacent_faces(source_edge)
                .into_iter()
                .flatten()
                .next()
                .expect("a boundary Delaunay edge has exactly 1 incident face");
            let third = third_vertex(&v.delaunay, face, u, w);

            let pu = v.delaunay.vertex_point(u);
            let pw = v.delaunay.vertex_point(w);
            let pthird = v.delaunay.vertex_point(third);

            match v.edge_geometry(edge).unwrap() {
                VoronoiEdgeGeometry::Ray { origin, direction } => {
                    assert_eq!(
                        (origin.x(), origin.y()),
                        (expected_origin.x(), expected_origin.y())
                    );
                    let probe = origin + direction;
                    assert_ne!(
                        orient2d(pu, pw, pthird),
                        orient2d(pu, pw, probe),
                        "ray direction must point to the opposite side of the boundary \
                         edge from the triangle's third vertex"
                    );
                }
                VoronoiEdgeGeometry::Segment { .. } => panic!("Unbounded edge produced a Segment"),
            }
        }
    }

    /// Regression: `outward_ray_direction` used to build `candidate = pu +
    /// perp` (a plain, unchecked `Point2 + Vector2` add) purely to probe
    /// its `orient2d` side. When `pu` is far from the origin and the
    /// triangle's edge is comparatively short, `perp` is too small to
    /// survive that add -- `candidate` silently rounds back down to `pu`
    /// exactly, making `orient2d(pu, pv, candidate)` degenerately
    /// `Collinear` and the old side-test (`orient2d(pu,pv,pw) ==
    /// orient2d(pu,pv,candidate)`) always false, always returning `perp`
    /// regardless of `pw`'s real side. This fixture makes that concrete:
    /// `pu=(1e20,0)`, `pv=(1e20,5)` (edge magnitude 5, far below `1e20`'s
    /// ULP of ~32768) with a genuinely non-collinear third vertex offset
    /// by 50000 in `x` (well above that ULP, so `orient2d(pu,pv,pw)` is
    /// non-degenerate). Fixed by deciding the side from `edge`/`perp`'s
    /// rotation relation alone, never materializing `candidate` at all.
    #[test]
    fn ray_direction_correct_side_survives_large_offset_precision_loss() {
        let p0 = pt(1e20, 0.0);
        let p1 = pt(1e20, 5.0);
        let p2 = pt(1e20 - 50000.0, 2.5);
        assert_ne!(
            p2.x(),
            p0.x(),
            "fixture requires a genuinely distinct 3rd point"
        );
        let v = voronoi2(delaunay2(&[p0, p1, p2]));

        let mut checked = 0;
        for edge in v.edges() {
            if !matches!(v.edge_kind(edge), VoronoiEdgeKind::Unbounded { .. }) {
                continue;
            }
            let source_edge = v.dual_delaunay_edge(edge);
            let (du, dv) = v.delaunay.edge_vertices(source_edge);
            let face = v
                .delaunay
                .adjacent_faces(source_edge)
                .into_iter()
                .flatten()
                .next()
                .expect("a boundary Delaunay edge has exactly 1 incident face");
            let third = third_vertex(&v.delaunay, face, du, dv);

            let pu = v.delaunay.vertex_point(du);
            let pv = v.delaunay.vertex_point(dv);
            let pw = v.delaunay.vertex_point(third);
            let direction = v.outward_ray_direction(du, dv, third);

            // Independent side check, computed directly from the original
            // (unrounded) coordinate differences -- never materializes a
            // `pu + anything` point, so it isn't subject to the same
            // precision loss as the code under test.
            let edge_vec = (pv.x() - pu.x(), pv.y() - pu.y());
            let w_vec = (pw.x() - pu.x(), pw.y() - pu.y());
            let cross = |a: (f64, f64), b: (f64, f64)| a.0 * b.1 - a.1 * b.0;
            let side_w = cross(edge_vec, w_vec);
            let side_dir = cross(edge_vec, (direction.x(), direction.y()));
            assert!(
                side_w.signum() != side_dir.signum(),
                "direction must point to the opposite side from the third vertex \
                 (side_w={side_w}, side_dir={side_dir})"
            );
            checked += 1;
        }
        assert_eq!(checked, 3, "a single triangle has exactly 3 hull edges");
    }

    /// `edge_vector`'s core guarantee: finite, non-zero, for two distinct
    /// finite points regardless of magnitude -- including the case a
    /// plain `Point2 - Point2` genuinely cannot represent. A hull edge
    /// with endpoints at `-f64::MAX`/`f64::MAX` makes the plain
    /// subtraction overflow for real (`2*f64::MAX`, not just close to
    /// it), unlike this file's earlier `K = 2^1023` false start (which
    /// broke `orient2d` itself, not just the edge difference -- see
    /// `docs/numerical-model.md`). This test only checks `edge_vector` in
    /// isolation, not `orient2d`-based side correctness: at this
    /// magnitude, any orientation test involving this edge and a 3rd
    /// vertex would itself need a product term of order `edge_length *
    /// (3rd vertex offset)`, which overflows `f64` range for essentially
    /// any non-degenerate triangle -- a pre-existing `orient2d` limit, not
    /// something `edge_vector` changes or is responsible for.
    /// `docs/numerical-model.md`'s own measured-safe ceiling for
    /// `circumcenter`/`vertex_point` is `1e150` *uniform* magnitude, a
    /// narrower and different claim than "any mixed-magnitude input up to
    /// `f64::MAX` is fine" -- and a fuzz run of the new
    /// `fuzz/voronoi_geometry` target found this limit is sharper still:
    /// mixing an ordinary-magnitude point with one near `4e304` can make
    /// `orient2d` itself return *permutation-inconsistent* answers
    /// (`Clockwise` for `(a,b,c)`, `Collinear` for `(a,c,b)`) rather than
    /// just losing precision -- tracked as discovered work, not fixed by
    /// this construction.
    #[test]
    fn edge_vector_finite_and_nonzero_at_opposite_sign_near_f64_max() {
        let cases = [
            (pt(-f64::MAX, 0.0), pt(f64::MAX, 0.0)),
            (pt(0.0, -f64::MAX), pt(0.0, f64::MAX)),
            (pt(-f64::MAX, -f64::MAX), pt(f64::MAX, f64::MAX)),
            (pt(-f64::MAX * 0.6, 3.0), pt(f64::MAX * 0.6, -3.0)),
        ];
        for (pu, pv) in cases {
            assert!(
                !(pv.x() - pu.x()).is_finite() || !(pv.y() - pu.y()).is_finite(),
                "fixture must actually overflow plain subtraction: pu={pu:?} pv={pv:?}"
            );
            let e = edge_vector(pu, pv);
            assert!(
                e.x().is_finite() && e.y().is_finite(),
                "pu={pu:?} pv={pv:?} -> {e:?}"
            );
            assert!(
                e.x() != 0.0 || e.y() != 0.0,
                "pu={pu:?} pv={pv:?} -> zero vector"
            );
        }
    }

    /// `edge_vector` changes nothing for coordinate ranges this crate
    /// already exercises: below the overflow threshold, it must return
    /// the exact same value plain `pv - pu` would.
    #[test]
    fn edge_vector_matches_plain_subtraction_below_overflow_threshold() {
        let cases = [
            (pt(0.0, 0.0), pt(1.0, 0.0)),
            (pt(1e20, 0.0), pt(1e20, 5.0)),
            (pt(-1e150, 2e100), pt(3e150, -4e100)),
        ];
        for (pu, pv) in cases {
            let e = edge_vector(pu, pv);
            assert_eq!((e.x(), e.y()), (pv.x() - pu.x(), pv.y() - pu.y()));
        }
    }

    /// A shared boundary edge with the 3rd vertex once on each side --
    /// exercises both branches of `outward_ray_direction`'s
    /// `orient2d`-based sign choice (a single triangle's own fixed
    /// winding could otherwise only ever hit one branch), each verified
    /// against an independent exact cross-product side check.
    #[test]
    fn outward_ray_direction_correct_for_third_vertex_on_either_side() {
        let pu = pt(0.0, 0.0);
        let pv = pt(0.0, 10.0);
        let left = pt(-5.0, 5.0);
        let right = pt(5.0, 5.0);

        for third in [left, right] {
            let v = voronoi2(assemble_triangulation(
                vec![pu, pv, third],
                vec![[VertexId(0), VertexId(1), VertexId(2)]],
            ));
            let direction = v.outward_ray_direction(VertexId(0), VertexId(1), VertexId(2));
            assert!(direction.x().is_finite() && direction.y().is_finite());
            assert!(direction.x() != 0.0 || direction.y() != 0.0);

            let edge_vec = (pv.x() - pu.x(), pv.y() - pu.y());
            let w_vec = (third.x() - pu.x(), third.y() - pu.y());
            let cross = |a: (f64, f64), b: (f64, f64)| a.0 * b.1 - a.1 * b.0;
            let side_w = cross(edge_vec, w_vec);
            let side_dir = cross(edge_vec, (direction.x(), direction.y()));
            assert!(
                side_w.signum() != side_dir.signum(),
                "third={third:?}: direction must point opposite the 3rd vertex \
                 (side_w={side_w}, side_dir={side_dir})"
            );
        }
    }

    #[test]
    fn cocircular_cluster_plus_outlier_mixes_bounded_and_excluded_edges() {
        // A cocircular square (p0,p1,p2,p3), split by diagonal p0-p2,
        // plus a far-outside point p4 pulled in as an "ear" against edge
        // p1-p2. Unlike every other test in this file, exclusion here is
        // *partial*: p0-p2 (shared by the two square faces) is cocircular
        // and excluded, but p1-p2 (shared by a square face and the ear)
        // is not -- p4 is nowhere near the square's circumcircle -- so it
        // must survive as a genuine Bounded edge. A construction that
        // over-merges (e.g. unions any adjacent pair regardless of the
        // incircle test) or under-excludes (keeps p0-p2) would pass every
        // other test in this file but fail this one.
        let p0 = pt(0.0, 0.0);
        let p1 = pt(2.0, 0.0);
        let p2 = pt(2.0, 2.0);
        let p3 = pt(0.0, 2.0);
        let p4 = pt(6.0, 1.0);
        let pts = vec![p0, p1, p2, p3, p4];
        let faces = vec![
            [VertexId(1), VertexId(4), VertexId(2)], // ear: (p1, p4, p2)
            [VertexId(0), VertexId(1), VertexId(2)], // square half sharing p1-p2 and p0-p2
            [VertexId(0), VertexId(2), VertexId(3)], // square half sharing p0-p2
        ];
        let v = voronoi2(assemble_triangulation(pts, faces));

        assert_eq!(
            v.group_faces.len(),
            2,
            "the square's 2 faces merge (cocircular); the ear stays its own group"
        );
        assert_eq!(
            v.edges.len(),
            6,
            "7 Delaunay edges (5 hull + 2 interior) minus 1 excluded same-group diagonal"
        );

        let bounded: Vec<_> = v
            .edges
            .iter()
            .filter(|e| matches!(e.kind, VoronoiEdgeKind::Bounded { .. }))
            .collect();
        assert_eq!(
            bounded.len(),
            1,
            "only p1-p2 (square face vs. ear) is a genuine, non-cocircular interior edge"
        );
        match bounded[0].kind {
            VoronoiEdgeKind::Bounded { vertices } => {
                assert_ne!(
                    vertices[0], vertices[1],
                    "a Bounded edge must separate 2 distinct groups"
                );
            }
            VoronoiEdgeKind::Unbounded { .. } => unreachable!(),
        }
        assert_eq!(
            v.edges.len() - bounded.len(),
            5,
            "the remaining 5 edges are the pentagon's hull, all Unbounded"
        );
        assert!(v.validate_voronoi_topology().is_empty());
    }

    // -- Query API (Phase 7B) --

    #[test]
    fn query_api_matches_underlying_edge_and_group_data() {
        let pts = vec![pt(0.0, 0.0), pt(2.0, 0.0), pt(2.0, 2.0), pt(0.0, 2.0)];
        let v = voronoi2(delaunay2(&pts));

        assert_eq!(v.cells().count(), v.delaunay.vertices().count());
        assert_eq!(v.vertices().count(), v.group_faces.len());
        assert_eq!(v.edges().count(), v.edges.len());

        for (i, id) in v.edges().enumerate() {
            let raw = &v.edges[i];
            assert_eq!(v.edge_cells(id), raw.cells);
            assert_eq!(*v.edge_kind(id), raw.kind);
            assert_eq!(v.dual_delaunay_edge(id), raw.source_edge);
        }

        for (i, id) in v.vertices().enumerate() {
            assert_eq!(v.vertex_delaunay_faces(id), v.group_faces[i].as_slice());
        }

        for cell in v.cells() {
            assert_eq!(cell.0, v.cell_site(cell));
        }
    }

    #[test]
    fn neighboring_and_unbounded_queries_on_the_mixed_fixture() {
        // Same construction as
        // cocircular_cluster_plus_outlier_mixes_bounded_and_excluded_edges:
        // a cocircular square (p0..p3) plus a far outlier p4 pulled in as
        // an ear against edge p1-p2.
        let pts = vec![
            pt(0.0, 0.0),
            pt(2.0, 0.0),
            pt(2.0, 2.0),
            pt(0.0, 2.0),
            pt(6.0, 1.0),
        ];
        let faces = vec![
            [VertexId(1), VertexId(4), VertexId(2)],
            [VertexId(0), VertexId(1), VertexId(2)],
            [VertexId(0), VertexId(2), VertexId(3)],
        ];
        let v = voronoi2(assemble_triangulation(pts, faces));
        let p0 = VoronoiCellId(VertexId(0));

        assert!(
            v.cell_is_unbounded(p0),
            "p0 is a hull vertex of the pentagon"
        );
        let neighbor_sites: Vec<VertexId> =
            v.neighboring_cells(p0).map(|c| v.cell_site(c)).collect();
        assert_eq!(
            neighbor_sites.len(),
            2,
            "p0-p2 is cocircular and excluded, so p2 must not appear as a neighbor"
        );
        assert!(neighbor_sites.contains(&VertexId(1)));
        assert!(neighbor_sites.contains(&VertexId(3)));

        // Symmetry: p0 is a neighbor of each of its own neighbors.
        for cell in v.cells() {
            for neighbor in v.neighboring_cells(cell).collect::<Vec<_>>() {
                assert!(v.neighboring_cells(neighbor).any(|c| c == cell));
            }
        }
    }

    // -- Validator extension (Phase 7B) --
    //
    // voronoi2() itself never produces any of these 4 violations -- these
    // tests deliberately corrupt a valid Voronoi2's private fields (only
    // possible from within this module) to prove each check's *logic* is
    // right, as a regression guard, not because the constructor is
    // currently suspected of being wrong.

    #[test]
    fn validator_catches_deliberately_corrupted_invariants() {
        let pts = vec![
            pt(0.0, 0.0),
            pt(2.0, 0.0),
            pt(2.0, 2.0),
            pt(0.0, 2.0),
            pt(6.0, 1.0),
        ];
        let faces = vec![
            [VertexId(1), VertexId(4), VertexId(2)],
            [VertexId(0), VertexId(1), VertexId(2)],
            [VertexId(0), VertexId(2), VertexId(3)],
        ];
        let valid = voronoi2(assemble_triangulation(pts, faces));
        assert!(valid.validate_voronoi_topology().is_empty());

        let bounded_i = valid
            .edges
            .iter()
            .position(|e| matches!(e.kind, VoronoiEdgeKind::Bounded { .. }))
            .expect("the fixture has exactly one Bounded edge (p1-p2)");
        let unbounded_i = valid
            .edges
            .iter()
            .position(|e| matches!(e.kind, VoronoiEdgeKind::Unbounded { .. }))
            .expect("the fixture has 5 Unbounded hull edges");
        let excluded_interior_edge = valid
            .delaunay
            .edges()
            .find(|&e| {
                matches!(valid.delaunay.adjacent_faces(e), [Some(_), Some(_)])
                    && !valid.edges.iter().any(|ve| ve.source_edge == e)
            })
            .expect("the square's cocircular diagonal (p0-p2) is excluded and interior");

        let mut broken = valid.clone();
        broken.edges[bounded_i].cells[1] = broken.edges[bounded_i].cells[0];
        assert!(broken.validate_voronoi_topology().contains(
            &VoronoiTopologyError::NonDistinctEdgeCells {
                edge: VoronoiEdgeId(bounded_i as u32)
            }
        ));

        let mut broken = valid.clone();
        if let VoronoiEdgeKind::Bounded { vertices } = &mut broken.edges[bounded_i].kind {
            vertices[1] = vertices[0];
        }
        assert!(broken.validate_voronoi_topology().contains(
            &VoronoiTopologyError::NonDistinctBoundedVertices {
                edge: VoronoiEdgeId(bounded_i as u32)
            }
        ));

        let mut broken = valid.clone();
        broken.edges[unbounded_i].source_edge = excluded_interior_edge;
        assert!(broken.validate_voronoi_topology().contains(
            &VoronoiTopologyError::UnboundedEdgeNotHullDual {
                edge: VoronoiEdgeId(unbounded_i as u32)
            }
        ));

        let mut broken = valid.clone();
        let dup = broken.group_faces[0][0];
        broken.group_faces[0].push(dup);
        assert!(broken.validate_voronoi_topology().contains(
            &VoronoiTopologyError::DuplicateFaceInGroup {
                vertex: VoronoiVertexId(0),
                face: dup,
            }
        ));
    }

    // -- cell_edges (Phase 7C) --

    fn other_cell_site(v: &Voronoi2, e: VoronoiEdgeId, this: VoronoiCellId) -> VertexId {
        let [a, b] = v.edge_cells(e);
        v.cell_site(if a == this { b } else { a })
    }

    #[test]
    fn cell_edges_square_corner_is_exactly_two_rays() {
        // Every prior "fully cocircular" fixture in this file collapses
        // the same way for cell_edges: the excluded diagonal leaves each
        // corner with exactly its 2 hull rays and no Bounded edge.
        let pts = vec![pt(0.0, 0.0), pt(2.0, 0.0), pt(2.0, 2.0), pt(0.0, 2.0)];
        let v = voronoi2(delaunay2(&pts));
        for cell in v.cells() {
            let edges: Vec<_> = v.cell_edges(cell).collect();
            assert_eq!(edges.len(), 2);
            assert!(
                edges
                    .iter()
                    .all(|&e| matches!(v.edge_kind(e), VoronoiEdgeKind::Unbounded { .. }))
            );
        }
        assert!(v.validate_voronoi_topology().is_empty());
    }

    #[test]
    fn cell_edges_cocircular_ngon_multiple_triangulations_all_two_rays() {
        for &n in &[5usize, 8] {
            let pts = cocircular_lattice_points(n);
            for start in [0, n / 2] {
                let v = voronoi2(assemble_triangulation(pts.clone(), fan_from(n, start)));
                for cell in v.cells() {
                    assert_eq!(
                        v.cell_edges(cell).count(),
                        2,
                        "n={n} start={start}: every site's cell must be exactly 2 rays \
                         once the whole n-gon merges into one Voronoi vertex"
                    );
                }
                assert!(v.validate_voronoi_topology().is_empty());
            }
        }
    }

    #[test]
    fn cell_edges_partially_cocircular_fixture_matches_hand_verified_order() {
        // Same fixture as
        // cocircular_cluster_plus_outlier_mixes_bounded_and_excluded_edges:
        // a cocircular square (p0..p3) plus a far outlier p4 pulled in as
        // an ear against edge p1-p2.
        let pts = vec![
            pt(0.0, 0.0),
            pt(2.0, 0.0),
            pt(2.0, 2.0),
            pt(0.0, 2.0),
            pt(6.0, 1.0),
        ];
        let faces = vec![
            [VertexId(1), VertexId(4), VertexId(2)],
            [VertexId(0), VertexId(1), VertexId(2)],
            [VertexId(0), VertexId(2), VertexId(3)],
        ];
        let v = voronoi2(assemble_triangulation(pts, faces));

        // p0: a pure square corner untouched by p4 -- 2 rays, same shape
        // as cell_edges_square_corner_is_exactly_two_rays.
        let p0 = VoronoiCellId(VertexId(0));
        let p0_edges: Vec<_> = v.cell_edges(p0).collect();
        assert_eq!(p0_edges.len(), 2);
        assert_eq!(other_cell_site(&v, p0_edges[0], p0), VertexId(1));
        assert_eq!(other_cell_site(&v, p0_edges[1], p0), VertexId(3));

        // p1: hand-verified CCW order against p1's actual neighbor
        // directions -- p4 at ~14 deg, p2 at 90 deg, p0 at 180 deg from
        // p1=(2,0). Entry ray to p4, a genuine Bounded edge to p2 (not
        // excluded -- p4 is nowhere near the square's circumcircle),
        // exit ray to p0.
        let p1 = VoronoiCellId(VertexId(1));
        let p1_edges: Vec<_> = v.cell_edges(p1).collect();
        assert_eq!(p1_edges.len(), 3);
        assert_eq!(other_cell_site(&v, p1_edges[0], p1), VertexId(4));
        assert!(matches!(
            v.edge_kind(p1_edges[0]),
            VoronoiEdgeKind::Unbounded { .. }
        ));
        assert_eq!(other_cell_site(&v, p1_edges[1], p1), VertexId(2));
        assert!(matches!(
            v.edge_kind(p1_edges[1]),
            VoronoiEdgeKind::Bounded { .. }
        ));
        assert_eq!(other_cell_site(&v, p1_edges[2], p1), VertexId(0));
        assert!(matches!(
            v.edge_kind(p1_edges[2]),
            VoronoiEdgeKind::Unbounded { .. }
        ));

        // edge_cells() consistency, for every cell -- the user's
        // explicit minimum requirement.
        for cell in v.cells() {
            for e in v.cell_edges(cell) {
                assert!(v.edge_cells(e).contains(&cell));
            }
        }
        assert!(v.validate_voronoi_topology().is_empty());
    }

    #[test]
    fn cell_edges_near_cocircular_but_not_does_not_merge() {
        // p3 nudged 0.001 off the circle through p0,p1,p2 -- close, but
        // the exact incircle predicate must not treat it as cocircular.
        let pts = vec![pt(0.0, 0.0), pt(2.0, 0.0), pt(2.0, 2.0), pt(0.0, 2.001)];
        let faces = vec![
            [VertexId(0), VertexId(1), VertexId(2)],
            [VertexId(0), VertexId(2), VertexId(3)],
        ];
        let v = voronoi2(assemble_triangulation(pts, faces));

        assert_eq!(
            v.group_faces.len(),
            2,
            "a near-miss cocircular quad must not merge into one Voronoi vertex"
        );
        let p0_edges: Vec<_> = v.cell_edges(VoronoiCellId(VertexId(0))).collect();
        assert_eq!(
            p0_edges.len(),
            3,
            "p0's diagonal to p2 is now a genuine Bounded edge, not excluded"
        );
        assert!(
            p0_edges
                .iter()
                .any(|&e| matches!(v.edge_kind(e), VoronoiEdgeKind::Bounded { .. }))
        );
        assert!(v.validate_voronoi_topology().is_empty());
    }

    #[test]
    fn cell_edges_interior_cell_is_cyclically_consistent_on_a_60_point_cloud() {
        struct Xorshift64(u64);
        impl Xorshift64 {
            fn next_u64(&mut self) -> u64 {
                let mut x = self.0;
                x ^= x << 13;
                x ^= x >> 7;
                x ^= x << 17;
                self.0 = x;
                x
            }
            fn next_f64_in(&mut self, scale: f64) -> f64 {
                let bits = self.next_u64();
                let unit = (bits >> 11) as f64 * (1.0 / (1u64 << 53) as f64);
                (unit * 2.0 - 1.0) * scale
            }
        }

        let mut rng = Xorshift64(0x00c0_ffee_1234_5678);
        let pts: Vec<Point2> = (0..60)
            .map(|_| pt(rng.next_f64_in(100.0), rng.next_f64_in(100.0)))
            .collect();
        let v = voronoi2(delaunay2(&pts));
        assert!(v.validate_voronoi_topology().is_empty());

        let hull_sites: std::collections::HashSet<VertexId> = v
            .delaunay
            .boundary_edges()
            .flat_map(|e| {
                let (a, b) = v.delaunay.edge_vertices(e);
                [a, b]
            })
            .collect();

        let mut checked_interior_cell = false;
        for cell in v.cells() {
            let edges: Vec<_> = v.cell_edges(cell).collect();
            for &e in &edges {
                assert!(v.edge_cells(e).contains(&cell));
            }

            if hull_sites.contains(&v.cell_site(cell)) {
                assert!(edges.len() >= 2);
                assert!(matches!(
                    v.edge_kind(edges[0]),
                    VoronoiEdgeKind::Unbounded { .. }
                ));
                assert!(matches!(
                    v.edge_kind(*edges.last().unwrap()),
                    VoronoiEdgeKind::Unbounded { .. }
                ));
                // Same ordering property as the interior/cyclic case,
                // but *not* wrapping past the last edge back to the
                // first -- a hull cell's sequence is linear, not a
                // closed loop. Without this, a walk that emitted the
                // right multiset of edges with the middle ones out of
                // order (or reversed) would still pass the first/last
                // check above.
                let endpoint_set = |e: VoronoiEdgeId| -> Vec<VoronoiVertexId> {
                    match v.edge_kind(e) {
                        VoronoiEdgeKind::Bounded { vertices } => vertices.to_vec(),
                        VoronoiEdgeKind::Unbounded { finite_vertex } => vec![*finite_vertex],
                    }
                };
                for w in 0..edges.len() - 1 {
                    let a = endpoint_set(edges[w]);
                    let b = endpoint_set(edges[w + 1]);
                    let shared = a.iter().filter(|x| b.contains(x)).count();
                    assert_eq!(
                        shared, 1,
                        "consecutive hull cell_edges must share exactly one Voronoi vertex, in order"
                    );
                }
            } else {
                // The check that actually distinguishes a correctly
                // *ordered* walk from one that emits the right *set* in
                // the wrong order: consecutive edges (cyclically,
                // wrapping past the last back to the first) must share
                // exactly one Voronoi vertex.
                checked_interior_cell = true;
                assert!(
                    edges.len() >= 3,
                    "an interior Voronoi cell needs at least 3 edges to close"
                );
                let endpoints = |e: VoronoiEdgeId| -> [VoronoiVertexId; 2] {
                    match v.edge_kind(e) {
                        VoronoiEdgeKind::Bounded { vertices } => *vertices,
                        VoronoiEdgeKind::Unbounded { .. } => {
                            panic!("an interior cell cannot have an Unbounded edge")
                        }
                    }
                };
                for w in 0..edges.len() {
                    let a = endpoints(edges[w]);
                    let b = endpoints(edges[(w + 1) % edges.len()]);
                    let shared = a.iter().filter(|x| b.contains(x)).count();
                    assert_eq!(
                        shared, 1,
                        "consecutive cell_edges must share exactly one Voronoi vertex, in order"
                    );
                }
            }
        }
        assert!(
            checked_interior_cell,
            "a 60-point generic-position cloud must have at least one interior site"
        );
    }
}