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
/*
 * // Copyright (c) Radzivon Bartoshyk 9/2026. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

//! Spline fitting: the decoder's render is linear in the color DCT, so color
//! is one least-squares solve per candidate width; widths live on the format's
//! quantized lattice and are seeded from the ridge scale; integer control
//! points are refined by +-1 px coordinate descent. Every candidate leaves with
//! a few alternative parametrisations for the RD gate to choose from.

use super::detect::{Chain, gaussian_kernels};
use super::filter::FilterPlan;
use super::geometry::Polyline;
use super::select::{BlockModel, pretest};
use super::{
    CHANNEL_WEIGHT, Point, QUANT_ADJUST, QuantizedSpline, adjusted_quant, blob_weight,
    catmull_rom_spans, fast_hypot, round_i32, sample_curve,
};
use crate::coder_scratch::CoderScratch;
use crate::encoding_context::EncodingContext;
use crate::image::Image3F;

static SIGMA_LATTICE: [i32; 8] = [1, 2, 3, 4, 5, 6, 8, 10];
const SEEDED_WIDTHS: usize = 2;
const SCALE_TO_SIGMA: (f32, f32) = (0.86, -0.21);
static FIT_CHANNEL_WEIGHT: [f64; 3] = [14.0, 1.0, 0.6];
const MIN_EXPLAINED: f64 = 0.3;
const REFINE_MIN_EXPLAINED: f64 = 0.6;
const MIN_ARC: f32 = 4.0;
const ARC_PER_COEFF: f32 = 10.0;
const LEAN_ARC_PER_COEFF: f32 = 30.0;
const RDP_EPS: f32 = 0.6;
const MAX_CONTROL_GAP: usize = 24;
/// Alternative geometries: control points inserted until the traced ridge lies
/// within this many pixels of the Catmull-Rom curve the decoder draws.
static CURVE_TOLERANCES: [f32; 2] = [1.0, 1.5];
const MAX_CURVE_POINTS: usize = 24;
const BORDER: i32 = 3;
const BACKGROUND_SIGMA: f32 = 3.0;
const MASK_RADIUS: isize = 2;
const MAX_COEFFS: usize = 32;
/// Refinement only needs the alignment signal: few color coefficients, tight window.
const REFINE_COEFFS: usize = 3;
const COMPACT_COEFFS: usize = 6;
const REFINE_NEIGHBOURS: usize = 3;
const WEIGHT_LUT_STEPS: f32 = 32.0;
/// Unrefined fits slightly below `MIN_EXPLAINED` may still get there after refinement.
const QUICK_MIN_EXPLAINED: f64 = 0.27;
/// Long faint lines get the cheapest representation there is: sparse control
/// points, luma only, one to three coefficients. Anything richer fits grain.
const LONG_LINE_MIN_SPACING: f32 = 64.0;
const LONG_LINE_SPANS: f32 = 3.0;
const LONG_LINE_MAX_COEFFS: usize = 3;
static LONG_LINE_WIDTHS: [i32; 5] = [2, 3, 4, 5, 6];
/// Long-line widths tried, nearest to the ridge-scale prediction first.
const LONG_LINE_SEEDED_WIDTHS: usize = 3;
/// A long line touches many blocks, and the DCT8 proxy's optimism adds up over
/// them: long splines must clear a higher bar on textured ground.
const LONG_LINE_BITS_FACTOR: f32 = 4.0;
/// A joined line gets two endpoints only when its ridge stays this close.
const JOINED_LINE_TOLERANCE: f32 = 0.7;

/// Alternative parametrisations of one detected line; the gate keeps at most one.
pub(super) struct Candidate {
    pub(super) alts: Vec<QuantizedSpline>,
    /// Extra factor on the spline bits in the RD gate.
    pub(super) bits_factor: f32,
    /// Star dot (see `dots`): priced by position and template, selected after lines.
    pub(super) dot: bool,
}

#[inline]
fn sigma_step() -> f32 {
    CHANNEL_WEIGHT[3] / adjusted_quant(QUANT_ADJUST)
}

/// `image - background`, the background being a normalized convolution that
/// ignores the detected line pixels.
fn line_targets(
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
    xyb: &Image3F,
    chains: &[Chain],
) -> [Vec<f32>; 3] {
    let (w, h) = (xyb.xsize(), xyb.ysize());
    let mut keep = vec![1f32; w * h];
    for chain in chains {
        for &Point { x: px, y: py } in &chain.points {
            let (cx, cy) = (px as isize, py as isize);
            for dy in -MASK_RADIUS..=MASK_RADIUS {
                for dx in -(MASK_RADIUS - dy.abs())..=(MASK_RADIUS - dy.abs()) {
                    let (x, y) = (cx + dx, cy + dy);
                    if x >= 0 && y >= 0 && x < w as isize && y < h as isize {
                        keep[y as usize * w + x as usize] = 0.0;
                    }
                }
            }
        }
    }
    let [kernel, _, _] = gaussian_kernels(BACKGROUND_SIGMA);
    let horizontal = FilterPlan::new(w, &kernel);
    let vertical = FilterPlan::new(h, &kernel);
    let mut rows = vec![0.0; w * h];
    let mut blur = |plane: &[f32]| {
        let mut out = vec![0.0; w * h];
        horizontal.horizontal(ctx, scratch, plane, &mut rows);
        vertical.vertical(ctx, scratch, &rows, &mut out);
        out
    };
    let weight = blur(&keep);
    [0, 1, 2].map(|c| {
        let src = xyb.plane_data(c);
        let masked: Vec<f32> = src.iter().zip(&keep).map(|(&v, &m)| v * m).collect();
        let smooth = blur(&masked);
        src.iter()
            .zip(smooth.iter().zip(&weight))
            .map(|(&v, (&s, &n))| v - s / (n + 1e-6))
            .collect()
    })
}

fn smooth_chain(points: &[Point<f32>], sigma: f32) -> Vec<Point<f32>> {
    let [kernel, _, _] = gaussian_kernels(sigma);
    let radius = kernel.len() / 2;
    let n = points.len();
    (0..n)
        .map(|i| {
            let (mut x, mut y) = (0f32, 0f32);
            for (j, &k) in kernel.iter().enumerate() {
                let p = points[(i + j).saturating_sub(radius).min(n - 1)];
                x += k * p.x;
                y += k * p.y;
            }
            Point::new(x, y)
        })
        .collect()
}

fn push_rounded(out: &mut Vec<Point<i32>>, p: Point<f32>) {
    let q = Point::new(round_i32(p.x), round_i32(p.y));
    if out.last() != Some(&q) {
        out.push(q);
    }
}

/// Douglas-Peucker control points, with a cap on the span between neighbors
/// (Catmull-Rom overshoots on long spans).
fn rdp_control_points(chain: &[Point<f32>]) -> Vec<Point<i32>> {
    let sm = smooth_chain(chain, 1.5);
    let n = sm.len();
    let mut keep = vec![false; n];
    keep[0] = true;
    keep[n - 1] = true;
    let mut stack = vec![(0usize, n - 1)];
    while let Some((a, b)) = stack.pop() {
        if b <= a + 1 {
            continue;
        }
        let (p0, p1) = (sm[a], sm[b]);
        let d = (p1.x - p0.x, p1.y - p0.y);
        let len = fast_hypot(d.0, d.1);
        let (mut worst, mut worst_dist) = (a + 1, -1f32);
        for (i, p) in sm.iter().enumerate().take(b).skip(a + 1) {
            let dist = if len < 1e-9 {
                fast_hypot(p.x - p0.x, p.y - p0.y)
            } else {
                (d.0 * (p.y - p0.y) - d.1 * (p.x - p0.x)).abs() / len
            };
            if dist > worst_dist {
                (worst, worst_dist) = (i, dist);
            }
        }
        if worst_dist > RDP_EPS {
            keep[worst] = true;
            stack.push((a, worst));
            stack.push((worst, b));
        }
    }
    let mut out = Vec::new();
    let mut last = 0usize;
    push_rounded(&mut out, sm[0]);
    for i in (1..n).filter(|&i| keep[i]) {
        while i - last > MAX_CONTROL_GAP {
            last += MAX_CONTROL_GAP;
            push_rounded(&mut out, sm[last]);
        }
        push_rounded(&mut out, sm[i]);
        last = i;
    }
    out
}

/// Control points chosen against the curve the decoder actually draws: start
/// from the end points and insert the chain point farthest from the
/// Catmull-Rom curve until the whole chain lies within `tol` px of it.
/// Douglas-Peucker measures against the polyline instead and over-samples
/// every smooth bend.
/// Stop once the rounded controls exceed the caller's acceptance budget.
fn curve_control_points(
    ctx: &EncodingContext,
    chain: &[Point<f32>],
    tol: f32,
    max_points: usize,
) -> Vec<Point<i32>> {
    let sm = smooth_chain(chain, 1.5);
    let mut idx = vec![0usize, sm.len() - 1];
    loop {
        let mut ctrl: Vec<Point<i32>> = Vec::with_capacity(idx.len());
        for &i in &idx {
            push_rounded(&mut ctrl, sm[i]);
        }
        // Check after rounding: an inserted point can collapse onto its
        // neighbor, leaving a two-point line that the caller still accepts.
        if ctrl.len() < 2
            || ctrl.len() != idx.len()
            || idx.len() >= MAX_CURVE_POINTS
            || ctrl.len() > max_points
        {
            return ctrl;
        }
        let control: Vec<Point<f32>> = ctrl.iter().map(|p| p.as_f32()).collect();
        let curve = super::catmull_rom(&control);
        let curve_distance = Polyline::new(ctx, &curve);
        let (mut worst, mut worst_d) = (0usize, tol * tol);
        for (k, &p) in sm.iter().enumerate() {
            let d = curve_distance.distance(p);
            if d > worst_d && !idx.contains(&k) {
                (worst, worst_d) = (k, d);
            }
        }
        if worst_d <= tol * tol {
            return ctrl;
        }
        let at = idx.partition_point(|&i| i < worst);
        idx.insert(at, worst);
    }
}

/// Remove redundant controls from an already aligned curve. Compare both
/// directions: checking only the new curve would allow shortcuts across bends.
/// Each deletion changes at most four spans, so no color fitting is needed.
fn prune_control_points(
    ctx: &EncodingContext,
    points: &[Point<i32>],
    tolerance: f32,
) -> Vec<Point<i32>> {
    let reference: Vec<_> = points.iter().map(|p| p.as_f32()).collect();
    let reference = super::catmull_rom(&reference);
    let reference_distance = Polyline::new(ctx, &reference);
    let mut indices: Vec<usize> = (0..points.len()).collect();
    let mut points = points.to_vec();
    let mut errors = vec![None; points.len()];
    loop {
        let mut best = None;
        let mut best_error = tolerance * tolerance;
        for i in 1..points.len() - 1 {
            let error = *errors[i].get_or_insert_with(|| {
                let mut control: Vec<_> = points.iter().map(|p| p.as_f32()).collect();
                control.remove(i);
                let lo = i.saturating_sub(2);
                let hi = (i + 1).min(control.len() - 1);
                let curve = catmull_rom_spans(&control, lo..hi);
                let curve_distance = Polyline::new(ctx, &curve);
                let original_hi = if hi >= i { hi + 1 } else { hi };
                let range = indices[lo] * 16..indices[original_hi] * 16;
                let original = &reference[range.start..=range.end];
                let mut error = 0.0f32;
                for distance in curve
                    .iter()
                    .map(|&p| reference_distance.distance_range(p, range.clone()))
                    .chain(original.iter().map(|&p| curve_distance.distance(p)))
                {
                    error = error.max(distance);
                    if error >= tolerance * tolerance {
                        break;
                    }
                }
                error
            });
            if error < best_error {
                best_error = error;
                best = Some(i);
            }
        }
        let Some(i) = best else { break };
        points.remove(i);
        indices.remove(i);
        errors.remove(i);
        // A deletion only changes the tangents of neighboring spans.
        let end = (i + 4).min(errors.len());
        errors[i.saturating_sub(3)..end].fill(None);
    }
    points
}

/// Equal arc spacing keeps the double-delta coordinate tokens small.
fn uniform_control_points(chain: &[Point<f32>], spacing: f32) -> Vec<Point<i32>> {
    let sm = smooth_chain(chain, 1.5);
    let mut cum = vec![0f32; sm.len()];
    let mut length = 0.0;
    for (distance, [a, b]) in cum[1..].iter_mut().zip(sm.array_windows::<2>()) {
        length += fast_hypot(b.x - a.x, b.y - a.y);
        *distance = length;
    }
    let total = cum[sm.len() - 1];
    let n = ((total / spacing + 0.5) as usize).max(1);
    let mut out = Vec::new();
    let mut seg = 0usize;
    for k in 0..=n {
        let target = total * k as f32 / n as f32;
        while seg + 2 < sm.len() && cum[seg + 1] < target {
            seg += 1;
        }
        let span = (cum[seg + 1] - cum[seg]).max(1e-9);
        let f = ((target - cum[seg]) / span).clamp(0.0, 1.0);
        push_rounded(
            &mut out,
            Point::new(
                sm[seg].x + f * (sm[seg + 1].x - sm[seg].x),
                sm[seg].y + f * (sm[seg + 1].y - sm[seg].y),
            ),
        );
    }
    out
}

struct Fit {
    err: f64,
    e0: f64,
    sigma_n: i32,
    coeffs: usize,
    arc: f32,
    /// Dequantized-convention color DCT per channel (X, Y, B).
    sol: [[f64; MAX_COEFFS]; 3],
}

impl Fit {
    fn gain(&self) -> f64 {
        self.e0 - self.err
    }

    fn explained(&self) -> f64 {
        1.0 - self.err / self.e0.max(1e-12)
    }
}

#[derive(Default)]
pub(crate) struct FitScratch {
    slots: Vec<i32>,
    rows: Vec<f64>,
    pixels: Vec<u32>,
    weight_luts: Vec<(i32, isize, Vec<f32>)>,
    points: Vec<Point<i32>>,
    samples: Vec<super::ArcSample>,
    arc: f32,
    basis: Vec<f64>,
    basis_coeffs: usize,
    origin: (usize, usize),
    width: usize,
}

impl FitScratch {
    fn geometry(&mut self, points: &[Point<i32>]) {
        if self.points == points {
            return;
        }
        self.points.clear();
        self.points.extend_from_slice(points);
        (self.samples, self.arc) = sample_curve(points);
        self.basis_coeffs = 0;
    }

    fn prepare_basis(&mut self, coeffs: usize) {
        if self.basis_coeffs == coeffs {
            return;
        }
        self.basis.clear();
        for k in 0..self.samples.len() {
            let t = 31.0 * (k as f32 / self.arc).min(1.0);
            self.basis.extend((0..coeffs).map(|i| {
                // Evaluate the angle in f32; retain f64 accumulation and solving.
                std::f64::consts::SQRT_2
                    * super::trig::f_cosf(std::f32::consts::PI / 32.0 * i as f32 * (t + 0.5)) as f64
            }));
        }
        self.basis_coeffs = coeffs;
    }

    fn weight_table(&mut self, sigma_n: i32, sigma: f32, reach: isize) -> usize {
        if let Some(i) = self
            .weight_luts
            .iter()
            .position(|&(n, r, _)| n == sigma_n && r == reach)
        {
            return i;
        }
        let len = ((reach as f32 + 1.0) * std::f32::consts::SQRT_2 * WEIGHT_LUT_STEPS) as usize + 2;
        let table = (0..len)
            .map(|i| blob_weight(i as f32 / WEIGHT_LUT_STEPS, 0.0, 1.0 / sigma, 1.0))
            .collect();
        self.weight_luts.push((sigma_n, reach, table));
        self.weight_luts.len() - 1
    }

    /// Retain ordinary candidate buffers, without keeping an unusually large
    /// curve's allocations alive on every encoder worker.
    fn trim(&mut self) {
        const MAX_BYTES: usize = 32 * 1024 * 1024;
        fn trim<T>(v: &mut Vec<T>) {
            if v.capacity() > MAX_BYTES / size_of::<T>() {
                *v = Vec::new();
            }
        }
        trim(&mut self.slots);
        trim(&mut self.rows);
        trim(&mut self.pixels);
        if self.basis.capacity() > MAX_BYTES / size_of::<f64>() {
            self.basis = Vec::new();
            self.basis_coeffs = 0;
        }
    }
}

/// Fit precision: `Full` is what gets quantized, `Probe` ranks geometry moves.
#[derive(Clone, Copy, PartialEq)]
enum Precision {
    Full,
    Probe,
    Compact,
}

/// Cholesky solve of the leading `k x k` block of `ata`.
fn solve_leading(
    ata: &[[f64; MAX_COEFFS]; MAX_COEFFS],
    k: usize,
    rhs: &[f64; MAX_COEFFS],
    out: &mut [f64; MAX_COEFFS],
) {
    out.fill(0.0);
    if k == 0 {
        return;
    }
    let mut l = [[0f64; MAX_COEFFS]; MAX_COEFFS];
    for i in 0..k {
        for j in 0..=i {
            let mut sum = ata[i][j] + if i == j { 1e-9 } else { 0.0 };
            for (&a, &b) in l[i][..j].iter().zip(&l[j][..j]) {
                sum -= a * b;
            }
            l[i][j] = if i == j {
                sum.max(1e-30).sqrt()
            } else {
                sum / l[j][j]
            };
        }
    }
    let mut y = [0f64; MAX_COEFFS];
    for i in 0..k {
        let mut sum = rhs[i];
        for (&a, &b) in l[i][..i].iter().zip(&y[..i]) {
            sum -= a * b;
        }
        y[i] = sum / l[i][i];
    }
    for i in (0..k).rev() {
        let mut sum = y[i];
        for (row, &value) in l[i + 1..k].iter().zip(&out[i + 1..k]) {
            sum -= row[i] * value;
        }
        out[i] = sum / l[i][i];
    }
}

/// Least-squares color fit of the curve through `points` at lattice width
/// `sigma_n`, with `(kx, ky, kb)` free coefficients per channel (`None` = all).
fn fit_at(
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    points: &[Point<i32>],
    sigma_n: i32,
    free: Option<(usize, usize, usize)>,
    precision: Precision,
    scratch: &mut FitScratch,
) -> Option<Fit> {
    Some(fit_system(targets, w, h, points, sigma_n, precision, scratch)?.solve(free))
}

/// Geometry and pixel terms shared by all coefficient budgets of one fit.
struct FitSystem {
    ata: [[f64; MAX_COEFFS]; MAX_COEFFS],
    atb: [[f64; MAX_COEFFS]; 3],
    btb: [f64; 3],
    sigma_n: i32,
    coeffs: usize,
    arc: f32,
}

fn fit_system(
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    points: &[Point<i32>],
    sigma_n: i32,
    precision: Precision,
    scratch: &mut FitScratch,
) -> Option<FitSystem> {
    scratch.geometry(points);
    let arc = scratch.arc;
    if arc < MIN_ARC {
        return None;
    }
    let mut coeffs = ((arc / ARC_PER_COEFF + 0.5) as usize).clamp(1, MAX_COEFFS);
    let sigma = sigma_n as f32 * sigma_step();
    let mut reach = (3.6 * sigma + 1.5).ceil() as isize;
    if precision == Precision::Probe {
        coeffs = coeffs.min(REFINE_COEFFS);
        reach = (2.6 * sigma + 1.0).ceil() as isize;
    }
    if precision == Precision::Compact {
        coeffs = coeffs.min(COMPACT_COEFFS);
    }
    scratch.prepare_basis(coeffs);
    let table = scratch.weight_table(sigma_n, sigma, reach);
    // Refinement uses three coefficients; compact extension and long-line
    // fits use six. Expose these common sizes to the compiler without changing
    // the raster or normal-equation accumulation order.
    match coeffs {
        REFINE_COEFFS => raster_system::<REFINE_COEFFS>(
            targets, w, h, sigma_n, sigma, reach, coeffs, table, scratch,
        ),
        COMPACT_COEFFS => raster_system::<COMPACT_COEFFS>(
            targets, w, h, sigma_n, sigma, reach, coeffs, table, scratch,
        ),
        _ => raster_system::<0>(targets, w, h, sigma_n, sigma, reach, coeffs, table, scratch),
    }
}

fn raster_system<const FIXED_COEFFS: usize>(
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    sigma_n: i32,
    sigma: f32,
    reach: isize,
    coeffs: usize,
    table: usize,
    scratch: &mut FitScratch,
) -> Option<FitSystem> {
    let coeffs = if FIXED_COEFFS == 0 {
        coeffs
    } else {
        FIXED_COEFFS
    };
    let arc = scratch.arc;
    let weight_lut = &scratch.weight_luts[table].2;
    let samples = &scratch.samples;

    let (mut bx0, mut by0, mut bx1, mut by1) = (isize::MAX, isize::MAX, isize::MIN, isize::MIN);
    for sample in samples {
        let Point { x: cx, y: cy } = sample.position;
        let (rx, ry) = (round_i32(cx) as isize, round_i32(cy) as isize);
        bx0 = bx0.min(rx - reach);
        by0 = by0.min(ry - reach);
        bx1 = bx1.max(rx + reach);
        by1 = by1.max(ry + reach);
    }
    let (bx0, by0) = (bx0.max(0), by0.max(0));
    let (bx1, by1) = (bx1.min(w as isize - 1), by1.min(h as isize - 1));
    if bx1 < bx0 || by1 < by0 {
        return None;
    }
    let (bw, bh) = ((bx1 - bx0 + 1) as usize, (by1 - by0 + 1) as usize);
    scratch.origin = (bx0 as usize, by0 as usize);
    scratch.width = bw;
    scratch.slots.clear();
    scratch.slots.resize(bw * bh, -1);
    scratch.rows.clear();
    scratch.pixels.clear();

    for (sample, basis) in samples.iter().zip(scratch.basis.chunks_exact(coeffs)) {
        let Point { x: cx, y: cy } = sample.position;
        let mult = sample.multiplier;
        let amp = 0.25 * sigma * mult;
        let (rx, ry) = (round_i32(cx) as isize, round_i32(cy) as isize);
        let x0 = (rx - reach).max(bx0);
        let x1 = (rx + reach).min(bx1);
        if x0 > x1 {
            continue;
        }
        for y in (ry - reach).max(by0)..=(ry + reach).min(by1) {
            let dy = y as f32 - cy;
            let offset = (y - by0) as usize * bw;
            let slots = &mut scratch.slots[offset..offset + bw];
            for (x, slot) in (x0..=x1).zip(&mut slots[(x0 - bx0) as usize..=(x1 - bx0) as usize]) {
                let dx = x as f32 - cx;
                let pos = (dx * dx + dy * dy).sqrt() * WEIGHT_LUT_STEPS;
                let cell = pos as usize;
                let frac = pos - cell as f32;
                let weight = amp * (weight_lut[cell] * (1.0 - frac) + weight_lut[cell + 1] * frac);
                if weight.abs() <= 1e-7 {
                    continue;
                }
                if *slot < 0 {
                    *slot = scratch.pixels.len() as i32;
                    scratch.pixels.push((y as usize * w + x as usize) as u32);
                    // Initialize directly on first contact. Keep the addition
                    // to +0.0 so signed-zero behavior matches the old update.
                    scratch
                        .rows
                        .extend(basis.iter().map(|&b| 0.0 + weight as f64 * b));
                } else {
                    let row =
                        &mut scratch.rows[*slot as usize * coeffs..(*slot as usize + 1) * coeffs];
                    for (r, &b) in row.iter_mut().zip(&basis[..coeffs]) {
                        *r += weight as f64 * b;
                    }
                }
            }
        }
    }
    if scratch.pixels.is_empty() {
        return None;
    }

    let mut ata = [[0f64; MAX_COEFFS]; MAX_COEFFS];
    let mut atb = [[0f64; MAX_COEFFS]; 3];
    let mut btb = [0f64; 3];
    for (&pix, row) in scratch.pixels.iter().zip(scratch.rows.chunks_exact(coeffs)) {
        for (i, (&value, ata_row)) in row.iter().zip(&mut ata).enumerate() {
            for (a, &b) in ata_row[..=i].iter_mut().zip(&row[..=i]) {
                *a += value * b;
            }
        }
        for ((atb, btb), target) in atb.iter_mut().zip(&mut btb).zip(targets) {
            let t = target[pix as usize] as f64;
            *btb += t * t;
            for (a, &b) in atb.iter_mut().zip(row) {
                *a += b * t;
            }
        }
    }
    for i in 0..coeffs {
        for j in i + 1..coeffs {
            ata[i][j] = ata[j][i];
        }
    }

    Some(FitSystem {
        ata,
        atb,
        btb,
        sigma_n,
        coeffs,
        arc,
    })
}

impl FitSystem {
    /// Fit the color to the gradient of the original image. A smooth pedestal
    /// under a line belongs in VarDCT: removing it along with the line creates
    /// a narrow trough that costs AC coefficients. Differencing both the image
    /// and the render basis eliminates constant and linear backgrounds without
    /// trusting the masked blur. Reuse the expensive rasterized basis rows.
    fn residual_system(&self, source: &Image3F, scratch: &FitScratch) -> Self {
        let mut result = Self {
            ata: [[0.0; MAX_COEFFS]; MAX_COEFFS],
            atb: [[0.0; MAX_COEFFS]; 3],
            btb: [0.0; 3],
            sigma_n: self.sigma_n,
            coeffs: self.coeffs,
            arc: self.arc,
        };
        let k = self.coeffs;
        let (w, h) = (source.xsize(), source.ysize());
        let (x0, y0) = scratch.origin;
        let bw = scratch.width;
        let bh = scratch.slots.len() / bw;
        for (slot, &pixel) in scratch.pixels.iter().enumerate() {
            let pixel = pixel as usize;
            let (x, y) = (pixel % w, pixel / w);
            let row = &scratch.rows[slot * k..][..k];
            for (dx, dy) in [(1isize, 0isize), (0, 1), (-1, 0), (0, -1)] {
                let (nx, ny) = (x as isize + dx, y as isize + dy);
                if nx < 0 || ny < 0 || nx >= w as isize || ny >= h as isize {
                    continue;
                }
                let (nx, ny) = (nx as usize, ny as usize);
                let neighbor = if nx >= x0 && ny >= y0 && nx < x0 + bw && ny < y0 + bh {
                    scratch.slots[(ny - y0) * bw + nx - x0]
                } else {
                    -1
                };
                // Interior edges once, and all edges of the finite support.
                if neighbor >= 0 && (neighbor as usize) < slot {
                    continue;
                }
                let mut diff = [0.0; MAX_COEFFS];
                for i in 0..k {
                    diff[i] = row[i]
                        - if neighbor >= 0 {
                            scratch.rows[neighbor as usize * k + i]
                        } else {
                            0.0
                        };
                }
                for i in 0..k {
                    for j in 0..=i {
                        result.ata[i][j] += diff[i] * diff[j];
                    }
                }
                for c in 0..3 {
                    let plane = source.plane_data(c);
                    let target = (plane[pixel] - plane[ny * w + nx]) as f64;
                    result.btb[c] += target * target;
                    for (a, &d) in result.atb[c][..k].iter_mut().zip(&diff) {
                        *a += d * target;
                    }
                }
            }
        }
        for i in 0..k {
            for j in i + 1..k {
                result.ata[i][j] = result.ata[j][i];
            }
        }
        result
    }

    fn solve(&self, free: Option<(usize, usize, usize)>) -> Fit {
        let Self { ata, atb, btb, .. } = self;
        let coeffs = self.coeffs;
        let (kx, ky, kb) = free.unwrap_or((coeffs, coeffs, coeffs));
        let mut sol = [[0f64; MAX_COEFFS]; 3];
        solve_leading(ata, ky.min(coeffs), &atb[1], &mut sol[1]);
        solve_leading(ata, kx.min(coeffs), &atb[0], &mut sol[0]);
        // B is stored as a residual of Y (base correlation 1.0): fit the residual
        let mut rhs = atb[2];
        for (rhs, row) in rhs[..coeffs].iter_mut().zip(ata) {
            for (&a, &y) in row[..coeffs].iter().zip(&sol[1]) {
                *rhs -= a * y;
            }
        }
        let mut residual = [0f64; MAX_COEFFS];
        solve_leading(ata, kb.min(coeffs), &rhs, &mut residual);
        let [_, y, b] = &mut sol;
        for ((b, &y), &residual) in b[..coeffs].iter_mut().zip(y.iter()).zip(&residual) {
            *b = y + residual;
        }

        let (mut err, mut e0) = (0f64, 0f64);
        for c in 0..3 {
            let mut quad = 0f64;
            let mut lin = 0f64;
            for ((&value, &rhs), row) in sol[c][..coeffs].iter().zip(&atb[c]).zip(ata) {
                lin += value * rhs;
                for (&a, &b) in row[..coeffs].iter().zip(&sol[c]) {
                    quad += value * a * b;
                }
            }
            let weight = FIT_CHANNEL_WEIGHT[c] * FIT_CHANNEL_WEIGHT[c];
            err += weight * (btb[c] - 2.0 * lin + quad).max(0.0);
            e0 += weight * btb[c];
        }
        Fit {
            err,
            e0,
            sigma_n: self.sigma_n,
            coeffs,
            arc: self.arc,
            sol,
        }
    }
}

/// Best fit over a set of lattice widths. Supports differ per width, so widths
/// compete on energy reduction, not on the residual sum.
fn fit_best(
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    points: &[Point<i32>],
    widths: &[i32],
    free: Option<(usize, usize, usize)>,
    scratch: &mut FitScratch,
) -> Option<Fit> {
    let mut best: Option<Fit> = None;
    for &n in widths {
        if let Some(fit) = fit_at(targets, w, h, points, n, free, Precision::Full, scratch)
            && best.as_ref().is_none_or(|b| fit.gain() > b.gain())
        {
            best = Some(fit);
        }
    }
    best
}

#[inline]
fn quantized_coefficient(value: f64) -> i32 {
    if value.abs() < 0.5 {
        0
    } else {
        (value + 0.5f64.copysign(value)) as i32
    }
}

fn quantize(points: &[Point<i32>], fit: &Fit) -> QuantizedSpline {
    let quant = adjusted_quant(QUANT_ADJUST) as f64;
    let mut dct = [[0i32; 32]; 4];
    let [x, y, b, sigma] = &mut dct;
    for (i, ((x, y), b)) in x[..fit.coeffs].iter_mut().zip(y).zip(b).enumerate() {
        let f = if i == 0 {
            std::f64::consts::SQRT_2
        } else {
            1.0
        };
        *y = quantized_coefficient(fit.sol[1][i] * f * quant / CHANNEL_WEIGHT[1] as f64);
        let restored = *y as f64 / f * CHANNEL_WEIGHT[1] as f64 / quant;
        *x = quantized_coefficient(fit.sol[0][i] * f * quant / CHANNEL_WEIGHT[0] as f64);
        *b = quantized_coefficient(
            (fit.sol[2][i] - restored) * f * quant / CHANNEL_WEIGHT[2] as f64,
        );
    }
    sigma[0] = fit.sigma_n;
    QuantizedSpline {
        points: points.to_vec(),
        dct,
    }
}

/// +-1 px coordinate descent of every control point at a fixed width.
fn refine(
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    points: &[Point<i32>],
    sigma_n: i32,
    sweeps: usize,
    scratch: &mut FitScratch,
) -> Vec<Point<i32>> {
    let cost = |pts: &[Point<i32>], scratch: &mut FitScratch| -> f64 {
        if pts.array_windows::<2>().any(|p| p[0] == p[1]) {
            return f64::INFINITY;
        }
        fit_at(targets, w, h, pts, sigma_n, None, Precision::Probe, scratch)
            .map_or(f64::INFINITY, |f| -f.gain())
    };
    // A control point only shapes the curve a few spans around it: rank its
    // moves on that sub-curve instead of re-fitting the whole spline.
    let mut points = points.to_vec();
    for _ in 0..sweeps {
        let mut moved = false;
        for i in 0..points.len() {
            let lo = i.saturating_sub(REFINE_NEIGHBOURS);
            let hi = (i + REFINE_NEIGHBOURS).min(points.len() - 1);
            let local = &mut points[lo..=hi];
            let center = i - lo;
            let mut best_point = local[center];
            let mut best = cost(local, scratch);
            for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
                let trial = Point::new(best_point.x + dx, best_point.y + dy);
                local[center] = trial;
                let value = cost(local, scratch);
                if value < best - 1e-12 {
                    best = value;
                    best_point = trial;
                    moved = true;
                }
            }
            local[center] = best_point;
        }
        if !moved {
            break;
        }
    }
    points
}

/// Squared distance from `p` to the polyline `chain`.
#[cfg(test)]
fn distance_sq_to_chain(p: Point<f32>, chain: &[Point<f32>]) -> f32 {
    let mut best = f32::INFINITY;
    for &[a, b] in chain.array_windows::<2>() {
        let (dx, dy) = (b.x - a.x, b.y - a.y);
        let len2 = dx * dx + dy * dy;
        let t = if len2 > 1e-12 {
            (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0)
        } else {
            0.0
        };
        let (ex, ey) = (p.x - (a.x + t * dx), p.y - (a.y + t * dy));
        best = best.min(ex * ex + ey * ey);
    }
    best
}

/// Collapse two interior controls, allowing their replacement to leave either
/// old knot. Test positions on the old curve and a small integer neighborhood;
/// this is geometry only, before the selector pays for rendering one proposal.
pub(super) fn collapse_control_pair(
    ctx: &EncodingContext,
    points: &[Point<i32>],
    i: usize,
) -> Option<Vec<Point<i32>>> {
    if i == 0 || i + 2 >= points.len() {
        return None;
    }
    let control: Vec<_> = points.iter().map(|p| p.as_f32()).collect();
    // The merged knot can influence four spans in the shorter polygon.
    let lo = i.saturating_sub(2);
    let hi = (i + 3).min(points.len() - 1);
    let reference = catmull_rom_spans(&control, lo..hi);
    let reference_distance = Polyline::new(ctx, &reference);
    let samples = catmull_rom_spans(&control, i..i + 1);
    let mut reduced = points.to_vec();
    reduced.remove(i + 1);
    let cost = |points: &[Point<i32>]| {
        if points.array_windows::<2>().any(|p| p[0] == p[1]) {
            return f32::INFINITY;
        }
        let control: Vec<_> = points.iter().map(|p| p.as_f32()).collect();
        let curve = catmull_rom_spans(&control, lo..hi - 1);
        let curve_distance = Polyline::new(ctx, &curve);
        let forward: f32 = curve.iter().map(|&p| reference_distance.distance(p)).sum();
        let backward: f32 = reference.iter().map(|&p| curve_distance.distance(p)).sum();
        forward / curve.len() as f32 + backward / reference.len() as f32
    };
    let (mut best_point, mut best_cost) = (reduced[i], f32::INFINITY);
    for k in [0, 4, 8, 12, 16] {
        reduced[i] = Point::new(round_i32(samples[k].x), round_i32(samples[k].y));
        let value = cost(&reduced);
        if value < best_cost {
            best_cost = value;
            best_point = reduced[i];
        }
    }
    for step in [2, 1] {
        let origin = best_point;
        for (dx, dy) in [
            (0, 0),
            (1, 0),
            (-1, 0),
            (0, 1),
            (0, -1),
            (1, 1),
            (-1, -1),
            (1, -1),
            (-1, 1),
        ] {
            reduced[i] = Point::new(origin.x + dx * step, origin.y + dy * step);
            let value = cost(&reduced);
            if value < best_cost {
                best_cost = value;
                best_point = reduced[i];
            }
        }
    }
    reduced[i] = best_point;
    best_cost.is_finite().then_some(reduced)
}

/// +-1 px coordinate descent against the sub-pixel ridge: pulls the
/// Catmull-Rom curve onto the chain. Pure geometry, no rendering; a control
/// point only moves the four curve segments around it.
fn refine_geometric(
    ctx: &EncodingContext,
    points: &[Point<i32>],
    chain: &[Point<f32>],
    sweeps: usize,
) -> Vec<Point<i32>> {
    let sm = smooth_chain(chain, 1.0);
    let distance = Polyline::new(ctx, &sm);
    let local_cost = |pts: &[Point<i32>], i: usize| -> f32 {
        if pts.array_windows::<2>().any(|p| p[0] == p[1]) {
            return f32::INFINITY;
        }
        let control: Vec<Point<f32>> = pts.iter().map(|&p| p.as_f32()).collect();
        let spans = i.saturating_sub(2)..(i + 2).min(pts.len() - 1);
        let first = spans.start * 16;
        let last = spans.end * 16;
        let curve = catmull_rom_spans(&control, spans);
        // the curve runs along the chain: only search the matching stretch
        let per_point = sm.len() as f32 / ((pts.len() - 1) * 16).max(1) as f32;
        let slack = (3 * sm.len() / pts.len() + 8) as f32;
        let lo = ((first as f32 * per_point - slack).max(0.0) as usize).min(sm.len() - 2);
        let hi = ((last as f32 * per_point + slack) as usize + 2).min(sm.len());
        curve
            .iter()
            .map(|&p| distance.distance_range(p, lo..hi - 1))
            .sum()
    };
    let mut points = points.to_vec();
    for _ in 0..sweeps {
        let mut moved = false;
        for i in 0..points.len() {
            let mut best = local_cost(&points, i);
            for (dx, dy) in [
                (1, 0),
                (-1, 0),
                (0, 1),
                (0, -1),
                (1, 1),
                (1, -1),
                (-1, 1),
                (-1, -1),
            ] {
                let previous = points[i];
                points[i] = Point::new(previous.x + dx, previous.y + dy);
                let value = local_cost(&points, i);
                if value < best - 1e-6 {
                    best = value;
                    moved = true;
                } else {
                    points[i] = previous;
                }
            }
        }
        if !moved {
            break;
        }
    }
    points
}

fn inside(points: &[Point<i32>], w: usize, h: usize) -> bool {
    points.iter().all(|p| {
        p.x >= BORDER && p.y >= BORDER && p.x < w as i32 - BORDER && p.y < h as i32 - BORDER
    })
}

struct Primary {
    points: Vec<Point<i32>>,
    fit: Fit,
    spline: QuantizedSpline,
}

/// Seeded-width fit of the unrefined control points.
fn quick_primary(
    ctx: &EncodingContext,
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    chain: &Chain,
    scratch: &mut FitScratch,
) -> Option<Primary> {
    let points = prune_control_points(ctx, &rdp_control_points(&chain.points), 0.5);
    if points.len() < 2 || !inside(&points, w, h) {
        return None;
    }
    let predicted = SCALE_TO_SIGMA.0 * chain.scale + SCALE_TO_SIGMA.1;
    let mut seeds = SIGMA_LATTICE;
    seeds.sort_by(|&a, &b| {
        (a as f32 * sigma_step() - predicted)
            .abs()
            .total_cmp(&(b as f32 * sigma_step() - predicted).abs())
    });
    let fit = fit_best(
        targets,
        w,
        h,
        &points,
        &seeds[..SEEDED_WIDTHS],
        None,
        scratch,
    )?;
    if fit.explained() < QUICK_MIN_EXPLAINED {
        return None;
    }
    let spline = quantize(&points, &fit);
    Some(Primary {
        points,
        fit,
        spline,
    })
}

/// Refines a primary that survived the RD pre-test and builds its alternatives.
fn expand(
    ctx: &EncodingContext,
    targets: &[Vec<f32>; 3],
    source: &Image3F,
    w: usize,
    h: usize,
    chain: &Chain,
    primary: Primary,
    scratch: &mut FitScratch,
) -> Option<Candidate> {
    let Primary {
        mut points,
        mut fit,
        ..
    } = primary;
    if fit.explained() > REFINE_MIN_EXPLAINED {
        let aligned = refine_geometric(ctx, &points, &chain.points, 2);
        let refined = refine(targets, w, h, &aligned, fit.sigma_n, 1, scratch);
        let at = SIGMA_LATTICE
            .iter()
            .position(|&n| n == fit.sigma_n)
            .unwrap_or(0);
        let nearby = &SIGMA_LATTICE[at.saturating_sub(1)..(at + 2).min(SIGMA_LATTICE.len())];
        // Width and geometry change pixel support, so compare error removed
        // rather than raw residual errors over different sets of pixels.
        if let Some(better) = fit_best(targets, w, h, &refined, nearby, None, scratch)
            && better.gain() > fit.gain()
        {
            (points, fit) = (refined, better);
        }
    }
    if fit.explained() < MIN_EXPLAINED || !inside(&points, w, h) {
        return None;
    }
    let primary = quantize(&points, &fit);
    if primary.dct[..3]
        .iter()
        .all(|row| row.iter().all(|&v| v == 0))
    {
        return None;
    }

    let lean = (1, ((fit.arc / LEAN_ARC_PER_COEFF + 0.5) as usize).max(1), 1);
    let mut alts = vec![primary];
    let mut geometries = vec![points];
    for tol in CURVE_TOLERANCES {
        let sparse = curve_control_points(ctx, &chain.points, tol, MAX_CURVE_POINTS);
        if sparse.len() >= 2 {
            let aligned = refine_geometric(ctx, &sparse, &chain.points, 2);
            let refined = if aligned.len() < geometries[0].len() {
                refine(targets, w, h, &aligned, fit.sigma_n, 1, scratch)
            } else {
                aligned
            };
            if !geometries.contains(&refined) {
                geometries.push(refined);
            }
        }
    }
    for (g, geometry) in geometries.iter().enumerate() {
        if !inside(geometry, w, h) || geometry.array_windows::<2>().any(|p| p[0] == p[1]) {
            continue;
        }
        let Some(system) = fit_system(
            targets,
            w,
            h,
            geometry,
            fit.sigma_n,
            Precision::Full,
            scratch,
        ) else {
            continue;
        };
        for free in [None, Some(lean)] {
            if g == 0 && free.is_none() {
                continue;
            }
            let alt = system.solve(free);
            let spline = quantize(geometry, &alt);
            if spline.dct[1].iter().any(|&v| v != 0) {
                alts.push(spline);
            }
        }
        let residual = system.residual_system(source, scratch);
        for free in [None, Some(lean)] {
            let spline = quantize(geometry, &residual.solve(free));
            if spline.dct[1].iter().any(|&v| v != 0)
                && !alts
                    .iter()
                    .any(|a| a.points == spline.points && a.dct == spline.dct)
            {
                alts.push(spline);
            }
        }
    }
    // A fit explaining less than half its footprint is admitted on the gate's
    // say-so alone; weight its bits by how far below that it sits.
    let bits_factor = (0.5 / fit.explained() as f32).max(1.0).powi(2);
    Some(Candidate {
        alts,
        bits_factor,
        dot: false,
    })
}

/// Economical representations for a long continuation: six color coefficients
/// on the dense geometry, then curve-aware sparse geometries with full, lean
/// and luma-only color. A continuation is faint and nearly straight; dense
/// points and full color alone price most of them out of the gate.
fn fit_extension(
    ctx: &EncodingContext,
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    chain: &Chain,
    scratch: &mut FitScratch,
) -> Option<Candidate> {
    let points = rdp_control_points(&chain.points);
    if points.len() < 2 || !inside(&points, w, h) {
        return None;
    }
    let predicted = SCALE_TO_SIGMA.0 * chain.scale + SCALE_TO_SIGMA.1;
    let mut widths = SIGMA_LATTICE;
    widths.sort_by(|&a, &b| {
        (a as f32 * sigma_step() - predicted)
            .abs()
            .total_cmp(&(b as f32 * sigma_step() - predicted).abs())
    });
    let mut best: Option<Fit> = None;
    for n in &widths[..SEEDED_WIDTHS] {
        if let Some(fit) = fit_at(
            targets,
            w,
            h,
            &points,
            *n,
            None,
            Precision::Compact,
            scratch,
        ) && best.as_ref().is_none_or(|b| fit.gain() > b.gain())
        {
            best = Some(fit);
        }
    }
    let fit = best?;
    // The original block pre-test remains the decision about coding value.
    // Broad residual support can depress the explained fraction of a faint line.
    let spline = quantize(&points, &fit);
    let mut alts = Vec::new();
    if spline.dct[..3].iter().flatten().any(|&v| v != 0) {
        alts.push(spline);
    }
    let at = SIGMA_LATTICE
        .iter()
        .position(|&n| n == fit.sigma_n)
        .unwrap_or(0);
    let nearby = &SIGMA_LATTICE[at.saturating_sub(1)..(at + 2).min(SIGMA_LATTICE.len())];
    let lean = ((chain.points.len() as f32 / LEAN_ARC_PER_COEFF + 0.5) as usize).max(1);
    for tol in CURVE_TOLERANCES {
        let sparse = curve_control_points(ctx, &chain.points, tol, MAX_CURVE_POINTS);
        if sparse.len() < 2 || sparse.len() >= points.len() {
            continue;
        }
        let sparse = refine_geometric(ctx, &sparse, &chain.points, 2);
        if !inside(&sparse, w, h) || sparse.array_windows::<2>().any(|p| p[0] == p[1]) {
            continue;
        }
        for free in [Some((1, lean, 1)), Some((0, lean, 0))] {
            let mut best: Option<Fit> = None;
            for &n in nearby {
                if let Some(fit) =
                    fit_at(targets, w, h, &sparse, n, free, Precision::Compact, scratch)
                    && best.as_ref().is_none_or(|b| fit.gain() > b.gain())
                {
                    best = Some(fit);
                }
            }
            let Some(fit) = best else { continue };
            let mut spline = quantize(&sparse, &fit);
            if matches!(free, Some((0, _, 0))) {
                spline.dct[0] = [0; 32];
                spline.dct[2] = [0; 32];
            }
            if spline.dct[1].iter().any(|&v| v != 0)
                && !alts
                    .iter()
                    .any(|a| a.points == spline.points && a.dct == spline.dct)
            {
                alts.push(spline);
            }
        }
    }
    (!alts.is_empty()).then_some(Candidate {
        alts,
        bits_factor: 1.0,
        dot: false,
    })
}

/// Lean luma-only alternatives for a long straight line. Coding value is left
/// to the RD tests: a faint line's explained fraction is dominated by grain.
fn fit_long_line(
    ctx: &EncodingContext,
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    chain: &Chain,
    scratch: &mut FitScratch,
) -> Option<Candidate> {
    let spacing = LONG_LINE_MIN_SPACING.max(chain.points.len() as f32 / LONG_LINE_SPANS);
    let points = uniform_control_points(&chain.points, spacing);
    if points.len() < 2 || !inside(&points, w, h) {
        return None;
    }
    let points = refine_geometric(ctx, &points, &chain.points, 2);
    if !inside(&points, w, h) || points.array_windows::<2>().any(|p| p[0] == p[1]) {
        return None;
    }
    let predicted = SCALE_TO_SIGMA.0 * chain.scale + SCALE_TO_SIGMA.1;
    let mut widths = LONG_LINE_WIDTHS;
    widths.sort_by(|&a, &b| {
        (a as f32 * sigma_step() - predicted)
            .abs()
            .total_cmp(&(b as f32 * sigma_step() - predicted).abs())
    });
    // Geometry and width determine the system; coefficient budgets only solve it.
    let systems: Vec<FitSystem> = widths[..LONG_LINE_SEEDED_WIDTHS]
        .iter()
        .filter_map(|&n| fit_system(targets, w, h, &points, n, Precision::Compact, scratch))
        .collect();
    let mut alts: Vec<QuantizedSpline> = Vec::new();
    for k in 1..=LONG_LINE_MAX_COEFFS {
        let mut best: Option<Fit> = None;
        for system in &systems {
            let fit = system.solve(Some((0, k, 0)));
            if best.as_ref().is_none_or(|b| fit.gain() > b.gain()) {
                best = Some(fit);
            }
        }
        let Some(fit) = best else { continue };
        let mut spline = quantize(&points, &fit);
        spline.dct[0] = [0; 32];
        spline.dct[2] = [0; 32];
        if spline.dct[1].iter().any(|&v| v != 0) && !alts.iter().any(|a| a.dct == spline.dct) {
            alts.push(spline);
        }
    }
    (!alts.is_empty()).then_some(Candidate {
        alts,
        bits_factor: LONG_LINE_BITS_FACTOR,
        dot: false,
    })
}

/// Fit a well-supported join as a single straight, colored spline. These
/// candidates precede fragments so the greedy gate can buy the complete line
/// once. The lean luma-only fallback still handles faint, interrupted lines.
fn fit_joined_line(
    ctx: &EncodingContext,
    targets: &[Vec<f32>; 3],
    w: usize,
    h: usize,
    chain: &Chain,
    scratch: &mut FitScratch,
) -> Option<Candidate> {
    let points = curve_control_points(ctx, &chain.points, JOINED_LINE_TOLERANCE, 2);
    if points.len() != 2 || !inside(&points, w, h) {
        return None;
    }
    let mut alts: Vec<QuantizedSpline> = Vec::new();
    // Include the narrowest width: fine grids can be thinner than the faint
    // lines handled by LONG_LINE_WIDTHS. Share each system across budgets.
    for &n in &SIGMA_LATTICE[..6] {
        let Some(system) = fit_system(targets, w, h, &points, n, Precision::Compact, scratch)
        else {
            continue;
        };
        for k in [1, REFINE_COEFFS, COMPACT_COEFFS] {
            let fit = system.solve(Some((k, k, k)));
            if fit.explained() < MIN_EXPLAINED {
                continue;
            }
            let spline = quantize(&points, &fit);
            // Different coefficient budgets often quantize to the same
            // spline. Keep the first occurrence, preserving RD tie order.
            // All alternatives here share the same two control points.
            if spline.dct[1].iter().any(|&v| v != 0)
                && !alts.iter().any(|alt| alt.dct == spline.dct)
            {
                alts.push(spline);
            }
        }
    }
    (!alts.is_empty()).then_some(Candidate {
        alts,
        bits_factor: LONG_LINE_BITS_FACTOR,
        dot: false,
    })
}

pub(super) fn fit_candidates(
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
    distance: f32,
    xyb: &Image3F,
    quant_field: &[f32],
    chains: &[Chain],
    extensions: &[Chain],
    long_lines: &super::lines::LongLines,
) -> Vec<Candidate> {
    let (w, h) = (xyb.xsize(), xyb.ysize());
    let targets = line_targets(ctx, scratch, xyb, chains);
    let targets = &targets;
    let model = BlockModel::new(ctx, distance);
    let model = &model;
    ctx.thread_pool
        .steal_map(
            scratch,
            long_lines.joined.len() + chains.len() + extensions.len() + long_lines.chains.len(),
            |i, worker| {
                let fit_scratch = &mut worker.spline_fit;
                let result = (|| {
                    if i < long_lines.joined.len() {
                        let line = &long_lines.chains[long_lines.joined[i]];
                        let candidate = fit_joined_line(ctx, targets, w, h, line, fit_scratch)?;
                        return candidate
                            .alts
                            .iter()
                            .any(|alt| pretest(model, xyb, quant_field, alt))
                            .then_some(candidate);
                    }
                    let i = i - long_lines.joined.len();
                    // Lean stand-ins still come last, after the colored and
                    // curved candidates and the well-supported straight joins.
                    if i >= chains.len() + extensions.len() {
                        let line = &long_lines.chains[i - chains.len() - extensions.len()];
                        let candidate = fit_long_line(ctx, targets, w, h, line, fit_scratch)?;
                        return candidate
                            .alts
                            .iter()
                            .any(|alt| pretest(model, xyb, quant_field, alt))
                            .then_some(candidate);
                    }
                    if i >= chains.len() {
                        let candidate = fit_extension(
                            ctx,
                            targets,
                            w,
                            h,
                            &extensions[i - chains.len()],
                            fit_scratch,
                        )?;
                        return candidate
                            .alts
                            .iter()
                            .any(|alt| pretest(model, xyb, quant_field, alt))
                            .then_some(candidate);
                    }
                    let primary = quick_primary(ctx, targets, w, h, &chains[i], fit_scratch)?;
                    if !pretest(model, xyb, quant_field, &primary.spline) {
                        return None;
                    }
                    expand(ctx, targets, xyb, w, h, &chains[i], primary, fit_scratch)
                })();
                fit_scratch.trim();
                result
            },
        )
        .into_iter()
        .flatten()
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn refinement_compares_gain_over_different_pixel_supports() {
        let ctx = EncodingContext::default();
        let (w, h) = (128, 96);
        let points = vec![Point::new(16, 48), Point::new(112, 48)];
        let mut truth = QuantizedSpline {
            points: points.clone(),
            dct: [[0; 32]; 4],
        };
        truth.dct[1][0] = 10;
        truth.dct[3][0] = 6;
        let mut image = Image3F::new(w, h);
        super::super::render_spline(&ctx, &truth, QUANT_ADJUST, &mut image, 1.0);
        let mut targets = std::array::from_fn(|c| image.plane_data(c).to_vec());
        // Unrelated detail enters the wider fit's support. Its raw residual
        // error grows even though that width removes more of the actual line.
        for x in 16..113 {
            targets[1][55 * w + x] += 0.1;
        }
        let mut scratch = FitScratch::default();
        let initial = fit_at(
            &targets,
            w,
            h,
            &points,
            5,
            None,
            Precision::Full,
            &mut scratch,
        )
        .unwrap();
        let wider = fit_at(
            &targets,
            w,
            h,
            &points,
            6,
            None,
            Precision::Full,
            &mut scratch,
        )
        .unwrap();
        assert!(wider.err > initial.err);
        assert!(wider.gain() > initial.gain());
        assert!(initial.explained() > REFINE_MIN_EXPLAINED);
        let primary = Primary {
            spline: quantize(&points, &initial),
            points,
            fit: initial,
        };
        let chain = Chain {
            points: (16..=112).map(|x| Point::new(x as f32, 48.0)).collect(),
            scale: 1.5,
        };
        let candidate =
            expand(&ctx, &targets, &image, w, h, &chain, primary, &mut scratch).unwrap();
        assert_eq!(candidate.alts[0].dct[3][0], truth.dct[3][0]);
    }

    #[test]
    fn two_point_budget_preserves_acceptance_at_rounding_boundaries() {
        let ctx = EncodingContext::default();
        let (mut accepted, mut rejected) = (0, 0);
        for length in [2, 20, 120] {
            for origin in [0.499_999_97, 0.5, 0.500_000_06, 1_048_576.0] {
                for amplitude in [0.0, 0.1, 0.7, 1.5, 6.0] {
                    for step in [0.03, 0.65, 1.0] {
                        let chain: Vec<_> = (0..length)
                            .map(|i| {
                                let x = i as f32 * step;
                                Point::new(
                                    origin + x,
                                    origin + 0.2 * x + amplitude * (x * 0.1).sin(),
                                )
                            })
                            .collect();
                        for tol in [
                            JOINED_LINE_TOLERANCE.next_down(),
                            JOINED_LINE_TOLERANCE,
                            JOINED_LINE_TOLERANCE.next_up(),
                        ] {
                            let reference =
                                curve_control_points(&ctx, &chain, tol, MAX_CURVE_POINTS);
                            let limited = curve_control_points(&ctx, &chain, tol, 2);
                            if reference.len() <= 2 {
                                assert_eq!(limited, reference);
                                accepted += 1;
                            } else {
                                assert!(limited.len() > 2);
                                rejected += 1;
                            }
                        }
                    }
                }
            }
        }
        assert!(accepted > 0 && rejected > 0);
    }

    #[test]
    fn joined_line_fit_preserves_color_and_rejects_bends() {
        let ctx = EncodingContext::default();
        let (w, h) = (256, 96);
        let targets = [0.012f32, -0.35, -0.15].map(|color| {
            (0..w * h)
                .map(|i| {
                    if (16..240).contains(&(i % w)) {
                        let d = (i / w) as f32 - 48.0;
                        color * (-0.5 * (d / 0.6).powi(2)).exp()
                    } else {
                        0.0
                    }
                })
                .collect()
        });
        let mut chain = Chain {
            points: (16..240).map(|x| Point::new(x as f32, 48.0)).collect(),
            scale: 0.7,
        };
        let mut scratch = FitScratch::default();
        let fit = fit_joined_line(&ctx, &targets, w, h, &chain, &mut scratch).unwrap();
        assert!(fit.alts.iter().all(|s| s.points.len() == 2));
        assert!(
            fit.alts
                .iter()
                .enumerate()
                .all(|(i, s)| { fit.alts[..i].iter().all(|earlier| earlier.dct != s.dct) })
        );
        assert!(
            fit.alts
                .iter()
                .any(|s| { s.dct[0].iter().any(|&c| c != 0) && s.dct[2].iter().any(|&c| c != 0) })
        );
        for p in &mut chain.points {
            p.y += 8.0 * ((p.x - 16.0) * std::f32::consts::PI / 223.0).sin();
        }
        assert!(fit_joined_line(&ctx, &targets, w, h, &chain, &mut scratch).is_none());
    }

    #[test]
    fn common_coefficient_kernels_match_dynamic_accumulation() {
        let (w, h) = (93, 67);
        let targets = std::array::from_fn(|c| {
            (0..w * h)
                .map(|i| ((i * 19 + c * 31) % 101) as f32 * 0.003 - 0.15)
                .collect::<Vec<_>>()
        });
        let points = [Point::new(2, 4), Point::new(33, 53), Point::new(88, 58)];
        let mut scratch = FitScratch::default();
        for precision in [Precision::Probe, Precision::Compact] {
            for sigma_n in SIGMA_LATTICE {
                let fixed =
                    fit_system(&targets, w, h, &points, sigma_n, precision, &mut scratch).unwrap();
                let coeffs = if precision == Precision::Probe {
                    REFINE_COEFFS
                } else {
                    COMPACT_COEFFS
                };
                assert_eq!(fixed.coeffs, coeffs);
                let sigma = sigma_n as f32 * sigma_step();
                let reach = if precision == Precision::Probe {
                    (2.6 * sigma + 1.0).ceil()
                } else {
                    (3.6 * sigma + 1.5).ceil()
                } as isize;
                let table = scratch.weight_table(sigma_n, sigma, reach);
                let dynamic = raster_system::<0>(
                    &targets,
                    w,
                    h,
                    sigma_n,
                    sigma,
                    reach,
                    coeffs,
                    table,
                    &mut scratch,
                )
                .unwrap();
                assert_eq!(fixed.ata, dynamic.ata);
                assert_eq!(fixed.atb, dynamic.atb);
                assert_eq!(fixed.btb, dynamic.btb);
            }
        }
    }

    #[test]
    fn cached_geometry_and_widths_do_not_reuse_image_terms() {
        let (w, h) = (91, 63);
        let mut targets = std::array::from_fn(|c| {
            (0..w * h)
                .map(|i| ((i * 19 + c * 31) % 101) as f32 * 0.003)
                .collect::<Vec<_>>()
        });
        let shapes = [
            vec![Point::new(2, 4), Point::new(33, 53), Point::new(88, 58)],
            vec![Point::new(4, 60), Point::new(49, 17), Point::new(89, 3)],
        ];
        let mut reused = FitScratch::default();
        for (shape, width, precision) in [
            (0, 1, Precision::Full),
            (0, 6, Precision::Full),
            (0, 6, Precision::Compact),
            (1, 4, Precision::Probe),
            (1, 4, Precision::Full),
            (0, 1, Precision::Full),
        ] {
            let cached = fit_system(
                &targets,
                w,
                h,
                &shapes[shape],
                width,
                precision,
                &mut reused,
            )
            .unwrap();
            let fresh = fit_system(
                &targets,
                w,
                h,
                &shapes[shape],
                width,
                precision,
                &mut FitScratch::default(),
            )
            .unwrap();
            assert_eq!(cached.ata, fresh.ata);
            assert_eq!(cached.atb, fresh.atb);
            assert_eq!(cached.btb, fresh.btb);
            assert_eq!(cached.arc, fresh.arc);
            for plane in &mut targets {
                for v in plane {
                    *v *= 0.75;
                }
            }
        }
    }

    #[test]
    fn pair_collapse_relocates_controls_to_preserve_a_bend() {
        let kernels = crate::encoding_context::EncodingContext::default();
        let points: Vec<_> = (0..=8)
            .map(|i| {
                let a = i as f32 * std::f32::consts::FRAC_PI_2 / 8.0;
                Point::new(
                    round_i32(32.0 + 100.0 * a.sin()),
                    round_i32(32.0 + 100.0 * (1.0 - a.cos())),
                )
            })
            .collect();
        let reference =
            super::super::catmull_rom(&points.iter().map(|p| p.as_f32()).collect::<Vec<_>>());
        let error = |points: &[Point<i32>]| {
            let curve =
                super::super::catmull_rom(&points.iter().map(|p| p.as_f32()).collect::<Vec<_>>());
            curve
                .iter()
                .map(|&p| distance_sq_to_chain(p, &reference))
                .sum::<f32>()
                / curve.len() as f32
                + reference
                    .iter()
                    .map(|&p| distance_sq_to_chain(p, &curve))
                    .sum::<f32>()
                    / reference.len() as f32
        };
        let mut relocated = false;
        for i in 1..points.len() - 2 {
            let reduced = collapse_control_pair(&kernels, &points, i).unwrap();
            assert_eq!(reduced.len(), points.len() - 1);
            assert_eq!(reduced.first(), points.first());
            assert_eq!(reduced.last(), points.last());
            assert!(reduced.array_windows::<2>().all(|p| p[0] != p[1]));
            let mut left = points.clone();
            left.remove(i);
            let mut right = points.clone();
            right.remove(i + 1);
            relocated |= reduced[i] != points[i]
                && reduced[i] != points[i + 1]
                && error(&reduced) < error(&left).min(error(&right));
        }
        assert!(
            relocated,
            "merging should improve on merely deleting either old knot"
        );
        assert!(collapse_control_pair(&kernels, &points, 0).is_none());
        assert!(collapse_control_pair(&kernels, &points, points.len() - 2).is_none());
        assert!(collapse_control_pair(&kernels, &points[..3], 1).is_none());
    }

    #[test]
    fn pruning_keeps_curve_shape_and_collapses_straight_spans() {
        let kernels = crate::encoding_context::EncodingContext::default();
        let straight: Vec<_> = (0..12)
            .map(|i| Point::new(20 + i * 8, 40 + i * 4))
            .collect();
        assert_eq!(
            prune_control_points(&kernels, &straight, 0.5),
            [straight[0], straight[11]]
        );
        let chain: Vec<_> = (0..=160)
            .map(|i| {
                let t = i as f32 / 90.0;
                Point::new(30.0 + 90.0 * t.sin(), 40.0 + 90.0 * (1.0 - t.cos()))
            })
            .collect();
        let dense = rdp_control_points(&chain);
        let sparse = prune_control_points(&kernels, &dense, 0.5);
        assert!(sparse.len() < dense.len());
        assert_eq!(sparse.first(), dense.first());
        assert_eq!(sparse.last(), dense.last());
        let a = super::super::catmull_rom(&dense.iter().map(|p| p.as_f32()).collect::<Vec<_>>());
        let b = super::super::catmull_rom(&sparse.iter().map(|p| p.as_f32()).collect::<Vec<_>>());
        for (&point, other) in a
            .iter()
            .map(|p| (p, b.as_slice()))
            .chain(b.iter().map(|p| (p, a.as_slice())))
        {
            assert!(distance_sq_to_chain(point, other) <= 0.501 * 0.501);
        }
    }

    #[test]
    fn residual_fit_leaves_affine_background_in_vardct() {
        let kernels = crate::encoding_context::EncodingContext::default();
        let (w, h) = (96, 64);
        let points = vec![Point::new(16, 30), Point::new(48, 34), Point::new(80, 30)];
        let mut line = QuantizedSpline {
            points: points.clone(),
            dct: [[0; 32]; 4],
        };
        line.dct[0][0] = 3;
        line.dct[1][0] = 5;
        line.dct[2][0] = -2;
        line.dct[3][0] = 4;
        let mut image = Image3F::new(w, h);
        super::super::render_spline(&kernels, &line, QUANT_ADJUST, &mut image, 1.0);
        let targets = std::array::from_fn(|c| image.plane_data(c).to_vec());
        let mut scratch = FitScratch::default();
        let system = fit_system(&targets, w, h, &points, 4, Precision::Full, &mut scratch).unwrap();
        let bare = system.residual_system(&image, &scratch).solve(None);
        for c in 0..3 {
            for y in 0..h {
                for (x, v) in image.plane_row_mut(c, y).iter_mut().enumerate() {
                    *v += 0.2 + c as f32 * 0.03 + 0.001 * x as f32 - 0.002 * y as f32;
                }
            }
        }
        let pedestal = system.residual_system(&image, &scratch).solve(None);
        for (a, b) in bare.sol.iter().flatten().zip(pedestal.sol.iter().flatten()) {
            assert!((a - b).abs() < 1e-6, "{a} != {b}");
        }
        assert_eq!(quantize(&points, &bare).dct, line.dct);
        assert_eq!(quantize(&points, &pedestal).dct, line.dct);
    }

    #[test]
    fn curve_aware_control_points_follow_a_bend_with_fewer_points() {
        let kernels = crate::encoding_context::EncodingContext::default();
        // a quarter circle of radius 120 px, traced at about 1 px steps
        let chain: Vec<Point<f32>> = (0..=188)
            .map(|k| {
                let a = k as f32 / 120.0;
                Point::new(40.0 + 120.0 * a.sin(), 160.0 - 120.0 * a.cos())
            })
            .collect();
        let sparse = curve_control_points(&kernels, &chain, 1.0, MAX_CURVE_POINTS);
        let dense = rdp_control_points(&chain);
        assert!(
            sparse.len() >= 2 && sparse.len() < dense.len(),
            "{} vs {}",
            sparse.len(),
            dense.len()
        );
        let control: Vec<Point<f32>> = sparse.iter().map(|p| p.as_f32()).collect();
        let curve = crate::splines::catmull_rom(&control);
        for &p in &chain[4..chain.len() - 4] {
            assert!(distance_sq_to_chain(p, &curve) <= 1.6 * 1.6);
        }
        assert!(sparse.array_windows::<2>().all(|p| p[0] != p[1]));
    }

    #[test]
    fn compact_fit_matches_full_support_with_six_free_coefficients() {
        let (w, h) = (256, 128);
        let targets = std::array::from_fn(|c| {
            (0..w * h)
                .map(|i| {
                    let (x, y) = ((i % w) as f32, (i / w) as f32);
                    let a = [0.002, 0.08, 0.07][c] * (1.0 + 0.2 * (x * 0.03).sin());
                    a * (-0.5 * ((y - 64.0) / 1.2).powi(2)).exp()
                        + 0.0001 * (x * 0.1 + y * 0.2).cos()
                })
                .collect()
        });
        let points = [Point::new(20, 64), Point::new(220, 64)];
        let mut scratch = FitScratch::default();
        let full = fit_at(
            &targets,
            w,
            h,
            &points,
            2,
            Some((6, 6, 6)),
            Precision::Full,
            &mut scratch,
        )
        .unwrap();
        let compact = fit_at(
            &targets,
            w,
            h,
            &points,
            2,
            None,
            Precision::Compact,
            &mut scratch,
        )
        .unwrap();
        assert!(full.coeffs > 6);
        assert_eq!(compact.coeffs, 6);
        assert_eq!(full.sol, compact.sol);
        assert_eq!(full.e0, compact.e0);
        assert!((full.err - compact.err).abs() < 1e-9);
    }

    #[test]
    fn cholesky_recovers_known_solution_for_each_leading_size() {
        let ata = std::array::from_fn(|i| std::array::from_fn(|j| if i == j { 40.0 } else { 1.0 }));
        let expected: [f64; MAX_COEFFS] = std::array::from_fn(|i| (i as f64 - 15.0) * 0.125);
        for k in 0..=MAX_COEFFS {
            let rhs = std::array::from_fn(|i| {
                ata[i][..k]
                    .iter()
                    .zip(&expected)
                    .map(|(&a, &x)| a * x)
                    .sum()
            });
            let mut actual = [1.0; MAX_COEFFS];
            solve_leading(&ata, k, &rhs, &mut actual);
            for (&actual, &expected) in actual[..k].iter().zip(&expected) {
                assert!((actual - expected).abs() < 1e-9, "k={k}");
            }
            assert!(actual[k..].iter().all(|&v| v == 0.0));
        }
    }

    #[test]
    fn signed_coefficients_round_away_from_zero_at_ties() {
        for value in [
            -1024.5, -2.75, -1.5, -0.5, -0.25, 0.0, 0.25, 0.5, 1.5, 2.75, 1024.5,
        ] {
            assert_eq!(quantized_coefficient(value), value.round() as i32);
        }
        for value in [0.5f64.next_down(), 0.5, 0.5f64.next_up(), i32::MAX as f64] {
            for value in [value, -value] {
                assert_eq!(quantized_coefficient(value), value.round() as i32);
            }
        }
    }
}