cgar 0.2.0

CGAL-like computational geometry library in Rust
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
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2025 Alexandre Severino
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

use std::{
    array::from_fn,
    ops::{Add, Div, Mul, Sub},
};

use ahash::AHashSet;
use smallvec::SmallVec;

use crate::{
    geometry::{
        Aabb, AabbTree,
        plane::Plane,
        point::{Point, PointOps},
        segment::Segment,
        spatial_element::SpatialElement,
        util::*,
        vector::*,
    },
    impl_mesh,
    kernel::{self, predicates::TrianglePoint},
    mesh::basic_types::{
        IntersectionHit, IntersectionResult, Mesh, PairRing, PointInMeshResult, VertexRing,
    },
    numeric::scalar::Scalar,
    operations::Zero,
};

/// - Inside:    (f, usize::MAX, usize::MAX, 0)
/// - OnEdge:    (f, he_of_f_edge, usize::MAX, u in [0,1] along that half-edge)
/// - OnVertex:  (f, usize::MAX, vertex_id, 0)
#[derive(Debug)]
pub enum FindFaceResult<T> {
    Inside { f: usize, bary: (T, T, T) },
    OnEdge { f: usize, he: usize, u: T },
    OnVertex { f: usize, v: usize },
}

/// Kind of self-intersection detected between two faces.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelfIntersectionKind {
    // Non-coplanar triangles cross along a segment of positive length
    NonCoplanarCrossing,
    // Coplanar triangles have overlapping positive area (polygon overlap)
    CoplanarAreaOverlap,
    // Coplanar triangles overlap along a segment (not just a shared mesh edge)
    CoplanarEdgeOverlap,
}

/// A detected self-intersection/overlap between faces `a` and `b`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelfIntersection {
    pub a: usize,
    pub b: usize,
    pub kind: SelfIntersectionKind,
}

#[derive(Debug, Clone, PartialEq)]
pub enum VertexRayResult<T: Scalar> {
    /// Ray intersects opposite edge at distance t from vertex, at position u along the edge
    EdgeIntersection {
        half_edge: usize,
        distance: T,
        edge_parameter: T,
    },
    /// Ray is collinear with an edge of the triangle
    CollinearWithEdge(usize),
}

impl_mesh! {
    pub fn face_normal(&self, face_idx: usize) -> Vector<T, N> where Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>, {
        let face_vertices = self
            .face_vertices(face_idx)
            .map(|v| &self.vertices[v].position);
        let edge1 = (face_vertices[1] - face_vertices[0]).as_vector();
        let edge2 = (face_vertices[2] - face_vertices[0]).as_vector();
        edge1.cross(&edge2)
    }

    pub fn source(&self, he: usize) -> usize {
        self.half_edges[self.half_edges[he].prev].vertex
    }

    pub fn target(&self, he: usize) -> usize {
        self.half_edges[he].vertex
    }

    pub fn face_from_vertices(&self, v0: usize, v1: usize, v2: usize) -> usize {
        // find a face with the given vertex indices
        // It's more efficient to get faces around each vertex and check for a match
        let fs0 = self.faces_around_vertex(v0);
        let fs1 = self.faces_around_vertex(v1);
        let fs2 = self.faces_around_vertex(v2);

        for &face_id in fs0.iter() {
            if fs1.contains(&face_id) && fs2.contains(&face_id) {
                return face_id;
            }
        }
        usize::MAX
    }

    pub fn plane_from_face(&self, face_idx: usize) -> Plane<T, N> where Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,{
        let verts = self.face_vertices(face_idx); // [usize; N]
        let v0 = &self.vertices[verts[0]].position;
        let v1 = &self.vertices[verts[1]].position;
        let v2 = &self.vertices[verts[2]].position;

        Plane::from_points(v0, v1, v2)
    }

    /// Find existing vertex near position using spatial hash
    // fn find_nearby_vertex(&self, pos: &Point<T, N>, tolerance: T) -> Option<usize>
    // {
    //     let center_key = self.position_to_hash_key(pos);

    //     // Check center cell and 26 neighboring cells (3x3x3 grid)
    //     for dx in -1..=1 {
    //         for dy in -1..=1 {
    //             for dz in -1..=1 {
    //                 let key = (center_key.0 + dx, center_key.1 + dy, center_key.2 + dz);

    //                 if let Some(candidates) = self.vertex_spatial_hash.get(&key) {
    //                     for &vi in candidates {
    //                         if vi < self.vertices.len()
    //                             && self.vertices[vi].position.distance_to(pos) < tolerance
    //                         {
    //                             return Some(vi);
    //                         }
    //                     }
    //                 }
    //             }
    //         }
    //     }
    //     None
    // }

    pub fn faces_containing_point_aabb(
        &self,
        aabb_tree: &mut AabbTree<T, N, Point<T, N>, usize>,
        p: &Point<T, N>,
    ) -> Vec<usize>
    where
        Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
        for<'a> &'a T: Add<&'a T, Output = T>
            + Sub<&'a T, Output = T>
            + Mul<&'a T, Output = T>,
    {
        // 1) tight query box around p (avoid `.into()`; it’s a no-op but may hide clones)
        let tol  = T::query_tolerance();
        let qmin = Point::<T, N>::from_vals(std::array::from_fn(|i| &p[i] - &tol));
        let qmax = Point::<T, N>::from_vals(std::array::from_fn(|i| &p[i] + &tol));
        let query_aabb = Aabb::new(qmin, qmax);

        // 2) gather candidates
        let mut candidates = Vec::new();
        aabb_tree.query_valid(&query_aabb, &mut candidates);

        // Optional very-wide retry BEFORE rebuilding (keep constants exact)
        if candidates.is_empty() {
            let big = &T::tolerance() * &T::from(100); // exact 100
            let qmin2 = Point::<T, N>::from_vals(std::array::from_fn(|i| &p[i] - &big));
            let qmax2 = Point::<T, N>::from_vals(std::array::from_fn(|i| &p[i] + &big));
            let large = Aabb::from_points(&qmin2, &qmax2);
            aabb_tree.query_valid(&large, &mut candidates);
            // Avoid rebuilding here unless you really must. Rebuilding with LazyExact is expensive.
            // Prefer a periodic/explicit rebuild based on needs_rebuild().
        }

        if candidates.is_empty() {
            return Vec::new();
        }

        let mut result = Vec::with_capacity(candidates.len().min(8));

        // helpers only used when N==3; bail early otherwise
        if N != 3 {
            // fallback: keep your old kernel path if you support 2D as well
            for &face_idx in &candidates {
                let he0 = self.faces[*face_idx].half_edge;
                if he0 >= self.half_edges.len() { continue; }
                let he1 = self.half_edges[he0].next;
                let he2 = self.half_edges[he1].next;
                if he2 >= self.half_edges.len() || self.half_edges[he2].next != he0 { continue; }

                let a = &self.vertices[self.half_edges[he0].vertex].position;
                let b = &self.vertices[self.half_edges[he1].vertex].position;
                let c = &self.vertices[self.half_edges[he2].vertex].position;

                if kernel::point_in_or_on_triangle(p, a, b, c) == TrianglePoint::In {
                    result.push(*face_idx);
                }
            }
            return result;
        }

        // 3D fast path with zero duplicated math, squared plane test, sign-only decisions
        let tol2 = &tol * &tol;

        for &face_idx in &candidates {
            // (A) lightweight topology checks — ideally validate once at build!
            let he0 = self.faces[*face_idx].half_edge;
            if he0 >= self.half_edges.len() { continue; }
            let he1 = self.half_edges[he0].next;
            let he2 = self.half_edges[he1].next;
            if he1 >= self.half_edges.len() || he2 >= self.half_edges.len() || self.half_edges[he2].next != he0 { continue; }

            let v0 = self.half_edges[he0].vertex;
            let v1 = self.half_edges[he1].vertex;
            let v2 = self.half_edges[he2].vertex;
            if v0 >= self.vertices.len() || v1 >= self.vertices.len() || v2 >= self.vertices.len() { continue; }

            let a = &self.vertices[v0].position;
            let b = &self.vertices[v1].position;
            let c = &self.vertices[v2].position;

            // (B) geometry (single pass)
            let ab = (b - a).as_vector();
            let ac = (c - a).as_vector();
            let ap = (p - a).as_vector();

            let n   = ab.cross(&ac);
            let n2  = n.dot(&n);
            if n2.is_zero() { continue; } // degenerate face

            // plane distance squared: (n·ap)^2  ?  (tol^2) * (n·n)
            let d_plane = n.dot(&ap);
            let d2      = &d_plane * &d_plane;
            let rhs     = &tol2 * &n2;
            if (&d2 - &rhs).is_positive() { continue; }

            // edge functions on projected point: compute two, derive the third
            let bp = (p - b).as_vector();
            // let cp = (p - c).as_vector();
            let bc = (c - b).as_vector();
            // let ca = (a - c).as_vector();

            let e0 = ab.cross(&ap).dot(&n);
            let e1 = bc.cross(&bp).dot(&n);
            let e2 = &(&n2 - &e0) - &e1; // identity: e0 + e1 + e2 = n·n

            // inside iff all same sign or zero; treat boundary as "not strictly inside"
            // (If you want to count boundary as inside, change the checks to >= 0.)
            let z0 = e0.is_zero(); let z1 = e1.is_zero(); let z2 = e2.is_zero();
            let neg = (!z0 && e0.is_negative()) || (!z1 && e1.is_negative()) || (!z2 && e2.is_negative());
            let pos = (!z0 && e0.is_positive()) || (!z1 && e1.is_positive()) || (!z2 && e2.is_positive());

            if !(neg && pos) && !(z0 || z1 || z2) {
                // all nonzero and same sign -> strictly inside
                result.push(*face_idx);
            }
            // else: discard or record separately if you want “on edge/vertex”
        }

        result
    }

    /// Return the centroid of face `f` as a Vec<f64> of length = dimensions().
    /// Currently works for any dimension, but returns a flat Vec.
    pub fn face_centroid(&self, f: usize) -> Vector<T, N>
    {
        let face_vertices = self.face_vertices(f);
        let n = T::from(face_vertices.len() as f64);

        let mut centroid: Vector<T, N> = Vector::zero();

        for &v_idx in &face_vertices {
            let coords = self.vertices[v_idx].position.coords();
            for i in 0..3.min(N) {
                centroid[i] += &coords[i];
            }
        }

        for coord in centroid.coords_mut().iter_mut() {
            *coord = &*coord / &n;
        }

        centroid
    }

    pub fn face_centroid_fast(&self, face_idx: usize) -> Point<T, N> {
        let vs = self.face_vertices(face_idx);
        let coords = (0..N).map(|i| {
            let sum = (self.vertices[vs[0]].position[i].ball_center_f64() +
                    self.vertices[vs[1]].position[i].ball_center_f64() +
                    self.vertices[vs[2]].position[i].ball_center_f64()) / 3.0;
            sum
        }).collect::<Vec<_>>();
        Point::<T, N>::from_vals(from_fn(|i| T::from(coords[i])))
    }

    pub fn face_area(&self, f: usize) -> T
    {
        match N {
            2 => self.face_area_2(f),
            3 => self.face_area_3(f),
            _ => panic!("face_area only supports 2D and 3D"),
        }
    }

    fn face_area_2(&self, f: usize) -> T
    {
        let face_vertices = self.face_vertices(f);
        if face_vertices.len() != 3 {
            panic!("face_area only works for triangular faces");
        }

        let a = &self.vertices[face_vertices[0]].position;
        let b = &self.vertices[face_vertices[1]].position;
        let c = &self.vertices[face_vertices[2]].position;

        let ab = b - a;
        let ac = c - a;

        let ab_2 = Vector::<T, 2>::from_vals([ab[0].clone(), ab[1].clone()]);
        let ac_2 = Vector::<T, 2>::from_vals([ac[0].clone(), ac[1].clone()]);

        let cross_product = ab_2.cross(&ac_2);
        cross_product.abs() / T::from_num_den(2, 1)
    }

    fn face_area_3(&self, f: usize) -> T
    {
        let face_vertices = self.face_vertices(f);
        assert!(face_vertices.len() == 3, "face_area only works for triangular faces");

        let a = &self.vertices[face_vertices[0]].position;
        let b = &self.vertices[face_vertices[1]].position;
        let c = &self.vertices[face_vertices[2]].position;

        let ab = (b - a).as_vector();
        let ac = (c - a).as_vector();

        let ab_3 = Vector::<T, 3>::from_vals([ab[0].clone(), ab[1].clone(), ab[2].clone()]);
        let ac_3 = Vector::<T, 3>::from_vals([ac[0].clone(), ac[1].clone(), ac[2].clone()]);

        let cross = ab_3.cross(&ac_3);
        // area^2 = ||cross||^2 / 4
        cross.norm2() / T::from_num_den(4, 1)
    }

    /// Enumerate all outgoing half-edges from `v` exactly once,
    /// in CCW order.  Works even on meshes with open boundaries,
    /// *provided* you’ve first called `build_boundary_loops()`.
    pub fn outgoing_half_edges(&self, v: usize) -> Vec<usize> {
        let start = self.vertices[v]
            .half_edge
            .expect("vertex has no incident edges");
        let mut result = Vec::new();
        let mut h = start;
        loop {
            result.push(h);
            let t = self.half_edges[h].twin;
            // Now that every edge has a twin (real or ghost), we never hit usize::MAX
            h = self.half_edges[t].next;
            println!("trapped");
            if h == start {
                break;
            }
        }
        result
    }

    /// Returns true if vertex `v` has any outgoing ghost edge (face == None).
    pub fn is_boundary_vertex(&self, v: usize) -> bool {
        self.outgoing_half_edges(v)
            .into_iter()
            .any(|he| self.half_edges[he].face.is_none())
    }

    // /// Returns all vertex indices that lie on at least one boundary loop.
    pub fn boundary_vertices(&self) -> Vec<usize> {
        (0..self.vertices.len())
            .filter(|&v| self.is_boundary_vertex(v))
            .collect()
    }

    /// Returns the one-ring neighbors of vertex `v`.
    pub fn one_ring_neighbors(&self, v: usize) -> Vec<usize> {
        self.outgoing_half_edges(v)
            .iter()
            .map(|&he_idx| self.half_edges[he_idx].vertex)
            .collect()
    }

    /// Returns the indices of the half-edges bounding face `f`,
    /// in CCW order.
    pub fn face_half_edges(&self, f: usize) -> SmallVec<[usize; 3]> {
        if self.faces[f].removed {
            panic!("face_half_edges called on removed face {}", f);
        }
        let mut result = SmallVec::new();
        let start = self.faces[f].half_edge;
        let mut h = start;
        let mut iter_guard = 0;
        loop {
            result.push(h);
            h = self.half_edges[h].next;

            if h == start {
                break;
            }

            iter_guard += 1;

            if iter_guard > 3 {
                // panic!("face_half_edges: possible infinite loop detected");
                return result;
            }
        }
        result
    }

    #[inline]
    pub fn face_vertices(&self, f: usize) -> [usize; 3] {
        let he0 = self.faces[f].half_edge;
        let he1 = self.half_edges[he0].next;
        // debug_assert_eq!(self.half_edges[he2].next, he0);

        let a = self.half_edges[self.half_edges[he0].prev].vertex; // TAIL of he0
        let b = self.half_edges[he0].vertex;                       // HEAD of he0
        let c = self.half_edges[he1].vertex;                       // HEAD of he1
        [a, b, c]
    }

    /// Collect unique faces incident to `v` (with real faces only)
    pub fn incident_faces(&self, v: usize) -> AHashSet<usize> {
        let mut faces = AHashSet::new();
        let ring = self.vertex_ring_ccw(v);
        for &fopt in &ring.faces_ccw {
            if let Some(f) = fopt {
                if !self.faces[f].removed { faces.insert(f); }
            }
        }
        faces
    }

    pub fn point_on_half_edge(&self, he: usize, p: &Point<T, N>) -> Option<T>
    {
        let start = &self.vertices[self.half_edges[self.half_edges[he].prev].vertex].position;
        let end = &self.vertices[self.half_edges[he].vertex].position;

        kernel::point_u_on_segment(start, end, p)
    }

    pub fn point_on_half_edge_with_tolerance(&self, he: usize, p: &Point<T, N>, tolerance: &T) -> Option<T>
    {
        let start = &self.vertices[self.half_edges[self.half_edges[he].prev].vertex].position;
        let end = &self.vertices[self.half_edges[he].vertex].position;

        kernel::point_u_on_segment_with_tolerance(start, end, p, tolerance)
    }

    pub fn segment_from_half_edge(&self, he: usize) -> Segment<T, N> {
        let target = self.half_edges[he].vertex;
        let source = self.half_edges[self.half_edges[he].prev].vertex;
        Segment::new(
            &self.vertices[source].position,
            &self.vertices[target].position,
        )
    }

    pub fn adjacent_faces(&self, face_idx: usize) -> impl Iterator<Item = usize> + '_ {
        self.get_face_half_edges_iterative(face_idx)
            .into_iter()
            .flatten()
            .filter_map(move |he_idx| {
                let twin_idx = self.half_edges[he_idx].twin;
                if twin_idx != usize::MAX && twin_idx < self.half_edges.len() {
                    self.half_edges[twin_idx].face
                } else {
                    None
                }
            })
            .filter(move |&twin_face| twin_face != face_idx)
    }

    pub fn are_faces_adjacent(&self, f1: usize, f2: usize) -> bool {
        // Check if any half-edge of f1 is a twin of any half-edge of f2
        for h1 in self.face_half_edges(f1) {
            for h2 in self.face_half_edges(f2) {
                if self.half_edges[h1].twin == h2 {
                    return true;
                }
            }
        }
        false
    }

    pub fn point_in_mesh(
        &self,
        tree: &AabbTree<T, N, Point<T, N>, usize>,
        p: &Point<T, N>,
    ) -> PointInMeshResult where T: Into<T>, Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
    {
        let mut inside_count = 0;
        let mut total_rays = 0;
        let mut on_surface = false;

        let arr_rays = [
            [T::one(), T::zero(), T::zero()],
            [T::zero(), T::one(), T::zero()],
            [T::zero(), T::zero(), T::one()],
            [T::from(-1.0), T::zero(), T::zero()],
            [T::zero(), T::from(-1.0), T::zero()],
            [T::zero(), T::zero(), T::from(-1.0)],
        ];

        let rays = vec![
            Vector::<T, N>::from_vals(from_fn(|i| arr_rays[0][i].clone())),
            Vector::<T, N>::from_vals(from_fn(|i| arr_rays[1][i].clone())),
            Vector::<T, N>::from_vals(from_fn(|i| arr_rays[2][i].clone())),
            Vector::<T, N>::from_vals(from_fn(|i| arr_rays[3][i].clone())),
            Vector::<T, N>::from_vals(from_fn(|i| arr_rays[4][i].clone())),
            Vector::<T, N>::from_vals(from_fn(|i| arr_rays[5][i].clone())),
        ];

        for r in rays {
            if let IntersectionResult::Hit(hit, t) = self.cast_ray(p, &r, tree, &None) {
                match hit {
                    IntersectionHit::Face(..) => {
                        if t.is_zero() { on_surface = true; }
                        inside_count += 1;
                        total_rays += 1;
                    }
                    IntersectionHit::Edge(..) => {
                        if t.is_zero() { on_surface = true; }
                        inside_count += 1;
                        total_rays += 1;
                    }
                    IntersectionHit::Vertex(_) => {
                        if t.is_zero() { on_surface = true; }
                        inside_count += 1;
                        total_rays += 1;
                    }
                }
            }

        }

        if on_surface {
            PointInMeshResult::OnSurface
        } else if total_rays > 0 && inside_count > total_rays / 2 {
            PointInMeshResult::Inside
        } else {
            PointInMeshResult::Outside
        }
    }

    pub fn cast_ray(
        &self,
        p: &Point<T, N>,
        dir: &Vector<T, N>,
        tree: &AabbTree<T, N, Point<T, N>, usize>,
        tolerance: &Option<T>,
    ) -> IntersectionResult<T>
    where
        Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
        for<'a> &'a T: Add<&'a T, Output = T>
            + Sub<&'a T, Output = T>
            + Mul<&'a T, Output = T>
            + Div<&'a T, Output = T>,
    {
        let mut best_t: Option<T> = None;
        let mut best_result = IntersectionResult::Miss;

        let far_multiplier = T::from(10e6); // 10 km in mm units
        let far_point = Point::<T, N>::from_vals(std::array::from_fn(|i| {
            let tmp = &p[i] + &(&dir[i] * &far_multiplier);
            tmp.into()
        }));
        let p_f = Point::<T, N>::from_vals(std::array::from_fn(|i| {
            p[i].clone().into()
        }));
        let ray_aabb = Aabb::<T, N, Point<T, N>>::from_points(&p_f, &far_point);

        let mut candidate_faces = Vec::new();
        tree.query_valid(&ray_aabb, &mut candidate_faces);

        for &fi in &candidate_faces {
            let vs_idxs = self.face_vertices(*fi);
            let vs = [
                &self.vertices[vs_idxs[0]].position,
                &self.vertices[vs_idxs[1]].position,
                &self.vertices[vs_idxs[2]].position,
            ];

            if N == 3 {
                if let Some((t, u, v)) = ray_triangle_intersection(p, dir, std::array::from_fn(|i| vs[i]), tolerance) {
                    if t.is_negative() {
                        continue;
                    }
                    let one = T::one();
                    // Barycentrics from MT: l0 = 1 - u - v, l1 = u, l2 = v
                    let l1 = u;
                    let l2 = v;
                    let l0 = &one - &(&l1 + &l2);

                    let tol = tolerance.clone().unwrap_or_else(T::query_tolerance);

                    // Zero tests with tolerance (consistent with acceptance)
                    let z0 = !(&l0 - &tol).is_positive() && !(&l0 + &tol).is_negative();
                    let z1 = !(&l1 - &tol).is_positive() && !(&l1 + &tol).is_negative();
                    let z2 = !(&l2 - &tol).is_positive() && !(&l2 + &tol).is_negative();
                    let zero_count = (z0 as u8) + (z1 as u8) + (z2 as u8);

                    // Vertex hit: two zeros
                    if zero_count >= 2 {
                        let v_id = if z1 && z2 { vs_idxs[0] }
                                   else if z2 && z0 { vs_idxs[1] }
                                   else { vs_idxs[2] };
                        if best_t.is_none() || t < best_t.clone().unwrap() {
                            best_t = Some(t.clone());
                            best_result = IntersectionResult::Hit(IntersectionHit::Vertex(v_id), t.clone());
                        }
                        continue;
                    }

                    // Edge hit: exactly one zero
                    if zero_count == 1 {
                        // Snap near-zero to exact zero for stable mapping
                        let mut l0z = l0.clone();
                        let mut l1z = l1.clone();
                        let mut l2z = l2.clone();
                        if z0 { l0z = T::zero(); }
                        if z1 { l1z = T::zero(); }
                        if z2 { l2z = T::zero(); }

                        if let Some((he, mut u_edge)) = self.edge_and_u_from_bary_zero(*fi, &l0z, &l1z, &l2z) {
                            // Clamp u into [0,1] defensively
                            if u_edge.is_negative() { u_edge = T::zero(); }
                            if (&u_edge - &one).is_positive() { u_edge = one.clone(); }

                            let src = self.half_edges[self.half_edges[he].prev].vertex;
                            let dst = self.half_edges[he].vertex;

                            if best_t.is_none() || t < best_t.clone().unwrap() {
                                best_t = Some(t.clone());
                                best_result = IntersectionResult::Hit(IntersectionHit::Edge(src, dst, u_edge), t.clone());
                            }
                            continue;
                        }
                    }

                    // Face hit
                    if best_t.is_none() || t < best_t.clone().unwrap() {
                        best_t = Some(t.clone());
                        best_result = IntersectionResult::Hit(IntersectionHit::Face(*fi, (l0, l1, l2)), t);
                    }
                }
            }
        }

        best_result
    }

    pub fn faces_around_face(&self, face: usize) -> [usize; 3] {
        let mut result = [usize::MAX; 3];
        let mut current_he_idx = self.faces[face].half_edge;
        if current_he_idx == usize::MAX {
            panic!("Face has no half-edge.");
        }
        let starting_he_idx = current_he_idx;

        let mut i = 0;
        loop {
            let current_he = &self.half_edges[current_he_idx];
            if let Some(face_idx) = current_he.face
                && !self.faces[face_idx].removed
            {
                result[i] = face_idx; // valid half_edges should always point to valid faces
                i += 1;
                if i == 3 {
                    break; // we only need 3 faces
                }
            }

            let twin_idx = current_he.twin;
            let next_idx = self.half_edges[twin_idx].next;

            if next_idx == starting_he_idx {
                break;
            }

            current_he_idx = next_idx;
        }

        result
    }

    pub fn faces_around_vertex(&self, vertex: usize) -> Vec<usize> {
        let mut result = Vec::new();
        let mut current_he_idx = self.vertices[vertex]
            .half_edge
            .expect("Vertex has no half-edge.");
        let starting_he_idx = current_he_idx;

        loop {
            let current_he = &self.half_edges[current_he_idx];
            if let Some(face_idx) = current_he.face {
                if self.faces[face_idx].removed {
                    panic!("The structure here should always be valid.");
                }
                result.push(face_idx); // valid half_edges should always point to valid faces
            }

            let twin_idx = current_he.twin;
            let next_idx = self.half_edges[twin_idx].next;

            if next_idx == starting_he_idx {
                break;
            }

            current_he_idx = next_idx;
        }

        result
    }

    /// Cast a ray from a vertex within a triangle face along the geodesic direction.
    /// Preserves the surface curvature relationship of the direction vector.
    pub fn cast_ray_from_vertex_in_triangle_3(
        &self,
        face: usize,
        vertex: usize,
        direction: &Vector<T, N>,
    ) -> Option<VertexRayResult<T>>
    where
        Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
    {
        let vs = self.face_vertices(face);

        // Find vertex position in face and identify opposite edge
        let vertex_idx = vs.iter().position(|&v| v == vertex)?;
        let (opp_v1, opp_v2) = match vertex_idx {
            0 => (vs[1], vs[2]), // vertex is A, opposite edge is BC
            1 => (vs[2], vs[0]), // vertex is B, opposite edge is CA
            2 => (vs[0], vs[1]), // vertex is C, opposite edge is AB
            _ => return None,
        };

        let p0 = &self.vertices[vertex].position;
        let p1 = &self.vertices[opp_v1].position;
        let p2 = &self.vertices[opp_v2].position;

        // Calculate face normal and tangent vectors
        let vs_tri = [&self.vertices[vs[0]].position, &self.vertices[vs[1]].position, &self.vertices[vs[2]].position];
        let e1 = (vs_tri[1] - vs_tri[0]).as_vector();
        let e2 = (vs_tri[2] - vs_tri[0]).as_vector();
        let face_normal = e1.cross(&e2);

        let n2 = face_normal.dot(&face_normal);
        if n2.is_zero() {
            return None; // degenerate triangle
        }

        // Compute discrete metric tensor for geodesic preservation
        let e1_norm2 = e1.dot(&e1);
        let e2_norm2 = e2.dot(&e2);
        let e1_dot_e2 = e1.dot(&e2);

        let tol = T::tolerance();
        if e1_norm2.is_zero() || e2_norm2.is_zero() {
            return None; // degenerate edges
        }

        // Geodesic direction via parallel transport
        // Transform direction using the metric tensor to preserve geodesic properties
        let d_dot_e1 = direction.dot(&e1);
        let d_dot_e2 = direction.dot(&e2);

        // Metric determinant
        let metric_det = &e1_norm2 * &e2_norm2 - &e1_dot_e2 * &e1_dot_e2;
        if metric_det.abs() <= &tol * &tol {
            return None; // singular metric
        }

        // Geodesic-preserving projection using inverse metric tensor
        let inv_metric_det = T::one() / metric_det;
        let coeff1 = &(&d_dot_e1 * &e2_norm2 - &d_dot_e2 * &e1_dot_e2) * &inv_metric_det;
        let coeff2 = &(&d_dot_e2 * &e1_norm2 - &d_dot_e1 * &e1_dot_e2) * &inv_metric_det;

        let geodesic_dir = &e1.scale(&coeff1) + &e2.scale(&coeff2);

        // Validate geodesic direction magnitude
        let tol2 = &tol * &tol;
        if geodesic_dir.dot(&geodesic_dir) <= tol2 {
            return None; // geodesic direction too small
        }

        // Check collinearity with edges from the vertex
        let adjacent_edges = match vertex_idx {
            0 => [(vs[0], vs[1]), (vs[0], vs[2])],
            1 => [(vs[1], vs[2]), (vs[1], vs[0])],
            2 => [(vs[2], vs[0]), (vs[2], vs[1])],
            _ => return None,
        };

        for &(v_start, v_end) in &adjacent_edges {
            let edge_vec = (&self.vertices[v_end].position - &self.vertices[v_start].position).as_vector();
            let cross = geodesic_dir.cross(&edge_vec);

            if cross.dot(&cross) <= tol2 {
                if let Some(he) = self.half_edge_between(v_start, v_end) {
                    let dot = geodesic_dir.dot(&edge_vec);
                    if dot > tol {
                        return Some(VertexRayResult::CollinearWithEdge(he));
                    }
                }
                if let Some(he) = self.half_edge_between(v_end, v_start) {
                    let reverse_edge_vec = -edge_vec;
                    let dot = geodesic_dir.dot(&reverse_edge_vec);
                    if dot > tol {
                        return Some(VertexRayResult::CollinearWithEdge(he));
                    }
                }
            }
        }

        // Ray-segment intersection using geodesic direction
        let edge_vec = (p2 - p1).as_vector();
        let rhs = (p1 - p0).as_vector();

        let det = geodesic_dir.cross(&edge_vec).dot(&face_normal);
        if det.abs() <= tol {
            return None; // ray parallel to opposite edge
        }

        let inv_det = T::one() / det;
        let t = &rhs.cross(&edge_vec).dot(&face_normal) * &inv_det;
        let u = &geodesic_dir.cross(&rhs).dot(&face_normal) * &inv_det;

        // Validate solution
        if t <= tol || u < T::zero() || u > T::one() {
            println!("t is: {:?}", t);
            println!("Original direction: {:?}", direction);
            println!("Direction magnitude: {:?}", direction.dot(direction));
            println!("hit is behind or at start point");
            return None;
        }

        // Find the half-edge corresponding to the opposite edge
        let he_fwd = self.half_edge_between(opp_v1, opp_v2);
        let he_bwd = self.half_edge_between(opp_v2, opp_v1);

        let he = match (he_fwd, he_bwd) {
            (Some(h0), Some(h1)) => {
                if self.half_edges[h0].face == Some(face) { h0 }
                else if self.half_edges[h1].face == Some(face) { h1 }
                else { return None; }
            }
            (Some(h0), None) => {
                if self.half_edges[h0].face == Some(face) { h0 } else { return None; }
            }
            (None, Some(h1)) => {
                if self.half_edges[h1].face == Some(face) { h1 } else { return None; }
            }
            _ => return None,
        };

        // Adjust u parameter to match half-edge orientation
        let he_src = self.half_edges[self.half_edges[he].twin].vertex;
        let he_dst = self.half_edges[he].vertex;

        let u_param = if he_src == opp_v1 && he_dst == opp_v2 {
            u
        } else if he_src == opp_v2 && he_dst == opp_v1 {
            T::one() - u
        } else {
            return None;
        };

        Some(VertexRayResult::EdgeIntersection {
            half_edge: he,
            distance: t,
            edge_parameter: u_param,
        })
    }


    /// Cast a ray from a vertex within a triangle face along the given direction.
    /// Returns either an intersection with the opposite edge or indicates collinearity with an edge.
    pub fn cast_ray_from_vertex_in_triangle(
        &self,
        face: usize,
        vertex: usize,
        direction: &Vector<T, N>,
    ) -> Option<VertexRayResult<T>>
    where
        Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
    {
        let vs = self.face_vertices(face);

        // Find vertex position in face and identify opposite edge
        let vertex_idx = vs.iter().position(|&v| v == vertex)?;
        let (opp_v1, opp_v2) = match vertex_idx {
            0 => (vs[1], vs[2]), // vertex is A, opposite edge is BC
            1 => (vs[2], vs[0]), // vertex is B, opposite edge is CA
            2 => (vs[0], vs[1]), // vertex is C, opposite edge is AB
            _ => return None,
        };

        let p0 = &self.vertices[vertex].position;
        let p1 = &self.vertices[opp_v1].position;
        let p2 = &self.vertices[opp_v2].position;

        // Calculate face normal
        let vs_tri = [&self.vertices[vs[0]].position, &self.vertices[vs[1]].position, &self.vertices[vs[2]].position];
        let face_normal = {
            let e1 = (vs_tri[1] - vs_tri[0]).as_vector();
            let e2 = (vs_tri[2] - vs_tri[0]).as_vector();
            e1.cross(&e2)
        };

        let n2 = face_normal.dot(&face_normal);
        if n2.is_zero() {
            println!("degenerate triangle");
            return None; // degenerate triangle
        }

        // Project direction onto the face plane
        let dot_dn = direction.dot(&face_normal);
        let projected_dir = direction - &face_normal.scale(&(&dot_dn / &n2));

        // Check if projected direction is essentially zero
        let tol = T::tolerance();
        let tol2 = &tol * &tol;
        if projected_dir.dot(&projected_dir) <= tol2 {
            println!("direction is perpendicular to face plane");
            return None; // direction is perpendicular to face plane
        }

        // Check collinearity with edges from the vertex
        let adjacent_edges = match vertex_idx {
            0 => [(vs[0], vs[1]), (vs[0], vs[2])], // edges from vertex A
            1 => [(vs[1], vs[2]), (vs[1], vs[0])], // edges from vertex B
            2 => [(vs[2], vs[0]), (vs[2], vs[1])], // edges from vertex C
            _ => return None,
        };

        for &(v_start, v_end) in &adjacent_edges {
            let edge_vec = (&self.vertices[v_end].position - &self.vertices[v_start].position).as_vector();
            let cross = projected_dir.cross(&edge_vec);

            // Check if vectors are collinear (cross product near zero)
            if cross.dot(&cross) <= tol2 {
                // Find the half-edge for this edge direction
                if let Some(he) = self.half_edge_between(v_start, v_end) {
                    // Ensure the direction is forward along the edge (not backward)
                    let dot = projected_dir.dot(&edge_vec);
                    if dot > tol {
                        return Some(VertexRayResult::CollinearWithEdge(he));
                    }
                }
                // Check reverse direction
                if let Some(he) = self.half_edge_between(v_end, v_start) {
                    let reverse_edge_vec = -edge_vec;
                    let dot = projected_dir.dot(&reverse_edge_vec);
                    if dot > tol {
                        return Some(VertexRayResult::CollinearWithEdge(he));
                    }
                }
            }
        }

        // Ray-segment intersection using projected direction
        let edge_vec = (p2 - p1).as_vector();
        let rhs = (p1 - p0).as_vector();

        // Solve 2x2 system using cross products projected onto face normal
        let det = projected_dir.cross(&edge_vec).dot(&face_normal);

        if det.abs() <= tol {
            println!("Starting pos: {:?}", &self.vertices[vertex].position);
            println!("Original direction: {:?}", direction);
            println!("Direction magnitude: {:?}", direction.dot(direction));
            println!("half-edge endpoints: {:?}", (&self.vertices[opp_v1].position, &self.vertices[opp_v2].position));
            println!("-> ray parallel to opposite edge");
            return None; // ray parallel to opposite edge
        }

        let inv_det = T::one() / det;
        let t = &rhs.cross(&edge_vec).dot(&face_normal) * &inv_det;
        let u = &rhs.cross(&projected_dir).dot(&face_normal) * &inv_det;

        // Validate solution
        if t <= tol {
            println!("Starting pos: {:?}", &self.vertices[vertex].position);
            println!("t is: {:?}", t);
            println!("Original direction: {:?}", direction);
            println!("Direction magnitude: {:?}", direction.dot(direction));
            println!("half-edge endpoints: {:?}", (&self.vertices[opp_v1].position, &self.vertices[opp_v2].position));
            println!("-> hit is behind or at start point");
            return None; // hit is behind or at start point
        }

        if u < T::zero() || u > T::one() {
            println!("Starting pos: {:?}", &self.vertices[vertex].position);
            println!("u is: {:?}", u);
            println!("Original direction: {:?}", direction);
            println!("Direction magnitude: {:?}", direction.dot(direction));
            println!("half-edge endpoints: {:?}", (&self.vertices[opp_v1].position, &self.vertices[opp_v2].position));
            println!("-> hit is outside segment");
            return None; // hit is outside segment
        }

        // Find the half-edge corresponding to the opposite edge
        let he_fwd = self.half_edge_between(opp_v1, opp_v2);
        let he_bwd = self.half_edge_between(opp_v2, opp_v1);

        let he = match (he_fwd, he_bwd) {
            (Some(h0), Some(h1)) => {
                // Prefer the half-edge whose face is the query face
                if self.half_edges[h0].face == Some(face) {
                    h0
                } else if self.half_edges[h1].face == Some(face) {
                    h1
                } else {
                    println!("no matching half-edge found for face 1 - {}", face);
                    return None;
                }
            }
            (Some(h0), None) => {
                if self.half_edges[h0].face == Some(face) {
                    h0
                } else {
                    println!("no matching half-edge found for face 2 - {}", face);
                    return None;
                }
            }
            (None, Some(h1)) => {
                if self.half_edges[h1].face == Some(face) {
                    h1
                } else {
                    println!("no matching half-edge found for face 3 - {}", face);
                    return None;
                }
            }
            _ => { println!("no matching half-edge found for face 4 - {}", face); return None },
        };

        // Adjust u parameter to match half-edge orientation
        let he_src = self.half_edges[self.half_edges[he].twin].vertex;
        let he_dst = self.half_edges[he].vertex;

        let u_param = if he_src == opp_v1 && he_dst == opp_v2 {
            u // half-edge goes v1->v2, u is correct
        } else if he_src == opp_v2 && he_dst == opp_v1 {
            T::one() - u // half-edge goes v2->v1, flip u
        } else {
            println!("topology mismatch");
            return None; // topology mismatch
        };

        Some(VertexRayResult::EdgeIntersection {
            half_edge: he,
            distance: t,
            edge_parameter: u_param,
        })
    }

    pub fn get_first_half_edge_intersection_on_face(
        &self,
        face: usize,
        from: &Point<T, N>,
        direction: &Vector<T, N>,
    ) -> Option<(usize, T, T)>
    where Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
    {
        // 0) Quick sanity: face must be valid and triangular
        if self.faces[face].removed {
            return None;
        }

        let hes = self.face_half_edges(face);
        if hes.len() != 3 {
            // This routine is triangle-only.
            return None;
        }
        if self.half_edges[hes[0]].removed
            || self.half_edges[hes[1]].removed
            || self.half_edges[hes[2]].removed
        {
            return None;
        }

        // 1) Plane data
        let plane = self.plane_from_face(face);
        let origin = plane.origin();            // a point on the plane
        let origin = Point::<T, N>::from_vals(from_fn(|i| origin[i].clone()));
        let (u3, v3) = plane.basis();           // two independent in-plane vectors
        let n3 = u3.cross(&v3);                 // plane normal (not necessarily unit)

        // Guard against degenerate plane (area ~ 0)
        let tol = T::tolerance();
        let tol2 = &tol * &tol;
        let n2 = n3.dot(&n3);
        if n2 <= tol2 {
            // Degenerate face: skip
            return None;
        }

        // 2) Intersect 3D ray with plane: from + t_plane * direction
        let w = (from - &origin).as_vector();
        let num  = -w.dot(&n3);
        let den  = direction.dot(&n3);

        // Helper: near-zero test
        let near_zero = |x: &T| -> bool {
            let mtol = -tol.clone();
            x >= &mtol && x <= &tol
        };

        let start_on_plane: Point<T, N>;
        let mut dir_in_plane3  = direction.clone();

        if near_zero(&den) {
            // Ray parallel to plane
            if !near_zero(&num) {
                // Off-plane and parallel => never meets the plane
                return None;
            }
            // In-plane ray: remove any residual normal component (robust)
            // dir_in_plane3 = direction - proj_n(direction)
            let k = &direction.dot(&n3) / &n2; // this is ~0 but keeps consistency
            dir_in_plane3 = &dir_in_plane3 - &n3.scale(&k);
            start_on_plane = from.clone();
        } else {
            // Proper intersection: advance origin to the hit point on the plane
            let t_plane = &num / &den;

            // FIX 1: accept starts exactly on the plane (t≈0); only reject if strictly behind more than tol
            if &t_plane < &(-tol.clone()) {
                return None;
            }
            // Clamp tiny negative t to zero to stay numerically stable
            let t_clamped = if t_plane > T::zero() { t_plane } else { T::zero() };

            // start_on_plane = from + t_clamped * direction
            start_on_plane = (&from.as_vector() + &direction.scale(&t_clamped)).0;

            // Only the in-plane component should drive the boundary hit
            let k = &direction.dot(&n3) / &n2;
            dir_in_plane3 = &dir_in_plane3 - &n3.scale(&k);
        }

        // 3) Project to a 2D basis on the plane
        let project2 = |p: &Point<T, N>| -> Point<T, 2> {
            let d = (p - &origin).as_vector();
            Point::<T, 2>::new([d.dot(&u3), d.dot(&v3)])
        };
        let projectv2 = |v: &Vector<T, N>| -> Vector<T, 2> {
            Vector::<T, 2>::new([v.dot(&u3), v.dot(&v3)])
        };

        let from2 = project2(&start_on_plane);
        let dir2  = projectv2(&dir_in_plane3);

        // If projected direction is (near) zero, there is no forward in-plane march
        if dir2.dot(&dir2) <= tol2 {
            return None;
        }

        // 4) Build 2D endpoints for each half-edge using the half-edge's TAIL -> HEAD (prev.vertex -> he.vertex)
        let mut best: Option<(usize, T, T)> = None; // (he_idx, t_in_plane, u_on_segment)

        for &he_idx in &hes {
            let he = &self.half_edges[he_idx];

            // FIX 2: use geometric edge of he = (tail -> head) = (prev.vertex -> he.vertex)
            let src = self.half_edges[he.prev].vertex; // tail of he
            let dst = he.vertex;                       // head of he

            let a3 = &self.vertices[src].position;
            let b3 = &self.vertices[dst].position;

            let a2 = project2(a3);
            let b2 = project2(b3);

            if let Some((t_hit, u_seg)) =
                ray_segment_intersection_2d_robust(&from2, &dir2, &a2, &b2, &tol)
            {
                if t_hit >= tol {
                    match &mut best {
                        None => best = Some((he_idx, t_hit, u_seg)),
                        Some((best_he, best_t, best_u)) => {
                            if &t_hit < best_t {
                                *best_he = he_idx;
                                *best_t = t_hit;
                                *best_u = u_seg;
                            } else if near_zero(&(&t_hit - best_t)) && he_idx < *best_he {
                                *best_he = he_idx;
                                *best_t = t_hit;
                                *best_u = u_seg;
                            }
                        }
                    }
                }
            }
        }

        best
    }

    pub fn half_edge_between(&self, vi0: usize, vi1: usize) -> Option<usize> {
        self.edge_map.get(&(vi0, vi1)).copied()
    }

    pub fn edge_half_edges(&self, v0: usize, v1: usize) -> Option<(usize, usize)> {
        if let Some(&he0) = self.edge_map.get(&(v0, v1)) {
            return Some((he0, self.half_edges[he0].twin));
        }
        None
    }

    pub fn point_is_on_some_half_edge(&self, face: usize, point: &Point<T, N>) -> Option<(usize, T)>
    where
        Point<T, N>: PointOps<T, N, Vector = Vector<T, N>>,
        Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
        for<'a> &'a T: Sub<&'a T, Output = T>
            + Mul<&'a T, Output = T>
            + Add<&'a T, Output = T>
            + Div<&'a T, Output = T>,
    {
        if self.faces[face].removed {
            return None;
        }
        // Check if point is on any edge of the face
        for &he in &self.face_half_edges(face) {
            let src = self.half_edges[self.half_edges[he].prev].vertex;
            let dst = self.half_edges[he].vertex;
            let ps = &self.vertices[src].position;
            let pd = &self.vertices[dst].position;
            // Is point on segment [ps, pd]?
            if let Some(u) = kernel::point_u_on_segment(ps, pd, point) {
                return Some((he, u));
            }
        }
        None
    }

    #[inline]
    pub fn face_edges(&self, f: usize) -> (usize, usize, usize) {
        let e0 = self.faces[f].half_edge;
        let e1 = self.half_edges[e0].next;
        let e2 = self.half_edges[e1].next;
        debug_assert_eq!(self.half_edges[e2].next, e0);
        (e0, e1, e2) // e0: a->b, e1: b->c, e2: c->a
    }

    // Map bary zero to (edge, u) on face f:
    // l2==0 => edge a-b -> e0, u=l1;  l0==0 => edge b-c -> e1, u=l2;  l1==0 => edge c-a -> e2, u=l0.
    pub fn edge_and_u_from_bary_zero(&self, f: usize, l0: &T, l1: &T, l2: &T) -> Option<(usize, T)> {
        let (e0,e1,e2) = self.face_edges(f);
        if l2.is_zero() { return Some((e0, l1.clone())); }
        if l0.is_zero() { return Some((e1, l2.clone())); }
        if l1.is_zero() { return Some((e2, l0.clone())); }
        None
    }

    // Two bary zeros => vertex id on face f.
    pub fn vertex_from_bary_zero(&self, f: usize, l0: &T, l1: &T, l2: &T) -> Option<usize> {
        let [a,b,c] = self.face_vertices(f);
        if l1.is_zero() && l2.is_zero() { return Some(a); }
        if l2.is_zero() && l0.is_zero() { return Some(b); }
        if l0.is_zero() && l1.is_zero() { return Some(c); }
        None
    }

    pub fn location_on_face(&self, f: usize, p: &Point<T, N>)  -> FindFaceResult<T> {
        let zero = T::zero();
        let one  = T::one();

        let [i0, i1, i2] = self.face_vertices(f);
        let (l0, l1, l2) = barycentric_coords(
                p,
                &self.vertices[i0].position,
                &self.vertices[i1].position,
                &self.vertices[i2].position,
            ).unwrap();

        // OnEdge (exactly one zero)
        let zc = l0.is_zero() as u8 + l1.is_zero() as u8 + l2.is_zero() as u8;
        if zc == 1 {
            if let Some((he_guess, mut u_bary)) = self.edge_and_u_from_bary_zero(f, &l0, &l1, &l2) {
                if u_bary.is_negative() { u_bary = zero.clone(); }
                if (&u_bary - &one).is_positive() { u_bary = one.clone(); }
                return FindFaceResult::OnEdge { f, he: he_guess, u: u_bary };
            }
        }

        // OnVertex (exactly two zeros)
        if zc >= 2 {
            if let Some(v_id) = self.vertex_from_bary_zero(f, &l0, &l1, &l2) {
                return FindFaceResult::OnVertex { f, v: v_id };
            }
            // Fallback if ambiguous: treat as inside
            return FindFaceResult::Inside { f, bary: (l0, l1, l2) };
        }

        // Inside (no zeros, all non-negative)
        return FindFaceResult::Inside { f, bary: (l0, l1, l2) };
    }

    /// Returns (face_id, half_edge_id, vertex_id, u).
    /// Order of detection priority: OnEdge -> OnVertex -> Inside.
    /// - Inside:    (f, usize::MAX, usize::MAX, 0)
    /// - OnEdge:    (f, he_of_f_edge, usize::MAX, u in [0,1] along that half-edge)
    /// - OnVertex:  (f, usize::MAX, vertex_id, 0)
    pub fn find_valid_face(&self, start_face: usize, point: &Point<T, N>) -> FindFaceResult<T>
    where
        Point<T, N>: PointOps<T, N, Vector = Vector<T, N>>,
        Vector<T, N>: VectorOps<T, N>,
        Vector<T, 3>: VectorOps<T, 3, Cross = Vector<T, 3>>,
        for<'a> &'a T:
            Sub<&'a T, Output = T> +
            Mul<&'a T, Output = T> +
            Add<&'a T, Output = T> +
            Div<&'a T, Output = T>,
    {
        use std::collections::VecDeque;

        let zero = T::zero();
        let one  = T::one();

        #[inline]
        fn live_face_degenerate<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, f: usize) -> bool
        where
            Point<TS, M>: PointOps<TS, M, Vector = Vector<TS, M>>,
            Vector<TS, M>: VectorOps<TS, M>,
            Vector<TS, 3>: VectorOps<TS, 3, Cross = Vector<TS, 3>>,
            for<'a> &'a TS: Add<&'a TS, Output = TS>
                        + Sub<&'a TS, Output = TS>
                        + Mul<&'a TS, Output = TS>,
        {
            // vertices (A,B,C) of face f
            let [i0, i1, i2] = {
                let e0 = mesh.faces[f].half_edge;
                let e1 = mesh.half_edges[e0].next;
                let a = mesh.half_edges[mesh.half_edges[e0].prev].vertex; // tail(e0)
                let b = mesh.half_edges[e0].vertex;                       // head(e0)
                let c = mesh.half_edges[e1].vertex;                       // head(e1)
                [a, b, c]
            };

            // zero-length edge => degenerate
            let ab = (&mesh.vertices[i1].position - &mesh.vertices[i0].position).as_vector();
            let ac = (&mesh.vertices[i2].position - &mesh.vertices[i0].position).as_vector();
            let bc = (&mesh.vertices[i2].position - &mesh.vertices[i1].position).as_vector();
            if ab.dot(&ab).is_zero() || ac.dot(&ac).is_zero() || bc.dot(&bc).is_zero() {
                return true;
            }

            // collinear A,B,C => degenerate (3D-safe; for 2D z=0 it still works)
            let ab3 = ab.0.as_vector_3();
            let ac3 = ac.0.as_vector_3();
            let n = ab3.cross(&ac3);               // compute once
            // exact test with LazyExact: only true if *exactly* collinear
            n[0].is_zero() && n[1].is_zero() && n[2].is_zero()
        }

        // Exact barycentrics (l0,l1,l2) with respect to face f, using current vertex positions
        let bary_live = |f: usize| -> (T, T, T) {
            let [i0,i1,i2] = self.face_vertices(f);
            barycentric_coords(
                point,
                &self.vertices[i0].position,
                &self.vertices[i1].position,
                &self.vertices[i2].position,
            ).unwrap()
        };

        // neighbors of a live face via twins (skip borders / removed faces)
        let push_live_neighbors = |mesh: &Mesh<T, N>, f: usize, q: &mut VecDeque<usize>, seen: &AHashSet<usize>| {
            let (e0,e1,e2) = self.face_edges(f);
            for e in [e0,e1,e2] {
                let tw = mesh.half_edges[e].twin;
                if let Some(fnbr) = mesh.half_edges[tw].face {
                    if !mesh.faces[fnbr].removed && !seen.contains(&fnbr) {
                        q.push_back(fnbr);
                    }
                }
            }
        };

        // --- BFS over descendants + neighbors ---
        let mut q: VecDeque<usize> = VecDeque::new();
        let mut seen: AHashSet<usize> = AHashSet::new();
        q.push_back(start_face);

        let mut steps = 0usize;
        while let Some(f) = q.pop_front() {
            if !seen.insert(f) { continue; }
            steps += 1;
            debug_assert!(steps < 1_000_000, "find_valid_face: excessive traversal");

            if !self.faces[f].removed {
                // Barycentric-driven membership and priority: Edge -> Vertex -> Inside
                let (l0, l1, l2) = bary_live(f);
                let neg = |x: &T| -> bool { x.is_negative() };

                if neg(&l0) || neg(&l1) || neg(&l2) {
                    // Off this face; explore neighbors
                    push_live_neighbors(self, f, &mut q, &seen);
                    continue;
                }

                return self.location_on_face(f, point);
            }

            // Removed face: descend via recorded triangles (use current vertex positions for test)
            if let Some(mapping) = self.face_split_map.get(&f) {
                let mut interior: Vec<usize> = Vec::new();
                let mut boundary:  Vec<usize> = Vec::new();

                for tri in &mapping.new_faces {
                    let [i0,i1,i2] = tri.vertices.as_array();
                    let (l0,l1,l2) = barycentric_coords(
                        point,
                        &self.vertices[i0].position,
                        &self.vertices[i1].position,
                        &self.vertices[i2].position,
                    ).unwrap();

                    let neg = |x: &T| -> bool { x.is_negative() };
                    if neg(&l0) || neg(&l1) || neg(&l2) {
                        continue; // Off
                    }

                    let zc = l0.is_zero() as u8 + l1.is_zero() as u8 + l2.is_zero() as u8;
                    if zc >= 1 {
                        boundary.push(tri.face_idx); // OnEdge or OnVertex -> boundary
                    } else {
                        interior.push(tri.face_idx); // Inside
                    }
                }

                for fc in interior { if !seen.contains(&fc) { q.push_front(fc); } }
                for fc in boundary  { if !seen.contains(&fc) { q.push_back(fc); } }
                for tri in &mapping.new_faces {
                    let fc = tri.face_idx;
                    if !seen.contains(&fc) { q.push_back(fc); }
                }
                continue;
            }
        }

        // --- Global fallback: scan all live faces and pick the first match by priority ---
        let mut best_edge:   Option<(usize, usize, T)> = None; // (f, he, u)
        let mut best_vertex: Option<(usize, usize)>    = None; // (f, v_id)
        let mut best_inside: Option<(usize, (T, T, T))> = None; // (f, bary)

        for f in 0..self.faces.len() {
            if self.faces[f].removed { continue; }
            if live_face_degenerate(self, f) { continue; }

            let (l0,l1,l2) = bary_live(f);
            let neg = |x: &T| -> bool { x.is_negative() };
            if neg(&l0) || neg(&l1) || neg(&l2) { continue; }

            let zc = l0.is_zero() as u8 + l1.is_zero() as u8 + l2.is_zero() as u8;

            if zc == 1 && best_edge.is_none() {
                if let Some((he_guess, mut u_bary2)) = self.edge_and_u_from_bary_zero(f, &l0, &l1, &l2) {
                    if u_bary2.is_negative() { u_bary2 = zero.clone(); }
                    if (&u_bary2 - &one).is_positive() { u_bary2 = one.clone(); }
                    best_edge = Some((f, he_guess, u_bary2));
                    break; // edge has highest priority
                }
            } else if zc >= 2 && best_vertex.is_none() {
                if let Some(v_id) = self.vertex_from_bary_zero(f, &l0, &l1, &l2) {
                    best_vertex = Some((f, v_id));
                }
            } else if zc == 0 && best_inside.is_none() {
                best_inside = Some((f, (l0, l1, l2)));
            }
        }

        if let Some((f, he, u)) = best_edge   { return FindFaceResult::OnEdge { f, he, u }; }
        if let Some((f, v))     = best_vertex { return FindFaceResult::OnVertex { f, v }; }
        if let Some((f, bary))  = best_inside { return FindFaceResult::Inside { f, bary }; }

        panic!("find_valid_face: could not locate a face/edge/vertex for the point starting from {}", start_face);
    }

    /// Returns (face_id, half_edge_id, vertex_id, u).
    /// - Inside:    (f, usize::MAX, usize::MAX, 0)
    /// - OnEdge:    (f, he_of_f_edge, usize::MAX, u in [0,1] along that half-edge)
    /// - OnVertex:  (f, usize::MAX, vertex_id, 0)
    pub fn find_valid_face_working_but_weird(&self, start_face: usize, point: &Point<T, N>) -> (usize, usize, usize, T)
    where
        Point<T, N>: PointOps<T, N, Vector = Vector<T, N>>,
        Vector<T, N>: VectorOps<T, N>,
        Vector<T, 3>: VectorOps<T, 3, Cross = Vector<T, 3>>,
        for<'a> &'a T:
            Sub<&'a T, Output = T> +
            Mul<&'a T, Output = T> +
            Add<&'a T, Output = T> +
            Div<&'a T, Output = T>,
    {
        use std::collections::VecDeque;

        let zero = T::zero();
        let one  = T::one();

        #[inline]
        fn get_face_cycle<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, f: usize) -> (usize, usize, usize) {
            let e0 = mesh.faces[f].half_edge;
            let e1 = mesh.half_edges[e0].next;
            let e2 = mesh.half_edges[e1].next;
            debug_assert_eq!(mesh.half_edges[e2].next, e0);
            (e0, e1, e2) // e0: a->b, e1: b->c, e2: c->a
        }

        #[inline]
        fn face_vertices<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, f: usize) -> [usize; 3] {
            let (e0, e1, _e2) = get_face_cycle(mesh, f);
            let a = mesh.half_edges[mesh.half_edges[e0].prev].vertex; // origin(e0)
            let b = mesh.half_edges[e0].vertex;                       // target(e0)
            let c = mesh.half_edges[e1].vertex;                       // target(e1)
            [a, b, c]
        }

        #[inline]
        fn live_face_degenerate<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, f: usize) -> bool
        where
            Point<TS, M>: PointOps<TS, M, Vector = Vector<TS, M>>,
            Vector<TS, M>: VectorOps<TS, M>,
            Vector<TS, 3>: VectorOps<TS, 3, Cross = Vector<TS, 3>>,
            for<'a> &'a TS: Add<&'a TS, Output = TS> + Sub<&'a TS, Output = TS> + Mul<&'a TS, Output = TS>,
        {
            let [i0,i1,i2] = face_vertices(mesh, f);
            let u = (&mesh.vertices[i1].position - &mesh.vertices[i0].position).as_vector_3();
            let v = (&mesh.vertices[i2].position - &mesh.vertices[i0].position).as_vector_3();
            let n = u.cross(&v);
            let n2 = n.dot(&n);
            n2.is_zero()
        }

        let classify_live = |f: usize| -> TrianglePoint {
            let [i0,i1,i2] = face_vertices(self, f);
            kernel::point_in_or_on_triangle(
                point,
                &self.vertices[i0].position,
                &self.vertices[i1].position,
                &self.vertices[i2].position,
            )
        };

        // IMPORTANT: use exact barycentrics with LazyExact
        let bary_live = |f: usize| -> (T, T, T) {
            let [i0,i1,i2] = face_vertices(self, f);
            barycentric_coords(
                point,
                &self.vertices[i0].position,
                &self.vertices[i1].position,
                &self.vertices[i2].position,
            ).unwrap()
        };

        // Map bary zeros to (half-edge, u) on face f:
        // l2==0 => edge a-b -> e0, u=l1;  l0==0 => edge b-c -> e1, u=l2;  l1==0 => edge c-a -> e2, u=l0.
        let edge_and_u_from_bary_zero = |f: usize, l0: &T, l1: &T, l2: &T| -> Option<(usize, T)> {
            let (e0,e1,e2) = get_face_cycle(self, f);
            if l2.is_zero() { return Some((e0, l1.clone())); }
            if l0.is_zero() { return Some((e1, l2.clone())); }
            if l1.is_zero() { return Some((e2, l0.clone())); }
            None
        };

        // Map bary zeros to vertex id on face f:
        // (l1==0 && l2==0) -> vertex a; (l2==0 && l0==0) -> b; (l0==0 && l1==0) -> c.
        let vertex_from_bary_zero = |f: usize, l0: &T, l1: &T, l2: &T| -> Option<usize> {
            let [a,b,c] = face_vertices(self, f);
            if l1.is_zero() && l2.is_zero() { return Some(a); }
            if l2.is_zero() && l0.is_zero() { return Some(b); }
            if l0.is_zero() && l1.is_zero() { return Some(c); }
            None
        };

        // neighbors of a live face via twins (skip borders / removed faces)
        let push_live_neighbors = |mesh: &Mesh<T, N>, f: usize, q: &mut VecDeque<usize>, seen: &AHashSet<usize>| {
            let (e0,e1,e2) = get_face_cycle(mesh, f);
            for e in [e0,e1,e2] {
                let tw = mesh.half_edges[e].twin;
                if let Some(fnbr) = mesh.half_edges[tw].face {
                    if !mesh.faces[fnbr].removed && !seen.contains(&fnbr) {
                        q.push_back(fnbr);
                    }
                }
            }
        };

        // --- BFS over descendants + neighbors ---
        let mut q: VecDeque<usize> = VecDeque::new();
        let mut seen: AHashSet<usize> = AHashSet::new();
        q.push_back(start_face);

        let mut steps = 0usize;
        while let Some(f) = q.pop_front() {
            if !seen.insert(f) { continue; }
            steps += 1;
            debug_assert!(steps < 1_000_000, "find_valid_face: excessive traversal");

            if !self.faces[f].removed {
                if live_face_degenerate(self, f) {
                    push_live_neighbors(self, f, &mut q, &seen);
                    continue;
                }

                match classify_live(f) {
                    TrianglePoint::In => {
                        return (f, usize::MAX, usize::MAX, zero);
                    }
                    TrianglePoint::OnEdge => {
                        let (l0,l1,l2) = bary_live(f);
                        if let Some((he, mut u)) = edge_and_u_from_bary_zero(f, &l0, &l1, &l2) {
                            if u < zero { u = zero.clone(); }
                            if u > one  { u = one.clone(); }
                            return (f, he, usize::MAX, u);
                        }
                        // If mapping failed (shouldn't in exact mode), treat as inside
                        return (f, usize::MAX, usize::MAX, zero);
                    }
                    TrianglePoint::OnVertex => {
                        let (l0,l1,l2) = bary_live(f);
                        if let Some(v_id) = vertex_from_bary_zero(f, &l0, &l1, &l2) {
                            return (f, usize::MAX, v_id, zero);
                        }
                        // Fallback: inside
                        return (f, usize::MAX, usize::MAX, zero);
                    }
                    TrianglePoint::Off => {
                        // Explore neighbors; the correct owner might be adjacent
                        push_live_neighbors(self, f, &mut q, &seen);
                        continue;
                    }
                }
            }

            // Removed face: descend via recorded triangles (use current vertex positions for test)
            if let Some(mapping) = self.face_split_map.get(&f) {
                let mut interior: Vec<usize> = Vec::new();
                let mut boundary:  Vec<usize> = Vec::new();

                for tri in &mapping.new_faces {
                    let [i0,i1,i2] = tri.vertices.as_array();
                    let cls = kernel::point_in_or_on_triangle(
                        point,
                        &self.vertices[i0].position,
                        &self.vertices[i1].position,
                        &self.vertices[i2].position,
                    );
                    match cls {
                        TrianglePoint::In => interior.push(tri.face_idx),
                        TrianglePoint::OnEdge | TrianglePoint::OnVertex => boundary.push(tri.face_idx),
                        TrianglePoint::Off => {}
                    }
                }

                for fc in interior { if !seen.contains(&fc) { q.push_front(fc); } }
                for fc in boundary  { if !seen.contains(&fc) { q.push_back(fc); } }
                for tri in &mapping.new_faces {
                    let fc = tri.face_idx;
                    if !seen.contains(&fc) { q.push_back(fc); }
                }
                continue;
            }
        }

        // --- Global fallback: scan all live faces and pick best match ---
        let mut best_inside: Option<usize> = None;
        let mut best_edge:   Option<(usize, usize, T)> = None;
        let mut best_vertex: Option<usize> = None;

        for f in 0..self.faces.len() {
            if self.faces[f].removed { continue; }
            if live_face_degenerate(self, f) { continue; }

            match classify_live(f) {
                TrianglePoint::In => { best_inside = Some(f); break; }
                TrianglePoint::OnEdge => {
                    let (l0,l1,l2) = bary_live(f);
                    if let Some((he, mut u)) = edge_and_u_from_bary_zero(f, &l0, &l1, &l2) {
                        if u < zero { u = zero.clone(); }
                        if u > one  { u = one.clone(); }
                        if best_edge.is_none() { best_edge = Some((f, he, u)); }
                    }
                }
                TrianglePoint::OnVertex => {
                    if best_vertex.is_none() { best_vertex = Some(f); }
                }
                TrianglePoint::Off => {}
            }
        }

        if let Some(f) = best_inside { return (f, usize::MAX, usize::MAX, zero); }
        if let Some((f,he,u)) = best_edge { return (f, he, usize::MAX, u); }
        if let Some(f) = best_vertex {
            // Identify which vertex
            let (l0,l1,l2) = bary_live(f);
            if let Some(v_id) = vertex_from_bary_zero(f, &l0, &l1, &l2) {
                return (f, usize::MAX, v_id, zero);
            }
            return (f, usize::MAX, usize::MAX, zero);
        }

        panic!("find_valid_face: could not locate a face/edge/vertex for the point starting from {}", start_face);
    }

    /// Returns (face_id, half_edge_id, u). For Inside/OnVertex: (f, usize::MAX, 0).
    /// For OnEdge: (f, he_of_f_edge, u in [0,1] along that half-edge).
    pub fn find_valid_face_almost_working(&self, start_face: usize, point: &Point<T, N>) -> (usize, usize, T)
    {
        use std::collections::VecDeque;

        let zero = T::zero();
        let one  = T::one();

        #[inline]
        fn get_face_cycle<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, f: usize) -> (usize, usize, usize) {
            let e0 = mesh.faces[f].half_edge;
            let e1 = mesh.half_edges[e0].next;
            let e2 = mesh.half_edges[e1].next;
            debug_assert_eq!(mesh.half_edges[e2].next, e0);
            (e0, e1, e2) // e0: a->b, e1: b->c, e2: c->a
        }

        #[inline]
        fn face_vertices<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, f: usize) -> [usize; 3] {
            let (e0, e1, _e2) = get_face_cycle(mesh, f);
            let a = mesh.half_edges[mesh.half_edges[e0].prev].vertex; // origin(e0)
            let b = mesh.half_edges[e0].vertex;                       // target(e0)
            let c = mesh.half_edges[e1].vertex;                       // target(e1)
            [a, b, c]
        }

        #[inline]
        fn live_face_degenerate<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, f: usize) -> bool
        where
            Point<TS, M>: PointOps<TS, M, Vector = Vector<TS, M>>,
            Vector<TS, M>: VectorOps<TS, M>,
            Vector<TS, 3>: VectorOps<TS, 3, Cross = Vector<TS, 3>>,
            for<'a> &'a TS:
                Add<&'a TS, Output = TS> + Sub<&'a TS, Output = TS> + Mul<&'a TS, Output = TS>,
        {
            let [i0,i1,i2] = face_vertices(mesh, f);
            let u = (&mesh.vertices[i1].position - &mesh.vertices[i0].position).as_vector_3();
            let v = (&mesh.vertices[i2].position - &mesh.vertices[i0].position).as_vector_3();
            let cross_product = u.cross(&v);
            let n2 = cross_product.dot(&cross_product);
            n2.is_zero()
        }

        let classify_live = |f: usize| -> TrianglePoint {
            let [i0,i1,i2] = face_vertices(self, f);
            kernel::point_in_or_on_triangle(
                point,
                &self.vertices[i0].position,
                &self.vertices[i1].position,
                &self.vertices[i2].position,
            )
        };

        let bary_live = |f: usize| -> (T, T, T) {
            // let [i0,i1,i2] = face_vertices(self, f);
            self.barycentric_coords_on_face(
                f,
                point
            ).unwrap()
        };

        // l2==0 => on edge a-b -> e0, u=l1; l0==0 => on edge b-c -> e1, u=l2; l1==0 => on edge c-a -> e2, u=l0.
        let edge_and_u_from_bary_zero = |f: usize, l0: &T, l1: &T, l2: &T| -> Option<(usize, T)> {
            let (e0,e1,e2) = get_face_cycle(self, f);
            if l2.is_zero() { return Some((e0, l1.clone())); }
            if l0.is_zero() { return Some((e1, l2.clone())); }
            if l1.is_zero() { return Some((e2, l0.clone())); }
            None
        };

        // neighbors of a live face via twins (skip borders / removed faces)
        let push_live_neighbors = |mesh: &Mesh<T, N>, f: usize, q: &mut VecDeque<usize>, seen: &AHashSet<usize>| {
            let (e0,e1,e2) = get_face_cycle(mesh, f);
            for e in [e0,e1,e2] {
                let tw = mesh.half_edges[e].twin;
                if let Some(fnbr) = mesh.half_edges[tw].face {
                    if !mesh.faces[fnbr].removed && !seen.contains(&fnbr) {
                        q.push_back(fnbr);
                    }
                }
            }
        };

        // --- BFS over descendants + neighbors ---
        let mut q: VecDeque<usize> = VecDeque::new();
        let mut seen: AHashSet<usize> = AHashSet::new();
        q.push_back(start_face);

        let mut steps = 0usize;
        while let Some(f) = q.pop_front() {
            if !seen.insert(f) { continue; }
            steps += 1;
            debug_assert!(steps < 1_000_000, "find_valid_face: excessive traversal");

            if !self.faces[f].removed {
                if live_face_degenerate(self, f) {
                    // degenerate triangle — don't classify, just flow to neighbors
                    push_live_neighbors(self, f, &mut q, &seen);
                    continue;
                }

                match classify_live(f) {
                    TrianglePoint::In | TrianglePoint::OnVertex => {
                        return (f, usize::MAX, zero);
                    }
                    TrianglePoint::OnEdge => {
                        let (l0,l1,l2) = bary_live(f);
                        if let Some((he, mut u)) = edge_and_u_from_bary_zero(f, &l0, &l1, &l2) {
                            if u < zero { u = zero.clone(); }
                            if u > one  { u = one.clone(); }
                            return (f, he, u);
                        }
                        // If edge mapping failed, treat as inside
                        return (f, usize::MAX, zero);
                    }
                    TrianglePoint::Off => {
                        // We’re in the wrong live face; explore all live neighbors.
                        push_live_neighbors(self, f, &mut q, &seen);
                        continue;
                    }
                }
            }

            // Removed face: expand to children at this split level
            if let Some(mapping) = self.face_split_map.get(&f) {
                // Classify against recorded triangles; enqueue interior first, then boundary;
                // but also enqueue all children (as low-priority) so we won't dead-end on ties.
                let mut interior: Vec<usize> = Vec::new();
                let mut boundary:  Vec<usize> = Vec::new();

                for tri in &mapping.new_faces {
                    let [i0,i1,i2] = tri.vertices.as_array();
                    let cls = kernel::point_in_or_on_triangle(
                        point,
                        &self.vertices[i0].position,
                        &self.vertices[i1].position,
                        &self.vertices[i2].position,
                    );
                    match cls {
                        TrianglePoint::In => interior.push(tri.face_idx),
                        TrianglePoint::OnEdge | TrianglePoint::OnVertex => boundary.push(tri.face_idx),
                        TrianglePoint::Off => {}
                    }
                }

                for fc in interior { if !seen.contains(&fc) { q.push_front(fc); } }
                for fc in boundary  { if !seen.contains(&fc) { q.push_back(fc); } }
                for tri in &mapping.new_faces {
                    let fc = tri.face_idx;
                    if !seen.contains(&fc) { q.push_back(fc); }
                }
                continue;
            }

            // Removed but no mapping — data hole: try neighbors of any surviving twins
            // (best-effort salvage)
            // If you want, you can also log this condition for debugging.
        }

        println!("find_valid_face: Global fallback");
        // --- Global fallback: scan all live faces and pick the best match ---
        let mut best_inside: Option<usize> = None;
        let mut best_edge:   Option<(usize, usize, T)> = None;
        let mut best_vertex: Option<usize> = None;

        for f in 0..self.faces.len() {
            if self.faces[f].removed { continue; }
            if live_face_degenerate(self, f) { continue; }

            match classify_live(f) {
                TrianglePoint::In => { best_inside = Some(f); break; }
                TrianglePoint::OnEdge => {
                    let (l0,l1,l2) = bary_live(f);
                    if let Some((he, mut u)) = edge_and_u_from_bary_zero(f, &l0, &l1, &l2) {
                        if u < zero { u = zero.clone(); }
                        if u > one  { u = one.clone(); }
                        if best_edge.is_none() { best_edge = Some((f, he, u)); }
                    }
                }
                TrianglePoint::OnVertex => {
                    if best_vertex.is_none() { best_vertex = Some(f); }
                }
                TrianglePoint::Off => {}
            }
        }

        if let Some(f) = best_inside { return (f, usize::MAX, zero); }
        if let Some(res) = best_edge   { return res; }
        if let Some(f) = best_vertex { return (f, usize::MAX, zero); }

        panic!("find_valid_face: could not locate a face/edge for the point starting from {}", start_face);
    }

    pub fn find_valid_half_edge(&self, he_start: usize, point: &Point<T, N>) -> usize
    where
        Point<T, N>: PointOps<T, N, Vector = Vector<T, N>>,
        Vector<T, N>: VectorOps<T, N>,
        for<'a> &'a T:
            Sub<&'a T, Output = T> +
            Mul<&'a T, Output = T> +
            Add<&'a T, Output = T> +
            Div<&'a T, Output = T>,
    {
        use std::collections::VecDeque;

        let zero = T::zero();
        let one  = T::one();

        #[inline]
        fn origin_of<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, he: usize) -> usize {
            mesh.half_edges[ mesh.half_edges[he].twin ].vertex
        }
        #[inline]
        fn target_of<TS: Scalar, const M: usize>(mesh: &Mesh<TS, M>, he: usize) -> usize {
            mesh.half_edges[he].vertex
        }

        // Return (u_raw, d2). d2 uses clamped u, u_raw is unclamped.
        // Uses sign-based predicates to avoid forcing exact on LazyExact.
        let proj_u_and_dist2 = |a: &Point<T, N>, p: &Point<T, N>, b: &Point<T, N>| -> (T, T) {
            let ab = (b - a).as_vector();
            let ap = (p - a).as_vector();
            let denom = ab.dot(&ab);
            if denom.is_zero() {
                // degenerate edge → distance to 'a'
                return (zero.clone(), ap.norm2());
            }
            let u_raw = ap.dot(&ab) / denom;
            // Clamp without PartialOrd
            let u_clamped =
                if u_raw.is_negative() { zero.clone() }
                else if (&u_raw - &one).is_positive() { one.clone() }
                else { u_raw.clone() };
            // closest point on segment = a + ab * u_clamped
            let closest = a + &ab.scale(&u_clamped).0;
            let d2 = (&(point - &closest).as_vector()).norm2();
            (u_raw, d2)
        };

        // Exact containment on a directed half-edge (including endpoints).
        // Bounds checks avoid PartialOrd to keep laziness.
        let contains_exact = |he: usize| -> Option<T> {
            let v0 = origin_of(self, he);
            let v1 = target_of(self, he);
            let a = &self.vertices[v0].position;
            let b = &self.vertices[v1].position;
            let (u_raw, d2) = proj_u_and_dist2(a, point, b);
            if d2.is_zero()
                && !u_raw.is_negative()
                && (&u_raw - &one).is_negative_or_zero()
            {
                Some(u_raw)
            } else {
                None
            }
        };

        // Keep the best (closest) live descendant as a fallback if no exact containment is found.
        let mut best_live: Option<(usize, T)> = None; // (he, d2)

        // BFS over descendants through half_edge_split_map
        let mut q: VecDeque<usize> = VecDeque::new();
        let mut seen: AHashSet<usize> = AHashSet::new();
        q.push_back(he_start);

        let mut steps = 0usize;
        while let Some(he) = q.pop_front() {
            if !seen.insert(he) { continue; }
            steps += 1;
            debug_assert!(steps < 1_000_000, "find_valid_half_edge: excessive traversal");

            if !self.half_edges[he].removed {
                // Live candidate: exact containment?
                if let Some(_u) = contains_exact(he) {
                    return he;
                }
                // Track nearest descendant (use clamped distance)
                let v0 = origin_of(self, he);
                let v1 = target_of(self, he);
                let a = &self.vertices[v0].position;
                let b = &self.vertices[v1].position;
                let (_u_raw, d2) = proj_u_and_dist2(a, point, b);
                match &mut best_live {
                    None => best_live = Some((he, d2)),
                    Some((_bhe, bd2)) => {
                        if (&d2 - bd2).is_negative() {
                            *_bhe = he;
                            *bd2 = d2;
                        }
                    }
                }
                continue;
            }

            // Removed: expand to children if present
            if let Some(&(c0, c1)) = self.half_edge_split_map.get(&he) {
                if c0 != usize::MAX { q.push_back(c0); }
                if c1 != usize::MAX { q.push_back(c1); }
                continue;
            }
            // Removed but no mapping: nothing to enqueue; just continue.
        }

        // No exact-containing descendant found. Fall back to closest live descendant if we have one.
        if let Some((he, _d2)) = best_live {
            return he;
        }

        // Last resort: locate via the face that contains the point and use that edge.
        if let Some(f_anchor) = self.half_edges[he_start].face.or(self.half_edges[self.half_edges[he_start].twin].face) {
            match self.find_valid_face(f_anchor, point) {
                FindFaceResult::OnEdge { he, .. } => {
                    return he;
                },
                FindFaceResult::OnVertex { f, .. } => {
                    return self.half_edges[self.faces[f].half_edge].twin;
                },
                FindFaceResult::Inside { f, .. } => {
                    // Choose the boundary edge of that face that is closest.
                    let (e0, e1, e2) = {
                        let e0 = self.faces[f].half_edge;
                        let e1 = self.half_edges[e0].next;
                        let e2 = self.half_edges[e1].next;
                        (e0, e1, e2)
                    };
                    let mut best = (e0, T::from(1_000_000_000));
                    for e in [e0, e1, e2] {
                        let v0 = origin_of(self, e);
                        let v1 = target_of(self, e);
                        let a = &self.vertices[v0].position;
                        let b = &self.vertices[v1].position;
                        let (_u_raw, d2) = proj_u_and_dist2(a, point, b);
                        if (&d2 - &best.1).is_negative() {
                            best = (e, d2);
                        }
                    }
                    return best.0;
                },
            }
        }

        panic!("find_valid_half_edge: Half-edge {} is removed and unmapped (no descendants, no anchor)", he_start);
    }

    pub fn barycentric_coords_on_face(
        &self,
        face_idx: usize,
        point: &Point<T, N>,
    ) -> Option<(T, T, T)>
    where
        Point<T, N>: PointOps<T, N, Vector = Vector<T, N>>,
        Vector<T, N>: VectorOps<T, N>,
        for<'a> &'a T: Sub<&'a T, Output = T>
            + Mul<&'a T, Output = T>
            + Add<&'a T, Output = T>
            + Div<&'a T, Output = T>,
    {
        let face_vertices = self.face_vertices(face_idx);
        if face_vertices.len() != 3 {
            return None;
        }

        let v0 = &self.vertices[face_vertices[0]].position;
        let v1 = &self.vertices[face_vertices[1]].position;
        let v2 = &self.vertices[face_vertices[2]].position;

        if kernel::point_in_or_on_triangle(point, v0, v1, v2) != TrianglePoint::Off {
            barycentric_coords(point, v0, v1, v2)
        } else {
            None
        }
    }

    /// Checks if two vertices have an edge between them in the mesh.
    pub fn are_vertices_connected(&self, vertex_a: usize, vertex_b: usize) -> bool {
        return self.edge_map.contains_key(&(vertex_a, vertex_b))
            || self.edge_map.contains_key(&(vertex_b, vertex_a));
    }

    /// Checks if two vertices have an edge between them and return the half-edge pointing to B if it exists.
    pub fn vertices_connection(&self, vertex_a: usize, vertex_b: usize) -> usize {
        if vertex_a >= self.vertices.len() || vertex_b >= self.vertices.len() {
            return usize::MAX; // Invalid vertex indices
        }
        self.edge_map
            .get(&(vertex_a, vertex_b))
            .copied()
            .unwrap_or(usize::MAX)
    }

    pub fn vertex_touches_face(&self, v: usize, face_id: usize) -> bool {
        if v >= self.vertices.len() { return false; }
        // follow outgoing ring
        if let Some(mut h) = self.vertices[v].half_edge {
            let start = h;
            loop {
                let he = &self.half_edges[h];
                if he.face == Some(face_id) { return true; }
                h = he.twin;
                if h == usize::MAX { break; }
                h = self.half_edges[h].next;
                if h == start { break; }
            }
        }
        false
    }

    pub fn validate_connectivity(&self) {
        // For every half-edge, check next/prev/twin consistency:
        for (i, he) in self.half_edges.iter().enumerate() {
            if he.removed {
                continue; // skip removed half-edges
            }
            assert_eq!(
                self.half_edges[he.next].prev, i,
                "he {} next -> prev mismatch",
                i
            );
            assert_eq!(
                self.half_edges[he.prev].next, i,
                "he {} prev -> next mismatch",
                i
            );
            assert_eq!(
                self.half_edges[he.twin].twin, i,
                "he {} twin -> twin mismatch",
                i
            );

            // face must match the one it's stored on:
            if let Some(f) = he.face {
                // check that f really contains i somewhere in its cycle…
                let mut cur = self.faces[f].half_edge;
                loop {
                    if cur == i {
                        break;
                    }
                    cur = self.half_edges[cur].next;
                    assert!(cur != self.faces[f].half_edge, "he {} not in face {}", i, f);
                }
            }
        }

        let mut edge_set = AHashSet::new();
        for (_i, he) in self.half_edges.iter().enumerate() {
            if he.removed {
                continue;
            }
            let src = self.half_edges[he.prev].vertex;
            let dst = he.vertex;
            assert!(
                edge_set.insert((src, dst)),
                "duplicate half-edge ({},{})",
                src,
                dst
            );
        }

        // Check every face's entry half_edge still belongs to that face:
        for (fi, face) in self.faces.iter().enumerate() {
            if face.removed {
                continue;
            }
            let start = face.half_edge;
            let mut cur = start;
            loop {
                assert_eq!(
                    self.half_edges[cur].face,
                    Some(fi),
                    "face {} half-edge {} points at wrong face",
                    fi,
                    cur
                );
                cur = self.half_edges[cur].next;
                if cur == start {
                    break;
                }
            }
        }

        // Check every vertex's half_edge really points at a target half-edge:
        for (vi, v) in self.vertices.iter().enumerate() {
            if let Some(he0) = v.half_edge {
                let prev = self.half_edges[he0].prev;
                let prev_he = &self.half_edges[prev];
                assert_eq!(
                    prev_he.vertex, // the 'to' of the previous edge is 'from' of this one
                    vi,             // should match the current vertex index
                    "vertex {}: half_edge {} is not outgoing from this vertex (prev edge points to {})",
                    vi,
                    he0,
                    prev_he.vertex
                );
            }
        }
    }

    pub fn validate_half_edges(&self) {
        let mut edge_set = AHashSet::new();
        for (_i, he) in self.half_edges.iter().enumerate() {
            if he.removed {
                continue;
            }
            let src = self.half_edges[he.prev].vertex;
            let dst = he.vertex;
            assert!(
                edge_set.insert((src, dst)),
                "duplicate half-edge ({},{})",
                src,
                dst
            );
        }
    }

    // Iterative face half-edge traversal to eliminate recursion
    pub fn get_face_half_edges_iterative(
        &self,
        face_idx: usize,
    ) -> Option<Vec<usize>> {
        if face_idx >= self.faces.len() {
            return None;
        }

        let face = &self.faces[face_idx];
        if face.half_edge == usize::MAX || self.half_edges[face.half_edge].removed {
            return None;
        }

        let start_he = face.half_edge;
        if start_he >= self.half_edges.len() {
            return None;
        }

        let mut result = Vec::new();
        let mut current_he = start_he;
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 10;

        loop {
            iterations += 1;
            if iterations > MAX_ITERATIONS {
                panic!("Exceeded maximum iterations while traversing face half-edges, possible infinite loop.");
            }

            if current_he >= self.half_edges.len() {
                return None;
            }

            result.push(current_he);

            current_he = self.half_edges[current_he].next;
            if current_he >= self.half_edges.len() {
                return None;
            }

            if current_he == start_he {
                break;
            }
        }

        Some(result)
    }

    #[inline]
    pub fn rot_ccw_around_vertex(&self, h: usize) -> usize {
        // CCW around the *origin* (tail) of h. Works for interior and border
        // once boundary loops have valid prev/next.
        let prev = self.half_edges[h].prev;
        self.half_edges[prev].twin
    }

    pub fn vertex_ring_ccw(&self, v: usize) -> VertexRing {
        // --- Seed: ensure we start from an OUTGOING half-edge of v ---
        let mut seed = match self.vertices[v].half_edge {
            Some(h) => h,
            None => {
                // No incident half-edge recorded — return an empty, harmless ring.
                return VertexRing {
                    center: v,
                    halfedges_ccw: vec![],
                    neighbors_ccw: vec![],
                    faces_ccw: vec![],
                    is_border: true,
                };
            }
        };
        if self.source(seed) != v {
            seed = self.half_edges[seed].twin;
        }

        // If the cached seed is removed, rotate to find a live outgoing spoke.
        // If *all* spokes are removed, return an empty ring.
        {
            let mut cur = seed;
            let mut seen = AHashSet::new();
            while self.half_edges[cur].removed && seen.insert(cur) {
                cur = self.rot_ccw_around_vertex(cur);
                if cur == seed { break; }
            }
            if self.half_edges[cur].removed {
                return VertexRing {
                    center: v,
                    halfedges_ccw: vec![],
                    neighbors_ccw: vec![],
                    faces_ccw: vec![],
                    is_border: true,
                };
            }
            seed = cur;
        }

        // --- Traverse once around v in CCW order ---
        let mut halfedges = Vec::new();
        let mut neighbors = Vec::new();
        let mut faces     = Vec::new();
        let mut is_border = false;

        let start = seed;
        let mut cur = start;
        let mut seen = AHashSet::new();

        loop {
            // Emit only live spokes (but still rotate across anything, since wiring is valid)
            if !self.half_edges[cur].removed {
                // neighbor is the head of the half-edge
                neighbors.push(self.half_edges[cur].vertex);

                // face entry is None for border or if the face is marked removed
                let f = if self.face_ok(cur) { self.half_edges[cur].face } else { None };
                if f.is_none() { is_border = true; }
                faces.push(f);

                halfedges.push(cur);
            }

            let nxt = self.rot_ccw_around_vertex(cur);
            if nxt == start { break; }

            // Safety guard against accidental loops if wiring is corrupt
            if !seen.insert(nxt) { break; }

            cur = nxt;
        }

        VertexRing {
            center: v,
            halfedges_ccw: halfedges,
            neighbors_ccw: neighbors,
            faces_ccw: faces,
            is_border,
        }
    }

    #[inline]
    pub fn face_ok(&self, h: usize) -> bool {
        match self.half_edges[h].face {
            Some(f) => !self.faces[f].removed,
            None => false,
        }
    }

    pub fn ring_pair(&self, v0: usize, v1: usize) -> Option<PairRing> {
        if v0 == v1 { return None; }

        // Exact directed incidences
        let he_v0v1 = self.half_edge_between(v0, v1)?;
        let he_v1v0 = self.half_edge_between(v1, v0)?;

        let ring0 = self.vertex_ring_ccw(v0);
        let ring1 = self.vertex_ring_ccw(v1);

        // Index by the EXACT half-edge ids
        let idx_v1_in_ring0 = ring0.halfedges_ccw.iter().position(|&h| h == he_v0v1)?;
        let idx_v0_in_ring1 = ring1.halfedges_ccw.iter().position(|&h| h == he_v1v0)?;

        // (Optional sanity while debugging)
        debug_assert_eq!(ring0.neighbors_ccw[idx_v1_in_ring0], v1);
        debug_assert_eq!(ring1.neighbors_ccw[idx_v0_in_ring1], v0);

        // Third (opposite) vertex only if the incident face exists and is not removed
        let opposite_a = if self.face_ok(he_v0v1) {
            let hn = self.half_edges[he_v0v1].next;
            Some(self.half_edges[hn].vertex)
        } else { None };

        let opposite_b = if self.face_ok(he_v1v0) {
            let hn = self.half_edges[he_v1v0].next;
            Some(self.half_edges[hn].vertex)
        } else { None };

        let set0: AHashSet<_> = ring0.neighbors_ccw.iter().copied().filter(|&x| x != v1).collect();
        let set1: AHashSet<_> = ring1.neighbors_ccw.iter().copied().filter(|&x| x != v0).collect();

        let is_border_edge = !(self.face_ok(he_v0v1) && self.face_ok(he_v1v0));

        Some(PairRing {
            v0, v1,
            ring0, ring1,
            idx_v1_in_ring0: Some(idx_v1_in_ring0),
            idx_v0_in_ring1: Some(idx_v0_in_ring1),
            opposite_a,
            opposite_b,
            common_neighbors: set0.intersection(&set1).copied().collect(),
            union_neighbors:  set0.union(&set1).copied().collect(),
            is_border_edge,
        })
    }

    /// Convenience: the classic triangle-mesh link condition for collapsing edge (v0,v1).
    /// Accepts borders: on border, common neighbors must be exactly {a} or {b}.
    pub fn collapse_link_condition_triangle(&self, v0: usize, v1: usize) -> bool {
        let Some(pr) = self.ring_pair(v0, v1) else { return false; };

        // Gather expected opposite set (ignoring None)
        let mut expected = AHashSet::new();
        if let Some(a) = pr.opposite_a { expected.insert(a); }
        if let Some(b) = pr.opposite_b { expected.insert(b); }

        // Intersection of neighbor sets should equal expected
        pr.common_neighbors == expected
    }

    /// Compute area-squared (2*Area)^2 of face `f` if vertex `mv` moved to `p_star`.
    #[inline]
    pub fn area2x4_after_move(
        &self,
        f: usize,
        mv: usize,
        p_star: &Point<T, N>,
    ) -> T
    where     Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
    {
        let [i, j, k] = self.face_vertices(f);
        let p = |idx: usize| -> &Point<T, N> {
            if idx == mv {
                p_star
            } else {
                &self.vertices[idx].position
            }
        };
        let ab = (p(j) - p(i)).as_vector();
        let ac = (p(k) - p(i)).as_vector();
        let n = ab.cross(&ac);
        n.dot(&n)
    }
}

pub fn ray_segment_intersection_2d<T>(
    o: &crate::geometry::point::Point<T, 2>,
    d: &crate::geometry::vector::Vector<T, 2>,
    a: &crate::geometry::point::Point<T, 2>,
    b: &crate::geometry::point::Point<T, 2>,
) -> Option<(T, T)>
where
    T: crate::numeric::scalar::Scalar + PartialOrd + Clone,
    for<'a> &'a T: Add<&'a T, Output = T>
        + Sub<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Div<&'a T, Output = T>,
{
    // Ray direction must be non-zero
    let rx = d[0].clone();
    let ry = d[1].clone();
    let rr = &rx * &rx + &ry * &ry;
    if rr.is_zero() {
        return None;
    }

    // Segment direction s = b - a
    let sx = &b[0] - &a[0];
    let sy = &b[1] - &a[1];

    // Vector from ray origin to segment start q = a - o
    let qx = &a[0] - &o[0];
    let qy = &a[1] - &o[1];

    // Cross products
    let rxs = &rx * &sy - &ry * &sx;
    let qxr = &qx * &ry - &qy * &rx; // cross(q, r)
    let qxs = &qx * &sy - &qy * &sx; // cross(q, s)

    // Parallel?
    if rxs.is_zero() {
        // Collinear if q x r == 0 (use kernel-backed collinearity to be safe)
        // Faster short-circuit via cross check, then confirm with kernel to avoid false positives.
        let collinear = qxr.is_zero()
            && kernel::are_collinear(o, &(Point::<T, 2>::from([&o[0] + &rx, &o[1] + &ry])), a)
            && kernel::are_collinear(o, &(Point::<T, 2>::from([&o[0] + &rx, &o[1] + &ry])), b);

        if !collinear {
            return None; // parallel disjoint
        }

        // Collinear overlap: project endpoints onto the ray to get [t0, t1] on the ray
        // t = ((p - o) · r) / |r|^2
        let t0 = &(&qx * &rx + &qy * &ry) / &rr;
        let t1 = &t0 + &(&(&sx * &rx + &sy * &ry) / &rr);

        let (tmin, tmax) = if t0 <= t1 { (t0, t1) } else { (t1, t0) };
        if tmax < T::zero() {
            return None; // entire segment lies behind the ray
        }

        // Hit point is the closest point along the ray that overlaps the segment
        let t_hit = if tmin >= T::zero() { tmin } else { T::zero() };

        // Compute intersection point p_hit = o + t_hit * r
        let px = &o[0] + &(&rx * &t_hit);
        let py = &o[1] + &(&ry * &t_hit);
        let p_hit = crate::geometry::point::Point::<T, 2>::from([px, py]);

        // Get segment parameter u in [0,1] using the kernel helper (handles degenerate [a==b] cleanly)
        if let Some(u) = crate::kernel::point_u_on_segment(a, b, &p_hit) {
            return Some((t_hit, u));
        }
        return None;
    }

    // Skew lines: unique intersection
    // Solve:
    //   t = cross(q, s) / cross(r, s)
    //   u = cross(q, r) / cross(r, s)
    let t = &qxs / &rxs;
    let u = &qxr / &rxs;

    if t < T::zero() || u < T::zero() || u > T::one() {
        return None;
    }
    Some((t, u))
}

/// Robust ray-triangle intersection using Möller-Trumbore algorithm
fn ray_triangle_intersection<T: Scalar, const N: usize>(
    ray_origin: &Point<T, N>,
    ray_dir: &Vector<T, N>,
    triangle: [&Point<T, N>; N],
    tolerance: &Option<T>,
) -> Option<(T, T, T)>
where
    Point<T, N>: PointOps<T, N, Vector = Vector<T, N>>,
    Vector<T, N>: VectorOps<T, N, Cross = Vector<T, N>>,
    for<'a> &'a T: Add<&'a T, Output = T>
        + Sub<&'a T, Output = T>
        + Mul<&'a T, Output = T>
        + Div<&'a T, Output = T>,
{
    if N != 3 {
        panic!("Currently, only 3 dimensions are supported.");
    }

    let eps = tolerance.as_ref().cloned().unwrap_or_else(T::tolerance);
    let zero = T::zero();
    let one = T::one();

    // Triangle vertices
    let v0 = triangle[0];
    let v1 = triangle[1];
    let v2 = triangle[2];

    // Triangle edges
    let edge1 = Vector::<T, 3>::from_vals([&v1[0] - &v0[0], &v1[1] - &v0[1], &v1[2] - &v0[2]]);
    let edge2 = Vector::<T, 3>::from_vals([&v2[0] - &v0[0], &v2[1] - &v0[1], &v2[2] - &v0[2]]);

    // pvec = ray_dir x edge2
    let pvec = Vector::<T, 3>::from_vals([
        &ray_dir[1] * &edge2[2] - &ray_dir[2] * &edge2[1],
        &ray_dir[2] * &edge2[0] - &ray_dir[0] * &edge2[2],
        &ray_dir[0] * &edge2[1] - &ray_dir[1] * &edge2[0],
    ]);

    // Determinant
    let det = edge1.dot(&pvec);

    // Parallel or near-parallel: reject
    if det.abs() <= eps {
        return None;
    }

    let inv_det = T::one() / det;

    // s = ray_origin - v0
    let s = Vector::<T, 3>::from_vals([
        &ray_origin[0] - &v0[0],
        &ray_origin[1] - &v0[1],
        &ray_origin[2] - &v0[2],
    ]);

    // u = (s . pvec) / det
    let u = &s.dot(&pvec) * &inv_det;
    // Tolerant range check for u
    if (&u + &eps).is_negative() || (&u - &(&one + &eps)).is_positive() {
        return None;
    }

    // qvec = s x edge1
    let qvec = Vector::<T, 3>::from_vals([
        &s[1] * &edge1[2] - &s[2] * &edge1[1],
        &s[2] * &edge1[0] - &s[0] * &edge1[2],
        &s[0] * &edge1[1] - &s[1] * &edge1[0],
    ]);

    // v = (ray_dir . qvec) / det
    let v = &ray_dir.0.as_vector_3().dot(&qvec) * &inv_det;

    // Tolerant range check for v and u+v
    let sum_uv = &u + &v;
    if (&v + &eps).is_negative() || (&sum_uv - &(&one + &eps)).is_positive() {
        return None;
    }

    // t = (edge2 . qvec) / det
    let t_raw = &edge2.dot(&qvec) * &inv_det;

    // Tolerant forward-only ray
    if (&t_raw + &eps).is_negative() {
        return None;
    }
    let t = if t_raw.is_negative() { zero } else { t_raw };

    Some((t, u, v))
}

/// Robust 2D ray–segment intersection:
/// Solves p + t*r = a + u*e, with t >= 0 and u in (ε, 1+ε] to own the vertex once.
/// Returns (t, u) if an intersection exists.
fn ray_segment_intersection_2d_robust<T>(
    p: &Point<T, 2>,
    r: &Vector<T, 2>,
    a: &Point<T, 2>,
    b: &Point<T, 2>,
    eps: &T,
) -> Option<(T, T)>
where
    T: Scalar + PartialOrd + Clone,
    Vector<T, 2>: VectorOps<T, 2, Cross = T>,
    for<'a> &'a T: core::ops::Sub<&'a T, Output = T>
        + core::ops::Mul<&'a T, Output = T>
        + core::ops::Add<&'a T, Output = T>
        + core::ops::Div<&'a T, Output = T>
        + core::ops::Neg<Output = T>,
{
    let e = (b - a).as_vector();
    let w = (a - p).as_vector();

    let denom = r.cross(&e); // scalar
    let t_num = w.cross(&e);
    let u_num = w.cross(&r);

    let near_zero = |x: &T| -> bool {
        let meps = -(eps.clone());
        x >= &meps && x <= &eps
    };

    // Non-parallel case
    if !near_zero(&denom) {
        let t = &t_num / &denom;
        let u = &u_num / &denom;

        // Accept forward t and "own the vertex once":
        //   u in (eps, 1 + eps]  => exclude ~0; include ~1
        if &t >= &eps && &u > &eps && &u <= &(&T::one() + &eps) {
            return Some((t, u));
        }
        return None;
    }

    // Parallel or collinear
    // If not collinear (w not perpendicular to both r and e), there's no hit.
    // Collinearity: r × (a - p) ≈ 0 AND r × e ≈ 0  (the latter is denom≈0 already)
    if !near_zero(&w.cross(r)) {
        return None;
    }

    // Collinear overlap handling:
    // Project (a-p) and (b-p) on r to get t-parameters; take the smallest t >= eps.
    let r2 = r.dot(r);
    if near_zero(&r2) {
        // Ray has no direction: no meaningful intersection
        return None;
    }

    let t0 = &(a.as_vector() - p.as_vector()).dot(r) / &r2;
    let t1 = &(b.as_vector() - p.as_vector()).dot(r) / &r2;

    let (t_enter, t_exit) = if t0 <= t1 {
        (t0.clone(), t1.clone())
    } else {
        (t1.clone(), t0.clone())
    };

    // Intersection with the ray exists iff t_exit >= eps
    if &t_exit < &eps {
        return None;
    }

    // First contact along the ray:
    let t_hit = if &t_enter >= &eps { t_enter } else { t_exit };

    // Recover u on [0,1] for (a->b)
    let e2 = e.dot(&e);
    if near_zero(&e2) {
        // Degenerate segment
        return None;
    }
    // Point on segment: q = p + t_hit*r; u = ((q - a)·e)/(e·e)
    let q = &(p.as_vector() + r.scale(&t_hit)).0;
    let u = &(&q.as_vector() - &a.as_vector()).dot(&e) / &e2;

    // Apply the same ownership rule for the vertex:
    if &t_hit >= &eps && &u > &eps && &u <= &(&T::one() + &eps) {
        return Some((t_hit, u));
    }
    None
}