agg-rust 1.0.2

Pure Rust port of Anti-Grain Geometry (AGG) 2.6 - high quality 2D vector graphics rendering
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
//! Anti-aliased outline renderer.
//!
//! Port of `agg_renderer_outline_aa.h` + `agg_line_profile_aa.cpp`.
//! Renders anti-aliased lines with sub-pixel precision using distance
//! interpolation and a configurable width profile.
//!
//! Copyright 2025.

use crate::basics::{iround, RectI};
use crate::dda_line::Dda2LineInterpolator;
use crate::ellipse_bresenham::EllipseBresenhamInterpolator;
use crate::line_aa_basics::*;
use crate::math::fast_sqrt;
use crate::pixfmt_rgba::PixelFormat;
use crate::renderer_base::RendererBase;

// ============================================================================
// Line Profile
// ============================================================================

// These must match C++ line_profile_aa::subpixel_scale_e
const PROFILE_SUBPIXEL_SHIFT: i32 = LINE_SUBPIXEL_SHIFT; // 8
const PROFILE_SUBPIXEL_SCALE: i32 = 1 << PROFILE_SUBPIXEL_SHIFT; // 256
const PROFILE_AA_SHIFT: i32 = 8;
const PROFILE_AA_SCALE: i32 = 1 << PROFILE_AA_SHIFT; // 256
const PROFILE_AA_MASK: i32 = PROFILE_AA_SCALE - 1; // 255

/// Anti-aliased line width profile.
///
/// Port of C++ `line_profile_aa`. Builds a lookup table mapping perpendicular
/// distance from line center → coverage value, with configurable width and
/// gamma correction.
pub struct LineProfileAa {
    profile: Vec<u8>,
    gamma: [u8; 256],
    subpixel_width: i32,
    min_width: f64,
    smoother_width: f64,
}

impl LineProfileAa {
    pub fn new() -> Self {
        let mut s = Self {
            profile: Vec::new(),
            gamma: [0u8; 256],
            subpixel_width: 0,
            min_width: 1.0,
            smoother_width: 1.0,
        };
        // Identity gamma
        for i in 0..256 {
            s.gamma[i] = i as u8;
        }
        s
    }

    /// Create with a specific width.
    pub fn with_width(w: f64) -> Self {
        let mut s = Self::new();
        s.set_width(w);
        s
    }

    pub fn min_width(&self) -> f64 {
        self.min_width
    }
    pub fn smoother_width(&self) -> f64 {
        self.smoother_width
    }
    pub fn subpixel_width(&self) -> i32 {
        self.subpixel_width
    }

    pub fn set_min_width(&mut self, w: f64) {
        self.min_width = w;
    }
    pub fn set_smoother_width(&mut self, w: f64) {
        self.smoother_width = w;
    }

    /// Set the line width (in pixels).
    /// Port of C++ `line_profile_aa::width`.
    pub fn set_width(&mut self, mut w: f64) {
        if w < 0.0 { w = 0.0; }

        if w < self.smoother_width {
            w += w;
        } else {
            w += self.smoother_width;
        }

        w *= 0.5;
        w -= self.smoother_width;
        let mut s = self.smoother_width;
        if w < 0.0 {
            s += w;
            w = 0.0;
        }
        self.build_profile(w, s);
    }

    /// Apply gamma function.
    pub fn set_gamma<F: Fn(f64) -> f64>(&mut self, gamma_fn: F) {
        for i in 0..256 {
            self.gamma[i] = iround(gamma_fn(i as f64 / 255.0) * 255.0) as u8;
        }
    }

    /// Lookup coverage for a given perpendicular distance.
    #[inline]
    pub fn value(&self, dist: i32) -> u8 {
        let idx = (dist + PROFILE_SUBPIXEL_SCALE * 2) as usize;
        if idx < self.profile.len() {
            self.profile[idx]
        } else {
            0
        }
    }

    fn profile_size(&self) -> usize {
        self.profile.len()
    }

    /// Port of C++ `line_profile_aa::set` + `line_profile_aa::profile`.
    fn build_profile(&mut self, center_width: f64, smoother_width: f64) {
        let mut base_val = 1.0f64;
        let mut cw = center_width;
        let mut sw = smoother_width;

        if cw == 0.0 {
            cw = 1.0 / PROFILE_SUBPIXEL_SCALE as f64;
        }
        if sw == 0.0 {
            sw = 1.0 / PROFILE_SUBPIXEL_SCALE as f64;
        }

        let width = cw + sw;
        if width < self.min_width {
            let k = width / self.min_width;
            base_val *= k;
            cw /= k;
            sw /= k;
        }

        // C++ profile(): m_subpixel_width = uround(w * subpixel_scale)
        self.subpixel_width = iround((cw + sw) * PROFILE_SUBPIXEL_SCALE as f64);
        let size = self.subpixel_width as usize + PROFILE_SUBPIXEL_SCALE as usize * 6;
        self.profile.resize(size, 0);

        let subpixel_center_width = (cw * PROFILE_SUBPIXEL_SCALE as f64) as usize;
        let subpixel_smoother_width = (sw * PROFILE_SUBPIXEL_SCALE as f64) as usize;

        let ch_center = PROFILE_SUBPIXEL_SCALE as usize * 2;

        // Fill center region with full-alpha value
        let val = self.gamma[(base_val * PROFILE_AA_MASK as f64) as usize];
        for i in 0..subpixel_center_width {
            self.profile[ch_center + i] = val;
        }

        // Fill smoother region with falloff
        let ch_smoother = ch_center + subpixel_center_width;
        for i in 0..subpixel_smoother_width {
            let k = base_val - base_val * (i as f64 / subpixel_smoother_width as f64);
            self.profile[ch_smoother + i] =
                self.gamma[(k * PROFILE_AA_MASK as f64) as usize];
        }

        // Fill remaining with gamma[0]
        let n_smoother = size
            - subpixel_smoother_width
            - subpixel_center_width
            - PROFILE_SUBPIXEL_SCALE as usize * 2;
        let gamma_zero = self.gamma[0];
        for i in 0..n_smoother {
            self.profile[ch_smoother + subpixel_smoother_width + i] = gamma_zero;
        }

        // Mirror to the left (C++: *--ch = *ch_center++)
        let mut src = ch_center;
        let mut dst = ch_center;
        for _ in 0..(PROFILE_SUBPIXEL_SCALE as usize * 2) {
            if dst == 0 || src >= self.profile.len() {
                break;
            }
            dst -= 1;
            let v = self.profile[src];
            self.profile[dst] = v;
            src += 1;
        }
    }
}

impl Default for LineProfileAa {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Distance Interpolators
// ============================================================================

/// Distance interpolator 0 — for semidot/pie (distance from point).
///
/// Port of C++ `distance_interpolator0`.
/// Uses `line_mr()` (medium resolution) for dx/dy.
pub struct DistanceInterpolator0 {
    dx: i32,
    dy: i32,
    dist: i32,
}

impl DistanceInterpolator0 {
    pub fn new(x1: i32, y1: i32, x2: i32, y2: i32, x: i32, y: i32) -> Self {
        let mut dx = line_mr(x2) - line_mr(x1);
        let mut dy = line_mr(y2) - line_mr(y1);
        let dist = (line_mr(x + LINE_SUBPIXEL_SCALE / 2) - line_mr(x2)) * dy
            - (line_mr(y + LINE_SUBPIXEL_SCALE / 2) - line_mr(y2)) * dx;
        dx <<= LINE_MR_SUBPIXEL_SHIFT;
        dy <<= LINE_MR_SUBPIXEL_SHIFT;
        Self { dx, dy, dist }
    }

    #[inline]
    pub fn inc_x(&mut self) {
        self.dist += self.dy;
    }

    #[inline]
    pub fn dist(&self) -> i32 {
        self.dist
    }
}

/// Distance interpolator 00 — for pie (two rays).
///
/// Port of C++ `distance_interpolator00`.
/// Uses `line_mr()` (medium resolution) for dx/dy.
pub struct DistanceInterpolator00 {
    dx1: i32,
    dy1: i32,
    dx2: i32,
    dy2: i32,
    dist1: i32,
    dist2: i32,
}

impl DistanceInterpolator00 {
    pub fn new(
        xc: i32, yc: i32,
        x1: i32, y1: i32,
        x2: i32, y2: i32,
        x: i32, y: i32,
    ) -> Self {
        let mut dx1 = line_mr(x1) - line_mr(xc);
        let mut dy1 = line_mr(y1) - line_mr(yc);
        let mut dx2 = line_mr(x2) - line_mr(xc);
        let mut dy2 = line_mr(y2) - line_mr(yc);
        let dist1 = (line_mr(x + LINE_SUBPIXEL_SCALE / 2) - line_mr(x1)) * dy1
            - (line_mr(y + LINE_SUBPIXEL_SCALE / 2) - line_mr(y1)) * dx1;
        let dist2 = (line_mr(x + LINE_SUBPIXEL_SCALE / 2) - line_mr(x2)) * dy2
            - (line_mr(y + LINE_SUBPIXEL_SCALE / 2) - line_mr(y2)) * dx2;
        dx1 <<= LINE_MR_SUBPIXEL_SHIFT;
        dy1 <<= LINE_MR_SUBPIXEL_SHIFT;
        dx2 <<= LINE_MR_SUBPIXEL_SHIFT;
        dy2 <<= LINE_MR_SUBPIXEL_SHIFT;
        Self { dx1, dy1, dx2, dy2, dist1, dist2 }
    }

    #[inline]
    pub fn inc_x(&mut self) {
        self.dist1 += self.dy1;
        self.dist2 += self.dy2;
    }

    #[inline]
    pub fn dist1(&self) -> i32 {
        self.dist1
    }
    #[inline]
    pub fn dist2(&self) -> i32 {
        self.dist2
    }
}

/// Distance interpolator 1 — basic perpendicular distance tracker.
///
/// Port of C++ `distance_interpolator1`.
pub struct DistanceInterpolator1 {
    dx: i32,
    dy: i32,
    dist: i32,
}

impl DistanceInterpolator1 {
    pub fn new(x1: i32, y1: i32, x2: i32, y2: i32, x: i32, y: i32) -> Self {
        let mut dx = x2 - x1;
        let mut dy = y2 - y1;
        let dist = iround(
            (x + LINE_SUBPIXEL_SCALE / 2 - x2) as f64 * dy as f64
                - (y + LINE_SUBPIXEL_SCALE / 2 - y2) as f64 * dx as f64,
        );
        dx <<= LINE_SUBPIXEL_SHIFT;
        dy <<= LINE_SUBPIXEL_SHIFT;
        Self { dx, dy, dist }
    }

    #[inline]
    pub fn inc_x(&mut self, dy: i32) {
        self.dist += self.dy;
        if dy > 0 {
            self.dist -= self.dx;
        }
        if dy < 0 {
            self.dist += self.dx;
        }
    }

    #[inline]
    pub fn dec_x(&mut self, dy: i32) {
        self.dist -= self.dy;
        if dy > 0 {
            self.dist -= self.dx;
        }
        if dy < 0 {
            self.dist += self.dx;
        }
    }

    #[inline]
    pub fn inc_y(&mut self, dx: i32) {
        self.dist -= self.dx;
        if dx > 0 {
            self.dist += self.dy;
        }
        if dx < 0 {
            self.dist -= self.dy;
        }
    }

    #[inline]
    pub fn dec_y(&mut self, dx: i32) {
        self.dist += self.dx;
        if dx > 0 {
            self.dist += self.dy;
        }
        if dx < 0 {
            self.dist -= self.dy;
        }
    }

    #[inline]
    pub fn dist(&self) -> i32 {
        self.dist
    }
    #[inline]
    pub fn dx(&self) -> i32 {
        self.dx
    }
    #[inline]
    pub fn dy(&self) -> i32 {
        self.dy
    }
}

/// Distance interpolator 2 — tracks main distance + start or end join distance.
///
/// Port of C++ `distance_interpolator2`.
pub struct DistanceInterpolator2 {
    dx: i32,
    dy: i32,
    dx_start: i32,
    dy_start: i32,
    dist: i32,
    dist_start: i32,
}

impl DistanceInterpolator2 {
    /// Start join variant.
    pub fn new_start(
        x1: i32, y1: i32, x2: i32, y2: i32, sx: i32, sy: i32, x: i32, y: i32,
    ) -> Self {
        let mut dx = x2 - x1;
        let mut dy = y2 - y1;
        let mut dx_start = line_mr(sx) - line_mr(x1);
        let mut dy_start = line_mr(sy) - line_mr(y1);
        let dist = iround(
            (x + LINE_SUBPIXEL_SCALE / 2 - x2) as f64 * dy as f64
                - (y + LINE_SUBPIXEL_SCALE / 2 - y2) as f64 * dx as f64,
        );
        let dist_start = (line_mr(x + LINE_SUBPIXEL_SCALE / 2) - line_mr(sx)) * dy_start
            - (line_mr(y + LINE_SUBPIXEL_SCALE / 2) - line_mr(sy)) * dx_start;
        dx <<= LINE_SUBPIXEL_SHIFT;
        dy <<= LINE_SUBPIXEL_SHIFT;
        dx_start <<= LINE_MR_SUBPIXEL_SHIFT;
        dy_start <<= LINE_MR_SUBPIXEL_SHIFT;
        Self { dx, dy, dx_start, dy_start, dist, dist_start }
    }

    /// End join variant.
    pub fn new_end(
        x1: i32, y1: i32, x2: i32, y2: i32, ex: i32, ey: i32, x: i32, y: i32,
    ) -> Self {
        let mut dx = x2 - x1;
        let mut dy = y2 - y1;
        let mut dx_start = line_mr(ex) - line_mr(x2);
        let mut dy_start = line_mr(ey) - line_mr(y2);
        let dist = iround(
            (x + LINE_SUBPIXEL_SCALE / 2 - x2) as f64 * dy as f64
                - (y + LINE_SUBPIXEL_SCALE / 2 - y2) as f64 * dx as f64,
        );
        let dist_start = (line_mr(x + LINE_SUBPIXEL_SCALE / 2) - line_mr(ex)) * dy_start
            - (line_mr(y + LINE_SUBPIXEL_SCALE / 2) - line_mr(ey)) * dx_start;
        dx <<= LINE_SUBPIXEL_SHIFT;
        dy <<= LINE_SUBPIXEL_SHIFT;
        dx_start <<= LINE_MR_SUBPIXEL_SHIFT;
        dy_start <<= LINE_MR_SUBPIXEL_SHIFT;
        Self { dx, dy, dx_start, dy_start, dist, dist_start }
    }

    #[inline]
    pub fn inc_x(&mut self, dy: i32) {
        self.dist += self.dy;
        self.dist_start += self.dy_start;
        if dy > 0 {
            self.dist -= self.dx;
            self.dist_start -= self.dx_start;
        }
        if dy < 0 {
            self.dist += self.dx;
            self.dist_start += self.dx_start;
        }
    }

    #[inline]
    pub fn dec_x(&mut self, dy: i32) {
        self.dist -= self.dy;
        self.dist_start -= self.dy_start;
        if dy > 0 {
            self.dist -= self.dx;
            self.dist_start -= self.dx_start;
        }
        if dy < 0 {
            self.dist += self.dx;
            self.dist_start += self.dx_start;
        }
    }

    #[inline]
    pub fn inc_y(&mut self, dx: i32) {
        self.dist -= self.dx;
        self.dist_start -= self.dx_start;
        if dx > 0 {
            self.dist += self.dy;
            self.dist_start += self.dy_start;
        }
        if dx < 0 {
            self.dist -= self.dy;
            self.dist_start -= self.dy_start;
        }
    }

    #[inline]
    pub fn dec_y(&mut self, dx: i32) {
        self.dist += self.dx;
        self.dist_start += self.dx_start;
        if dx > 0 {
            self.dist += self.dy;
            self.dist_start += self.dy_start;
        }
        if dx < 0 {
            self.dist -= self.dy;
            self.dist_start -= self.dy_start;
        }
    }

    #[inline]
    pub fn dist(&self) -> i32 {
        self.dist
    }
    #[inline]
    pub fn dist_start(&self) -> i32 {
        self.dist_start
    }
    #[inline]
    pub fn dist_end(&self) -> i32 {
        self.dist_start
    }
    #[inline]
    pub fn dx_start(&self) -> i32 {
        self.dx_start
    }
    #[inline]
    pub fn dy_start(&self) -> i32 {
        self.dy_start
    }
    #[inline]
    pub fn dx_end(&self) -> i32 {
        self.dx_start
    }
    #[inline]
    pub fn dy_end(&self) -> i32 {
        self.dy_start
    }
}

/// Distance interpolator 3 — tracks main + start + end join distances.
///
/// Port of C++ `distance_interpolator3`.
pub struct DistanceInterpolator3 {
    dx: i32,
    dy: i32,
    dx_start: i32,
    dy_start: i32,
    dx_end: i32,
    dy_end: i32,
    dist: i32,
    dist_start: i32,
    dist_end: i32,
}

impl DistanceInterpolator3 {
    pub fn new(
        x1: i32, y1: i32, x2: i32, y2: i32,
        sx: i32, sy: i32, ex: i32, ey: i32,
        x: i32, y: i32,
    ) -> Self {
        let mut dx = x2 - x1;
        let mut dy = y2 - y1;
        let mut dx_start = line_mr(sx) - line_mr(x1);
        let mut dy_start = line_mr(sy) - line_mr(y1);
        let mut dx_end = line_mr(ex) - line_mr(x2);
        let mut dy_end = line_mr(ey) - line_mr(y2);

        let dist = iround(
            (x + LINE_SUBPIXEL_SCALE / 2 - x2) as f64 * dy as f64
                - (y + LINE_SUBPIXEL_SCALE / 2 - y2) as f64 * dx as f64,
        );
        let dist_start = (line_mr(x + LINE_SUBPIXEL_SCALE / 2) - line_mr(sx)) * dy_start
            - (line_mr(y + LINE_SUBPIXEL_SCALE / 2) - line_mr(sy)) * dx_start;
        let dist_end = (line_mr(x + LINE_SUBPIXEL_SCALE / 2) - line_mr(ex)) * dy_end
            - (line_mr(y + LINE_SUBPIXEL_SCALE / 2) - line_mr(ey)) * dx_end;

        dx <<= LINE_SUBPIXEL_SHIFT;
        dy <<= LINE_SUBPIXEL_SHIFT;
        dx_start <<= LINE_MR_SUBPIXEL_SHIFT;
        dy_start <<= LINE_MR_SUBPIXEL_SHIFT;
        dx_end <<= LINE_MR_SUBPIXEL_SHIFT;
        dy_end <<= LINE_MR_SUBPIXEL_SHIFT;

        Self {
            dx, dy, dx_start, dy_start, dx_end, dy_end, dist, dist_start, dist_end,
        }
    }

    #[inline]
    pub fn inc_x(&mut self, dy: i32) {
        self.dist += self.dy;
        self.dist_start += self.dy_start;
        self.dist_end += self.dy_end;
        if dy > 0 {
            self.dist -= self.dx;
            self.dist_start -= self.dx_start;
            self.dist_end -= self.dx_end;
        }
        if dy < 0 {
            self.dist += self.dx;
            self.dist_start += self.dx_start;
            self.dist_end += self.dx_end;
        }
    }

    #[inline]
    pub fn dec_x(&mut self, dy: i32) {
        self.dist -= self.dy;
        self.dist_start -= self.dy_start;
        self.dist_end -= self.dy_end;
        if dy > 0 {
            self.dist -= self.dx;
            self.dist_start -= self.dx_start;
            self.dist_end -= self.dx_end;
        }
        if dy < 0 {
            self.dist += self.dx;
            self.dist_start += self.dx_start;
            self.dist_end += self.dx_end;
        }
    }

    #[inline]
    pub fn inc_y(&mut self, dx: i32) {
        self.dist -= self.dx;
        self.dist_start -= self.dx_start;
        self.dist_end -= self.dx_end;
        if dx > 0 {
            self.dist += self.dy;
            self.dist_start += self.dy_start;
            self.dist_end += self.dy_end;
        }
        if dx < 0 {
            self.dist -= self.dy;
            self.dist_start -= self.dy_start;
            self.dist_end -= self.dy_end;
        }
    }

    #[inline]
    pub fn dec_y(&mut self, dx: i32) {
        self.dist += self.dx;
        self.dist_start += self.dx_start;
        self.dist_end += self.dx_end;
        if dx > 0 {
            self.dist += self.dy;
            self.dist_start += self.dy_start;
            self.dist_end += self.dy_end;
        }
        if dx < 0 {
            self.dist -= self.dy;
            self.dist_start -= self.dy_start;
            self.dist_end -= self.dy_end;
        }
    }

    #[inline]
    pub fn dist(&self) -> i32 {
        self.dist
    }
    #[inline]
    pub fn dist_start(&self) -> i32 {
        self.dist_start
    }
    #[inline]
    pub fn dist_end(&self) -> i32 {
        self.dist_end
    }
    #[inline]
    pub fn dx_start(&self) -> i32 {
        self.dx_start
    }
    #[inline]
    pub fn dy_start(&self) -> i32 {
        self.dy_start
    }
    #[inline]
    pub fn dx_end(&self) -> i32 {
        self.dx_end
    }
    #[inline]
    pub fn dy_end(&self) -> i32 {
        self.dy_end
    }
}

// ============================================================================
// Outline AA Renderer Trait
// ============================================================================

pub const MAX_HALF_WIDTH: usize = 64;

/// Trait for renderers used with `RasterizerOutlineAa`.
///
/// Both `RendererOutlineAa` (solid color) and `RendererOutlineImage`
/// (image pattern) implement this trait, allowing the rasterizer to
/// work with either renderer type.
///
/// Port of the C++ template interface used by `rasterizer_outline_aa`.
pub trait OutlineAaRenderer {
    /// Returns true if this renderer only supports accurate (miter) joins.
    /// Image pattern renderers return true; solid AA renderers return false.
    fn accurate_join_only(&self) -> bool;

    /// Render a simple line segment (no join information).
    fn line0(&mut self, lp: &LineParameters);

    /// Render a line segment with start join bisectrix.
    fn line1(&mut self, lp: &LineParameters, sx: i32, sy: i32);

    /// Render a line segment with end join bisectrix.
    fn line2(&mut self, lp: &LineParameters, ex: i32, ey: i32);

    /// Render a line segment with both start and end join bisectrices.
    fn line3(&mut self, lp: &LineParameters, sx: i32, sy: i32, ex: i32, ey: i32);

    /// Render a semi-circular dot (for round caps).
    fn semidot(&mut self, cmp: fn(i32) -> bool, xc1: i32, yc1: i32, xc2: i32, yc2: i32);

    /// Render a pie slice (for round joins).
    fn pie(&mut self, xc: i32, yc: i32, x1: i32, y1: i32, x2: i32, y2: i32);
}

// ============================================================================
// Renderer Outline AA
// ============================================================================

/// Anti-aliased outline renderer.
///
/// Port of C++ `renderer_outline_aa<BaseRenderer>`.
/// Renders anti-aliased lines using a distance interpolation technique
/// with configurable width profile.
pub struct RendererOutlineAa<'a, PF: PixelFormat> {
    ren: &'a mut RendererBase<PF>,
    profile: &'a LineProfileAa,
    color: PF::ColorType,
    clip_box: RectI,
    clipping: bool,
}

impl<'a, PF: PixelFormat> RendererOutlineAa<'a, PF>
where
    PF::ColorType: Default + Clone,
{
    pub fn new(ren: &'a mut RendererBase<PF>, profile: &'a LineProfileAa) -> Self {
        Self {
            ren,
            profile,
            color: PF::ColorType::default(),
            clip_box: RectI::new(0, 0, 0, 0),
            clipping: false,
        }
    }

    pub fn ren(&self) -> &RendererBase<PF> {
        self.ren
    }

    pub fn set_color(&mut self, c: PF::ColorType) {
        self.color = c;
    }

    pub fn color(&self) -> &PF::ColorType {
        &self.color
    }

    pub fn subpixel_width(&self) -> i32 {
        self.profile.subpixel_width()
    }

    pub fn set_clip_box(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) {
        self.clip_box = RectI::new(
            line_coord_sat(x1),
            line_coord_sat(y1),
            line_coord_sat(x2),
            line_coord_sat(y2),
        );
        self.clipping = true;
    }

    pub fn reset_clipping(&mut self) {
        self.clipping = false;
    }

    #[inline]
    fn cover(&self, d: i32) -> u8 {
        self.profile.value(d)
    }

    /// Render a simple line (no joins).
    pub fn line0(&mut self, lp: &LineParameters) {
        if self.clipping {
            let (mut x1, mut y1, mut x2, mut y2) = (lp.x1, lp.y1, lp.x2, lp.y2);
            let flags = clip_line_segment(&mut x1, &mut y1, &mut x2, &mut y2, &self.clip_box);
            if flags >= 4 {
                return;
            }
            if flags != 0 {
                let lp2 = LineParameters::new(
                    x1, y1, x2, y2,
                    uround(calc_distance_i(x1, y1, x2, y2)),
                );
                self.line0_no_clip(&lp2);
                return;
            }
        }
        self.line0_no_clip(lp);
    }

    fn line0_no_clip(&mut self, lp: &LineParameters) {
        if lp.len > LINE_MAX_LENGTH {
            let (lp1, lp2) = lp.divide();
            self.line0_no_clip(&lp1);
            self.line0_no_clip(&lp2);
            return;
        }

        let li = LineInterpolatorAa0::new(lp, self.profile.subpixel_width());
        if li.count > 0 {
            if lp.vertical {
                self.draw_line0_ver(li, lp);
            } else {
                self.draw_line0_hor(li, lp);
            }
        }
    }

    fn draw_line0_hor(&mut self, mut li: LineInterpolatorAa0, lp: &LineParameters) {
        while let Some(span) = li.step_hor(self.profile, lp) {
            let x = li.x();
            let y = li.y() - span.offset as i32 + 1;
            self.ren.blend_solid_vspan(
                x, y, span.len as i32, &self.color,
                &li.covers[span.p0..span.p0 + span.len],
            );
        }
    }

    fn draw_line0_ver(&mut self, mut li: LineInterpolatorAa0, lp: &LineParameters) {
        while let Some(span) = li.step_ver(self.profile, lp) {
            let x = li.x() - span.offset as i32 + 1;
            let y = li.y();
            self.ren.blend_solid_hspan(
                x, y, span.len as i32, &self.color,
                &li.covers[span.p0..span.p0 + span.len],
            );
        }
    }

    /// Render line with start join.
    pub fn line1(&mut self, lp: &LineParameters, sx: i32, sy: i32) {
        if self.clipping {
            let (mut x1, mut y1, mut x2, mut y2) = (lp.x1, lp.y1, lp.x2, lp.y2);
            let flags = clip_line_segment(&mut x1, &mut y1, &mut x2, &mut y2, &self.clip_box);
            if flags >= 4 {
                return;
            }
            if flags != 0 {
                let lp2 = LineParameters::new(
                    x1, y1, x2, y2,
                    uround(calc_distance_i(x1, y1, x2, y2)),
                );
                if flags & 1 != 0 {
                    // Start was clipped — use line0 instead
                    self.line0_no_clip(&lp2);
                } else {
                    self.line1_no_clip(&lp2, sx, sy);
                }
                return;
            }
        }
        self.line1_no_clip(lp, sx, sy);
    }

    fn line1_no_clip(&mut self, lp: &LineParameters, mut sx: i32, mut sy: i32) {
        if lp.len > LINE_MAX_LENGTH {
            let (lp1, lp2) = lp.divide();
            self.line1_no_clip(
                &lp1,
                (lp.x1 + sx) >> 1,
                (lp.y1 + sy) >> 1,
            );
            self.line1_no_clip(
                &lp2,
                lp1.x2 + (lp1.y2 - lp1.y1),
                lp1.y2 - (lp1.x2 - lp1.x1),
            );
            return;
        }

        fix_degenerate_bisectrix_start(lp, &mut sx, &mut sy);
        let li = LineInterpolatorAa1::new(lp, sx, sy, self.profile.subpixel_width());
        if lp.vertical {
            self.draw_line1_ver(li, lp);
        } else {
            self.draw_line1_hor(li, lp);
        }
    }

    fn draw_line1_hor(&mut self, mut li: LineInterpolatorAa1, lp: &LineParameters) {
        while let Some(span) = li.step_hor(self.profile, lp) {
            self.ren.blend_solid_vspan(
                li.x(), li.y() - span.offset as i32 + 1, span.len as i32, &self.color,
                &li.covers[span.p0..span.p0 + span.len],
            );
        }
    }

    fn draw_line1_ver(&mut self, mut li: LineInterpolatorAa1, lp: &LineParameters) {
        while let Some(span) = li.step_ver(self.profile, lp) {
            self.ren.blend_solid_hspan(
                li.x() - span.offset as i32 + 1, li.y(), span.len as i32, &self.color,
                &li.covers[span.p0..span.p0 + span.len],
            );
        }
    }

    /// Render line with end join.
    pub fn line2(&mut self, lp: &LineParameters, ex: i32, ey: i32) {
        if self.clipping {
            let (mut x1, mut y1, mut x2, mut y2) = (lp.x1, lp.y1, lp.x2, lp.y2);
            let flags = clip_line_segment(&mut x1, &mut y1, &mut x2, &mut y2, &self.clip_box);
            if flags >= 4 {
                return;
            }
            if flags != 0 {
                let lp2 = LineParameters::new(
                    x1, y1, x2, y2,
                    uround(calc_distance_i(x1, y1, x2, y2)),
                );
                if flags & 2 != 0 {
                    self.line0_no_clip(&lp2);
                } else {
                    self.line2_no_clip(&lp2, ex, ey);
                }
                return;
            }
        }
        self.line2_no_clip(lp, ex, ey);
    }

    fn line2_no_clip(&mut self, lp: &LineParameters, mut ex: i32, mut ey: i32) {
        if lp.len > LINE_MAX_LENGTH {
            let (lp1, lp2) = lp.divide();
            self.line2_no_clip(
                &lp1,
                lp1.x2 + (lp1.y2 - lp1.y1),
                lp1.y2 - (lp1.x2 - lp1.x1),
            );
            self.line2_no_clip(
                &lp2,
                (lp.x2 + ex) >> 1,
                (lp.y2 + ey) >> 1,
            );
            return;
        }

        fix_degenerate_bisectrix_end(lp, &mut ex, &mut ey);
        let li = LineInterpolatorAa2::new(lp, ex, ey, self.profile.subpixel_width());
        if lp.vertical {
            self.draw_line2_ver(li, lp);
        } else {
            self.draw_line2_hor(li, lp);
        }
    }

    fn draw_line2_hor(&mut self, mut li: LineInterpolatorAa2, lp: &LineParameters) {
        while let Some(span) = li.step_hor(self.profile, lp) {
            self.ren.blend_solid_vspan(
                li.x(), li.y() - span.offset as i32 + 1, span.len as i32, &self.color,
                &li.covers[span.p0..span.p0 + span.len],
            );
        }
    }

    fn draw_line2_ver(&mut self, mut li: LineInterpolatorAa2, lp: &LineParameters) {
        while let Some(span) = li.step_ver(self.profile, lp) {
            self.ren.blend_solid_hspan(
                li.x() - span.offset as i32 + 1, li.y(), span.len as i32, &self.color,
                &li.covers[span.p0..span.p0 + span.len],
            );
        }
    }

    /// Render line with both joins.
    pub fn line3(
        &mut self,
        lp: &LineParameters,
        sx: i32,
        sy: i32,
        ex: i32,
        ey: i32,
    ) {
        if self.clipping {
            let (mut x1, mut y1, mut x2, mut y2) = (lp.x1, lp.y1, lp.x2, lp.y2);
            let flags = clip_line_segment(&mut x1, &mut y1, &mut x2, &mut y2, &self.clip_box);
            if flags >= 4 {
                return;
            }
            if flags != 0 {
                let lp2 = LineParameters::new(
                    x1, y1, x2, y2,
                    uround(calc_distance_i(x1, y1, x2, y2)),
                );
                match flags & 3 {
                    3 => self.line0_no_clip(&lp2),
                    1 => self.line2_no_clip(&lp2, ex, ey),
                    2 => self.line1_no_clip(&lp2, sx, sy),
                    _ => self.line3_no_clip(&lp2, sx, sy, ex, ey),
                }
                return;
            }
        }
        self.line3_no_clip(lp, sx, sy, ex, ey);
    }

    fn line3_no_clip(
        &mut self,
        lp: &LineParameters,
        mut sx: i32,
        mut sy: i32,
        mut ex: i32,
        mut ey: i32,
    ) {
        if lp.len > LINE_MAX_LENGTH {
            let (lp1, lp2) = lp.divide();
            let mx = lp1.x2 + (lp1.y2 - lp1.y1);
            let my = lp1.y2 - (lp1.x2 - lp1.x1);
            self.line3_no_clip(
                &lp1,
                (lp.x1 + sx) >> 1,
                (lp.y1 + sy) >> 1,
                mx, my,
            );
            self.line3_no_clip(
                &lp2,
                mx, my,
                (lp.x2 + ex) >> 1,
                (lp.y2 + ey) >> 1,
            );
            return;
        }

        fix_degenerate_bisectrix_start(lp, &mut sx, &mut sy);
        fix_degenerate_bisectrix_end(lp, &mut ex, &mut ey);
        let li = LineInterpolatorAa3::new(lp, sx, sy, ex, ey, self.profile.subpixel_width());
        if lp.vertical {
            self.draw_line3_ver(li, lp);
        } else {
            self.draw_line3_hor(li, lp);
        }
    }

    fn draw_line3_hor(&mut self, mut li: LineInterpolatorAa3, lp: &LineParameters) {
        while let Some(span) = li.step_hor(self.profile, lp) {
            self.ren.blend_solid_vspan(
                li.x(), li.y() - span.offset as i32 + 1, span.len as i32, &self.color,
                &li.covers[span.p0..span.p0 + span.len],
            );
        }
    }

    fn draw_line3_ver(&mut self, mut li: LineInterpolatorAa3, lp: &LineParameters) {
        while let Some(span) = li.step_ver(self.profile, lp) {
            self.ren.blend_solid_hspan(
                li.x() - span.offset as i32 + 1, li.y(), span.len as i32, &self.color,
                &li.covers[span.p0..span.p0 + span.len],
            );
        }
    }

    /// Render a semi-circular dot (for round caps).
    /// Port of C++ `semidot`.
    pub fn semidot<F: Fn(i32) -> bool>(
        &mut self,
        cmp: F,
        xc1: i32,
        yc1: i32,
        xc2: i32,
        yc2: i32,
    ) {
        let r = ((self.profile.subpixel_width() + LINE_SUBPIXEL_MASK) >> LINE_SUBPIXEL_SHIFT) as i32;
        if r < 1 {
            return;
        }
        let mut ei = EllipseBresenhamInterpolator::new(r, r);
        let mut dx = 0i32;
        let mut dy = -r;
        let mut dy0 = dy;
        let mut dx0 = dx;

        let x = xc1 >> LINE_SUBPIXEL_SHIFT;
        let y = yc1 >> LINE_SUBPIXEL_SHIFT;

        loop {
            dx += ei.dx();
            dy += ei.dy();
            if dy != dy0 {
                self.semidot_hline(&cmp, xc1, yc1, xc2, yc2, x - dx0, y + dy0, x + dx0);
                self.semidot_hline(&cmp, xc1, yc1, xc2, yc2, x - dx0, y - dy0, x + dx0);
            }
            dx0 = dx;
            dy0 = dy;
            ei.next();
            if dy >= 0 {
                break;
            }
        }
        self.semidot_hline(&cmp, xc1, yc1, xc2, yc2, x - dx0, y + dy0, x + dx0);
    }

    /// Port of C++ `semidot_hline`.
    /// x1, y1, x2 are in pixel coordinates; xc1/yc1/xc2/yc2 are subpixel.
    fn semidot_hline<F: Fn(i32) -> bool>(
        &mut self,
        cmp: &F,
        xc1: i32,
        yc1: i32,
        xc2: i32,
        yc2: i32,
        mut x1: i32,
        y1: i32,
        x2: i32,
    ) {
        let mut covers = [0u8; MAX_HALF_WIDTH * 2 + 4];
        let mut p0 = 0usize;
        let mut p1 = 0usize;

        // C++ passes pixel coords << subpixel_shift to DI0
        let x = x1 << LINE_SUBPIXEL_SHIFT;
        let y = y1 << LINE_SUBPIXEL_SHIFT;
        let w = self.profile.subpixel_width();

        let mut di = DistanceInterpolator0::new(xc1, yc1, xc2, yc2, x, y);

        // Offset to pixel center for distance calculation
        let mut dx = x + LINE_SUBPIXEL_SCALE / 2 - xc1;
        let dy = y + LINE_SUBPIXEL_SCALE / 2 - yc1;

        loop {
            let d = fast_sqrt((dx * dx + dy * dy) as u32) as i32;
            covers[p1] = 0;
            if cmp(di.dist()) && d <= w {
                covers[p1] = self.cover(d);
            }
            p1 += 1;
            dx += LINE_SUBPIXEL_SCALE;
            di.inc_x();
            x1 += 1;
            if x1 > x2 {
                break;
            }
        }

        self.ren.blend_solid_hspan(
            x1 - (p1 as i32), y1, (p1 - p0) as i32, &self.color, &covers[p0..p1],
        );
    }

    /// Render a pie slice (for round joins between two line segments).
    /// Port of C++ `pie`.
    pub fn pie(
        &mut self,
        xc: i32,
        yc: i32,
        x1: i32,
        y1: i32,
        x2: i32,
        y2: i32,
    ) {
        let r = ((self.profile.subpixel_width() + LINE_SUBPIXEL_MASK) >> LINE_SUBPIXEL_SHIFT) as i32;
        if r < 1 {
            return;
        }
        let mut ei = EllipseBresenhamInterpolator::new(r, r);
        let mut dx = 0i32;
        let mut dy = -r;
        let mut dy0 = dy;
        let mut dx0 = dx;

        let x = xc >> LINE_SUBPIXEL_SHIFT;
        let y = yc >> LINE_SUBPIXEL_SHIFT;

        loop {
            dx += ei.dx();
            dy += ei.dy();
            if dy != dy0 {
                self.pie_hline(xc, yc, x1, y1, x2, y2, x - dx0, y + dy0, x + dx0);
                self.pie_hline(xc, yc, x1, y1, x2, y2, x - dx0, y - dy0, x + dx0);
            }
            dx0 = dx;
            dy0 = dy;
            ei.next();
            if dy >= 0 {
                break;
            }
        }
        self.pie_hline(xc, yc, x1, y1, x2, y2, x - dx0, y + dy0, x + dx0);
    }

    /// Port of C++ `pie_hline`.
    /// xh1, yh1, xh2 are in pixel coordinates; xc/yc/xp1/yp1/xp2/yp2 are subpixel.
    fn pie_hline(
        &mut self,
        xc: i32,
        yc: i32,
        xp1: i32,
        yp1: i32,
        xp2: i32,
        yp2: i32,
        mut xh1: i32,
        yh1: i32,
        xh2: i32,
    ) {
        let mut covers = [0u8; MAX_HALF_WIDTH * 2 + 4];
        let mut p0 = 0usize;
        let mut p1 = 0usize;

        let x = xh1 << LINE_SUBPIXEL_SHIFT;
        let y = yh1 << LINE_SUBPIXEL_SHIFT;
        let w = self.profile.subpixel_width();

        let mut di = DistanceInterpolator00::new(
            xc, yc, xp1, yp1, xp2, yp2, x, y,
        );

        let mut dx = x + LINE_SUBPIXEL_SCALE / 2 - xc;
        let dy = y + LINE_SUBPIXEL_SCALE / 2 - yc;

        let xh0 = xh1;
        loop {
            let d = fast_sqrt((dx * dx + dy * dy) as u32) as i32;
            covers[p1] = 0;
            if di.dist1() <= 0 && di.dist2() > 0 && d <= w {
                covers[p1] = self.cover(d);
            }
            p1 += 1;
            dx += LINE_SUBPIXEL_SCALE;
            di.inc_x();
            xh1 += 1;
            if xh1 > xh2 {
                break;
            }
        }

        self.ren.blend_solid_hspan(
            xh0, yh1, (p1 - p0) as i32, &self.color, &covers[p0..p1],
        );
    }
}

// Implementation of OutlineAaRenderer for RendererOutlineAa.
impl<'a, PF: PixelFormat> OutlineAaRenderer for RendererOutlineAa<'a, PF>
where
    PF::ColorType: Default + Clone,
{
    fn accurate_join_only(&self) -> bool {
        false
    }

    fn line0(&mut self, lp: &LineParameters) {
        self.line0(lp);
    }

    fn line1(&mut self, lp: &LineParameters, sx: i32, sy: i32) {
        self.line1(lp, sx, sy);
    }

    fn line2(&mut self, lp: &LineParameters, ex: i32, ey: i32) {
        self.line2(lp, ex, ey);
    }

    fn line3(&mut self, lp: &LineParameters, sx: i32, sy: i32, ex: i32, ey: i32) {
        self.line3(lp, sx, sy, ex, ey);
    }

    fn semidot(&mut self, cmp: fn(i32) -> bool, xc1: i32, yc1: i32, xc2: i32, yc2: i32) {
        self.semidot(cmp, xc1, yc1, xc2, yc2);
    }

    fn pie(&mut self, xc: i32, yc: i32, x1: i32, y1: i32, x2: i32, y2: i32) {
        self.pie(xc, yc, x1, y1, x2, y2);
    }
}

// ============================================================================
// Helpers
// ============================================================================

#[inline]
fn calc_distance_i(x1: i32, y1: i32, x2: i32, y2: i32) -> f64 {
    let dx = (x2 - x1) as f64;
    let dy = (y2 - y1) as f64;
    (dx * dx + dy * dy).sqrt()
}

#[inline]
fn uround(v: f64) -> i32 {
    (v + 0.5) as i32
}

// ============================================================================
// Line Interpolator AA base functionality
// ============================================================================

const COVER_SIZE: usize = MAX_HALF_WIDTH * 2 + 4;
const DIST_SIZE: usize = MAX_HALF_WIDTH + 1;

/// Span result from a line interpolator step.
struct LineSpan {
    /// Index into covers array where the span starts.
    p0: usize,
    /// Number of cover values in the span.
    len: usize,
    /// For step_hor: vertical offset (dy) for blend_solid_vspan positioning.
    /// For step_ver: horizontal offset (dx) for blend_solid_hspan positioning.
    offset: i32,
}

// Common initialization for all line interpolator types
fn init_line_interpolator_base(lp: &LineParameters, width: i32) -> (
    Dda2LineInterpolator, // li
    i32, // x
    i32, // y
    i32, // count
    i32, // len
    i32, // max_extent
    [i32; DIST_SIZE], // dist table
) {
    let max_extent = (width + LINE_SUBPIXEL_MASK) >> LINE_SUBPIXEL_SHIFT;

    let x;
    let y;
    let count;
    let li;

    if lp.vertical {
        x = lp.x1 >> LINE_SUBPIXEL_SHIFT;
        y = lp.y1 >> LINE_SUBPIXEL_SHIFT;
        count = ((lp.y2 >> LINE_SUBPIXEL_SHIFT) - y).abs();
        li = Dda2LineInterpolator::new_relative(
            line_dbl_hr(lp.x2 - lp.x1),
            (lp.y2 - lp.y1).abs(),
        );
    } else {
        x = lp.x1 >> LINE_SUBPIXEL_SHIFT;
        y = lp.y1 >> LINE_SUBPIXEL_SHIFT;
        count = ((lp.x2 >> LINE_SUBPIXEL_SHIFT) - x).abs();
        li = Dda2LineInterpolator::new_relative(
            line_dbl_hr(lp.y2 - lp.y1),
            (lp.x2 - lp.x1).abs() + 1,
        );
    };

    let len = if lp.vertical == (lp.inc > 0) { -lp.len } else { lp.len };

    // Pre-compute distance table
    let mut dist = [0i32; DIST_SIZE];
    let mut dd = Dda2LineInterpolator::new_forward(
        0,
        if lp.vertical { lp.dy << LINE_SUBPIXEL_SHIFT } else { lp.dx << LINE_SUBPIXEL_SHIFT },
        lp.len,
    );
    let stop = width + LINE_SUBPIXEL_SCALE * 2;
    let mut i = 0;
    while i < MAX_HALF_WIDTH {
        dist[i] = dd.y();
        if dist[i] >= stop {
            break;
        }
        dd.inc();
        i += 1;
    }
    if i < DIST_SIZE {
        dist[i] = 0x7FFF_0000;
    }

    (li, x, y, count, len, max_extent, dist)
}

/// Line interpolator for AA line type 0 (no joins).
/// Port of C++ `line_interpolator_aa0`.
struct LineInterpolatorAa0 {
    di: DistanceInterpolator1,
    li: Dda2LineInterpolator,
    x: i32,
    y: i32,
    old_x: i32,
    old_y: i32,
    count: i32,
    width: i32,
    max_extent: i32,
    len: i32,
    step: i32,
    dist: [i32; DIST_SIZE],
    pub covers: [u8; COVER_SIZE],
}

impl LineInterpolatorAa0 {
    fn new(lp: &LineParameters, subpixel_width: i32) -> Self {
        let (mut li, x, y, count, len, max_extent, dist) =
            init_line_interpolator_base(lp, subpixel_width);

        // C++: m_di(lp.x1, lp.y1, lp.x2, lp.y2,
        //          lp.x1 & ~line_subpixel_mask, lp.y1 & ~line_subpixel_mask)
        let di = DistanceInterpolator1::new(
            lp.x1, lp.y1, lp.x2, lp.y2,
            lp.x1 & !LINE_SUBPIXEL_MASK,
            lp.y1 & !LINE_SUBPIXEL_MASK,
        );

        li.adjust_forward();

        Self {
            di,
            li,
            x,
            y,
            old_x: x,
            old_y: y,
            count,
            width: subpixel_width,
            max_extent,
            len,
            step: 0,
            dist,
            covers: [0u8; COVER_SIZE],
        }
    }

    fn x(&self) -> i32 { self.x }
    fn y(&self) -> i32 { self.y }

    fn step_hor(&mut self, profile: &LineProfileAa, lp: &LineParameters) -> Option<LineSpan> {
        // Check at the BEGINNING — C++ does blend first, then `return ++step < count`.
        // We must check before work so that the LAST step still returns Some(span).
        if self.step >= self.count { return None; }

        self.li.inc();
        self.x += lp.inc;
        self.y = (lp.y1 + self.li.y()) >> LINE_SUBPIXEL_SHIFT;

        if lp.inc > 0 {
            self.di.inc_x(self.y - self.old_y);
        } else {
            self.di.dec_x(self.y - self.old_y);
        }
        self.old_y = self.y;

        let s1 = self.di.dist() / self.len;

        let center = MAX_HALF_WIDTH + 2;
        let mut p0 = center;
        let mut p1 = center;

        self.covers[p1] = profile.value(s1) as u8;
        p1 += 1;

        let mut dy = 1usize;
        loop {
            if dy >= DIST_SIZE { break; }
            let dist = self.dist[dy] - s1;
            if dist > self.width { break; }
            self.covers[p1] = profile.value(dist) as u8;
            p1 += 1;
            dy += 1;
        }

        let mut dy = 1usize;
        loop {
            if dy >= DIST_SIZE { break; }
            let dist = self.dist[dy] + s1;
            if dist > self.width { break; }
            p0 -= 1;
            self.covers[p0] = profile.value(dist) as u8;
            dy += 1;
        }

        self.step += 1;

        Some(LineSpan {
            p0,
            len: p1 - p0,
            offset: dy as i32,
        })
    }

    fn step_ver(&mut self, profile: &LineProfileAa, lp: &LineParameters) -> Option<LineSpan> {
        if self.step >= self.count { return None; }

        self.li.inc();
        self.y += lp.inc;
        self.x = (lp.x1 + self.li.y()) >> LINE_SUBPIXEL_SHIFT;

        if lp.inc > 0 {
            self.di.inc_y(self.x - self.old_x);
        } else {
            self.di.dec_y(self.x - self.old_x);
        }
        self.old_x = self.x;

        let s1 = self.di.dist() / self.len;

        let center = MAX_HALF_WIDTH + 2;
        let mut p0 = center;
        let mut p1 = center;

        self.covers[p1] = profile.value(s1) as u8;
        p1 += 1;

        let mut dx = 1usize;
        loop {
            if dx >= DIST_SIZE { break; }
            let dist = self.dist[dx] - s1;
            if dist > self.width { break; }
            self.covers[p1] = profile.value(dist) as u8;
            p1 += 1;
            dx += 1;
        }

        let mut dx = 1usize;
        loop {
            if dx >= DIST_SIZE { break; }
            let dist = self.dist[dx] + s1;
            if dist > self.width { break; }
            p0 -= 1;
            self.covers[p0] = profile.value(dist) as u8;
            dx += 1;
        }

        self.step += 1;

        Some(LineSpan {
            p0,
            len: p1 - p0,
            offset: dx as i32,
        })
    }
}

/// Line interpolator for AA line type 1 (start join).
/// Port of C++ `line_interpolator_aa1`.
struct LineInterpolatorAa1 {
    di: DistanceInterpolator2,
    li: Dda2LineInterpolator,
    x: i32,
    y: i32,
    old_x: i32,
    old_y: i32,
    count: i32,
    width: i32,
    max_extent: i32,
    len: i32,
    step: i32,
    dist: [i32; DIST_SIZE],
    pub covers: [u8; COVER_SIZE],
}

impl LineInterpolatorAa1 {
    fn new(lp: &LineParameters, sx: i32, sy: i32, subpixel_width: i32) -> Self {
        let (mut li, mut x, mut y, count, len, max_extent, dist) =
            init_line_interpolator_base(lp, subpixel_width);

        let mut di = DistanceInterpolator2::new_start(
            lp.x1, lp.y1, lp.x2, lp.y2, sx, sy,
            lp.x1 & !LINE_SUBPIXEL_MASK,
            lp.y1 & !LINE_SUBPIXEL_MASK,
        );

        let mut old_x = x;
        let mut old_y = y;
        let mut step = 0i32;

        // Backward stepping to find where start join begins
        let mut npix = 1i32;

        if lp.vertical {
            loop {
                li.dec();
                y -= lp.inc;
                x = (lp.x1 + li.y()) >> LINE_SUBPIXEL_SHIFT;

                if lp.inc > 0 {
                    di.dec_y(x - old_x);
                } else {
                    di.inc_y(x - old_x);
                }
                old_x = x;

                let mut dist1_start = di.dist_start();
                let mut dist2_start = dist1_start;

                let mut dx = 0;
                if dist1_start < 0 { npix += 1; }
                loop {
                    dist1_start += di.dy_start();
                    dist2_start -= di.dy_start();
                    if dist1_start < 0 { npix += 1; }
                    if dist2_start < 0 { npix += 1; }
                    dx += 1;
                    if dist[dx as usize] > subpixel_width { break; }
                }
                step -= 1;
                if npix == 0 { break; }
                npix = 0;
                if step < -max_extent { break; }
            }
        } else {
            loop {
                li.dec();
                x -= lp.inc;
                y = (lp.y1 + li.y()) >> LINE_SUBPIXEL_SHIFT;

                if lp.inc > 0 {
                    di.dec_x(y - old_y);
                } else {
                    di.inc_x(y - old_y);
                }
                old_y = y;

                let mut dist1_start = di.dist_start();
                let mut dist2_start = dist1_start;

                let mut dy = 0;
                if dist1_start < 0 { npix += 1; }
                loop {
                    dist1_start -= di.dx_start();
                    dist2_start += di.dx_start();
                    if dist1_start < 0 { npix += 1; }
                    if dist2_start < 0 { npix += 1; }
                    dy += 1;
                    if dist[dy as usize] > subpixel_width { break; }
                }
                step -= 1;
                if npix == 0 { break; }
                npix = 0;
                if step < -max_extent { break; }
            }
        }

        li.adjust_forward();

        Self {
            di, li, x, y, old_x, old_y,
            count, width: subpixel_width, max_extent, len, step,
            dist, covers: [0u8; COVER_SIZE],
        }
    }

    fn x(&self) -> i32 { self.x }
    fn y(&self) -> i32 { self.y }

    fn step_hor(&mut self, profile: &LineProfileAa, lp: &LineParameters) -> Option<LineSpan> {
        if self.step >= self.count { return None; }

        self.li.inc();
        self.x += lp.inc;
        self.y = (lp.y1 + self.li.y()) >> LINE_SUBPIXEL_SHIFT;
        if lp.inc > 0 { self.di.inc_x(self.y - self.old_y); }
        else { self.di.dec_x(self.y - self.old_y); }
        self.old_y = self.y;

        let s1 = self.di.dist() / self.len;
        let mut dist_start = self.di.dist_start();

        let center = MAX_HALF_WIDTH + 2;
        let mut p0 = center;
        let mut p1 = center;

        self.covers[p1] = 0;
        if dist_start <= 0 {
            self.covers[p1] = profile.value(s1) as u8;
        }
        p1 += 1;

        let mut dy = 1usize;
        loop {
            if dy >= DIST_SIZE { break; }
            let dist = self.dist[dy] - s1;
            if dist > self.width { break; }
            dist_start -= self.di.dx_start();
            self.covers[p1] = 0;
            if dist_start <= 0 {
                self.covers[p1] = profile.value(dist) as u8;
            }
            p1 += 1;
            dy += 1;
        }

        let mut dy = 1usize;
        dist_start = self.di.dist_start();
        loop {
            if dy >= DIST_SIZE { break; }
            let dist = self.dist[dy] + s1;
            if dist > self.width { break; }
            dist_start += self.di.dx_start();
            p0 -= 1;
            self.covers[p0] = 0;
            if dist_start <= 0 {
                self.covers[p0] = profile.value(dist) as u8;
            }
            dy += 1;
        }

        self.step += 1;

        Some(LineSpan { p0, len: p1 - p0, offset: dy as i32 })
    }

    fn step_ver(&mut self, profile: &LineProfileAa, lp: &LineParameters) -> Option<LineSpan> {
        if self.step >= self.count { return None; }

        self.li.inc();
        self.y += lp.inc;
        self.x = (lp.x1 + self.li.y()) >> LINE_SUBPIXEL_SHIFT;
        if lp.inc > 0 { self.di.inc_y(self.x - self.old_x); }
        else { self.di.dec_y(self.x - self.old_x); }
        self.old_x = self.x;

        let s1 = self.di.dist() / self.len;
        let mut dist_start = self.di.dist_start();

        let center = MAX_HALF_WIDTH + 2;
        let mut p0 = center;
        let mut p1 = center;

        self.covers[p1] = 0;
        if dist_start <= 0 {
            self.covers[p1] = profile.value(s1) as u8;
        }
        p1 += 1;

        let mut dx = 1usize;
        loop {
            if dx >= DIST_SIZE { break; }
            let dist = self.dist[dx] - s1;
            if dist > self.width { break; }
            dist_start += self.di.dy_start();
            self.covers[p1] = 0;
            if dist_start <= 0 {
                self.covers[p1] = profile.value(dist) as u8;
            }
            p1 += 1;
            dx += 1;
        }

        let mut dx = 1usize;
        dist_start = self.di.dist_start();
        loop {
            if dx >= DIST_SIZE { break; }
            let dist = self.dist[dx] + s1;
            if dist > self.width { break; }
            dist_start -= self.di.dy_start();
            p0 -= 1;
            self.covers[p0] = 0;
            if dist_start <= 0 {
                self.covers[p0] = profile.value(dist) as u8;
            }
            dx += 1;
        }

        self.step += 1;

        Some(LineSpan { p0, len: p1 - p0, offset: dx as i32 })
    }
}

/// Line interpolator for AA line type 2 (end join).
/// Port of C++ `line_interpolator_aa2`.
struct LineInterpolatorAa2 {
    di: DistanceInterpolator2,
    li: Dda2LineInterpolator,
    x: i32,
    y: i32,
    old_x: i32,
    old_y: i32,
    count: i32,
    width: i32,
    max_extent: i32,
    len: i32,
    step: i32,
    dist: [i32; DIST_SIZE],
    pub covers: [u8; COVER_SIZE],
}

impl LineInterpolatorAa2 {
    fn new(lp: &LineParameters, ex: i32, ey: i32, subpixel_width: i32) -> Self {
        let (mut li, x, y, count, len, max_extent, dist) =
            init_line_interpolator_base(lp, subpixel_width);

        let di = DistanceInterpolator2::new_end(
            lp.x1, lp.y1, lp.x2, lp.y2, ex, ey,
            lp.x1 & !LINE_SUBPIXEL_MASK,
            lp.y1 & !LINE_SUBPIXEL_MASK,
        );

        li.adjust_forward();
        let step = 0 - max_extent;

        Self {
            di, li, x, y, old_x: x, old_y: y,
            count, width: subpixel_width, max_extent, len, step,
            dist, covers: [0u8; COVER_SIZE],
        }
    }

    fn x(&self) -> i32 { self.x }
    fn y(&self) -> i32 { self.y }

    fn step_hor(&mut self, profile: &LineProfileAa, lp: &LineParameters) -> Option<LineSpan> {
        if self.step >= self.count { return None; }

        self.li.inc();
        self.x += lp.inc;
        self.y = (lp.y1 + self.li.y()) >> LINE_SUBPIXEL_SHIFT;
        if lp.inc > 0 { self.di.inc_x(self.y - self.old_y); }
        else { self.di.dec_x(self.y - self.old_y); }
        self.old_y = self.y;

        let s1 = self.di.dist() / self.len;
        let mut dist_end = self.di.dist_end();

        let center = MAX_HALF_WIDTH + 2;
        let mut p0 = center;
        let mut p1 = center;

        let mut npix = 0;
        self.covers[p1] = 0;
        if dist_end > 0 {
            self.covers[p1] = profile.value(s1) as u8;
            npix += 1;
        }
        p1 += 1;

        let mut dy = 1usize;
        loop {
            if dy >= DIST_SIZE { break; }
            let dist = self.dist[dy] - s1;
            if dist > self.width { break; }
            dist_end -= self.di.dx_end();
            self.covers[p1] = 0;
            if dist_end > 0 {
                self.covers[p1] = profile.value(dist) as u8;
                npix += 1;
            }
            p1 += 1;
            dy += 1;
        }

        let mut dy = 1usize;
        dist_end = self.di.dist_end();
        loop {
            if dy >= DIST_SIZE { break; }
            let dist = self.dist[dy] + s1;
            if dist > self.width { break; }
            dist_end += self.di.dx_end();
            p0 -= 1;
            self.covers[p0] = 0;
            if dist_end > 0 {
                self.covers[p0] = profile.value(dist) as u8;
                npix += 1;
            }
            dy += 1;
        }

        self.step += 1;
        if npix == 0 { return None; }

        Some(LineSpan { p0, len: p1 - p0, offset: dy as i32 })
    }

    fn step_ver(&mut self, profile: &LineProfileAa, lp: &LineParameters) -> Option<LineSpan> {
        if self.step >= self.count { return None; }

        self.li.inc();
        self.y += lp.inc;
        self.x = (lp.x1 + self.li.y()) >> LINE_SUBPIXEL_SHIFT;
        if lp.inc > 0 { self.di.inc_y(self.x - self.old_x); }
        else { self.di.dec_y(self.x - self.old_x); }
        self.old_x = self.x;

        let s1 = self.di.dist() / self.len;
        let mut dist_end = self.di.dist_end();

        let center = MAX_HALF_WIDTH + 2;
        let mut p0 = center;
        let mut p1 = center;

        let mut npix = 0;
        self.covers[p1] = 0;
        if dist_end > 0 {
            self.covers[p1] = profile.value(s1) as u8;
            npix += 1;
        }
        p1 += 1;

        let mut dx = 1usize;
        loop {
            if dx >= DIST_SIZE { break; }
            let dist = self.dist[dx] - s1;
            if dist > self.width { break; }
            dist_end += self.di.dy_end();
            self.covers[p1] = 0;
            if dist_end > 0 {
                self.covers[p1] = profile.value(dist) as u8;
                npix += 1;
            }
            p1 += 1;
            dx += 1;
        }

        let mut dx = 1usize;
        dist_end = self.di.dist_end();
        loop {
            if dx >= DIST_SIZE { break; }
            let dist = self.dist[dx] + s1;
            if dist > self.width { break; }
            dist_end -= self.di.dy_end();
            p0 -= 1;
            self.covers[p0] = 0;
            if dist_end > 0 {
                self.covers[p0] = profile.value(dist) as u8;
                npix += 1;
            }
            dx += 1;
        }

        self.step += 1;
        if npix == 0 { return None; }

        Some(LineSpan { p0, len: p1 - p0, offset: dx as i32 })
    }
}

/// Line interpolator for AA line type 3 (both joins).
/// Port of C++ `line_interpolator_aa3`.
struct LineInterpolatorAa3 {
    di: DistanceInterpolator3,
    li: Dda2LineInterpolator,
    x: i32,
    y: i32,
    old_x: i32,
    old_y: i32,
    count: i32,
    width: i32,
    max_extent: i32,
    len: i32,
    step: i32,
    dist: [i32; DIST_SIZE],
    pub covers: [u8; COVER_SIZE],
}

impl LineInterpolatorAa3 {
    fn new(
        lp: &LineParameters,
        sx: i32, sy: i32, ex: i32, ey: i32,
        subpixel_width: i32,
    ) -> Self {
        let (mut li, mut x, mut y, count, len, max_extent, dist) =
            init_line_interpolator_base(lp, subpixel_width);

        let mut di = DistanceInterpolator3::new(
            lp.x1, lp.y1, lp.x2, lp.y2,
            sx, sy, ex, ey,
            lp.x1 & !LINE_SUBPIXEL_MASK,
            lp.y1 & !LINE_SUBPIXEL_MASK,
        );

        let mut old_x = x;
        let mut old_y = y;
        let mut step = 0i32;

        // Backward stepping (same as AA1 but uses DI3)
        let mut npix = 1i32;

        if lp.vertical {
            loop {
                li.dec();
                y -= lp.inc;
                x = (lp.x1 + li.y()) >> LINE_SUBPIXEL_SHIFT;

                if lp.inc > 0 {
                    di.dec_y(x - old_x);
                } else {
                    di.inc_y(x - old_x);
                }
                old_x = x;

                let mut dist1_start = di.dist_start();
                let mut dist2_start = dist1_start;

                let mut dx = 0;
                if dist1_start < 0 { npix += 1; }
                loop {
                    dist1_start += di.dy_start();
                    dist2_start -= di.dy_start();
                    if dist1_start < 0 { npix += 1; }
                    if dist2_start < 0 { npix += 1; }
                    dx += 1;
                    if dist[dx as usize] > subpixel_width { break; }
                }
                if npix == 0 { break; }
                npix = 0;
                step -= 1;
                if step < -max_extent { break; }
            }
        } else {
            loop {
                li.dec();
                x -= lp.inc;
                y = (lp.y1 + li.y()) >> LINE_SUBPIXEL_SHIFT;

                if lp.inc > 0 {
                    di.dec_x(y - old_y);
                } else {
                    di.inc_x(y - old_y);
                }
                old_y = y;

                let mut dist1_start = di.dist_start();
                let mut dist2_start = dist1_start;

                let mut dy = 0;
                if dist1_start < 0 { npix += 1; }
                loop {
                    dist1_start -= di.dx_start();
                    dist2_start += di.dx_start();
                    if dist1_start < 0 { npix += 1; }
                    if dist2_start < 0 { npix += 1; }
                    dy += 1;
                    if dist[dy as usize] > subpixel_width { break; }
                }
                if npix == 0 { break; }
                npix = 0;
                step -= 1;
                if step < -max_extent { break; }
            }
        }

        li.adjust_forward();
        step -= max_extent;

        Self {
            di, li, x, y, old_x, old_y,
            count, width: subpixel_width, max_extent, len, step,
            dist, covers: [0u8; COVER_SIZE],
        }
    }

    fn x(&self) -> i32 { self.x }
    fn y(&self) -> i32 { self.y }

    fn step_hor(&mut self, profile: &LineProfileAa, lp: &LineParameters) -> Option<LineSpan> {
        if self.step >= self.count { return None; }

        self.li.inc();
        self.x += lp.inc;
        self.y = (lp.y1 + self.li.y()) >> LINE_SUBPIXEL_SHIFT;
        if lp.inc > 0 { self.di.inc_x(self.y - self.old_y); }
        else { self.di.dec_x(self.y - self.old_y); }
        self.old_y = self.y;

        let s1 = self.di.dist() / self.len;
        let mut dist_start = self.di.dist_start();
        let mut dist_end = self.di.dist_end();

        let center = MAX_HALF_WIDTH + 2;
        let mut p0 = center;
        let mut p1 = center;

        let mut npix = 0;
        self.covers[p1] = 0;
        if dist_end > 0 {
            if dist_start <= 0 {
                self.covers[p1] = profile.value(s1) as u8;
            }
            npix += 1;
        }
        p1 += 1;

        let mut dy = 1usize;
        loop {
            if dy >= DIST_SIZE { break; }
            let dist = self.dist[dy] - s1;
            if dist > self.width { break; }
            dist_start -= self.di.dx_start();
            dist_end -= self.di.dx_end();
            self.covers[p1] = 0;
            if dist_end > 0 && dist_start <= 0 {
                self.covers[p1] = profile.value(dist) as u8;
                npix += 1;
            }
            p1 += 1;
            dy += 1;
        }

        let mut dy = 1usize;
        dist_start = self.di.dist_start();
        dist_end = self.di.dist_end();
        loop {
            if dy >= DIST_SIZE { break; }
            let dist = self.dist[dy] + s1;
            if dist > self.width { break; }
            dist_start += self.di.dx_start();
            dist_end += self.di.dx_end();
            p0 -= 1;
            self.covers[p0] = 0;
            if dist_end > 0 && dist_start <= 0 {
                self.covers[p0] = profile.value(dist) as u8;
                npix += 1;
            }
            dy += 1;
        }

        self.step += 1;
        if npix == 0 { return None; }

        Some(LineSpan { p0, len: p1 - p0, offset: dy as i32 })
    }

    fn step_ver(&mut self, profile: &LineProfileAa, lp: &LineParameters) -> Option<LineSpan> {
        if self.step >= self.count { return None; }

        self.li.inc();
        self.y += lp.inc;
        self.x = (lp.x1 + self.li.y()) >> LINE_SUBPIXEL_SHIFT;
        if lp.inc > 0 { self.di.inc_y(self.x - self.old_x); }
        else { self.di.dec_y(self.x - self.old_x); }
        self.old_x = self.x;

        let s1 = self.di.dist() / self.len;
        let mut dist_start = self.di.dist_start();
        let mut dist_end = self.di.dist_end();

        let center = MAX_HALF_WIDTH + 2;
        let mut p0 = center;
        let mut p1 = center;

        let mut npix = 0;
        self.covers[p1] = 0;
        if dist_end > 0 {
            if dist_start <= 0 {
                self.covers[p1] = profile.value(s1) as u8;
            }
            npix += 1;
        }
        p1 += 1;

        let mut dx = 1usize;
        loop {
            if dx >= DIST_SIZE { break; }
            let dist = self.dist[dx] - s1;
            if dist > self.width { break; }
            dist_start += self.di.dy_start();
            dist_end += self.di.dy_end();
            self.covers[p1] = 0;
            if dist_end > 0 && dist_start <= 0 {
                self.covers[p1] = profile.value(dist) as u8;
                npix += 1;
            }
            p1 += 1;
            dx += 1;
        }

        let mut dx = 1usize;
        dist_start = self.di.dist_start();
        dist_end = self.di.dist_end();
        loop {
            if dx >= DIST_SIZE { break; }
            let dist = self.dist[dx] + s1;
            if dist > self.width { break; }
            dist_start -= self.di.dy_start();
            dist_end -= self.di.dy_end();
            p0 -= 1;
            self.covers[p0] = 0;
            if dist_end > 0 && dist_start <= 0 {
                self.covers[p0] = profile.value(dist) as u8;
                npix += 1;
            }
            dx += 1;
        }

        self.step += 1;
        if npix == 0 { return None; }

        Some(LineSpan { p0, len: p1 - p0, offset: dx as i32 })
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::color::Rgba8;
    use crate::pixfmt_rgba::PixfmtRgba32;
    use crate::rendering_buffer::RowAccessor;

    fn make_buffer(w: u32, h: u32) -> (Vec<u8>, RowAccessor) {
        let stride = (w * 4) as i32;
        let buf = vec![0u8; (h * w * 4) as usize];
        let mut ra = RowAccessor::new();
        unsafe {
            ra.attach(buf.as_ptr() as *mut u8, w, h, stride);
        }
        (buf, ra)
    }

    #[test]
    fn test_line_profile_creation() {
        let p = LineProfileAa::with_width(2.0);
        assert!(p.subpixel_width() > 0);
        assert!(p.profile_size() > 0);
    }

    #[test]
    fn test_line_profile_value_center() {
        let p = LineProfileAa::with_width(3.0);
        // Center should have high coverage
        let center = p.value(0);
        assert!(center > 200, "center coverage={center} should be > 200");
    }

    #[test]
    fn test_line_profile_value_edge() {
        let p = LineProfileAa::with_width(3.0);
        // Far from center should have zero coverage.
        // Width=3.0 → half-width in subpixel is ~512, so dist=800 should be zero.
        let far = p.value(800);
        assert_eq!(far, 0);
    }

    #[test]
    fn test_distance_interpolator1() {
        let di = DistanceInterpolator1::new(0, 0, 256, 0, 128, 128);
        // Distance from (128,128) to line (0,0)-(256,0) should be negative
        // (below the line) since line goes right and point is below
        assert_ne!(di.dist(), 0);
    }

    #[test]
    fn test_render_line0() {
        let (_buf, mut ra) = make_buffer(100, 100);
        let pixf = PixfmtRgba32::new(&mut ra);
        let mut ren = RendererBase::new(pixf);
        let prof = LineProfileAa::with_width(2.0);
        let mut ren_aa = RendererOutlineAa::new(&mut ren, &prof);
        ren_aa.set_color(Rgba8::new(255, 0, 0, 255));

        // Draw a horizontal line
        let lp = LineParameters::new(
            10 * 256, 50 * 256,
            90 * 256, 50 * 256,
            80 * 256,
        );
        ren_aa.line0(&lp);

        // Check that some pixels were drawn somewhere near the line
        let mut found = false;
        for y in 48..=52 {
            for x in 0..100 {
                let p = ren_aa.ren().pixel(x, y);
                if p.r > 0 {
                    found = true;
                    break;
                }
            }
            if found { break; }
        }
        assert!(found, "Expected red pixels near row 50");
    }

    #[test]
    fn test_render_line_diagonal() {
        let (_buf, mut ra) = make_buffer(100, 100);
        let pixf = PixfmtRgba32::new(&mut ra);
        let mut ren = RendererBase::new(pixf);
        let prof = LineProfileAa::with_width(1.5);
        let mut ren_aa = RendererOutlineAa::new(&mut ren, &prof);
        ren_aa.set_color(Rgba8::new(0, 255, 0, 255));

        let lp = LineParameters::new(
            10 * 256, 10 * 256,
            90 * 256, 90 * 256,
            uround(calc_distance_i(10 * 256, 10 * 256, 90 * 256, 90 * 256)),
        );
        ren_aa.line0(&lp);

        let p = ren_aa.ren().pixel(50, 50);
        assert!(p.g > 0, "Expected green pixel at (50,50), got g={}", p.g);
    }
}