hypercurve 0.2.0

Hyperreal-backed planar curves, contours, and regions for CAD topology
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
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
//! Rational quadratic Bezier and conic primitives.
//!
//! Rational quadratics are the lowest-degree Bezier representation that can
//! carry non-parabolic conics exactly. The homogeneous evaluation below keeps
//! the polynomial numerator and weight denominator visible instead of
//! flattening to sampled chords, matching Yap's exact geometric computation
//! advice to preserve object structure until a certified predicate boundary;
//! see Yap, "Towards Exact Geometric Computation," *Computational Geometry*
//! 7.1-2 (1997). The conic weight classifier follows the rational quadratic
//! treatment in Farin, *Curves and Surfaces for Computer-Aided Geometric
//! Design* (5th ed., 2002).

use std::cmp::Ordering;

use hyperreal::{Real, RealSign, ZeroKnowledge as ZeroStatus};

use crate::bezier_topology::polynomial_roots_in_unit_interval;
use crate::classify::{
    classify_oriented_line, compare_reals, is_zero, orient2d_real_expr, real_sign,
};
use crate::{
    Aabb2, Axis2, BezierCurveIntersectionPoint, BezierCurveIntersectionRegion, BezierCurveRelation,
    BezierLineContact, BezierLineContactKind, BezierLineContactRelation, BezierLineRelation,
    BezierMonotoneGraphOrder, BezierMonotoneSpan, Classification, CubicBezier2, CurveError,
    CurvePolicy, LineSeg2, LineSide, Point2, QuadraticBezier2, UncertaintyReason,
};

/// Coarse conic family represented by a rational quadratic Bezier segment.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RationalQuadraticConicKind {
    /// Ellipse-like conic arc, including circular arcs.
    EllipseLike,
    /// Parabolic conic arc.
    Parabola,
    /// Hyperbola-like conic arc.
    HyperbolaLike,
}

/// A rational quadratic Bezier segment with exact control points and weights.
#[derive(Clone, Debug, PartialEq)]
pub struct RationalQuadraticBezier2 {
    start: Point2,
    control: Point2,
    end: Point2,
    start_weight: Real,
    control_weight: Real,
    end_weight: Real,
}

impl RationalQuadraticBezier2 {
    /// Constructs a rational quadratic segment after rejecting provably zero weights.
    pub fn try_new(
        start: Point2,
        control: Point2,
        end: Point2,
        start_weight: Real,
        control_weight: Real,
        end_weight: Real,
    ) -> Result<Self, CurveError> {
        if [
            start_weight.zero_status(),
            control_weight.zero_status(),
            end_weight.zero_status(),
        ]
        .contains(&ZeroStatus::Zero)
        {
            return Err(CurveError::ZeroRationalBezierWeight);
        }
        Ok(Self {
            start,
            control,
            end,
            start_weight,
            control_weight,
            end_weight,
        })
    }

    /// Constructs the common conic form with endpoint weights equal to one.
    pub fn try_unit_end_weights(
        start: Point2,
        control: Point2,
        end: Point2,
        control_weight: Real,
    ) -> Result<Self, CurveError> {
        Self::try_new(
            start,
            control,
            end,
            Real::one(),
            control_weight,
            Real::one(),
        )
    }

    /// Returns the start point.
    pub const fn start(&self) -> &Point2 {
        &self.start
    }

    /// Returns the interior control point.
    pub const fn control(&self) -> &Point2 {
        &self.control
    }

    /// Returns the end point.
    pub const fn end(&self) -> &Point2 {
        &self.end
    }

    /// Returns the start weight.
    pub const fn start_weight(&self) -> &Real {
        &self.start_weight
    }

    /// Returns the interior control weight.
    pub const fn control_weight(&self) -> &Real {
        &self.control_weight
    }

    /// Returns the end weight.
    pub const fn end_weight(&self) -> &Real {
        &self.end_weight
    }

    /// Returns the control points in polynomial order.
    pub fn control_points(&self) -> [&Point2; 3] {
        [&self.start, &self.control, &self.end]
    }

    /// Returns the weights in polynomial order.
    pub fn weights(&self) -> [&Real; 3] {
        [&self.start_weight, &self.control_weight, &self.end_weight]
    }

    /// Evaluates the rational segment at affine parameter `t`.
    ///
    /// The numerator and denominator are evaluated in homogeneous Bernstein
    /// form: `(sum B_i(t) w_i P_i) / (sum B_i(t) w_i)`. A zero denominator is
    /// a projective boundary, so this API returns explicit uncertainty instead
    /// of inventing an affine point.
    pub fn point_at(&self, t: Real, policy: &CurvePolicy) -> Classification<Point2> {
        let one_minus_t = Real::one() - &t;
        let two = Real::from(2_i8);
        let b0 = &one_minus_t * &one_minus_t * &self.start_weight;
        let b1 = &two * &one_minus_t * &t * &self.control_weight;
        let b2 = &t * &t * &self.end_weight;
        let denominator = &b0 + &b1 + &b2;
        match is_zero(&denominator, policy) {
            Some(true) => return Classification::Uncertain(UncertaintyReason::Boundary),
            Some(false) => {}
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }

        let numerator_x = (&b0 * self.start.x()) + (&b1 * self.control.x()) + (&b2 * self.end.x());
        let numerator_y = (&b0 * self.start.y()) + (&b1 * self.control.y()) + (&b2 * self.end.y());
        let Ok(x) = numerator_x / &denominator else {
            return Classification::Uncertain(UncertaintyReason::Boundary);
        };
        let Ok(y) = numerator_y / denominator else {
            return Classification::Uncertain(UncertaintyReason::Boundary);
        };
        Classification::Decided(Point2::new(x, y))
    }

    /// Classifies whether `point` equals this conic at parameter `t`.
    ///
    /// This is a parameterized predicate rather than an existential conic
    /// solve. It first evaluates the homogeneous rational point, then certifies
    /// affine equality through the active curve policy. Returning uncertainty
    /// at denominator boundaries keeps projective singularities explicit in
    /// the style advocated by Yap's exact geometric computation model.
    pub fn contains_point_at_parameter(
        &self,
        point: &Point2,
        t: Real,
        policy: &CurvePolicy,
    ) -> Classification<bool> {
        let curve_point = match self.point_at(t, policy) {
            Classification::Decided(point) => point,
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        };
        is_zero(&curve_point.distance_squared(point), policy)
            .map(Classification::Decided)
            .unwrap_or(Classification::Uncertain(UncertaintyReason::RealSign))
    }

    /// Returns all certified affine parameters where `point` lies on this conic.
    ///
    /// This is the existential point-on-conic solver for rational quadratics.
    /// Each coordinate equation is kept in homogeneous form as
    /// `N_axis(t) - point_axis * D(t) = 0`, so the rational structure is
    /// preserved until exact candidate parameters are certified by
    /// re-evaluating the conic. That follows Yap's requirement to keep exact
    /// geometric objects explicit until a predicate boundary; see Yap,
    /// "Towards Exact Geometric Computation," *Computational Geometry* 7.1-2
    /// (1997). The weighted Bernstein numerator/denominator identities follow
    /// the rational Bezier treatment in Farin, *Curves and Surfaces for
    /// Computer-Aided Geometric Design* (5th ed., 2002).
    pub fn parameters_for_point(
        &self,
        point: &Point2,
        policy: &CurvePolicy,
    ) -> Classification<Vec<Real>> {
        rational_parameters_for_point(self, point, policy)
    }

    /// Classifies whether `point` lies anywhere on this finite conic segment.
    ///
    /// Denominator boundaries are reported as uncertainty instead of being
    /// projected into affine space. Use [`Self::parameters_for_point`] when the
    /// certified parameters themselves are needed by downstream topology.
    pub fn contains_point(&self, point: &Point2, policy: &CurvePolicy) -> Classification<bool> {
        self.parameters_for_point(point, policy)
            .map(|parameters| !parameters.is_empty())
    }

    /// Classifies this rational quadratic against a supporting line.
    ///
    /// The signed distance numerator of a rational Bezier to a line is a
    /// polynomial Bezier with control values `w_i * orient(line, P_i)`.
    /// Solving that numerator preserves the homogeneous conic structure instead
    /// of sampling or flattening the curve. This is the rational Bezier form of
    /// the line-incidence predicates described by Farin (2002), with branch
    /// decisions routed through exact scalar signs per Yap (1997).
    pub fn relation_to_line(
        &self,
        line: &LineSeg2,
        policy: &CurvePolicy,
    ) -> Classification<BezierLineRelation> {
        let controls = self.control_points();
        let weights = self.weights();
        let weighted_distances = controls
            .iter()
            .zip(weights)
            .map(|(point, weight)| orient2d_real_expr(line.start(), line.end(), point) * weight)
            .collect::<Vec<_>>();

        if weighted_distances
            .iter()
            .all(|value| is_zero(value, policy) == Some(true))
        {
            return Classification::Decided(BezierLineRelation::OnSupportingLine);
        }

        let two = Real::from(2_i8);
        let c0 = weighted_distances[0].clone();
        let c1 = &two * &(&weighted_distances[1] - &weighted_distances[0]);
        let c2 = &weighted_distances[0] - &(&two * &weighted_distances[1]) + &weighted_distances[2];
        let roots = match polynomial_roots_in_unit_interval(c0, c1, c2, policy) {
            Classification::Decided(roots) => roots,
            Classification::Uncertain(reason) => {
                if self.weights_known_same_nonzero_sign(policy) == Some(true) {
                    return isolate_rational_quadratic_line_roots(
                        [
                            weighted_distances[0].clone(),
                            weighted_distances[1].clone(),
                            weighted_distances[2].clone(),
                        ],
                        policy,
                    );
                }
                return Classification::Uncertain(reason);
            }
        };
        let mut retained_roots = Vec::new();
        for root in roots {
            match is_zero(&self.denominator_at(root.clone()), policy) {
                Some(true) => return Classification::Uncertain(UncertaintyReason::Boundary),
                Some(false) => retained_roots.push(root),
                None => return Classification::Uncertain(UncertaintyReason::RealSign),
            }
        }
        if !retained_roots.is_empty() {
            return Classification::Decided(BezierLineRelation::Intersects {
                parameters: retained_roots,
            });
        }

        if self.weights_known_same_nonzero_sign(policy) == Some(true) {
            let sides = controls
                .iter()
                .map(|point| classify_oriented_line(line.start(), line.end(), point, policy))
                .collect::<Vec<_>>();
            if sides
                .iter()
                .all(|side| matches!(side, Classification::Decided(LineSide::Left)))
            {
                return Classification::Decided(BezierLineRelation::ControlHullDisjoint {
                    side: LineSide::Left,
                });
            }
            if sides
                .iter()
                .all(|side| matches!(side, Classification::Decided(LineSide::Right)))
            {
                return Classification::Decided(BezierLineRelation::ControlHullDisjoint {
                    side: LineSide::Right,
                });
            }
        }

        Classification::Decided(BezierLineRelation::Unresolved)
    }

    /// Classifies represented conic/supporting-line contacts as crossings or tangencies.
    ///
    /// The signed affine line predicate for a rational quadratic is the
    /// weighted Bernstein numerator `sum B_i(t) w_i orient(line, P_i)`. A root
    /// becomes a finite conic contact only when the homogeneous denominator is
    /// certified nonzero at the same parameter; denominator zeros remain
    /// explicit projective-boundary uncertainty. Represented contacts are then
    /// labelled from the exact derivative of that numerator. This follows
    /// Yap's exact geometric computation boundary; see Yap, "Towards Exact
    /// Geometric Computation," *Computational Geometry* 7.1-2 (1997). The
    /// rational Bezier numerator/denominator identities are from Farin,
    /// *Curves and Surfaces for CAGD* (5th ed., 2002), and unrepresented
    /// roots remain Sederberg-Nishita Bezier-clipping brackets.
    pub fn relation_to_line_with_contacts(
        &self,
        line: &LineSeg2,
        policy: &CurvePolicy,
    ) -> Classification<BezierLineContactRelation> {
        let weighted_distances = self.weighted_line_distances(line);
        if weighted_distances
            .iter()
            .all(|value| is_zero(value, policy) == Some(true))
        {
            return Classification::Decided(BezierLineContactRelation::OnSupportingLine);
        }

        let two = Real::from(2_i8);
        let c0 = weighted_distances[0].clone();
        let c1 = &two * &(&weighted_distances[1] - &weighted_distances[0]);
        let c2 = &weighted_distances[0] - &(&two * &weighted_distances[1]) + &weighted_distances[2];
        let roots = match polynomial_roots_in_unit_interval(c0, c1, c2, policy) {
            Classification::Decided(roots) => roots,
            Classification::Uncertain(reason) => {
                if self.weights_known_same_nonzero_sign(policy) == Some(true) {
                    return rational_line_contact_relation_from_isolation(
                        self,
                        weighted_distances,
                        policy,
                    );
                }
                return Classification::Uncertain(reason);
            }
        };
        if roots.is_empty() {
            return rational_line_contact_miss_or_unresolved(self, line, policy);
        }
        rational_line_contacts_from_parameters(self, &weighted_distances, roots, policy)
    }

    /// Returns quotient-derivative roots that split this conic into monotone spans.
    ///
    /// For a rational coordinate `N(t) / D(t)`, extrema occur where
    /// `N'(t)D(t) - N(t)D'(t) = 0` and `D(t) != 0`. The cubic terms cancel for
    /// rational quadratics, leaving an exact quadratic root problem. This keeps
    /// the homogeneous numerator/denominator visible as recommended by Yap
    /// (1997), and follows the rational Bezier derivative identity in Farin
    /// (2002).
    pub fn axis_monotone_parameters(
        &self,
        axis: Axis2,
        policy: &CurvePolicy,
    ) -> Classification<Vec<Real>> {
        let (n0, n1, n2) = self.weighted_coordinate_power_basis(axis);
        let (d0, d1, d2) = self.weight_power_basis();
        let two = Real::from(2_i8);
        let c0 = (&n1 * &d0) - (&n0 * &d1);
        let c1 = &two * &((&n2 * &d0) - (&n0 * &d2));
        let c2 = (&n2 * &d1) - (&n1 * &d2);
        let roots = match polynomial_roots_in_unit_interval(c0, c1, c2, policy) {
            Classification::Decided(roots) => roots,
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        };

        let mut retained_roots = Vec::new();
        for root in roots {
            match is_zero(&self.denominator_at(root.clone()), policy) {
                Some(true) => return Classification::Uncertain(UncertaintyReason::Boundary),
                Some(false) => retained_roots.push(root),
                None => return Classification::Uncertain(UncertaintyReason::RealSign),
            }
        }
        Classification::Decided(retained_roots)
    }

    /// Decomposes the conic at all certified x/y quotient-derivative roots.
    pub fn monotone_spans(&self, policy: &CurvePolicy) -> Classification<Vec<BezierMonotoneSpan>> {
        crate::bezier_topology::monotone_spans_from_parameters(
            [
                self.axis_monotone_parameters(Axis2::X, policy),
                self.axis_monotone_parameters(Axis2::Y, policy),
            ],
            policy,
        )
    }

    /// Returns a certified rational-conic bounding box from endpoints and extrema.
    ///
    /// Non-equal same-sign weights also include the Euclidean control point as
    /// a conservative hull witness. A uniformly negative homogeneous lift is
    /// sign-normalized to the positive case, preserving the rational Bezier
    /// convex-hull guarantee when algebraic extrema are present while still
    /// avoiding topology decisions from approximate samples.
    pub fn certified_bounds(&self, policy: &CurvePolicy) -> Classification<Aabb2> {
        let mut samples = vec![self.start.clone(), self.end.clone()];
        if self.weights_known_same_nonzero_sign(policy) == Some(true)
            && self.weights_equal(policy) == Some(false)
        {
            samples.push(self.control.clone());
        }
        let spans = match self.monotone_spans(policy) {
            Classification::Decided(spans) => spans,
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        };
        for span in spans {
            if !is_unit_endpoint(span.start(), policy) {
                match self.point_at(span.start().clone(), policy) {
                    Classification::Decided(point) => samples.push(point),
                    Classification::Uncertain(reason) => return Classification::Uncertain(reason),
                }
            }
            if !is_unit_endpoint(span.end(), policy) {
                match self.point_at(span.end().clone(), policy) {
                    Classification::Decided(point) => samples.push(point),
                    Classification::Uncertain(reason) => return Classification::Uncertain(reason),
                }
            }
        }
        Aabb2::from_points(samples.iter(), policy)
    }

    /// Classifies a coarse relation between two rational quadratic conics.
    ///
    /// This is deliberately not a full conic/conic solver. It certifies exact
    /// homogeneous-control identity, same-sign convex-hull disjointness,
    /// certified point and endpoint line-segment images, and shared endpoints, then
    /// leaves overlapping boxes unresolved for a later resultant or subdivision
    /// predicate. Keeping that boundary explicit follows Yap's
    /// exact-computation separation between cheap structural facts and complete
    /// topology solvers.
    pub fn relation_to_rational_quadratic(
        &self,
        other: &Self,
        policy: &CurvePolicy,
    ) -> Classification<BezierCurveRelation> {
        match self.same_homogeneous_controls(other, policy) {
            Some(true) => return Classification::Decided(BezierCurveRelation::SameControlPolygon),
            Some(false) => {}
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }
        match self.same_projective_homogeneous_controls(other, policy) {
            Some(true) => return Classification::Decided(BezierCurveRelation::SameCurveImage),
            Some(false) => {}
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }
        match self.same_reversed_projective_homogeneous_controls(other, policy) {
            Some(true) => return Classification::Decided(BezierCurveRelation::SameCurveImage),
            Some(false) => {}
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }

        match polynomial_relation_for_equal_weight_rationals(self, other, policy) {
            Classification::Decided(Some(relation)) => return Classification::Decided(relation),
            Classification::Decided(None) => {}
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }

        if self.weights_known_same_nonzero_sign(policy) == Some(true)
            && other.weights_known_same_nonzero_sign(policy) == Some(true)
        {
            let first_box = match Aabb2::from_points(self.control_points(), policy) {
                Classification::Decided(bbox) => bbox,
                Classification::Uncertain(reason) => return Classification::Uncertain(reason),
            };
            let second_box = match Aabb2::from_points(other.control_points(), policy) {
                Classification::Decided(bbox) => bbox,
                Classification::Uncertain(reason) => return Classification::Uncertain(reason),
            };
            match first_box.overlaps(&second_box, policy) {
                Classification::Decided(false) => {
                    return Classification::Decided(BezierCurveRelation::BoundingBoxesDisjoint);
                }
                Classification::Decided(true) => {}
                Classification::Uncertain(reason) => return Classification::Uncertain(reason),
            }
        }

        match (
            rational_point_image(self, policy),
            rational_point_image(other, policy),
        ) {
            (Classification::Decided(Some(first)), Classification::Decided(Some(second))) => {
                match point_equal(&first, &second, policy) {
                    Some(true) => {
                        return Classification::Decided(BezierCurveRelation::IntersectionPoints {
                            points: vec![BezierCurveIntersectionPoint::new(first)],
                        });
                    }
                    Some(false) => {
                        return Classification::Decided(BezierCurveRelation::NoIntersection);
                    }
                    None => return Classification::Uncertain(UncertaintyReason::RealSign),
                }
            }
            (Classification::Decided(Some(point)), Classification::Decided(None)) => {
                match point_image_rational_intersections(&point, other, policy) {
                    Classification::Decided(points) if points.is_empty() => {
                        return Classification::Decided(BezierCurveRelation::NoIntersection);
                    }
                    Classification::Decided(points) => {
                        return Classification::Decided(BezierCurveRelation::IntersectionPoints {
                            points,
                        });
                    }
                    Classification::Uncertain(reason) => return Classification::Uncertain(reason),
                }
            }
            (Classification::Decided(None), Classification::Decided(Some(point))) => {
                match point_image_rational_intersections(&point, self, policy) {
                    Classification::Decided(points) if points.is_empty() => {
                        return Classification::Decided(BezierCurveRelation::NoIntersection);
                    }
                    Classification::Decided(points) => {
                        return Classification::Decided(BezierCurveRelation::IntersectionPoints {
                            points,
                        });
                    }
                    Classification::Uncertain(reason) => return Classification::Uncertain(reason),
                }
            }
            (Classification::Uncertain(reason), _) | (_, Classification::Uncertain(reason)) => {
                return Classification::Uncertain(reason);
            }
            _ => {}
        }

        match (
            rational_line_segment_image(self, policy),
            rational_line_segment_image(other, policy),
        ) {
            (Classification::Decided(Some(first)), Classification::Decided(Some(second))) => {
                return line_segment_intersection_relation(&first, &second, policy);
            }
            (Classification::Uncertain(reason), _) | (_, Classification::Uncertain(reason)) => {
                return Classification::Uncertain(reason);
            }
            _ => {}
        }

        let mut shared_endpoint_points = Vec::new();
        for a in [self.start(), self.end()] {
            for b in [other.start(), other.end()] {
                match point_equal(a, b, policy) {
                    Some(true) => push_unique_intersection_point(
                        &mut shared_endpoint_points,
                        a.clone(),
                        policy,
                    ),
                    Some(false) => {}
                    None => return Classification::Uncertain(UncertaintyReason::RealSign),
                }
            }
        }

        let endpoint_points = match rational_rational_endpoint_intersections(self, other, policy) {
            Classification::Decided(points) => points,
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        };

        match same_parameter_matching_weight_rational_relation(self, other, policy) {
            Classification::Decided(Some(relation)) => {
                return Classification::Decided(merge_endpoint_points_into_relation(
                    relation,
                    &endpoint_points,
                    policy,
                ));
            }
            Classification::Decided(None) => {}
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }

        if !endpoint_points.is_empty() {
            return if endpoint_points_are_shared_only(
                &endpoint_points,
                &shared_endpoint_points,
                policy,
            ) {
                Classification::Decided(BezierCurveRelation::SharedEndpoint)
            } else {
                Classification::Decided(BezierCurveRelation::EndpointIntersections {
                    points: endpoint_points,
                })
            };
        }

        if self.weights_known_same_nonzero_sign(policy) == Some(true)
            && other.weights_known_same_nonzero_sign(policy) == Some(true)
        {
            return isolate_curve_regions(
                RationalSubdivisionNode::from_rational(self),
                RationalSubdivisionNode::from_rational(other),
                policy,
            );
        }

        Classification::Decided(BezierCurveRelation::Unresolved)
    }

    /// Classifies graph order against another matching-weight conic over one shared axis.
    ///
    /// This is the rational quadratic analogue of polynomial Bezier graph
    /// ordering. It first certifies that both conics share the same
    /// homogeneous weights, that those weights have one nonzero sign, that the
    /// requested Euclidean coordinate is identical, and that this coordinate
    /// is strictly monotone. The remaining coordinate then reduces to one
    /// weighted Bernstein numerator over the common denominator. Strict order
    /// is sign-normalized by the denominator sign, so uniformly negative
    /// homogeneous weights report the same Euclidean order as their positive
    /// projective image. This follows Yap's exact geometric computation
    /// boundary; see Yap, "Towards Exact Geometric Computation,"
    /// *Computational Geometry* 7.1-2 (1997). The rational homogeneous Bezier
    /// model is Farin, *Curves and Surfaces for CAGD* (5th ed., 2002), and
    /// retained crossing brackets use Sederberg and Nishita, "Curve
    /// intersection using Bezier clipping" (1990).
    pub fn graph_order_to_rational_quadratic_over_axis(
        &self,
        other: &RationalQuadraticBezier2,
        shared_axis: Axis2,
        policy: &CurvePolicy,
    ) -> Classification<BezierMonotoneGraphOrder> {
        matching_weight_rational_graph_order(self, other, shared_axis, policy)
    }

    /// Classifies graph order against a polynomial quadratic.
    ///
    /// Equal homogeneous weights collapse a rational quadratic Bezier to the
    /// polynomial quadratic with the same Euclidean controls. This method
    /// exposes that exact collapse as the mixed conic/polynomial graph-order
    /// bridge, then delegates to the polynomial predicate. For non-equal
    /// same-sign weights, it also certifies strict graph order when one
    /// coordinate is exactly shared and the degree-4 homogeneous Bernstein
    /// numerator for the remaining coordinate has one strict sign. Non-strict
    /// mixed quartic roots are retained as represented parameters or isolating
    /// spans instead of being sampled. This preserves Yap's
    /// exact geometric computation boundary; see Yap, "Towards Exact
    /// Geometric Computation," *Computational Geometry* 7.1-2 (1997). The
    /// rational Bezier identities are from Farin, *Curves and Surfaces for
    /// CAGD* (5th ed., 2002), and the Bernstein sign argument is the
    /// Sederberg-Nishita Bezier clipping criterion (1990).
    pub fn graph_order_to_quadratic_over_axis(
        &self,
        other: &QuadraticBezier2,
        shared_axis: Axis2,
        policy: &CurvePolicy,
    ) -> Classification<BezierMonotoneGraphOrder> {
        match self.equal_weight_polynomial_quadratic_image(policy) {
            Classification::Decided(Some(curve)) => {
                collapsed_graph_order_to_quadratic(&curve, other, shared_axis, policy)
            }
            Classification::Decided(None) => {
                self.rational_quadratic_graph_order_to_quadratic(other, shared_axis, policy)
            }
            Classification::Uncertain(reason) => Classification::Uncertain(reason),
        }
    }

    /// Classifies graph order against a polynomial cubic.
    ///
    /// Equal same-sign nonzero weights certify that the rational conic is
    /// exactly the polynomial quadratic with the same Euclidean control
    /// points, so the predicate delegates to the degree-normalized polynomial
    /// quadratic/cubic graph order. For non-equal same-sign weights, this also
    /// certifies strict order when one coordinate is exactly shared and the
    /// degree-5 homogeneous Bernstein numerator for the remaining coordinate
    /// has one strict sign. Non-strict mixed quintic roots are retained as
    /// represented parameters or isolating spans. The branch boundary follows
    /// Yap, "Towards
    /// Exact Geometric Computation," *Computational Geometry* 7.1-2 (1997);
    /// the rational identities follow Farin, *Curves and Surfaces for CAGD*
    /// (5th ed., 2002), and strict Bernstein sign exclusion follows
    /// Sederberg-Nishita Bezier clipping (1990).
    pub fn graph_order_to_cubic_over_axis(
        &self,
        other: &CubicBezier2,
        shared_axis: Axis2,
        policy: &CurvePolicy,
    ) -> Classification<BezierMonotoneGraphOrder> {
        match self.equal_weight_polynomial_quadratic_image(policy) {
            Classification::Decided(Some(curve)) => {
                curve.graph_order_to_cubic_over_axis(other, shared_axis, policy)
            }
            Classification::Decided(None) => {
                self.rational_quadratic_graph_order_to_cubic(other, shared_axis, policy)
            }
            Classification::Uncertain(reason) => Classification::Uncertain(reason),
        }
    }

    /// Classifies a coarse relation between this conic and a polynomial quadratic.
    ///
    /// A same-sign rational Bezier segment sign-normalizes to the positive
    /// case and lies in the convex hull of its Euclidean control points, so a
    /// disjoint hull box is a certified miss. This is the convex-hull predicate
    /// for rational Beziers described by Farin (2002), used only when exact
    /// signs prove the weights share one nonzero sign in the EGC sense of Yap
    /// (1997). Equal weights collapse the homogeneous conic to the polynomial
    /// quadratic with the same control polygon.
    pub fn relation_to_quadratic(
        &self,
        other: &QuadraticBezier2,
        policy: &CurvePolicy,
    ) -> Classification<BezierCurveRelation> {
        relation_to_polynomial_bezier(self, other.control_points().as_slice(), policy)
    }

    /// Classifies a coarse relation between this conic and a polynomial cubic.
    ///
    /// Degree-mismatched overlaps are intentionally not solved here; the
    /// predicate certifies hull disjointness and shared endpoints, then returns
    /// [`BezierCurveRelation::Unresolved`] for cases needing a complete
    /// curve/curve root solver.
    pub fn relation_to_cubic(
        &self,
        other: &CubicBezier2,
        policy: &CurvePolicy,
    ) -> Classification<BezierCurveRelation> {
        relation_to_polynomial_bezier(self, other.control_points().as_slice(), policy)
    }

    /// Classifies the represented conic family from the homogeneous weights.
    pub fn conic_kind(&self, policy: &CurvePolicy) -> Classification<RationalQuadraticConicKind> {
        let discriminant =
            (&self.control_weight * &self.control_weight) - (&self.start_weight * &self.end_weight);
        match real_sign(&discriminant, policy) {
            Some(RealSign::Negative) => {
                Classification::Decided(RationalQuadraticConicKind::EllipseLike)
            }
            Some(RealSign::Zero) => Classification::Decided(RationalQuadraticConicKind::Parabola),
            Some(RealSign::Positive) => {
                Classification::Decided(RationalQuadraticConicKind::HyperbolaLike)
            }
            None => Classification::Uncertain(UncertaintyReason::RealSign),
        }
    }

    /// Returns conservative structural facts for exact predicate scheduling.
    pub fn structural_facts(&self) -> crate::RationalQuadraticBezier2Facts {
        crate::facts::rational_quadratic_bezier_facts(self)
    }

    fn denominator_at(&self, t: Real) -> Real {
        let one_minus_t = Real::one() - &t;
        let two = Real::from(2_i8);
        let b0 = &one_minus_t * &one_minus_t * &self.start_weight;
        let b1 = &two * &one_minus_t * &t * &self.control_weight;
        let b2 = &t * &t * &self.end_weight;
        &b0 + &b1 + &b2
    }

    fn weighted_line_distances(&self, line: &LineSeg2) -> [Real; 3] {
        let controls = self.control_points();
        let weights = self.weights();
        [
            orient2d_real_expr(line.start(), line.end(), controls[0]) * weights[0],
            orient2d_real_expr(line.start(), line.end(), controls[1]) * weights[1],
            orient2d_real_expr(line.start(), line.end(), controls[2]) * weights[2],
        ]
    }

    fn weighted_coordinate_power_basis(&self, axis: Axis2) -> (Real, Real, Real) {
        quadratic_bernstein_to_power([
            coordinate(self.start(), axis) * &self.start_weight,
            coordinate(self.control(), axis) * &self.control_weight,
            coordinate(self.end(), axis) * &self.end_weight,
        ])
    }

    fn weight_power_basis(&self) -> (Real, Real, Real) {
        quadratic_bernstein_to_power([
            self.start_weight.clone(),
            self.control_weight.clone(),
            self.end_weight.clone(),
        ])
    }

    fn weights_known_same_nonzero_sign(&self, policy: &CurvePolicy) -> Option<bool> {
        let mut expected = None;
        for weight in self.weights() {
            let sign = real_sign(weight, policy)?;
            match sign {
                RealSign::Positive | RealSign::Negative => {
                    if let Some(expected) = expected {
                        if sign != expected {
                            return Some(false);
                        }
                    } else {
                        expected = Some(sign);
                    }
                }
                RealSign::Zero => return Some(false),
            }
        }
        Some(expected.is_some())
    }

    fn weights_equal(&self, policy: &CurvePolicy) -> Option<bool> {
        [
            &self.start_weight - &self.control_weight,
            &self.control_weight - &self.end_weight,
        ]
        .into_iter()
        .map(|difference| is_zero(&difference, policy))
        .try_fold(true, |same, item| item.map(|item| same && item))
    }

    fn same_homogeneous_controls(&self, other: &Self, policy: &CurvePolicy) -> Option<bool> {
        let same_points = self
            .control_points()
            .iter()
            .zip(other.control_points().iter())
            .map(|(a, b)| point_equal(a, b, policy))
            .try_fold(true, |same, item| item.map(|item| same && item))?;
        let same_weights = self
            .weights()
            .iter()
            .zip(other.weights().iter())
            .map(|(a, b)| is_zero(&(*a - *b), policy))
            .try_fold(true, |same, item| item.map(|item| same && item))?;
        Some(same_points && same_weights)
    }

    fn same_projective_homogeneous_controls(
        &self,
        other: &Self,
        policy: &CurvePolicy,
    ) -> Option<bool> {
        let same_points = self
            .control_points()
            .iter()
            .zip(other.control_points().iter())
            .map(|(a, b)| point_equal(a, b, policy))
            .try_fold(true, |same, item| item.map(|item| same && item))?;
        if !same_points {
            return Some(false);
        }

        // Homogeneous rational Bezier controls are projective: multiplying all
        // weights by one nonzero scalar multiplies both numerator and
        // denominator by that scalar and leaves the represented conic segment
        // unchanged. We test proportionality by exact cross-products instead
        // of division, preserving Yap's exact predicate boundary; the
        // homogeneous rational Bezier model is the one described by Farin,
        // Curves and Surfaces for CAGD, 5th ed. (2002).
        let first = self.weights();
        let second = other.weights();
        [
            first[0] * second[1] - &(first[1] * second[0]),
            first[1] * second[2] - &(first[2] * second[1]),
        ]
        .into_iter()
        .map(|difference| is_zero(&difference, policy))
        .try_fold(true, |same, item| item.map(|item| same && item))
    }

    fn same_reversed_projective_homogeneous_controls(
        &self,
        other: &Self,
        policy: &CurvePolicy,
    ) -> Option<bool> {
        let same_reversed_points = self
            .control_points()
            .iter()
            .zip(other.control_points().iter().rev())
            .map(|(a, b)| point_equal(a, b, policy))
            .try_fold(true, |same, item| item.map(|item| same && item))?;
        if !same_reversed_points {
            return Some(false);
        }

        // Reversing Bernstein controls represents the same rational image with
        // parameter `1 - t`; multiplying every homogeneous weight by one common
        // nonzero scalar is projectively invisible. Exact cross-products test
        // that reversed proportionality without division, preserving Yap's
        // certified predicate boundary. The rational Bernstein and reversal
        // identities are the standard homogeneous Bezier identities in Farin,
        // *Curves and Surfaces for CAGD* (5th ed., 2002).
        let first = self.weights();
        let second = other.weights();
        [
            first[0] * second[1] - &(first[1] * second[2]),
            first[1] * second[0] - &(first[2] * second[1]),
        ]
        .into_iter()
        .map(|difference| is_zero(&difference, policy))
        .try_fold(true, |same, item| item.map(|item| same && item))
    }

    fn same_polynomial_quadratic_controls(
        &self,
        polynomial_controls: &[&Point2],
        policy: &CurvePolicy,
    ) -> Option<bool> {
        let same_points = self
            .control_points()
            .iter()
            .zip(polynomial_controls.iter())
            .map(|(a, b)| point_equal(a, b, policy))
            .try_fold(true, |same, item| item.map(|item| same && item))?;
        let same_weights = self.weights_equal(policy)?;
        Some(same_points && same_weights)
    }

    fn equal_weight_polynomial_quadratic_image(
        &self,
        policy: &CurvePolicy,
    ) -> Classification<Option<QuadraticBezier2>> {
        equal_weight_polynomial_quadratic_image(self, policy)
    }

    fn rational_quadratic_graph_order_to_quadratic(
        &self,
        other: &QuadraticBezier2,
        shared_axis: Axis2,
        policy: &CurvePolicy,
    ) -> Classification<BezierMonotoneGraphOrder> {
        rational_quadratic_graph_order_to_quadratic(self, other, shared_axis, policy)
    }

    fn rational_quadratic_graph_order_to_cubic(
        &self,
        other: &CubicBezier2,
        shared_axis: Axis2,
        policy: &CurvePolicy,
    ) -> Classification<BezierMonotoneGraphOrder> {
        rational_quadratic_graph_order_to_cubic(self, other, shared_axis, policy)
    }
}

fn coordinate(point: &Point2, axis: Axis2) -> &Real {
    match axis {
        Axis2::X => point.x(),
        Axis2::Y => point.y(),
    }
}

fn quadratic_bernstein_to_power(values: [Real; 3]) -> (Real, Real, Real) {
    let two = Real::from(2_i8);
    let c0 = values[0].clone();
    let c1 = &two * &(&values[1] - &values[0]);
    let c2 = &values[0] - &(&two * &values[1]) + &values[2];
    (c0, c1, c2)
}

#[derive(Clone, Debug, PartialEq)]
enum RationalPointRootSet {
    All,
    Roots(Vec<Real>),
}

#[derive(Clone, Debug, PartialEq)]
enum RationalQuadraticRootCover {
    All,
    Isolated {
        exact: Vec<Real>,
        spans: Vec<BezierMonotoneSpan>,
    },
}

fn rational_parameters_for_point(
    curve: &RationalQuadraticBezier2,
    point: &Point2,
    policy: &CurvePolicy,
) -> Classification<Vec<Real>> {
    let x_roots = match rational_axis_point_root_set(curve, point, Axis2::X, policy) {
        Classification::Decided(roots) => roots,
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    };
    let y_roots = match rational_axis_point_root_set(curve, point, Axis2::Y, policy) {
        Classification::Decided(roots) => roots,
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    };
    rational_point_parameters_from_root_sets(curve, point, x_roots, y_roots, policy)
}

fn rational_axis_point_root_set(
    curve: &RationalQuadraticBezier2,
    point: &Point2,
    axis: Axis2,
    policy: &CurvePolicy,
) -> Classification<RationalPointRootSet> {
    let target = coordinate(point, axis);
    let controls = curve.control_points();
    let weights = curve.weights();
    let values = [
        weights[0] * &(coordinate(controls[0], axis) - target),
        weights[1] * &(coordinate(controls[1], axis) - target),
        weights[2] * &(coordinate(controls[2], axis) - target),
    ];
    if values
        .iter()
        .all(|value| is_zero(value, policy) == Some(true))
    {
        return Classification::Decided(RationalPointRootSet::All);
    }
    let (c0, c1, c2) = quadratic_bernstein_to_power(values);
    polynomial_roots_in_unit_interval(c0, c1, c2, policy).map(RationalPointRootSet::Roots)
}

fn rational_point_parameters_from_root_sets(
    curve: &RationalQuadraticBezier2,
    point: &Point2,
    x_roots: RationalPointRootSet,
    y_roots: RationalPointRootSet,
    policy: &CurvePolicy,
) -> Classification<Vec<Real>> {
    let candidates = match (&x_roots, &y_roots) {
        (RationalPointRootSet::All, RationalPointRootSet::All) => vec![Real::zero()],
        (RationalPointRootSet::All, RationalPointRootSet::Roots(roots))
        | (RationalPointRootSet::Roots(roots), RationalPointRootSet::All) => roots.clone(),
        (RationalPointRootSet::Roots(left), RationalPointRootSet::Roots(right)) => {
            let mut candidates = left.clone();
            candidates.extend(right.iter().cloned());
            candidates
        }
    };

    let mut parameters = Vec::new();
    for candidate in candidates {
        match curve.point_at(candidate.clone(), policy) {
            Classification::Decided(curve_point) => {
                match point_equal(&curve_point, point, policy) {
                    Some(true) => parameters.push(candidate),
                    Some(false) => {}
                    None => return Classification::Uncertain(UncertaintyReason::RealSign),
                }
            }
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }
    }
    Classification::Decided(parameters)
}

fn is_unit_endpoint(value: &Real, policy: &CurvePolicy) -> bool {
    is_zero(value, policy) == Some(true) || is_zero(&(value - &Real::one()), policy) == Some(true)
}

fn equal_weight_polynomial_quadratic_image(
    rational: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<Option<QuadraticBezier2>> {
    match rational.weights_equal(policy) {
        Some(true) => {}
        Some(false) => return Classification::Decided(None),
        None => return Classification::Uncertain(UncertaintyReason::RealSign),
    }
    match rational.weights_known_same_nonzero_sign(policy) {
        Some(true) => {}
        Some(false) => return Classification::Decided(None),
        None => return Classification::Uncertain(UncertaintyReason::RealSign),
    }

    let controls = rational.control_points();
    Classification::Decided(Some(QuadraticBezier2::new(
        controls[0].clone(),
        controls[1].clone(),
        controls[2].clone(),
    )))
}

fn collapsed_graph_order_to_quadratic(
    collapsed: &QuadraticBezier2,
    other: &QuadraticBezier2,
    shared_axis: Axis2,
    policy: &CurvePolicy,
) -> Classification<BezierMonotoneGraphOrder> {
    collapsed.graph_order_to_quadratic_over_axis(other, shared_axis, policy)
}

fn rational_quadratic_graph_order_to_quadratic(
    rational: &RationalQuadraticBezier2,
    polynomial: &QuadraticBezier2,
    shared_axis: Axis2,
    policy: &CurvePolicy,
) -> Classification<BezierMonotoneGraphOrder> {
    // For non-equal weights, the supported mixed graph shortcut is deliberately
    // narrower than a full rational/polynomial intersection solver. If one
    // coordinate is certified identical, ordering of the other coordinate is
    // the sign of `(N_rational - P_polynomial * D_rational) / D_rational`.
    // The numerator is a degree-4 Bernstein polynomial. A common strict sign
    // certifies order; otherwise exact Bernstein sign subdivision retains the
    // graph roots as represented parameters or isolating spans. This is Yap's
    // EGC boundary applied to Farin's homogeneous rational Bezier model, using
    // Bernstein convex-hull signs as in Sederberg-Nishita Bezier clipping.
    match rational.weights_known_same_nonzero_sign(policy) {
        Some(true) => {}
        Some(false) => {
            return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
        }
        None => return Classification::Uncertain(UncertaintyReason::RealSign),
    }
    let Some(weight_sign) = common_rational_weight_sign(rational, policy) else {
        return Classification::Uncertain(UncertaintyReason::RealSign);
    };

    let shared_difference =
        rational_polynomial_axis_difference_degree4_controls(rational, polynomial, shared_axis);
    match degree4_controls_all_zero(&shared_difference, policy) {
        Classification::Decided(true) => {}
        Classification::Decided(false) => {
            return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
        }
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }
    match rational_axis_strictly_monotone(rational, shared_axis, policy) {
        Classification::Decided(true) => {}
        Classification::Decided(false) => {
            return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
        }
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }

    let order_axis = other_axis(shared_axis);
    let order_difference =
        rational_polynomial_axis_difference_degree4_controls(rational, polynomial, order_axis);
    match degree4_controls_all_zero(&order_difference, policy) {
        Classification::Decided(true) => {
            return Classification::Decided(BezierMonotoneGraphOrder::Coincident);
        }
        Classification::Decided(false) => {}
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }
    if let Some(order) = strict_rational_graph_order_from_degree4_weighted_signs(
        &order_difference,
        weight_sign,
        policy,
    ) {
        return Classification::Decided(order);
    }

    match degree4_root_cover(order_difference.clone(), policy) {
        Ok(RationalPolynomialRootCover::All) => {
            Classification::Decided(BezierMonotoneGraphOrder::Coincident)
        }
        Ok(RationalPolynomialRootCover::Isolated { exact, spans }) => {
            if exact.is_empty() && spans.is_empty() {
                match real_sign(&order_difference[0], policy) {
                    Some(RealSign::Positive | RealSign::Negative) => {
                        strict_rational_graph_order_from_degree4_weighted_signs(
                            &order_difference,
                            weight_sign,
                            policy,
                        )
                        .map_or(
                            Classification::Uncertain(UncertaintyReason::RealSign),
                            Classification::Decided,
                        )
                    }
                    Some(RealSign::Zero) | None => {
                        Classification::Uncertain(UncertaintyReason::RealSign)
                    }
                }
            } else {
                Classification::Decided(BezierMonotoneGraphOrder::IntersectsOrTouches {
                    parameters: exact,
                    spans,
                })
            }
        }
        Err(reason) => Classification::Uncertain(reason),
    }
}

fn rational_quadratic_graph_order_to_cubic(
    rational: &RationalQuadraticBezier2,
    polynomial: &CubicBezier2,
    shared_axis: Axis2,
    policy: &CurvePolicy,
) -> Classification<BezierMonotoneGraphOrder> {
    // This is the cubic partner of the degree-4 mixed graph shortcut above.
    // When one coordinate is shared, strict order is the sign of the degree-5
    // Bernstein numerator `(N_rational - P_cubic * D_rational)` divided by the
    // same-sign rational denominator. A common nonzero Bernstein sign is a
    // certified no-root certificate by the convex-hull property; crossings and
    // tangencies are retained by exact quintic sign subdivision rather than
    // collapsed into sampled topology.
    match rational.weights_known_same_nonzero_sign(policy) {
        Some(true) => {}
        Some(false) => {
            return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
        }
        None => return Classification::Uncertain(UncertaintyReason::RealSign),
    }
    let Some(weight_sign) = common_rational_weight_sign(rational, policy) else {
        return Classification::Uncertain(UncertaintyReason::RealSign);
    };

    let shared_difference =
        rational_cubic_axis_difference_degree5_controls(rational, polynomial, shared_axis);
    match degree5_controls_all_zero(&shared_difference, policy) {
        Classification::Decided(true) => {}
        Classification::Decided(false) => {
            return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
        }
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }
    match rational_axis_strictly_monotone(rational, shared_axis, policy) {
        Classification::Decided(true) => {}
        Classification::Decided(false) => {
            return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
        }
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }

    let order_axis = other_axis(shared_axis);
    let order_difference =
        rational_cubic_axis_difference_degree5_controls(rational, polynomial, order_axis);
    match degree5_controls_all_zero(&order_difference, policy) {
        Classification::Decided(true) => {
            return Classification::Decided(BezierMonotoneGraphOrder::Coincident);
        }
        Classification::Decided(false) => {}
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }
    if let Some(order) = strict_rational_graph_order_from_degree5_weighted_signs(
        &order_difference,
        weight_sign,
        policy,
    ) {
        return Classification::Decided(order);
    }

    match degree5_root_cover(order_difference.clone(), policy) {
        Ok(RationalPolynomialRootCover::All) => {
            Classification::Decided(BezierMonotoneGraphOrder::Coincident)
        }
        Ok(RationalPolynomialRootCover::Isolated { exact, spans }) => {
            if exact.is_empty() && spans.is_empty() {
                match real_sign(&order_difference[0], policy) {
                    Some(RealSign::Positive | RealSign::Negative) => {
                        strict_rational_graph_order_from_degree5_weighted_signs(
                            &order_difference,
                            weight_sign,
                            policy,
                        )
                        .map_or(
                            Classification::Uncertain(UncertaintyReason::RealSign),
                            Classification::Decided,
                        )
                    }
                    Some(RealSign::Zero) | None => {
                        Classification::Uncertain(UncertaintyReason::RealSign)
                    }
                }
            } else {
                Classification::Decided(BezierMonotoneGraphOrder::IntersectsOrTouches {
                    parameters: exact,
                    spans,
                })
            }
        }
        Err(reason) => Classification::Uncertain(reason),
    }
}

fn rational_polynomial_axis_difference_degree4_controls(
    rational: &RationalQuadraticBezier2,
    polynomial: &QuadraticBezier2,
    axis: Axis2,
) -> [Real; 5] {
    let rational_controls = rational.control_points();
    let weights = rational.weights();
    let rational_weighted_axis = [
        weights[0] * coordinate(rational_controls[0], axis),
        weights[1] * coordinate(rational_controls[1], axis),
        weights[2] * coordinate(rational_controls[2], axis),
    ];
    let numerator = elevate_quadratic_bernstein_to_quartic(rational_weighted_axis);
    let polynomial_controls = polynomial.control_points();
    let polynomial_axis = [
        coordinate(polynomial_controls[0], axis).clone(),
        coordinate(polynomial_controls[1], axis).clone(),
        coordinate(polynomial_controls[2], axis).clone(),
    ];
    let denominator = [weights[0].clone(), weights[1].clone(), weights[2].clone()];
    let product = multiply_quadratic_bernstein_to_quartic(polynomial_axis, denominator);
    [
        &numerator[0] - &product[0],
        &numerator[1] - &product[1],
        &numerator[2] - &product[2],
        &numerator[3] - &product[3],
        &numerator[4] - &product[4],
    ]
}

fn rational_cubic_axis_difference_degree5_controls(
    rational: &RationalQuadraticBezier2,
    polynomial: &CubicBezier2,
    axis: Axis2,
) -> [Real; 6] {
    let rational_controls = rational.control_points();
    let weights = rational.weights();
    let rational_weighted_axis = [
        weights[0] * coordinate(rational_controls[0], axis),
        weights[1] * coordinate(rational_controls[1], axis),
        weights[2] * coordinate(rational_controls[2], axis),
    ];
    let numerator = elevate_quadratic_bernstein_to_quintic(rational_weighted_axis);
    let polynomial_controls = polynomial.control_points();
    let polynomial_axis = [
        coordinate(polynomial_controls[0], axis).clone(),
        coordinate(polynomial_controls[1], axis).clone(),
        coordinate(polynomial_controls[2], axis).clone(),
        coordinate(polynomial_controls[3], axis).clone(),
    ];
    let denominator = [weights[0].clone(), weights[1].clone(), weights[2].clone()];
    let product = multiply_cubic_quadratic_bernstein_to_quintic(polynomial_axis, denominator);
    [
        &numerator[0] - &product[0],
        &numerator[1] - &product[1],
        &numerator[2] - &product[2],
        &numerator[3] - &product[3],
        &numerator[4] - &product[4],
        &numerator[5] - &product[5],
    ]
}

fn elevate_quadratic_bernstein_to_quartic(values: [Real; 3]) -> [Real; 5] {
    let two = Real::from(2_i8);
    let six = Real::from(6_i8);
    [
        values[0].clone(),
        ((&values[0] + &values[1]) / &two)
            .expect("division by positive integer constant is defined"),
        ((&values[0] + (&Real::from(4_i8) * &values[1]) + &values[2]) / &six)
            .expect("division by positive integer constant is defined"),
        ((&values[1] + &values[2]) / &two)
            .expect("division by positive integer constant is defined"),
        values[2].clone(),
    ]
}

fn elevate_quadratic_bernstein_to_quintic(values: [Real; 3]) -> [Real; 6] {
    let five = Real::from(5_i8);
    let ten = Real::from(10_i8);
    [
        values[0].clone(),
        (((Real::from(3_i8) * &values[0]) + (Real::from(2_i8) * &values[1])) / &five)
            .expect("division by positive integer constant is defined"),
        (((Real::from(3_i8) * &values[0]) + (Real::from(6_i8) * &values[1]) + &values[2]) / &ten)
            .expect("division by positive integer constant is defined"),
        ((&values[0] + (Real::from(6_i8) * &values[1]) + (Real::from(3_i8) * &values[2])) / &ten)
            .expect("division by positive integer constant is defined"),
        (((Real::from(2_i8) * &values[1]) + (Real::from(3_i8) * &values[2])) / &five)
            .expect("division by positive integer constant is defined"),
        values[2].clone(),
    ]
}

fn multiply_quadratic_bernstein_to_quartic(first: [Real; 3], second: [Real; 3]) -> [Real; 5] {
    let two = Real::from(2_i8);
    let six = Real::from(6_i8);
    [
        &first[0] * &second[0],
        (((&first[0] * &second[1]) + (&first[1] * &second[0])) / &two)
            .expect("division by positive integer constant is defined"),
        (((&first[0] * &second[2])
            + (Real::from(4_i8) * &first[1] * &second[1])
            + (&first[2] * &second[0]))
            / &six)
            .expect("division by positive integer constant is defined"),
        (((&first[1] * &second[2]) + (&first[2] * &second[1])) / &two)
            .expect("division by positive integer constant is defined"),
        &first[2] * &second[2],
    ]
}

fn multiply_cubic_quadratic_bernstein_to_quintic(first: [Real; 4], second: [Real; 3]) -> [Real; 6] {
    let five = Real::from(5_i8);
    let ten = Real::from(10_i8);
    [
        &first[0] * &second[0],
        (((Real::from(2_i8) * &first[0] * &second[1])
            + (Real::from(3_i8) * &first[1] * &second[0]))
            / &five)
            .expect("division by positive integer constant is defined"),
        (((&first[0] * &second[2])
            + (Real::from(6_i8) * &first[1] * &second[1])
            + (Real::from(3_i8) * &first[2] * &second[0]))
            / &ten)
            .expect("division by positive integer constant is defined"),
        (((Real::from(3_i8) * &first[1] * &second[2])
            + (Real::from(6_i8) * &first[2] * &second[1])
            + (&first[3] * &second[0]))
            / &ten)
            .expect("division by positive integer constant is defined"),
        (((Real::from(3_i8) * &first[2] * &second[2])
            + (Real::from(2_i8) * &first[3] * &second[1]))
            / &five)
            .expect("division by positive integer constant is defined"),
        &first[3] * &second[2],
    ]
}

fn degree4_controls_all_zero(controls: &[Real; 5], policy: &CurvePolicy) -> Classification<bool> {
    let mut all_zero = true;
    for control in controls {
        match is_zero(control, policy) {
            Some(true) => {}
            Some(false) => all_zero = false,
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }
    }
    Classification::Decided(all_zero)
}

fn degree5_controls_all_zero(controls: &[Real; 6], policy: &CurvePolicy) -> Classification<bool> {
    let mut all_zero = true;
    for control in controls {
        match is_zero(control, policy) {
            Some(true) => {}
            Some(false) => all_zero = false,
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }
    }
    Classification::Decided(all_zero)
}

#[derive(Clone, Debug, PartialEq)]
enum RationalPolynomialRootCover {
    All,
    Isolated {
        exact: Vec<Real>,
        spans: Vec<BezierMonotoneSpan>,
    },
}

fn degree4_root_cover(
    controls: [Real; 5],
    policy: &CurvePolicy,
) -> Result<RationalPolynomialRootCover, UncertaintyReason> {
    match degree4_controls_all_zero(&controls, policy) {
        Classification::Decided(true) => return Ok(RationalPolynomialRootCover::All),
        Classification::Decided(false) => {}
        Classification::Uncertain(reason) => return Err(reason),
    }

    let mut exact = Vec::new();
    let mut spans = Vec::new();
    isolate_scalar_bernstein_roots(
        controls.to_vec(),
        Real::zero(),
        Real::one(),
        0,
        policy,
        &mut exact,
        &mut spans,
    )?;
    Ok(RationalPolynomialRootCover::Isolated { exact, spans })
}

fn degree5_root_cover(
    controls: [Real; 6],
    policy: &CurvePolicy,
) -> Result<RationalPolynomialRootCover, UncertaintyReason> {
    match degree5_controls_all_zero(&controls, policy) {
        Classification::Decided(true) => return Ok(RationalPolynomialRootCover::All),
        Classification::Decided(false) => {}
        Classification::Uncertain(reason) => return Err(reason),
    }

    let mut exact = Vec::new();
    let mut spans = Vec::new();
    isolate_scalar_bernstein_roots(
        controls.to_vec(),
        Real::zero(),
        Real::one(),
        0,
        policy,
        &mut exact,
        &mut spans,
    )?;
    Ok(RationalPolynomialRootCover::Isolated { exact, spans })
}

fn isolate_scalar_bernstein_roots(
    controls: Vec<Real>,
    start: Real,
    end: Real,
    depth: usize,
    policy: &CurvePolicy,
    exact_parameters: &mut Vec<Real>,
    spans: &mut Vec<BezierMonotoneSpan>,
) -> Result<(), UncertaintyReason> {
    // This is the scalar sign-subdivision kernel used for mixed quartic and
    // quintic graph numerators. The control-polygon sign exclusion is the
    // Bezier clipping certificate of Sederberg and Nishita (1990), the
    // midpoint split is de Casteljau/Farin Bernstein subdivision, and the API
    // follows Yap (1997) by returning exact parameters or explicit brackets.
    debug_assert!(controls.len() >= 2);
    let signs = controls
        .iter()
        .map(|value| real_sign(value, policy).ok_or(UncertaintyReason::RealSign))
        .collect::<Result<Vec<_>, _>>()?;

    if signs[0] == RealSign::Zero {
        push_unique_graph_parameter(exact_parameters, start.clone(), policy);
    }
    if signs[signs.len() - 1] == RealSign::Zero {
        push_unique_graph_parameter(exact_parameters, end.clone(), policy);
    }

    let strict_signs = signs
        .iter()
        .copied()
        .filter(|sign| *sign != RealSign::Zero)
        .collect::<Vec<_>>();
    if strict_signs.is_empty() {
        push_unique_graph_region_span(spans, BezierMonotoneSpan::new(start, end), policy);
        return Ok(());
    }
    if strict_signs.iter().all(|sign| *sign == strict_signs[0]) {
        return Ok(());
    }

    let mid = ((&start + &end) / Real::from(2_i8)).map_err(|_| UncertaintyReason::Unsupported)?;
    let (left, right) = subdivide_scalar_bernstein_half(&controls);
    if is_zero(&left[left.len() - 1], policy) == Some(true) {
        push_unique_graph_parameter(exact_parameters, mid.clone(), policy);
    }

    if depth >= 32 {
        push_unique_graph_region_span(spans, BezierMonotoneSpan::new(start, end), policy);
        return Ok(());
    }

    isolate_scalar_bernstein_roots(
        left,
        start,
        mid.clone(),
        depth + 1,
        policy,
        exact_parameters,
        spans,
    )?;
    isolate_scalar_bernstein_roots(right, mid, end, depth + 1, policy, exact_parameters, spans)
}

fn subdivide_scalar_bernstein_half(controls: &[Real]) -> (Vec<Real>, Vec<Real>) {
    let degree = controls.len() - 1;
    let mut levels = Vec::with_capacity(controls.len());
    levels.push(controls.to_vec());
    for level in 1..=degree {
        let previous = &levels[level - 1];
        let next = previous
            .windows(2)
            .map(|pair| midpoint_real(&pair[0], &pair[1]))
            .collect::<Vec<_>>();
        levels.push(next);
    }

    let left = (0..=degree)
        .map(|level| levels[level][0].clone())
        .collect::<Vec<_>>();
    let right = (0..=degree)
        .map(|level| levels[degree - level][level].clone())
        .collect::<Vec<_>>();
    (left, right)
}

fn strict_rational_graph_order_from_degree4_weighted_signs(
    values: &[Real; 5],
    weight_sign: RealSign,
    policy: &CurvePolicy,
) -> Option<BezierMonotoneGraphOrder> {
    let mut common = None;
    for value in values {
        let sign = real_sign(value, policy)?;
        match (common, sign) {
            (_, RealSign::Zero) => return None,
            (None, RealSign::Positive | RealSign::Negative) => common = Some(sign),
            (Some(previous), RealSign::Positive | RealSign::Negative) if previous == sign => {}
            (Some(_), RealSign::Positive | RealSign::Negative) => return None,
        }
    }
    rational_graph_order_from_sign(common?, weight_sign)
}

fn strict_rational_graph_order_from_degree5_weighted_signs(
    values: &[Real; 6],
    weight_sign: RealSign,
    policy: &CurvePolicy,
) -> Option<BezierMonotoneGraphOrder> {
    let mut common = None;
    for value in values {
        let sign = real_sign(value, policy)?;
        match (common, sign) {
            (_, RealSign::Zero) => return None,
            (None, RealSign::Positive | RealSign::Negative) => common = Some(sign),
            (Some(previous), RealSign::Positive | RealSign::Negative) if previous == sign => {}
            (Some(_), RealSign::Positive | RealSign::Negative) => return None,
        }
    }
    rational_graph_order_from_sign(common?, weight_sign)
}

fn invert_graph_order(order: BezierMonotoneGraphOrder) -> BezierMonotoneGraphOrder {
    match order {
        BezierMonotoneGraphOrder::FirstLess => BezierMonotoneGraphOrder::FirstGreater,
        BezierMonotoneGraphOrder::FirstGreater => BezierMonotoneGraphOrder::FirstLess,
        BezierMonotoneGraphOrder::Coincident => BezierMonotoneGraphOrder::Coincident,
        BezierMonotoneGraphOrder::IntersectsOrTouches { parameters, spans } => {
            BezierMonotoneGraphOrder::IntersectsOrTouches { parameters, spans }
        }
        BezierMonotoneGraphOrder::NotSharedStrictlyMonotone => {
            BezierMonotoneGraphOrder::NotSharedStrictlyMonotone
        }
    }
}

impl QuadraticBezier2 {
    /// Classifies a coarse relation between this polynomial quadratic and a rational conic.
    pub fn relation_to_rational_quadratic(
        &self,
        other: &RationalQuadraticBezier2,
        policy: &CurvePolicy,
    ) -> Classification<BezierCurveRelation> {
        other.relation_to_quadratic(self, policy)
    }

    /// Classifies graph order against a rational quadratic conic.
    ///
    /// This is the polynomial-side companion to
    /// [`RationalQuadraticBezier2::graph_order_to_quadratic_over_axis`]. It
    /// includes the equal-weight polynomial collapse and the non-equal
    /// homogeneous numerator shortcut, then inverts the order so callers see
    /// the polynomial curve as `self`. Non-strict mixed quartic roots are
    /// retained as represented parameters or isolating spans following Yap's
    /// exact-predicate boundary.
    pub fn graph_order_to_rational_quadratic_over_axis(
        &self,
        other: &RationalQuadraticBezier2,
        shared_axis: Axis2,
        policy: &CurvePolicy,
    ) -> Classification<BezierMonotoneGraphOrder> {
        match other.equal_weight_polynomial_quadratic_image(policy) {
            Classification::Decided(Some(curve)) => {
                self.graph_order_to_quadratic_over_axis(&curve, shared_axis, policy)
            }
            Classification::Decided(None) => other
                .rational_quadratic_graph_order_to_quadratic(self, shared_axis, policy)
                .map(invert_graph_order),
            Classification::Uncertain(reason) => Classification::Uncertain(reason),
        }
    }
}

impl CubicBezier2 {
    /// Classifies a coarse relation between this polynomial cubic and a rational conic.
    pub fn relation_to_rational_quadratic(
        &self,
        other: &RationalQuadraticBezier2,
        policy: &CurvePolicy,
    ) -> Classification<BezierCurveRelation> {
        other.relation_to_cubic(self, policy)
    }

    /// Classifies graph order against a rational quadratic conic.
    ///
    /// Equal homogeneous conic weights collapse exactly to the polynomial
    /// quadratic image. Non-equal same-sign weights use the degree-5
    /// homogeneous Bernstein root/sign shortcut when one coordinate is exactly
    /// shared, then invert the result so `self` is the first curve. Non-strict
    /// mixed quintic roots are retained as represented parameters or isolating
    /// spans rather than sampled topology, preserving Yap's EGC boundary; see
    /// Yap, "Towards Exact Geometric
    /// Computation," *Computational Geometry* 7.1-2 (1997), Farin, *Curves and
    /// Surfaces for CAGD* (5th ed., 2002), and Sederberg-Nishita (1990).
    pub fn graph_order_to_rational_quadratic_over_axis(
        &self,
        other: &RationalQuadraticBezier2,
        shared_axis: Axis2,
        policy: &CurvePolicy,
    ) -> Classification<BezierMonotoneGraphOrder> {
        match other.equal_weight_polynomial_quadratic_image(policy) {
            Classification::Decided(Some(curve)) => {
                self.graph_order_to_quadratic_over_axis(&curve, shared_axis, policy)
            }
            Classification::Decided(None) => other
                .rational_quadratic_graph_order_to_cubic(self, shared_axis, policy)
                .map(invert_graph_order),
            Classification::Uncertain(reason) => Classification::Uncertain(reason),
        }
    }
}

fn relation_to_polynomial_bezier(
    rational: &RationalQuadraticBezier2,
    polynomial_controls: &[&Point2],
    policy: &CurvePolicy,
) -> Classification<BezierCurveRelation> {
    if polynomial_controls.len() == 3 {
        match rational.same_polynomial_quadratic_controls(polynomial_controls, policy) {
            Some(true) => return Classification::Decided(BezierCurveRelation::SameControlPolygon),
            Some(false) => {}
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }
    }

    match polynomial_relation_for_equal_weight_rational(rational, polynomial_controls, policy) {
        Classification::Decided(Some(relation)) => return Classification::Decided(relation),
        Classification::Decided(None) => {}
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }
    match polynomial_relation_for_strict_mixed_graph_order(rational, polynomial_controls, policy) {
        Classification::Decided(Some(relation)) => return Classification::Decided(relation),
        Classification::Decided(None) => {}
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }

    let mut deferred_uncertainty = None;
    if rational.weights_known_same_nonzero_sign(policy) == Some(true) {
        let boxes = match (
            Aabb2::from_points(rational.control_points(), policy),
            Aabb2::from_points(polynomial_controls.iter().copied(), policy),
        ) {
            (Classification::Decided(rational_box), Classification::Decided(polynomial_box)) => {
                Some((rational_box, polynomial_box))
            }
            (Classification::Uncertain(reason), _) | (_, Classification::Uncertain(reason)) => {
                deferred_uncertainty = Some(reason);
                None
            }
        };
        if let Some((rational_box, polynomial_box)) = boxes {
            match rational_box.overlaps(&polynomial_box, policy) {
                Classification::Decided(false) => {
                    return Classification::Decided(BezierCurveRelation::BoundingBoxesDisjoint);
                }
                Classification::Decided(true) => {}
                Classification::Uncertain(reason) => deferred_uncertainty = Some(reason),
            }
        }
    }

    let rational_point_image = match rational_point_image(rational, policy) {
        Classification::Decided(point) => point,
        Classification::Uncertain(reason) => {
            deferred_uncertainty.get_or_insert(reason);
            None
        }
    };
    let polynomial_point_image = match point_image_from_controls(polynomial_controls, policy) {
        Classification::Decided(point) => point,
        Classification::Uncertain(reason) => {
            deferred_uncertainty.get_or_insert(reason);
            None
        }
    };
    match (&rational_point_image, &polynomial_point_image) {
        (Some(first), Some(second)) => match point_equal(first, second, policy) {
            Some(true) => {
                return Classification::Decided(BezierCurveRelation::IntersectionPoints {
                    points: vec![BezierCurveIntersectionPoint::new(first.clone())],
                });
            }
            Some(false) => return Classification::Decided(BezierCurveRelation::NoIntersection),
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        },
        (Some(point), None) => {
            match point_image_polynomial_intersections(point, polynomial_controls, policy) {
                Classification::Decided(Some(points)) if points.is_empty() => {
                    return Classification::Decided(BezierCurveRelation::NoIntersection);
                }
                Classification::Decided(Some(points)) => {
                    return Classification::Decided(BezierCurveRelation::IntersectionPoints {
                        points,
                    });
                }
                Classification::Decided(None) => {}
                Classification::Uncertain(reason) => return Classification::Uncertain(reason),
            }
        }
        (None, Some(point)) => match point_image_rational_intersections(point, rational, policy) {
            Classification::Decided(points) if points.is_empty() => {
                return Classification::Decided(BezierCurveRelation::NoIntersection);
            }
            Classification::Decided(points) => {
                return Classification::Decided(BezierCurveRelation::IntersectionPoints { points });
            }
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        },
        (None, None) => {}
    }

    let rational_line_image = match rational_line_segment_image(rational, policy) {
        Classification::Decided(line) => line,
        Classification::Uncertain(reason) => {
            deferred_uncertainty.get_or_insert(reason);
            None
        }
    };
    let polynomial_line_image = match line_segment_image_from_controls(polynomial_controls, policy)
    {
        Classification::Decided(line) => line,
        Classification::Uncertain(reason) => {
            deferred_uncertainty.get_or_insert(reason);
            None
        }
    };
    match (&rational_line_image, &polynomial_line_image) {
        (Some(first), Some(second)) => {
            return line_segment_intersection_relation(first, second, policy);
        }
        (None, Some(line)) => match line_image_rational_relation(line, rational, false, policy) {
            Classification::Decided(Some(relation)) => {
                return Classification::Decided(relation);
            }
            Classification::Decided(None) => {}
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        },
        (Some(line), None) => {
            match line_image_polynomial_relation(line, polynomial_controls, true, policy) {
                Classification::Decided(Some(relation)) => {
                    return Classification::Decided(relation);
                }
                Classification::Decided(None) => {}
                Classification::Uncertain(reason) => return Classification::Uncertain(reason),
            }
        }
        (None, None) => {}
    }

    let mut shared_endpoint_points = Vec::new();
    for a in [rational.start(), rational.end()] {
        for b in [
            polynomial_controls[0],
            polynomial_controls[polynomial_controls.len() - 1],
        ] {
            match point_equal(a, b, policy) {
                Some(true) => {
                    push_unique_intersection_point(&mut shared_endpoint_points, a.clone(), policy)
                }
                Some(false) => {}
                None => return Classification::Uncertain(UncertaintyReason::RealSign),
            }
        }
    }

    let endpoint_points =
        match rational_polynomial_endpoint_intersections(rational, polynomial_controls, policy) {
            Classification::Decided(points) => points,
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        };

    match same_parameter_dyadic_rational_polynomial_relation(rational, polynomial_controls, policy)
    {
        Classification::Decided(Some(relation)) => {
            return Classification::Decided(merge_endpoint_points_into_relation(
                relation,
                &endpoint_points,
                policy,
            ));
        }
        Classification::Decided(None) => {}
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }

    if !endpoint_points.is_empty() {
        return if endpoint_points_are_shared_only(&endpoint_points, &shared_endpoint_points, policy)
        {
            Classification::Decided(BezierCurveRelation::SharedEndpoint)
        } else {
            Classification::Decided(BezierCurveRelation::EndpointIntersections {
                points: endpoint_points,
            })
        };
    }

    if let Some(reason) = deferred_uncertainty {
        return Classification::Uncertain(reason);
    }

    if rational.weights_known_same_nonzero_sign(policy) == Some(true) {
        return isolate_curve_regions(
            RationalSubdivisionNode::from_rational(rational),
            RationalSubdivisionNode::from_polynomial(polynomial_controls),
            policy,
        );
    }

    Classification::Decided(BezierCurveRelation::Unresolved)
}

const RATIONAL_POLYNOMIAL_DYADIC_CANDIDATE_DENOMINATOR: i16 = 512;

fn same_parameter_dyadic_rational_polynomial_relation(
    rational: &RationalQuadraticBezier2,
    polynomial_controls: &[&Point2],
    policy: &CurvePolicy,
) -> Classification<Option<BezierCurveRelation>> {
    let denominator = Real::from(RATIONAL_POLYNOMIAL_DYADIC_CANDIDATE_DENOMINATOR);
    let mut points = Vec::new();
    for numerator in 1..RATIONAL_POLYNOMIAL_DYADIC_CANDIDATE_DENOMINATOR {
        let parameter = (Real::from(numerator) / &denominator)
            .expect("division by positive dyadic-grid denominator is defined");
        let rational_point = match rational.point_at(parameter.clone(), policy) {
            Classification::Decided(point) => point,
            // Denominator-boundary candidates are not promoted. The caller keeps
            // the conservative subdivision/uncertainty path for topology.
            Classification::Uncertain(_) => continue,
        };
        let polynomial_point = polynomial_point_at(polynomial_controls, parameter);
        match point_coordinates_equal(&rational_point, &polynomial_point, policy) {
            Some(true) => push_unique_intersection_point(&mut points, rational_point, policy),
            Some(false) => {}
            // The finite grid is an opportunistic promotion pass, not a
            // no-intersection proof. If a non-hit candidate cannot be signed
            // cheaply, keep scanning and let the caller's conservative fallback
            // cover the unresolved topology.
            None => {}
        }
    }

    if points.is_empty() {
        Classification::Decided(None)
    } else {
        // This finite same-parameter grid is the conic/polynomial analogue of
        // the low-degree dyadic promotions used for polynomial Beziers. It
        // follows Yap's exact-geometric-computation boundary by promoting only
        // points that survive exact homogeneous rational evaluation and exact
        // de Casteljau polynomial evaluation; see Yap, "Towards Exact Geometric
        // Computation," Computational Geometry 7.1-2 (1997). The homogeneous
        // rational evaluation is Farin's rational Bezier form, *Curves and
        // Surfaces for CAGD* (5th ed., 2002), while the subdivision/evaluation
        // model is de Casteljau's algorithm (1959).
        Classification::Decided(Some(BezierCurveRelation::IntersectionPoints { points }))
    }
}

fn polynomial_relation_for_equal_weight_rationals(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<Option<BezierCurveRelation>> {
    match (first.weights_equal(policy), second.weights_equal(policy)) {
        (Some(true), Some(true)) => {
            let first_polynomial = polynomial_quadratic_from_rational_controls(first);
            let second_polynomial = polynomial_quadratic_from_rational_controls(second);
            // Equal Bernstein weights cancel from `sum B_i(t) w P_i /
            // sum B_i(t) w`, so the rational segment is exactly the
            // polynomial Bezier with the same Euclidean controls. This is the
            // homogeneous-to-affine reduction described by Farin, *Curves and
            // Surfaces for CAGD* (5th ed., 2002). Per Yap's EGC model, we
            // preserve that object identity and delegate to the polynomial
            // predicate surface instead of pushing an already-polynomial curve
            // through conservative conic subdivision; see Yap, "Towards Exact
            // Geometric Computation," Computational Geometry 7.1-2 (1997).
            first_polynomial
                .relation_to_quadratic(&second_polynomial, policy)
                .map(Some)
        }
        (Some(false), _) | (_, Some(false)) => Classification::Decided(None),
        _ => Classification::Uncertain(UncertaintyReason::RealSign),
    }
}

fn polynomial_relation_for_equal_weight_rational(
    rational: &RationalQuadraticBezier2,
    polynomial_controls: &[&Point2],
    policy: &CurvePolicy,
) -> Classification<Option<BezierCurveRelation>> {
    match rational.weights_equal(policy) {
        Some(true) => {
            let polynomial = polynomial_quadratic_from_rational_controls(rational);
            match polynomial_controls {
                [start, control, end] => {
                    let other =
                        QuadraticBezier2::new((*start).clone(), (*control).clone(), (*end).clone());
                    polynomial.relation_to_quadratic(&other, policy).map(Some)
                }
                [start, control1, control2, end] => {
                    let other = CubicBezier2::new(
                        (*start).clone(),
                        (*control1).clone(),
                        (*control2).clone(),
                        (*end).clone(),
                    );
                    polynomial.relation_to_cubic(&other, policy).map(Some)
                }
                _ => Classification::Uncertain(UncertaintyReason::Unsupported),
            }
        }
        Some(false) => Classification::Decided(None),
        None => Classification::Uncertain(UncertaintyReason::RealSign),
    }
}

fn polynomial_relation_for_strict_mixed_graph_order(
    rational: &RationalQuadraticBezier2,
    polynomial_controls: &[&Point2],
    policy: &CurvePolicy,
) -> Classification<Option<BezierCurveRelation>> {
    // Once one coordinate is certified identical and injective, the remaining
    // homogeneous numerator is a complete same-parameter graph predicate:
    // strict signs prove no intersection, represented roots promote exact
    // points, and non-represented roots stay as retained parameter regions.
    // This is the Sederberg-Nishita Bezier clipping exclusion/retention idea
    // used under Yap's exact branch boundary; Farin gives the homogeneous
    // rational Bernstein identities that produce the degree-4/5 numerators.
    for axis in [Axis2::X, Axis2::Y] {
        let order = match polynomial_controls {
            [start, control, end] => {
                let polynomial =
                    QuadraticBezier2::new((*start).clone(), (*control).clone(), (*end).clone());
                rational.graph_order_to_quadratic_over_axis(&polynomial, axis, policy)
            }
            [start, control1, control2, end] => {
                let polynomial = CubicBezier2::new(
                    (*start).clone(),
                    (*control1).clone(),
                    (*control2).clone(),
                    (*end).clone(),
                );
                rational.graph_order_to_cubic_over_axis(&polynomial, axis, policy)
            }
            _ => return Classification::Uncertain(UncertaintyReason::Unsupported),
        };
        match order {
            Classification::Decided(order) => {
                match relation_from_mixed_graph_order(rational, order, policy) {
                    Ok(Some(relation)) => return Classification::Decided(Some(relation)),
                    Ok(None) => {}
                    Err(reason) => return Classification::Uncertain(reason),
                }
            }
            Classification::Uncertain(UncertaintyReason::Unsupported) => {}
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }
    }

    Classification::Decided(None)
}

fn relation_from_mixed_graph_order(
    rational: &RationalQuadraticBezier2,
    order: BezierMonotoneGraphOrder,
    policy: &CurvePolicy,
) -> Result<Option<BezierCurveRelation>, UncertaintyReason> {
    match order {
        BezierMonotoneGraphOrder::FirstLess | BezierMonotoneGraphOrder::FirstGreater => {
            Ok(Some(BezierCurveRelation::NoIntersection))
        }
        BezierMonotoneGraphOrder::Coincident => Ok(Some(BezierCurveRelation::SameCurveImage)),
        BezierMonotoneGraphOrder::NotSharedStrictlyMonotone => Ok(None),
        BezierMonotoneGraphOrder::IntersectsOrTouches {
            parameters,
            mut spans,
        } => {
            if spans.is_empty() {
                let mut points = Vec::new();
                for parameter in parameters {
                    let point = match rational.point_at(parameter, policy) {
                        Classification::Decided(point) => point,
                        Classification::Uncertain(reason) => return Err(reason),
                    };
                    push_unique_intersection_point(&mut points, point, policy);
                }
                return Ok(Some(BezierCurveRelation::IntersectionPoints { points }));
            }

            for parameter in parameters {
                push_unique_graph_region_span(
                    &mut spans,
                    BezierMonotoneSpan::new(parameter.clone(), parameter),
                    policy,
                );
            }
            let regions = spans
                .into_iter()
                .map(|span| BezierCurveIntersectionRegion::new(span.clone(), span))
                .collect();
            Ok(Some(BezierCurveRelation::IntersectionRegions { regions }))
        }
    }
}

fn polynomial_quadratic_from_rational_controls(
    curve: &RationalQuadraticBezier2,
) -> QuadraticBezier2 {
    QuadraticBezier2::new(
        curve.start().clone(),
        curve.control().clone(),
        curve.end().clone(),
    )
}

fn rational_line_segment_image(
    curve: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<Option<LineSeg2>> {
    if curve.weights_known_same_nonzero_sign(policy) != Some(true) {
        return Classification::Decided(None);
    }
    line_segment_image_from_controls(&curve.control_points(), policy)
}

fn rational_point_image(
    curve: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<Option<Point2>> {
    if curve.weights_known_same_nonzero_sign(policy) != Some(true) {
        return Classification::Decided(None);
    }
    point_image_from_controls(&curve.control_points(), policy)
}

fn point_image_from_controls(
    controls: &[&Point2],
    policy: &CurvePolicy,
) -> Classification<Option<Point2>> {
    let Some(point) = controls.first().copied() else {
        return Classification::Uncertain(UncertaintyReason::Unsupported);
    };
    for control in controls.iter().skip(1) {
        match point_equal(point, control, policy) {
            Some(true) => {}
            Some(false) => return Classification::Decided(None),
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }
    }
    Classification::Decided(Some(point.clone()))
}

fn line_segment_image_from_controls(
    controls: &[&Point2],
    policy: &CurvePolicy,
) -> Classification<Option<LineSeg2>> {
    // Same-sign rational Bezier weights can be homogeneous-sign-normalized to
    // the positive case, preserving the Euclidean convex-hull property, while
    // collinear Bernstein controls keep the image on the supporting line; see
    // Farin, Curves and Surfaces for CAGD (2002). When every interior control
    // is also inside the endpoint box, the segment image is exactly the
    // endpoint line segment, so Yap's EGC boundary lets us dispatch to the
    // native exact line-line predicate instead of subdividing an already
    // linear object; see Yap, "Towards Exact Geometric Computation" (1997).
    if controls.len() < 2 {
        return Classification::Decided(None);
    }
    let start = controls[0];
    let end = controls[controls.len() - 1];
    let line = match LineSeg2::try_new(start.clone(), end.clone()) {
        Ok(line) => line,
        Err(CurveError::ZeroLengthLine) => return Classification::Decided(None),
        Err(_) => return Classification::Uncertain(UncertaintyReason::Unsupported),
    };
    let envelope = match Aabb2::from_points([start, end], policy) {
        Classification::Decided(envelope) => envelope,
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    };
    for point in controls
        .iter()
        .skip(1)
        .take(controls.len().saturating_sub(2))
    {
        match classify_oriented_line(start, end, point, policy) {
            Classification::Decided(LineSide::On) => {}
            Classification::Decided(_) => return Classification::Decided(None),
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }
        match envelope.contains_point(point, policy) {
            Classification::Decided(true) => {}
            Classification::Decided(false) => return Classification::Decided(None),
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }
    }
    Classification::Decided(Some(line))
}

fn line_segment_intersection_relation(
    first: &LineSeg2,
    second: &LineSeg2,
    policy: &CurvePolicy,
) -> Classification<BezierCurveRelation> {
    match first.intersect_line(second, policy) {
        Ok(intersection) => {
            Classification::Decided(BezierCurveRelation::LineSegmentIntersection { intersection })
        }
        Err(CurveError::Real(_)) => Classification::Uncertain(UncertaintyReason::RealSign),
        Err(_) => Classification::Uncertain(UncertaintyReason::Unsupported),
    }
}

fn rational_rational_endpoint_intersections(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<Vec<BezierCurveIntersectionPoint>> {
    let mut points = Vec::new();
    for endpoint in [first.start(), first.end()] {
        match second.parameters_for_point(endpoint, policy) {
            Classification::Decided(parameters) if !parameters.is_empty() => {
                push_unique_intersection_point(&mut points, endpoint.clone(), policy);
            }
            Classification::Decided(_) => {}
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }
    }
    for endpoint in [second.start(), second.end()] {
        match first.parameters_for_point(endpoint, policy) {
            Classification::Decided(parameters) if !parameters.is_empty() => {
                push_unique_intersection_point(&mut points, endpoint.clone(), policy);
            }
            Classification::Decided(_) => {}
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }
    }
    Classification::Decided(points)
}

fn merge_endpoint_points_into_relation(
    relation: BezierCurveRelation,
    endpoint_points: &[BezierCurveIntersectionPoint],
    policy: &CurvePolicy,
) -> BezierCurveRelation {
    if endpoint_points.is_empty() {
        return relation;
    }

    match relation {
        BezierCurveRelation::IntersectionPoints { mut points } => {
            // Rational/conic endpoints are exact lower-degree point predicates.
            // When a later same-parameter conic solve finds additional roots,
            // keep both evidence sets instead of letting an endpoint shortcut
            // mask interior topology. This follows Yap's exact-geometric-
            // computation boundary, and the rational homogeneous model is the
            // standard Farin representation retained by this module.
            for endpoint in endpoint_points {
                push_unique_intersection_point(&mut points, endpoint.point().clone(), policy);
            }
            BezierCurveRelation::IntersectionPoints { points }
        }
        BezierCurveRelation::NoIntersection
        | BezierCurveRelation::BoundingBoxesDisjoint
        | BezierCurveRelation::Unresolved => BezierCurveRelation::EndpointIntersections {
            points: endpoint_points.to_vec(),
        },
        relation => relation,
    }
}

fn endpoint_points_are_shared_only(
    endpoint_points: &[BezierCurveIntersectionPoint],
    shared_endpoint_points: &[BezierCurveIntersectionPoint],
    policy: &CurvePolicy,
) -> bool {
    !endpoint_points.is_empty()
        && endpoint_points.iter().all(|endpoint| {
            shared_endpoint_points
                .iter()
                .any(|shared| point_equal(endpoint.point(), shared.point(), policy) == Some(true))
        })
}

fn same_parameter_matching_weight_rational_relation(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<Option<BezierCurveRelation>> {
    match matching_rational_weights(first, second, policy) {
        Some(true) => {}
        Some(false) | None => return Classification::Decided(None),
    }

    match matching_weight_rational_graph_relation(first, second, policy) {
        Classification::Decided(Some(relation)) => return Classification::Decided(Some(relation)),
        Classification::Decided(None) => {}
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }

    let x_roots = match matching_weight_axis_difference_root_set(first, second, Axis2::X, policy) {
        Classification::Decided(Some(roots)) => roots,
        Classification::Decided(None) => return Classification::Decided(None),
        Classification::Uncertain(_) => return Classification::Decided(None),
    };
    let y_roots = match matching_weight_axis_difference_root_set(first, second, Axis2::Y, policy) {
        Classification::Decided(Some(roots)) => roots,
        Classification::Decided(None) => return Classification::Decided(None),
        Classification::Uncertain(_) => return Classification::Decided(None),
    };

    let candidates = match same_parameter_candidates_from_root_sets(x_roots, y_roots, policy) {
        Classification::Decided(candidates) => candidates,
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    };
    let mut points = Vec::new();
    for parameter in candidates {
        let first_point = match first.point_at(parameter.clone(), policy) {
            Classification::Decided(point) => point,
            Classification::Uncertain(_) => return Classification::Decided(None),
        };
        let second_point = match second.point_at(parameter, policy) {
            Classification::Decided(point) => point,
            Classification::Uncertain(_) => return Classification::Decided(None),
        };
        match point_equal(&first_point, &second_point, policy) {
            Some(true) => push_unique_intersection_point(&mut points, first_point, policy),
            Some(false) => {}
            None => return Classification::Decided(None),
        }
    }

    if points.is_empty() {
        match matching_weight_rational_same_parameter_is_complete(first, second, policy) {
            Classification::Decided(true) => {
                Classification::Decided(Some(BezierCurveRelation::NoIntersection))
            }
            Classification::Decided(false) => Classification::Decided(None),
            Classification::Uncertain(reason) => Classification::Uncertain(reason),
        }
    } else {
        Classification::Decided(Some(BezierCurveRelation::IntersectionPoints { points }))
    }
}

fn matching_weight_rational_graph_relation(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<Option<BezierCurveRelation>> {
    if first.weights_known_same_nonzero_sign(policy) != Some(true) {
        return Classification::Decided(None);
    }

    for shared_axis in [Axis2::X, Axis2::Y] {
        if !rational_matching_axis_equal(first, second, shared_axis, policy) {
            continue;
        }
        match rational_axis_strictly_monotone(first, shared_axis, policy) {
            Classification::Decided(true) => {}
            Classification::Decided(false) => continue,
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }

        let solve_axis = other_axis(shared_axis);
        let cover =
            match matching_weight_axis_difference_root_cover(first, second, solve_axis, policy) {
                Classification::Decided(Some(cover)) => cover,
                Classification::Decided(None) => return Classification::Decided(None),
                Classification::Uncertain(reason) => return Classification::Uncertain(reason),
            };

        let relation = match relation_from_matching_weight_graph_root_cover(first, cover, policy) {
            Ok(relation) => relation,
            Err(reason) => return Classification::Uncertain(reason),
        };
        return Classification::Decided(Some(relation));
    }

    Classification::Decided(None)
}

fn matching_weight_rational_graph_order(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    shared_axis: Axis2,
    policy: &CurvePolicy,
) -> Classification<BezierMonotoneGraphOrder> {
    match matching_rational_weights(first, second, policy) {
        Some(true) => {}
        Some(false) | None => {
            return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
        }
    }
    let Some(weight_sign) = common_rational_weight_sign(first, policy) else {
        return Classification::Uncertain(UncertaintyReason::RealSign);
    };

    if first.weights_known_same_nonzero_sign(policy) != Some(true) {
        return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
    }
    if !rational_matching_axis_equal(first, second, shared_axis, policy) {
        return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
    }
    match rational_axis_strictly_monotone(first, shared_axis, policy) {
        Classification::Decided(true) => {}
        Classification::Decided(false) => {
            return Classification::Decided(BezierMonotoneGraphOrder::NotSharedStrictlyMonotone);
        }
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }

    let solve_axis = other_axis(shared_axis);
    let values = matching_weight_axis_difference_values(first, second, solve_axis);
    if values
        .iter()
        .all(|value| is_zero(value, policy) == Some(true))
    {
        return Classification::Decided(BezierMonotoneGraphOrder::Coincident);
    }
    if let Some(order) =
        strict_rational_graph_order_from_weighted_signs(&values, weight_sign, policy)
    {
        return Classification::Decided(order);
    }

    let cover = match matching_weight_axis_difference_root_cover(first, second, solve_axis, policy)
    {
        Classification::Decided(Some(cover)) => cover,
        Classification::Decided(None) => {
            return Classification::Uncertain(UncertaintyReason::RealSign);
        }
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    };
    match cover {
        RationalQuadraticRootCover::All => {
            Classification::Decided(BezierMonotoneGraphOrder::Coincident)
        }
        RationalQuadraticRootCover::Isolated { exact, spans } => {
            if exact.is_empty() && spans.is_empty() {
                match real_sign(&values[0], policy) {
                    Some(sign) => match rational_graph_order_from_sign(sign, weight_sign) {
                        Some(order) => Classification::Decided(order),
                        None => Classification::Uncertain(UncertaintyReason::RealSign),
                    },
                    None => Classification::Uncertain(UncertaintyReason::RealSign),
                }
            } else {
                Classification::Decided(BezierMonotoneGraphOrder::IntersectsOrTouches {
                    parameters: exact,
                    spans,
                })
            }
        }
    }
}

fn matching_weight_rational_same_parameter_is_complete(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<bool> {
    // Matching weights give both rational quadratics one common homogeneous
    // denominator. If one Euclidean coordinate is also certified identical and
    // strictly monotone, that coordinate is injective, so every geometric
    // intersection has the same parameter on both curves. The remaining
    // coordinate is then a single exact quadratic Bernstein root problem. This
    // is the rational analogue of the polynomial graph shortcut above: Farin's
    // homogeneous rational Bezier model supplies the shared denominator, and
    // Yap's EGC model keeps the no-hit conclusion behind exact sign and root
    // certificates; see Farin, *Curves and Surfaces for CAGD* (5th ed., 2002),
    // and Yap, "Towards Exact Geometric Computation," Computational Geometry
    // 7.1-2 (1997).
    if first.weights_known_same_nonzero_sign(policy) != Some(true) {
        return Classification::Decided(false);
    }

    for axis in [Axis2::X, Axis2::Y] {
        if !rational_matching_axis_equal(first, second, axis, policy) {
            continue;
        }
        match rational_axis_strictly_monotone(first, axis, policy) {
            Classification::Decided(true) => return Classification::Decided(true),
            Classification::Decided(false) => {}
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }
    }
    Classification::Decided(false)
}

fn other_axis(axis: Axis2) -> Axis2 {
    match axis {
        Axis2::X => Axis2::Y,
        Axis2::Y => Axis2::X,
    }
}

fn rational_matching_axis_equal(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    axis: Axis2,
    policy: &CurvePolicy,
) -> bool {
    first
        .control_points()
        .iter()
        .zip(second.control_points().iter())
        .all(|(a, b)| is_zero(&(coordinate(a, axis) - coordinate(b, axis)), policy) == Some(true))
}

fn rational_axis_strictly_monotone(
    curve: &RationalQuadraticBezier2,
    axis: Axis2,
    policy: &CurvePolicy,
) -> Classification<bool> {
    let roots = match curve.axis_monotone_parameters(axis, policy) {
        Classification::Decided(roots) => roots,
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    };
    if !roots.is_empty() {
        return Classification::Decided(false);
    }
    let endpoint_delta = coordinate(curve.end(), axis) - coordinate(curve.start(), axis);
    Classification::Decided(!matches!(
        real_sign(&endpoint_delta, policy),
        Some(RealSign::Zero) | None
    ))
}

fn matching_rational_weights(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Option<bool> {
    first
        .weights()
        .iter()
        .zip(second.weights().iter())
        .map(|(a, b)| is_zero(&(*a - *b), policy))
        .try_fold(true, |same, item| item.map(|item| same && item))
}

fn common_rational_weight_sign(
    curve: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Option<RealSign> {
    let mut common = None;
    for weight in curve.weights() {
        let sign = real_sign(weight, policy)?;
        match (common, sign) {
            (_, RealSign::Zero) => return None,
            (None, RealSign::Positive | RealSign::Negative) => common = Some(sign),
            (Some(previous), RealSign::Positive | RealSign::Negative) if previous == sign => {}
            (Some(_), RealSign::Positive | RealSign::Negative) => return None,
        }
    }
    common
}

fn strict_rational_graph_order_from_weighted_signs(
    values: &[Real; 3],
    weight_sign: RealSign,
    policy: &CurvePolicy,
) -> Option<BezierMonotoneGraphOrder> {
    let mut common = None;
    for value in values {
        let sign = real_sign(value, policy)?;
        match (common, sign) {
            (_, RealSign::Zero) => return None,
            (None, RealSign::Positive | RealSign::Negative) => common = Some(sign),
            (Some(previous), RealSign::Positive | RealSign::Negative) if previous == sign => {}
            (Some(_), RealSign::Positive | RealSign::Negative) => return None,
        }
    }
    rational_graph_order_from_sign(common?, weight_sign)
}

fn rational_graph_order_from_sign(
    weighted_numerator_sign: RealSign,
    weight_sign: RealSign,
) -> Option<BezierMonotoneGraphOrder> {
    match (weighted_numerator_sign, weight_sign) {
        (RealSign::Positive, RealSign::Positive) | (RealSign::Negative, RealSign::Negative) => {
            Some(BezierMonotoneGraphOrder::FirstGreater)
        }
        (RealSign::Negative, RealSign::Positive) | (RealSign::Positive, RealSign::Negative) => {
            Some(BezierMonotoneGraphOrder::FirstLess)
        }
        _ => None,
    }
}

fn matching_weight_axis_difference_root_set(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    axis: Axis2,
    policy: &CurvePolicy,
) -> Classification<Option<RationalPointRootSet>> {
    let values = matching_weight_axis_difference_values(first, second, axis);
    if values
        .iter()
        .all(|value| is_zero(value, policy) == Some(true))
    {
        return Classification::Decided(Some(RationalPointRootSet::All));
    }

    // Matching rational weights give both curves the same Bernstein denominator,
    // so same-parameter equality reduces to zeros of the weighted homogeneous
    // numerator difference. This is Farin's rational Bezier model kept at Yap's
    // certified predicate boundary: exact scalar roots are promoted, while roots
    // outside the current scalar proof surface fall back to conservative
    // subdivision regions; see Farin, *Curves and Surfaces for CAGD* (2002), and
    // Yap, "Towards Exact Geometric Computation," Computational Geometry 7.1-2
    // (1997).
    let (c0, c1, c2) = quadratic_bernstein_to_power(values);
    match polynomial_roots_in_unit_interval(c0, c1, c2, policy) {
        Classification::Decided(roots) => {
            Classification::Decided(Some(RationalPointRootSet::Roots(roots)))
        }
        Classification::Uncertain(_) => Classification::Decided(None),
    }
}

fn matching_weight_axis_difference_root_cover(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    axis: Axis2,
    policy: &CurvePolicy,
) -> Classification<Option<RationalQuadraticRootCover>> {
    let values = matching_weight_axis_difference_values(first, second, axis);
    if values
        .iter()
        .all(|value| is_zero(value, policy) == Some(true))
    {
        return Classification::Decided(Some(RationalQuadraticRootCover::All));
    }

    let (c0, c1, c2) = quadratic_bernstein_to_power(values.clone());
    match polynomial_roots_in_unit_interval(c0, c1, c2, policy) {
        Classification::Decided(exact) => {
            return Classification::Decided(Some(RationalQuadraticRootCover::Isolated {
                exact,
                spans: Vec::new(),
            }));
        }
        Classification::Uncertain(_) => {}
    }

    // Complete graph cases still have a useful certificate when an exact
    // quadratic root cannot be represented by the scalar API: the Bernstein
    // convex-hull sign test either discards a subspan or keeps it as a bounded
    // parameter region. This mirrors the Bezier clipping exclusion of
    // Sederberg and Nishita, "Curve intersection using Bezier clipping" (1990),
    // while preserving Yap's exact-predicate boundary instead of converting the
    // undecidable root into an approximate point.
    let mut exact = Vec::new();
    let mut spans = Vec::new();
    if let Err(reason) = isolate_scalar_quadratic_roots(
        values,
        Real::zero(),
        Real::one(),
        0,
        policy,
        &mut exact,
        &mut spans,
    ) {
        return Classification::Uncertain(reason);
    }
    Classification::Decided(Some(RationalQuadraticRootCover::Isolated { exact, spans }))
}

fn matching_weight_axis_difference_values(
    first: &RationalQuadraticBezier2,
    second: &RationalQuadraticBezier2,
    axis: Axis2,
) -> [Real; 3] {
    let first_controls = first.control_points();
    let second_controls = second.control_points();
    let weights = first.weights();
    [
        weights[0] * &(coordinate(first_controls[0], axis) - coordinate(second_controls[0], axis)),
        weights[1] * &(coordinate(first_controls[1], axis) - coordinate(second_controls[1], axis)),
        weights[2] * &(coordinate(first_controls[2], axis) - coordinate(second_controls[2], axis)),
    ]
}

fn isolate_rational_quadratic_line_roots(
    weighted_distances: [Real; 3],
    policy: &CurvePolicy,
) -> Classification<BezierLineRelation> {
    // The signed distance numerator of a same-sign rational quadratic Bezier
    // has a denominator that cannot vanish on the affine segment, so its line
    // intersections are exactly the zeros of this scalar quadratic Bernstein
    // numerator. When the closed-form scalar solver cannot represent a root,
    // retain a certified dyadic Bernstein bracket instead of collapsing the
    // topology decision into an approximate sample. This is the same
    // convex-hull sign isolation used by Bezier clipping; see Sederberg and
    // Nishita, "Curve intersection using Bezier clipping" (1990), with the
    // rational homogeneous numerator/denominator model from Farin, *Curves and
    // Surfaces for CAGD* (5th ed., 2002), and Yap's exact predicate boundary.
    let mut exact_parameters = Vec::new();
    let mut spans = Vec::new();
    if let Err(reason) = isolate_scalar_quadratic_roots(
        weighted_distances,
        Real::zero(),
        Real::one(),
        0,
        policy,
        &mut exact_parameters,
        &mut spans,
    ) {
        return Classification::Uncertain(reason);
    }
    if !spans.is_empty() {
        for parameter in exact_parameters {
            push_unique_graph_region_span(
                &mut spans,
                BezierMonotoneSpan::new(parameter.clone(), parameter),
                policy,
            );
        }
        return Classification::Decided(BezierLineRelation::IsolatedIntersections { spans });
    }
    if !exact_parameters.is_empty() {
        return Classification::Decided(BezierLineRelation::Intersects {
            parameters: exact_parameters,
        });
    }
    Classification::Decided(BezierLineRelation::Unresolved)
}

fn rational_line_contact_relation_from_isolation(
    curve: &RationalQuadraticBezier2,
    weighted_distances: [Real; 3],
    policy: &CurvePolicy,
) -> Classification<BezierLineContactRelation> {
    let mut exact_parameters = Vec::new();
    let mut spans = Vec::new();
    if let Err(reason) = isolate_scalar_quadratic_roots(
        weighted_distances.clone(),
        Real::zero(),
        Real::one(),
        0,
        policy,
        &mut exact_parameters,
        &mut spans,
    ) {
        return Classification::Uncertain(reason);
    }
    if !spans.is_empty() {
        for parameter in exact_parameters {
            push_unique_graph_region_span(
                &mut spans,
                BezierMonotoneSpan::new(parameter.clone(), parameter),
                policy,
            );
        }
        return Classification::Decided(BezierLineContactRelation::IsolatedIntersections { spans });
    }
    if exact_parameters.is_empty() {
        return Classification::Decided(BezierLineContactRelation::Unresolved);
    }
    rational_line_contacts_from_parameters(curve, &weighted_distances, exact_parameters, policy)
}

fn rational_line_contacts_from_parameters(
    curve: &RationalQuadraticBezier2,
    weighted_distances: &[Real; 3],
    roots: Vec<Real>,
    policy: &CurvePolicy,
) -> Classification<BezierLineContactRelation> {
    let mut contacts = Vec::new();
    for root in roots {
        match is_zero(&curve.denominator_at(root.clone()), policy) {
            Some(true) => return Classification::Uncertain(UncertaintyReason::Boundary),
            Some(false) => {}
            None => return Classification::Uncertain(UncertaintyReason::RealSign),
        }
        let derivative = scalar_quadratic_bernstein_derivative_at(weighted_distances, &root);
        let Some(kind) = rational_line_contact_kind_from_derivative(&derivative, policy) else {
            return Classification::Uncertain(UncertaintyReason::RealSign);
        };
        push_unique_rational_line_contact(
            &mut contacts,
            BezierLineContact::new(root, kind),
            policy,
        );
    }
    Classification::Decided(BezierLineContactRelation::Contacts { contacts })
}

fn rational_line_contact_miss_or_unresolved(
    curve: &RationalQuadraticBezier2,
    line: &LineSeg2,
    policy: &CurvePolicy,
) -> Classification<BezierLineContactRelation> {
    if curve.weights_known_same_nonzero_sign(policy) == Some(true) {
        let sides = curve
            .control_points()
            .iter()
            .map(|point| classify_oriented_line(line.start(), line.end(), point, policy))
            .collect::<Vec<_>>();
        if sides
            .iter()
            .all(|side| matches!(side, Classification::Decided(LineSide::Left)))
        {
            return Classification::Decided(BezierLineContactRelation::ControlHullDisjoint {
                side: LineSide::Left,
            });
        }
        if sides
            .iter()
            .all(|side| matches!(side, Classification::Decided(LineSide::Right)))
        {
            return Classification::Decided(BezierLineContactRelation::ControlHullDisjoint {
                side: LineSide::Right,
            });
        }
    }
    Classification::Decided(BezierLineContactRelation::Unresolved)
}

fn scalar_quadratic_bernstein_derivative_at(controls: &[Real; 3], parameter: &Real) -> Real {
    let one_minus_t = Real::one() - parameter;
    let left = &controls[1] - &controls[0];
    let right = &controls[2] - &controls[1];
    Real::from(2_i8) * ((&one_minus_t * &left) + (parameter * &right))
}

fn rational_line_contact_kind_from_derivative(
    derivative: &Real,
    policy: &CurvePolicy,
) -> Option<BezierLineContactKind> {
    match real_sign(derivative, policy)? {
        RealSign::Zero => Some(BezierLineContactKind::Tangent),
        RealSign::Positive | RealSign::Negative => Some(BezierLineContactKind::Crossing),
    }
}

fn push_unique_rational_line_contact(
    contacts: &mut Vec<BezierLineContact>,
    contact: BezierLineContact,
    policy: &CurvePolicy,
) {
    if contacts.iter().any(|existing| {
        compare_reals(existing.parameter(), contact.parameter(), policy) == Some(Ordering::Equal)
    }) {
        return;
    }
    contacts.push(contact);
    contacts.sort_by(|a, b| {
        compare_reals(a.parameter(), b.parameter(), policy).unwrap_or(Ordering::Equal)
    });
}

fn same_parameter_candidates_from_root_sets(
    x_roots: RationalPointRootSet,
    y_roots: RationalPointRootSet,
    policy: &CurvePolicy,
) -> Classification<Vec<Real>> {
    let mut candidates = Vec::new();
    match (&x_roots, &y_roots) {
        (RationalPointRootSet::All, RationalPointRootSet::All) => {}
        (RationalPointRootSet::All, RationalPointRootSet::Roots(roots))
        | (RationalPointRootSet::Roots(roots), RationalPointRootSet::All) => {
            candidates.extend(roots.iter().cloned());
        }
        (RationalPointRootSet::Roots(left), RationalPointRootSet::Roots(right)) => {
            for left_root in left {
                if right
                    .iter()
                    .any(|right_root| is_zero(&(left_root - right_root), policy) == Some(true))
                {
                    match push_unique_real(&mut candidates, left_root.clone(), policy) {
                        Classification::Decided(()) => {}
                        Classification::Uncertain(reason) => {
                            return Classification::Uncertain(reason);
                        }
                    }
                }
            }
        }
    }
    Classification::Decided(candidates)
}

fn relation_from_matching_weight_graph_root_cover(
    curve: &RationalQuadraticBezier2,
    cover: RationalQuadraticRootCover,
    policy: &CurvePolicy,
) -> Result<BezierCurveRelation, UncertaintyReason> {
    match cover {
        RationalQuadraticRootCover::All => Ok(BezierCurveRelation::SameCurveImage),
        RationalQuadraticRootCover::Isolated { exact, spans } => {
            if spans.is_empty() {
                if exact.is_empty() {
                    return Ok(BezierCurveRelation::NoIntersection);
                }
                let mut points = Vec::new();
                for parameter in exact {
                    let point = match curve.point_at(parameter, policy) {
                        Classification::Decided(point) => point,
                        Classification::Uncertain(reason) => return Err(reason),
                    };
                    push_unique_intersection_point(&mut points, point, policy);
                }
                return Ok(BezierCurveRelation::IntersectionPoints { points });
            }

            let mut regions = spans;
            for parameter in exact {
                push_unique_graph_region_span(
                    &mut regions,
                    BezierMonotoneSpan::new(parameter.clone(), parameter),
                    policy,
                );
            }
            let regions = regions
                .into_iter()
                .map(|span| BezierCurveIntersectionRegion::new(span.clone(), span))
                .collect();
            Ok(BezierCurveRelation::IntersectionRegions { regions })
        }
    }
}

fn isolate_scalar_quadratic_roots(
    controls: [Real; 3],
    start: Real,
    end: Real,
    depth: usize,
    policy: &CurvePolicy,
    exact_parameters: &mut Vec<Real>,
    spans: &mut Vec<BezierMonotoneSpan>,
) -> Result<(), UncertaintyReason> {
    let signs = controls
        .iter()
        .map(|value| real_sign(value, policy).ok_or(UncertaintyReason::RealSign))
        .collect::<Result<Vec<_>, _>>()?;

    if signs[0] == RealSign::Zero {
        push_unique_graph_parameter(exact_parameters, start.clone(), policy);
    }
    if signs[2] == RealSign::Zero {
        push_unique_graph_parameter(exact_parameters, end.clone(), policy);
    }

    let strict_signs = signs
        .iter()
        .copied()
        .filter(|sign| *sign != RealSign::Zero)
        .collect::<Vec<_>>();
    if strict_signs.is_empty() {
        push_unique_graph_region_span(spans, BezierMonotoneSpan::new(start, end), policy);
        return Ok(());
    }
    if strict_signs.iter().all(|sign| *sign == strict_signs[0]) {
        return Ok(());
    }

    let mid = ((&start + &end) / Real::from(2_i8)).map_err(|_| UncertaintyReason::Unsupported)?;
    let mid_value = scalar_quadratic_at_half(&controls);
    if is_zero(&mid_value, policy) == Some(true) {
        push_unique_graph_parameter(exact_parameters, mid.clone(), policy);
    }

    if depth >= 32 {
        push_unique_graph_region_span(spans, BezierMonotoneSpan::new(start, end), policy);
        return Ok(());
    }

    let (left, right) = subdivide_scalar_quadratic_half(controls);
    isolate_scalar_quadratic_roots(
        left,
        start,
        mid.clone(),
        depth + 1,
        policy,
        exact_parameters,
        spans,
    )?;
    isolate_scalar_quadratic_roots(right, mid, end, depth + 1, policy, exact_parameters, spans)
}

fn scalar_quadratic_at_half(controls: &[Real; 3]) -> Real {
    let four = Real::from(4_i8);
    ((controls[0].clone() + (&Real::from(2_i8) * &controls[1]) + controls[2].clone()) / four)
        .expect("division by positive integer constant is defined")
}

fn subdivide_scalar_quadratic_half(controls: [Real; 3]) -> ([Real; 3], [Real; 3]) {
    let p01 = midpoint_real(&controls[0], &controls[1]);
    let p12 = midpoint_real(&controls[1], &controls[2]);
    let p012 = midpoint_real(&p01, &p12);
    (
        [controls[0].clone(), p01.clone(), p012.clone()],
        [p012, p12, controls[2].clone()],
    )
}

fn push_unique_graph_parameter(values: &mut Vec<Real>, value: Real, policy: &CurvePolicy) {
    if values
        .iter()
        .any(|existing| compare_reals(existing, &value, policy) == Some(Ordering::Equal))
    {
        return;
    }
    values.push(value);
    values.sort_by(|a, b| compare_reals(a, b, policy).unwrap_or(Ordering::Equal));
}

fn push_unique_graph_region_span(
    spans: &mut Vec<BezierMonotoneSpan>,
    span: BezierMonotoneSpan,
    policy: &CurvePolicy,
) {
    if spans.iter().any(|existing| {
        compare_reals(existing.start(), span.start(), policy) == Some(Ordering::Equal)
            && compare_reals(existing.end(), span.end(), policy) == Some(Ordering::Equal)
    }) {
        return;
    }
    spans.push(span);
    spans.sort_by(|a, b| compare_reals(a.start(), b.start(), policy).unwrap_or(Ordering::Equal));
}

fn rational_polynomial_endpoint_intersections(
    rational: &RationalQuadraticBezier2,
    polynomial_controls: &[&Point2],
    policy: &CurvePolicy,
) -> Classification<Vec<BezierCurveIntersectionPoint>> {
    let mut points = Vec::new();
    for endpoint in [
        polynomial_controls[0],
        polynomial_controls[polynomial_controls.len() - 1],
    ] {
        match rational.parameters_for_point(endpoint, policy) {
            Classification::Decided(parameters) if !parameters.is_empty() => {
                push_unique_intersection_point(&mut points, endpoint.clone(), policy);
            }
            Classification::Decided(_) => {}
            Classification::Uncertain(reason) => return Classification::Uncertain(reason),
        }
    }

    if let [start, control, end] = polynomial_controls {
        let polynomial =
            QuadraticBezier2::new((*start).clone(), (*control).clone(), (*end).clone());
        for endpoint in [rational.start(), rational.end()] {
            match polynomial.parameters_for_point(endpoint, policy) {
                Classification::Decided(parameters) if !parameters.is_empty() => {
                    push_unique_intersection_point(&mut points, endpoint.clone(), policy);
                }
                Classification::Decided(_) => {}
                Classification::Uncertain(reason) => return Classification::Uncertain(reason),
            }
        }
    }

    Classification::Decided(points)
}

fn point_image_rational_intersections(
    point: &Point2,
    rational: &RationalQuadraticBezier2,
    policy: &CurvePolicy,
) -> Classification<Vec<BezierCurveIntersectionPoint>> {
    // Once a rational conic is certified to collapse to one affine point, the
    // curve/curve predicate reduces to the other conic's homogeneous
    // point-parameter equations. This keeps Yap's exact branch boundary: no
    // sampled epsilon is introduced, and projective denominator uncertainty is
    // still surfaced by the rational point solver. See Yap, "Towards Exact
    // Geometric Computation," Computational Geometry 7.1-2 (1997), and
    // Farin's rational Bezier equations in *Curves and Surfaces for CAGD*
    // (5th ed., 2002).
    match rational.parameters_for_point(point, policy) {
        Classification::Decided(parameters) if parameters.is_empty() => {
            Classification::Decided(Vec::new())
        }
        Classification::Decided(_) => {
            Classification::Decided(vec![BezierCurveIntersectionPoint::new(point.clone())])
        }
        Classification::Uncertain(reason) => Classification::Uncertain(reason),
    }
}

fn point_image_polynomial_intersections(
    point: &Point2,
    controls: &[&Point2],
    policy: &CurvePolicy,
) -> Classification<Option<Vec<BezierCurveIntersectionPoint>>> {
    // Polynomial quadratic point queries are complete low-degree Bernstein
    // solves; cubic point queries currently remain a finite dyadic promotion
    // pass, so a miss for cubic controls is not a no-intersection proof. This
    // mirrors the polynomial Bezier dispatcher and follows Yap's distinction
    // between certified decisions and conservative unresolved cases.
    match controls {
        [start, control, end] => {
            let curve = QuadraticBezier2::new((*start).clone(), (*control).clone(), (*end).clone());
            match curve.parameters_for_point(point, policy) {
                Classification::Decided(parameters) if parameters.is_empty() => {
                    Classification::Decided(Some(Vec::new()))
                }
                Classification::Decided(_) => {
                    Classification::Decided(Some(vec![BezierCurveIntersectionPoint::new(
                        point.clone(),
                    )]))
                }
                Classification::Uncertain(reason) => Classification::Uncertain(reason),
            }
        }
        [start, control1, control2, end] => {
            let curve = CubicBezier2::new(
                (*start).clone(),
                (*control1).clone(),
                (*control2).clone(),
                (*end).clone(),
            );
            match curve.dyadic_parameters_for_point(point, policy) {
                Classification::Decided(parameters) if parameters.is_empty() => {
                    Classification::Decided(None)
                }
                Classification::Decided(_) => {
                    Classification::Decided(Some(vec![BezierCurveIntersectionPoint::new(
                        point.clone(),
                    )]))
                }
                Classification::Uncertain(reason) => Classification::Uncertain(reason),
            }
        }
        _ => Classification::Uncertain(UncertaintyReason::Unsupported),
    }
}

fn line_image_rational_relation(
    line: &LineSeg2,
    rational: &RationalQuadraticBezier2,
    line_is_first: bool,
    policy: &CurvePolicy,
) -> Classification<Option<BezierCurveRelation>> {
    // A line-image curve turns one side of the curve/curve problem into a
    // finite segment containment predicate. The rational side still uses its
    // homogeneous supporting-line numerator, following Farin's rational Bezier
    // incidence formulas. Isolated line roots become curve/curve regions with a
    // full span on the line-image side, preserving the Sederberg-Nishita
    // Bezier-clipping bracket (1990) at Yap's exact predicate boundary instead
    // of using sampled distances.
    match rational.relation_to_line(line, policy) {
        Classification::Decided(BezierLineRelation::ControlHullDisjoint { .. }) => {
            Classification::Decided(Some(BezierCurveRelation::NoIntersection))
        }
        Classification::Decided(BezierLineRelation::Intersects { parameters }) => {
            let mut points = Vec::new();
            for parameter in parameters {
                let point = match rational.point_at(parameter, policy) {
                    Classification::Decided(point) => point,
                    Classification::Uncertain(reason) => return Classification::Uncertain(reason),
                };
                match line.contains_point(&point, policy) {
                    Classification::Decided(true) => {
                        push_unique_intersection_point(&mut points, point, policy);
                    }
                    Classification::Decided(false) => {}
                    Classification::Uncertain(reason) => return Classification::Uncertain(reason),
                }
            }
            if points.is_empty() {
                Classification::Decided(Some(BezierCurveRelation::NoIntersection))
            } else {
                Classification::Decided(Some(BezierCurveRelation::IntersectionPoints { points }))
            }
        }
        Classification::Decided(BezierLineRelation::IsolatedIntersections { spans }) => {
            Classification::Decided(Some(line_image_regions_from_curve_spans(
                spans,
                line_is_first,
            )))
        }
        Classification::Decided(
            BezierLineRelation::OnSupportingLine | BezierLineRelation::Unresolved,
        ) => Classification::Decided(None),
        Classification::Uncertain(reason) => Classification::Uncertain(reason),
    }
}

fn line_image_polynomial_relation(
    line: &LineSeg2,
    controls: &[&Point2],
    line_is_first: bool,
    policy: &CurvePolicy,
) -> Classification<Option<BezierCurveRelation>> {
    // For polynomial quadratics, the supporting-line distance is an exact
    // quadratic Bernstein polynomial. Solving it before falling back to
    // subdivision is the low-degree slice of the Sederberg-Nishita Bezier
    // clipping strategy, kept exact by Yap-style certified containment checks.
    let relation = match polynomial_relation_to_line(controls, line, policy) {
        Classification::Decided(relation) => relation,
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    };
    match relation {
        BezierLineRelation::ControlHullDisjoint { .. } => {
            Classification::Decided(Some(BezierCurveRelation::NoIntersection))
        }
        BezierLineRelation::Intersects { parameters } => {
            let mut points = Vec::new();
            for parameter in parameters {
                let point = polynomial_point_at(controls, parameter);
                match line.contains_point(&point, policy) {
                    Classification::Decided(true) => {
                        push_unique_intersection_point(&mut points, point, policy)
                    }
                    Classification::Decided(false) => {}
                    Classification::Uncertain(reason) => return Classification::Uncertain(reason),
                }
            }
            if points.is_empty() {
                Classification::Decided(Some(BezierCurveRelation::NoIntersection))
            } else {
                Classification::Decided(Some(BezierCurveRelation::IntersectionPoints { points }))
            }
        }
        BezierLineRelation::IsolatedIntersections { spans } => Classification::Decided(Some(
            line_image_regions_from_curve_spans(spans, line_is_first),
        )),
        BezierLineRelation::OnSupportingLine | BezierLineRelation::Unresolved => {
            Classification::Decided(None)
        }
    }
}

fn line_image_regions_from_curve_spans(
    spans: Vec<BezierMonotoneSpan>,
    line_is_first: bool,
) -> BezierCurveRelation {
    let line_span = BezierMonotoneSpan::new(Real::zero(), Real::one());
    let regions = spans
        .into_iter()
        .map(|curve_span| {
            if line_is_first {
                BezierCurveIntersectionRegion::new(line_span.clone(), curve_span)
            } else {
                BezierCurveIntersectionRegion::new(curve_span, line_span.clone())
            }
        })
        .collect();
    BezierCurveRelation::IntersectionRegions { regions }
}

fn polynomial_relation_to_line(
    controls: &[&Point2],
    line: &LineSeg2,
    policy: &CurvePolicy,
) -> Classification<BezierLineRelation> {
    match controls {
        [start, control, end] => {
            QuadraticBezier2::new((*start).clone(), (*control).clone(), (*end).clone())
                .relation_to_line(line, policy)
        }
        [start, control1, control2, end] => CubicBezier2::new(
            (*start).clone(),
            (*control1).clone(),
            (*control2).clone(),
            (*end).clone(),
        )
        .relation_to_line(line, policy),
        _ => Classification::Uncertain(UncertaintyReason::Unsupported),
    }
}

fn polynomial_point_at(controls: &[&Point2], t: Real) -> Point2 {
    let mut level = controls
        .iter()
        .map(|point| (*point).clone())
        .collect::<Vec<_>>();
    while level.len() > 1 {
        level = level
            .windows(2)
            .map(|pair| pair[0].lerp(&pair[1], t.clone()))
            .collect();
    }
    level
        .pop()
        .expect("polynomial Bezier evaluation requires at least one control")
}

fn push_unique_intersection_point(
    points: &mut Vec<BezierCurveIntersectionPoint>,
    point: Point2,
    policy: &CurvePolicy,
) {
    if points
        .iter()
        .any(|existing| point_equal(existing.point(), &point, policy) == Some(true))
    {
        return;
    }
    points.push(BezierCurveIntersectionPoint::new(point));
}

fn push_unique_real(
    values: &mut Vec<Real>,
    value: Real,
    policy: &CurvePolicy,
) -> Classification<()> {
    if values
        .iter()
        .any(|existing| is_zero(&(existing - &value), policy) == Some(true))
    {
        return Classification::Decided(());
    }
    values.push(value);
    Classification::Decided(())
}

fn point_coordinates_equal(a: &Point2, b: &Point2, policy: &CurvePolicy) -> Option<bool> {
    let same_x = is_zero(&(a.x() - b.x()), policy)?;
    let same_y = is_zero(&(a.y() - b.y()), policy)?;
    Some(same_x && same_y)
}

#[derive(Clone, Debug)]
struct RationalSubdivisionNode {
    controls: Vec<Point2>,
    weights: Option<Vec<Real>>,
    span: BezierMonotoneSpan,
}

impl RationalSubdivisionNode {
    fn from_rational(curve: &RationalQuadraticBezier2) -> Self {
        Self {
            controls: curve.control_points().into_iter().cloned().collect(),
            weights: Some(curve.weights().into_iter().cloned().collect()),
            span: BezierMonotoneSpan::new(Real::zero(), Real::one()),
        }
    }

    fn from_polynomial(controls: &[&Point2]) -> Self {
        Self {
            controls: controls.iter().map(|point| (*point).clone()).collect(),
            weights: None,
            span: BezierMonotoneSpan::new(Real::zero(), Real::one()),
        }
    }

    fn with_span(
        controls: Vec<Point2>,
        weights: Option<Vec<Real>>,
        start: Real,
        end: Real,
    ) -> Self {
        Self {
            controls,
            weights,
            span: BezierMonotoneSpan::new(start, end),
        }
    }

    fn control_box(&self, policy: &CurvePolicy) -> Classification<Aabb2> {
        Aabb2::from_points(self.controls.iter(), policy)
    }

    fn split_half(&self, policy: &CurvePolicy) -> Result<(Self, Self), UncertaintyReason> {
        let (left_controls, left_weights, right_controls, right_weights) =
            match self.weights.as_ref() {
                Some(weights) => split_rational_controls_half(&self.controls, weights, policy)?,
                None => {
                    let (left, right) = split_polynomial_controls_half(&self.controls);
                    (left, None, right, None)
                }
            };
        let mid = ((self.span.start() + self.span.end()) / Real::from(2_i8))
            .map_err(|_| UncertaintyReason::Unsupported)?;
        Ok((
            Self::with_span(
                left_controls,
                left_weights,
                self.span.start().clone(),
                mid.clone(),
            ),
            Self::with_span(right_controls, right_weights, mid, self.span.end().clone()),
        ))
    }
}

fn isolate_curve_regions(
    first: RationalSubdivisionNode,
    second: RationalSubdivisionNode,
    policy: &CurvePolicy,
) -> Classification<BezierCurveRelation> {
    let mut regions = Vec::new();
    if let Err(reason) = isolate_curve_regions_recursive(first, second, 0, policy, &mut regions) {
        return Classification::Uncertain(reason);
    }
    if regions.is_empty() {
        Classification::Decided(BezierCurveRelation::Unresolved)
    } else {
        Classification::Decided(BezierCurveRelation::IntersectionRegions { regions })
    }
}

fn isolate_curve_regions_recursive(
    first: RationalSubdivisionNode,
    second: RationalSubdivisionNode,
    depth: usize,
    policy: &CurvePolicy,
    regions: &mut Vec<BezierCurveIntersectionRegion>,
) -> Result<(), UncertaintyReason> {
    // Positive-weight rational Beziers preserve the convex-hull property in
    // Euclidean control space. Subdividing in homogeneous coordinates preserves
    // that rational structure while allowing the same certified hull pruning
    // used by Bezier clipping; see Sederberg and Nishita (1990). Yap's EGC
    // boundary is kept by returning parameter regions instead of toleranced
    // intersection points.
    let first_box = match first.control_box(policy) {
        Classification::Decided(bbox) => bbox,
        Classification::Uncertain(reason) => return Err(reason),
    };
    let second_box = match second.control_box(policy) {
        Classification::Decided(bbox) => bbox,
        Classification::Uncertain(reason) => return Err(reason),
    };
    match first_box.overlaps(&second_box, policy) {
        Classification::Decided(false) => return Ok(()),
        Classification::Decided(true) => {}
        Classification::Uncertain(reason) => return Err(reason),
    }

    if depth >= 20 {
        regions.push(BezierCurveIntersectionRegion::new(first.span, second.span));
        return Ok(());
    }

    if depth.is_multiple_of(2) {
        let (left, right) = first.split_half(policy)?;
        isolate_curve_regions_recursive(left, second.clone(), depth + 1, policy, regions)?;
        isolate_curve_regions_recursive(right, second, depth + 1, policy, regions)
    } else {
        let (left, right) = second.split_half(policy)?;
        isolate_curve_regions_recursive(first.clone(), left, depth + 1, policy, regions)?;
        isolate_curve_regions_recursive(first, right, depth + 1, policy, regions)
    }
}

type RationalSplit = (
    Vec<Point2>,
    Option<Vec<Real>>,
    Vec<Point2>,
    Option<Vec<Real>>,
);

fn split_rational_controls_half(
    controls: &[Point2],
    weights: &[Real],
    policy: &CurvePolicy,
) -> Result<RationalSplit, UncertaintyReason> {
    let mut levels = vec![homogeneous_controls(controls, weights)];
    while levels.last().map(|level| level.len()).unwrap_or(0) > 1 {
        let previous = levels.last().expect("level exists");
        let next = previous
            .windows(2)
            .map(|pair| midpoint_homogeneous(&pair[0], &pair[1]))
            .collect::<Vec<_>>();
        levels.push(next);
    }

    let left_h = levels
        .iter()
        .map(|level| level[0].clone())
        .collect::<Vec<_>>();
    let right_h = levels
        .iter()
        .rev()
        .map(|level| level[level.len() - 1].clone())
        .collect::<Vec<_>>();
    let (left_controls, left_weights) = project_homogeneous_controls(&left_h, policy)?;
    let (right_controls, right_weights) = project_homogeneous_controls(&right_h, policy)?;
    Ok((
        left_controls,
        Some(left_weights),
        right_controls,
        Some(right_weights),
    ))
}

fn split_polynomial_controls_half(points: &[Point2]) -> (Vec<Point2>, Vec<Point2>) {
    let mut levels = vec![points.to_vec()];
    while levels.last().map(|level| level.len()).unwrap_or(0) > 1 {
        let previous = levels.last().expect("level exists");
        let next = previous
            .windows(2)
            .map(|pair| midpoint_point(&pair[0], &pair[1]))
            .collect::<Vec<_>>();
        levels.push(next);
    }

    let left = levels
        .iter()
        .map(|level| level[0].clone())
        .collect::<Vec<_>>();
    let right = levels
        .iter()
        .rev()
        .map(|level| level[level.len() - 1].clone())
        .collect::<Vec<_>>();
    (left, right)
}

#[derive(Clone, Debug)]
struct HomogeneousControl {
    x: Real,
    y: Real,
    weight: Real,
}

fn homogeneous_controls(controls: &[Point2], weights: &[Real]) -> Vec<HomogeneousControl> {
    controls
        .iter()
        .zip(weights.iter())
        .map(|(point, weight)| HomogeneousControl {
            x: point.x() * weight,
            y: point.y() * weight,
            weight: weight.clone(),
        })
        .collect()
}

fn midpoint_homogeneous(
    first: &HomogeneousControl,
    second: &HomogeneousControl,
) -> HomogeneousControl {
    HomogeneousControl {
        x: midpoint_real(&first.x, &second.x),
        y: midpoint_real(&first.y, &second.y),
        weight: midpoint_real(&first.weight, &second.weight),
    }
}

fn project_homogeneous_controls(
    controls: &[HomogeneousControl],
    policy: &CurvePolicy,
) -> Result<(Vec<Point2>, Vec<Real>), UncertaintyReason> {
    let mut points = Vec::with_capacity(controls.len());
    let mut weights = Vec::with_capacity(controls.len());
    for control in controls {
        match is_zero(&control.weight, policy) {
            Some(true) => return Err(UncertaintyReason::Boundary),
            Some(false) => {}
            None => return Err(UncertaintyReason::RealSign),
        }
        let x = (&control.x / &control.weight).map_err(|_| UncertaintyReason::Boundary)?;
        let y = (&control.y / &control.weight).map_err(|_| UncertaintyReason::Boundary)?;
        points.push(Point2::new(x, y));
        weights.push(control.weight.clone());
    }
    Ok((points, weights))
}

fn midpoint_point(first: &Point2, second: &Point2) -> Point2 {
    first.lerp(second, half())
}

fn midpoint_real(first: &Real, second: &Real) -> Real {
    ((first + second) / Real::from(2_i8)).expect("division by positive integer constant is defined")
}

fn half() -> Real {
    (Real::one() / Real::from(2_i8)).expect("division by positive integer constant is defined")
}

fn point_equal(a: &Point2, b: &Point2, policy: &CurvePolicy) -> Option<bool> {
    is_zero(&a.distance_squared(b), policy)
}