1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
//! Immediate-mode 2D drawing over the 3D view — p5's `rect`, `circle`, `line`
//! and `text`, for HUDs, labels, axes, plots and debug read-outs.
//!
//! Every project reaches this point: the render is right and now something has
//! to be written on top of it. The frame counter, the name of the thing under
//! the cursor, a legend for the colour ramp, a box around the selection. None
//! of that is 3D, and doing it in 3D — a textured quad per glyph, billboarded,
//! depth-disabled, re-uploaded when the string changes — is a disproportionate
//! amount of machinery for a line of text.
//!
//! So this is a CPU canvas of straight RGBA8 that
//! [`Renderer::draw_overlay`](crate::Renderer::draw_overlay) composites over an
//! already-rendered frame, uploading only the rows that changed.
//! [`crate::sketch`] wires it up for you — clear, draw, composite, once per
//! frame.
//!
//! ```
//! use threers::overlay::Overlay;
//! use threers::prelude::*;
//!
//! let mut o = Overlay::new(320, 200);
//! o.fill_alpha(Color::BLACK, 0.5);
//! o.rect(8.0, 8.0, 140.0, 48.0);
//! o.no_fill();
//! o.stroke(Color::from_hex(0x33ff99));
//! o.stroke_weight(2.0);
//! o.circle(80.0, 120.0, 30.0);
//! o.line(8.0, 190.0, 312.0, 190.0);
//! assert!(o.touched());
//! assert_eq!(o.pixels().len(), 320 * 200 * 4);
//! ```
//!
//! # State, not arguments
//!
//! `fill`/`stroke`/`stroke_weight` are sticky, the way p5's are, so a run of
//! shapes in one style is a run of one-line calls. The alternative — colour and
//! width on every call — reads worse at the call site for the common case of
//! drawing twenty things the same way.
//!
//! # Two things it gets right that are easy to get wrong
//!
//! Edges are anti-aliased from a signed distance field rather than sampled:
//! each primitive is one distance function, coverage is `0.5 - d` clamped, and
//! every shape goes through the same rasteriser. One path to get right, and no
//! supersampling cost.
//!
//! Compositing happens in linear light. [`Color`] holds linear values and the
//! buffer holds sRGB bytes — what the GPU pass wants — so overlapping shapes
//! decode, mix and re-encode. Blending coverage in sRGB directly is the classic
//! source of dark fringes on anti-aliased edges and of muddy half-transparent
//! fills.
use crate::math::{Color, Vector2};
use crate::sdf::{self, d2};
/// The error function, to about 5e-4: Wallace's approximation, which the
/// GPU UI pass uses too.
pub(crate) fn erf_approx(x: f32) -> f32 {
let (s, a) = (x.signum(), x.abs());
let t = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
let t = t * t;
s - s / (t * t)
}
/// How much of a box shadow covers `point`: the rounded box `(x0, y0, x1,
/// y1)` with corner `radius`, blurred by `sigma`. Wallace's closed form; see
/// [`Overlay::shadow`].
pub(crate) fn shadow_coverage(
b: (f32, f32, f32, f32),
point: (f32, f32),
sigma: f32,
radius: f32,
) -> f32 {
let (cx, cy) = ((b.0 + b.2) * 0.5, (b.1 + b.3) * 0.5);
let (hx, hy) = ((b.2 - b.0) * 0.5, (b.3 - b.1) * 0.5);
let corner = radius.clamp(0.0, hx.min(hy));
let (px, py) = (point.0 - cx, point.1 - cy);
let gaussian = |v: f32| (-(v * v) / (2.0 * sigma * sigma)).exp() / (2.506_628_3 * sigma);
let row = |x: f32, y: f32| {
let delta = (hy - corner - y.abs()).min(0.0);
let curved = hx - corner + (corner * corner - delta * delta).max(0.0).sqrt();
let k = std::f32::consts::FRAC_1_SQRT_2 / sigma;
let lo = 0.5 + 0.5 * erf_approx((x - curved) * k);
let hi = 0.5 + 0.5 * erf_approx((x + curved) * k);
hi - lo
};
let (low, high) = (py - hy, py + hy);
let start = (-3.0 * sigma).clamp(low, high);
let end = (3.0 * sigma).clamp(low, high);
let step = (end - start) / 4.0;
let mut v = start + step * 0.5;
let mut sum = 0.0;
for _ in 0..4 {
sum += row(px, py - v) * gaussian(v) * step;
v += step;
}
sum.clamp(0.0, 1.0)
}
/// Distance from `(px, py)` to the wave `y + a·sin(k (x − x0))`, to first
/// order: the vertical gap over the curve's slope.
pub(crate) fn wave_distance(px: f32, py: f32, x0: f32, y: f32, a: f32, k: f32) -> f32 {
let t = k * (px - x0);
let dy = py - (y + a * t.sin());
let slope = a * k * t.cos();
dy.abs() / (1.0 + slope * slope).sqrt()
}
/// Distance to a wave between `x0` and `x1`, capped round at its ends.
fn wave_centre(px: f32, py: f32, x0: f32, x1: f32, y: f32, a: f32, k: f32) -> f32 {
let x = px.clamp(x0, x1);
wave_distance(x, py, x0, y, a, k) + (px - x).abs()
}
/// How much of the pixel centred at `(px, py)` a wave stroke `half` either
/// side covers, by the rule strokes use ([`sdf::coverage_stroke`] over the
/// pixel's footprint). The GPU UI pass computes the same.
#[allow(clippy::too_many_arguments)]
pub(crate) fn wave_coverage(
px: f32,
py: f32,
x0: f32,
x1: f32,
y: f32,
a: f32,
k: f32,
half: f32,
) -> f32 {
const BAND: f32 = std::f32::consts::FRAC_1_SQRT_2;
let f = |x: f32, y2: f32| wave_centre(x, y2, x0, x1, y, a, k) - half;
let d = f(px, py);
if d >= BAND {
return 0.0;
}
if d <= -BAND {
return 1.0;
}
let e = 0.5;
let gx = ((f(px + e, py) - d) / e)
.abs()
.max(((d - f(px - e, py)) / e).abs());
let gy = ((f(px, py + e) - d) / e)
.abs()
.max(((d - f(px, py - e)) / e).abs());
let w = sdf::footprint(Vector2::new(gx, gy));
sdf::coverage_stroke(d + half, half, w)
}
/// sRGB-encoded byte to linear float, for the 256 values a byte can hold.
fn srgb_decode_table() -> &'static [f32; 256] {
static TABLE: std::sync::OnceLock<[f32; 256]> = std::sync::OnceLock::new();
TABLE.get_or_init(|| {
let mut t = [0.0f32; 256];
for (i, v) in t.iter_mut().enumerate() {
let s = i as f32 / 255.0;
*v = if s <= 0.040_45 {
s / 12.92
} else {
((s + 0.055) / 1.055).powf(2.4)
};
}
t
})
}
/// Linear float to an sRGB-encoded byte, the same curve [`Color::to_hex`] uses.
///
/// By table rather than by `powf`, and *exactly* rather than approximately. The
/// answer is one of 256 bytes, so the question is not "what is the encoded
/// value" but "which byte does this round to" — and that is answered by the 255
/// linear values where the rounding changes over. Byte `b` is chosen when `v`
/// reaches `decode((b - 0.5) / 255)`; the thresholds rise, so finding `b` is a
/// search and not a transcendental function.
///
/// Worth the trouble because it is the inner loop of every overlapping shape —
/// a panel with text on it encodes three channels per pixel — and it measures
/// 2.29 ns a call against 6.00 ns for the curve
/// (`cargo test --release overlay::tests::the_encode_table_is_faster -- --ignored
/// --nocapture`). End to end the gain is smaller than that ratio suggests,
/// because the encode interleaves with the loads and stores around it rather
/// than serialising; two overlapping full-viewport fills measure ~9 ms either
/// way on a loaded machine, so this is a faster function and not a measured
/// frame-time win.
fn srgb_encode(v: f32) -> u8 {
let thresholds = srgb_encode_thresholds();
let v = v.clamp(0.0, 1.0);
// Branchless binary search: eight steps, each committing one bit of the
// largest index whose threshold `v` has reached. `b` ends at 255 at most,
// so `probe` is always in range.
let mut b = 0usize;
let mut step = 128usize;
while step > 0 {
let probe = b + step;
if v >= thresholds[probe] {
b = probe;
}
step >>= 1;
}
b as u8
}
/// Linear to encoded byte by the curve itself. The table above is built from
/// this and replaces it everywhere else.
fn srgb_encode_by_curve(v: f32) -> u8 {
let v = v.clamp(0.0, 1.0);
let s = if v <= 0.003_130_8 {
v * 12.92
} else {
1.055 * v.powf(1.0 / 2.4) - 0.055
};
(s * 255.0 + 0.5) as u8
}
/// The linear value at which the encoded byte becomes `b`, for each `b`.
/// `[0]` is zero so the search always has somewhere to start.
///
/// Each threshold is the *smallest `f32`* the curve encodes to `b` or above,
/// found by bisecting the curve over the bit patterns of `0.0..=1.0` — which
/// are ordered for non-negative floats, so bisecting them walks representable
/// values rather than a real interval. Inverting the formula analytically
/// instead, `decode((b - 0.5) / 255)`, is the obvious way and lands on the
/// wrong side of 14 of the 255 switchover points: the midpoint between two
/// bytes is exactly where `f32` rounding decides the answer, so the only way to
/// agree with the curve there is to ask it.
///
/// Built once, lazily, from about seven thousand `powf` calls.
fn srgb_encode_thresholds() -> &'static [f32; 256] {
static TABLE: std::sync::OnceLock<[f32; 256]> = std::sync::OnceLock::new();
TABLE.get_or_init(|| {
let mut t = [0.0f32; 256];
for (b, v) in t.iter_mut().enumerate().skip(1) {
let (mut lo, mut hi) = (0u32, 1.0f32.to_bits());
while lo < hi {
let mid = lo + (hi - lo) / 2;
if srgb_encode_by_curve(f32::from_bits(mid)) as usize >= b {
hi = mid;
} else {
lo = mid + 1;
}
}
*v = f32::from_bits(lo);
}
t
})
}
/// A colour resolved for painting: linear for mixing, encoded for the fast
/// path, and an alpha.
#[derive(Debug, Clone, Copy)]
struct Paint {
linear: [f32; 3],
encoded: [u8; 3],
alpha: f32,
}
impl Paint {
fn new(color: Color, alpha: f32) -> Self {
Self {
linear: [color.r, color.g, color.b],
encoded: [
srgb_encode(color.r),
srgb_encode(color.g),
srgb_encode(color.b),
],
alpha: alpha.clamp(0.0, 1.0),
}
}
}
/// A 2D canvas drawn on the CPU and composited over a rendered frame.
///
/// Coordinates are pixels from the top-left, matching the pointer position in
/// [`sketch::Frame`](crate::sketch::Frame) so a cursor read-out needs no
/// conversion. Fractional coordinates are honoured — edges are anti-aliased, so
/// a rectangle at `x = 10.5` lands half a pixel over.
pub struct Overlay {
width: u32,
height: u32,
/// Straight (non-premultiplied) sRGB-encoded RGBA8, row-major from the
/// top-left — exactly what the compositing pass uploads.
pixels: Vec<u8>,
fill: Option<Paint>,
stroke: Option<Paint>,
stroke_weight: f32,
text_size: f32,
/// Whether anything has been drawn since the last [`Overlay::clear`]. Lets
/// a caller skip the texture upload on a frame that drew nothing.
touched: bool,
/// Rows whose pixels differ from what the GPU was last given, as one band.
/// Cleared only by [`Overlay::mark_uploaded`], so skipping a frame's
/// composite does not lose track of what changed during it.
dirty: Bands,
/// Rows drawn on since the last [`Overlay::clear`] — which is the band the
/// GPU will hold ink in once this frame is uploaded, and therefore the band
/// the *next* clear has to mark dirty. Without it, erasing a panel would
/// leave it on screen: the CPU buffer goes to zero and nothing tells the
/// texture.
content: Bands,
#[cfg(feature = "captions")]
painter: Option<crate::captions::CaptionPainter>,
/// CSS weight for text (400 regular, 700 bold), and italic.
#[cfg(feature = "captions")]
text_weight: u16,
#[cfg(feature = "captions")]
text_italic: bool,
/// The painter's face in the other styles used, so switching back and
/// forth keeps each one's glyph cache.
#[cfg(feature = "captions")]
other_weights: std::collections::HashMap<(u16, bool), crate::captions::CaptionFont>,
}
impl Overlay {
/// A transparent canvas of `width × height` pixels.
pub fn new(width: u32, height: u32) -> Self {
let (width, height) = (width.max(1), height.max(1));
Self {
width,
height,
pixels: vec![0; width as usize * height as usize * 4],
fill: Some(Paint::new(Color::WHITE, 1.0)),
stroke: None,
stroke_weight: 1.0,
text_size: 16.0,
touched: false,
dirty: Bands::default(),
content: Bands::default(),
#[cfg(feature = "captions")]
painter: None,
#[cfg(feature = "captions")]
text_weight: 400,
#[cfg(feature = "captions")]
text_italic: false,
#[cfg(feature = "captions")]
other_weights: std::collections::HashMap::new(),
}
}
/// Resize, discarding the contents. A no-op if the size is unchanged, so
/// calling it every frame from a resize handler costs nothing.
pub fn resize(&mut self, width: u32, height: u32) {
let (width, height) = (width.max(1), height.max(1));
if width == self.width && height == self.height {
return;
}
self.width = width;
self.height = height;
self.pixels = vec![0; width as usize * height as usize * 4];
self.touched = false;
// A new size means a new texture on the other side, which is uploaded
// whole, so there is nothing outstanding to describe.
self.dirty = Bands::default();
self.content = Bands::default();
}
/// Erase everything back to transparent.
pub fn clear(&mut self) {
// Only the rows something was drawn on: every write marks its rows, so
// the rest are zero already. A HUD with a panel at the top and a map at
// the bottom then clears those, not the screen.
let stride = self.width as usize * 4;
for &(a, b) in &self.content.0 {
let (a, b) = (a.min(self.height) as usize, b.min(self.height) as usize);
self.pixels[a * stride..b * stride].fill(0);
}
self.touched = false;
// Rows that had ink have none now. The CPU buffer knows; the texture
// does not, so they stay dirty until something uploads the zeroes.
//
// `dirty` only — not through `mark_rows`, which would put them back
// into `content` as well. Doing that kept every row ever drawn on in
// `content` for the life of the overlay, so a band that touched the
// bottom of the canvas once stayed full height forever.
for (a, b) in std::mem::take(&mut self.content).0 {
self.dirty.add(a, b);
}
}
/// Rows that have changed since the last [`Overlay::mark_uploaded`], as a
/// half-open range, or `None` if the texture is already current.
///
/// One band rather than a set of rectangles: a read-out is one region, rows
/// are contiguous in the buffer so a band is a contiguous upload with no
/// stride to get wrong, and tracking anything finer costs more bookkeeping
/// than the upload it would save.
///
/// [`Renderer::draw_overlay`](crate::Renderer::draw_overlay) uses this and
/// calls [`mark_uploaded`](Overlay::mark_uploaded) itself, which is the
/// reason to prefer it over doing the two by hand.
pub fn dirty_rows(&self) -> Option<(u32, u32)> {
let first = self.dirty.0.first()?.0;
let end = self.dirty.0.last()?.1;
Some((first.min(self.height), end.min(self.height))).filter(|(a, b)| a < b)
}
/// The same rows as separate bands, top to bottom, with what lies between
/// them left out: a panel at the top and another at the bottom are two
/// small uploads rather than one of the whole screen. Bands closer than a
/// few rows are joined, as two uploads cost more than the rows between.
pub fn dirty_bands(&self) -> Vec<(u32, u32)> {
self.dirty
.0
.iter()
.map(|&(a, b)| (a.min(self.height), b.min(self.height)))
.filter(|(a, b)| a < b)
.collect()
}
/// Say that the texture now matches the buffer.
pub fn mark_uploaded(&mut self) {
self.dirty = Bands::default();
}
/// Record that `y0..y1` was drawn on: outstanding for the texture, and part
/// of this frame's ink.
fn mark_rows(&mut self, y0: u32, y1: u32) {
if y0 >= y1 {
return;
}
self.dirty.add(y0, y1);
self.content.add(y0, y1);
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
/// The raw buffer: straight-alpha sRGB RGBA8, row-major from the top-left.
///
/// For compositing, [`Renderer::draw_overlay`](crate::Renderer::draw_overlay)
/// takes the whole overlay and uploads only what changed;
/// [`draw_overlay_rgba8`](crate::Renderer::draw_overlay_rgba8) takes these
/// bytes and uploads all of them.
pub fn pixels(&self) -> &[u8] {
&self.pixels
}
/// Copy a `width × height` image — straight-alpha sRGB RGBA8, row-major
/// from the top-left, as [`pixels`](Self::pixels) — onto the canvas with
/// its top-left corner at `(x, y)`, replacing what is there rather than
/// blending, as a canvas's `putImageData` does. Clipped to the canvas.
/// A frame from a CPU renderer, presented on either backend through
/// `WindowRenderer::render_frame`.
///
/// # Panics
///
/// If `rgba` is shorter than `width × height × 4` bytes.
pub fn put_image_data(&mut self, x: i32, y: i32, width: u32, height: u32, rgba: &[u8]) {
assert!(
rgba.len() >= width as usize * height as usize * 4,
"put_image_data: too few bytes"
);
let x0 = x.max(0);
let x1 = (x + width as i32).min(self.width as i32);
let y0 = y.max(0);
let y1 = (y + height as i32).min(self.height as i32);
if x0 >= x1 || y0 >= y1 {
return;
}
let row = (x1 - x0) as usize * 4;
for dy in y0..y1 {
let src = ((dy - y) as usize * width as usize + (x0 - x) as usize) * 4;
let dst = (dy as usize * self.width as usize + x0 as usize) * 4;
self.pixels[dst..dst + row].copy_from_slice(&rgba[src..src + row]);
}
self.touched = true;
self.mark_rows(y0 as u32, y1 as u32);
}
/// Whether anything has been drawn since the last [`Overlay::clear`].
pub fn touched(&self) -> bool {
self.touched
}
/// Fill subsequent shapes with `color`, opaque.
pub fn fill(&mut self, color: Color) {
self.fill = Some(Paint::new(color, 1.0));
}
/// Fill subsequent shapes with `color` at `alpha` (`0.0`–`1.0`).
pub fn fill_alpha(&mut self, color: Color, alpha: f32) {
self.fill = Some(Paint::new(color, alpha));
}
/// Draw subsequent shapes unfilled.
pub fn no_fill(&mut self) {
self.fill = None;
}
/// Outline subsequent shapes in `color`, opaque.
pub fn stroke(&mut self, color: Color) {
self.stroke = Some(Paint::new(color, 1.0));
}
/// Outline subsequent shapes in `color` at `alpha` (`0.0`–`1.0`).
pub fn stroke_alpha(&mut self, color: Color, alpha: f32) {
self.stroke = Some(Paint::new(color, alpha));
}
/// Draw subsequent shapes without an outline.
pub fn no_stroke(&mut self) {
self.stroke = None;
}
/// Outline width in pixels, centred on the shape's edge.
pub fn stroke_weight(&mut self, pixels: f32) {
self.stroke_weight = pixels.max(0.0);
}
/// Draw text in `font` from now on, instead of the UI face
/// ([`CaptionFont::ui`](crate::captions::CaptionFont::ui): SF Compact on
/// macOS, the bitmap face elsewhere).
#[cfg(feature = "captions")]
pub fn set_font(&mut self, font: crate::captions::CaptionFont) {
self.painter = Some(crate::captions::CaptionPainter::with_font(font));
self.other_weights.clear();
}
/// CSS weight for text from now on — 400 regular, 700 bold.
///
/// Returns whether the face can draw it: a TrueType face always can —
/// a variable font (SF Compact, or any
/// [`CaptionFont::from_ttf_bytes`](crate::captions::CaptionFont::from_ttf_bytes)
/// of one) at that weight, a static one with a synthetic bold (see
/// [`CaptionFont::styled`](crate::captions::CaptionFont::styled)). The
/// bitmap face returns `false` for anything but 400, leaving the caller
/// to fake it if it must.
#[cfg(feature = "captions")]
pub fn text_weight(&mut self, weight: u16) -> bool {
self.text_weight = weight.clamp(1, 1000);
self.apply_text_style()
}
/// Italic text from now on, or upright: the family's italic where it
/// has one, else slanted. Returns whether the face can (not the bitmap
/// face).
#[cfg(feature = "captions")]
pub fn text_italic(&mut self, italic: bool) -> bool {
self.text_italic = italic;
self.apply_text_style()
}
/// Put the painter's face in the current weight and italic; whether it
/// got there.
#[cfg(feature = "captions")]
fn apply_text_style(&mut self) -> bool {
let want = (self.text_weight, self.text_italic);
let painter = self
.painter
.get_or_insert_with(crate::captions::CaptionPainter::new);
let Some(have) = painter.font.style() else {
return want == (400, false);
};
if have == want {
return true;
}
let next = match self.other_weights.remove(&want) {
Some(f) => f,
None => match painter.font.styled(want.0, want.1) {
Some(f) => f,
None => return false,
},
};
let previous = std::mem::replace(&mut painter.font, next);
self.other_weights.insert(have, previous);
true
}
/// Type size in pixels for [`Overlay::text`].
pub fn text_size(&mut self, pixels: f32) {
self.text_size = pixels.max(1.0);
}
/// An image — `image_width × image_height` RGBA8, sRGB-encoded, straight
/// alpha — scaled to the rectangle at `(x, y)`, `width × height`, at
/// `alpha`, and drawn only inside `clip` (`x0, y0, x1, y1`) when given.
///
/// Sampled bilinearly in linear light with premultiplied alpha, so a
/// transparent edge does not bleed its colour, and composited as the
/// shapes are. Its edges are anti-aliased as [`rect`](Self::rect)'s
/// are, so an image and a rectangle in the same box meet exactly. Fill
/// and stroke play no part.
#[allow(clippy::too_many_arguments)]
pub fn image(
&mut self,
x: f32,
y: f32,
width: f32,
height: f32,
rgba: &[u8],
image_width: u32,
image_height: u32,
alpha: f32,
clip: Option<(f32, f32, f32, f32)>,
) {
let (iw, ih) = (image_width as usize, image_height as usize);
if width <= 0.0
|| height <= 0.0
|| iw == 0
|| ih == 0
|| rgba.len() < iw * ih * 4
|| alpha <= 0.0
{
return;
}
let (cx0, cy0, cx1, cy1) =
clip.unwrap_or((0.0, 0.0, self.width as f32, self.height as f32));
let (x0, y0) = (x.max(cx0).max(0.0), y.max(cy0).max(0.0));
let (x1, y1) = (
(x + width).min(cx1).min(self.width as f32),
(y + height).min(cy1).min(self.height as f32),
);
if x1 <= x0 || y1 <= y0 {
return;
}
let table = srgb_decode_table();
// A texel, decoded and premultiplied.
let texel = |tx: usize, ty: usize| -> [f32; 4] {
let i = (ty * iw + tx) * 4;
let a = rgba[i + 3] as f32 / 255.0;
[
table[rgba[i] as usize] * a,
table[rgba[i + 1] as usize] * a,
table[rgba[i + 2] as usize] * a,
a,
]
};
// The drawn region's field, and coverage by the rule `paint` uses.
let (hx, hy) = ((x1 - x0) * 0.5, (y1 - y0) * 0.5);
let (mx, my) = (x0 + hx, y0 + hy);
let field =
|px: f32, py: f32| d2::rect(Vector2::new(px - mx, py - my), Vector2::new(hx, hy));
const BAND: f32 = std::f32::consts::FRAC_1_SQRT_2;
let coverage = |cx: f32, cy: f32| {
let d = field(cx, cy);
if d >= BAND {
0.0
} else if d <= -BAND {
1.0
} else {
let gx = (field(cx + 0.5, cy) - d) / 0.5;
let gy = (field(cx, cy + 0.5) - d) / 0.5;
sdf::coverage_edge(d, sdf::footprint(Vector2::new(gx, gy)))
}
};
// A pixel either side: anti-aliasing reaches just past the edge, as
// `paint` pads its box.
let (py0, py1) = (
(y0 - 1.0).floor().max(0.0) as u32,
(y1.ceil() as u32 + 1).min(self.height),
);
let (px0, px1) = (
(x0 - 1.0).floor().max(0.0) as u32,
(x1.ceil() as u32 + 1).min(self.width),
);
self.mark_rows(py0, py1);
for py in py0..py1 {
// Texel coordinates of this row's pixel centres.
let v = ((py as f32 + 0.5 - y) / height * ih as f32 - 0.5).clamp(0.0, (ih - 1) as f32);
let (ty0, fy) = (v.floor() as usize, v - v.floor());
let ty1 = (ty0 + 1).min(ih - 1);
for px in px0..px1 {
let cover = coverage(px as f32 + 0.5, py as f32 + 0.5);
if cover <= 0.0 {
continue;
}
let u =
((px as f32 + 0.5 - x) / width * iw as f32 - 0.5).clamp(0.0, (iw - 1) as f32);
let (tx0, fx) = (u.floor() as usize, u - u.floor());
let tx1 = (tx0 + 1).min(iw - 1);
let (a, b, c, d) = (
texel(tx0, ty0),
texel(tx1, ty0),
texel(tx0, ty1),
texel(tx1, ty1),
);
let mix = |k: usize| {
let top = a[k] + (b[k] - a[k]) * fx;
let bottom = c[k] + (d[k] - c[k]) * fx;
top + (bottom - top) * fy
};
let sample_a = mix(3);
let src_a = sample_a * alpha * cover;
if src_a <= 0.0 {
continue;
}
let lin = [0, 1, 2].map(|k| {
if sample_a > 0.0 {
mix(k) / sample_a
} else {
0.0
}
});
let i = (py as usize * self.width as usize + px as usize) * 4;
let dst = &mut self.pixels[i..i + 4];
let da = dst[3] as f32 / 255.0;
let out_a = src_a + da * (1.0 - src_a);
for k in 0..3 {
let under = table[dst[k] as usize];
dst[k] = srgb_encode((lin[k] * src_a + under * da * (1.0 - src_a)) / out_a);
}
dst[3] = (out_a * 255.0 + 0.5) as u8;
self.touched = true;
}
}
}
/// Composites linear `color` at `alpha` into pixel `i` (a byte index).
fn blend_linear(&mut self, i: usize, color: [f32; 3], alpha: f32) {
let table = srgb_decode_table();
let dst = &mut self.pixels[i..i + 4];
let da = dst[3] as f32 / 255.0;
let out_a = alpha + da * (1.0 - alpha);
if out_a <= 0.0 {
return;
}
for k in 0..3 {
let under = table[dst[k] as usize];
dst[k] = srgb_encode((color[k] * alpha + under * da * (1.0 - alpha)) / out_a);
}
dst[3] = (out_a * 255.0 + 0.5) as u8;
self.touched = true;
}
/// A box shadow: the rounded rectangle at `(x, y)`, `width × height`,
/// corners `radius`, blurred by a Gaussian of standard deviation
/// `sigma` (CSS's blur radius halved), in the fill colour.
///
/// Evaluated in closed form per pixel (after Evan Wallace): the blur across a row of the rounded box is an error
/// function, and down the column four Gaussian-weighted samples. No
/// blur pass, and the GPU UI pass computes the same thing. A `sigma`
/// under half a pixel is a sharp rounded rectangle.
pub fn shadow(&mut self, x: f32, y: f32, width: f32, height: f32, radius: f32, sigma: f32) {
let Some(paint) = self.fill else { return };
if width <= 0.0 || height <= 0.0 || paint.alpha <= 0.0 {
return;
}
if sigma < 0.5 {
let stroke = self.stroke.take();
self.rounded_rect(x, y, width, height, radius);
self.stroke = stroke;
return;
}
let reach = 3.0 * sigma;
let (px0, py0) = (
(x - reach).floor().max(0.0) as u32,
(y - reach).floor().max(0.0) as u32,
);
let px1 = ((x + width + reach).ceil().max(0.0) as u32).min(self.width);
let py1 = ((y + height + reach).ceil().max(0.0) as u32).min(self.height);
if px0 >= px1 || py0 >= py1 {
return;
}
self.mark_rows(py0, py1);
for py in py0..py1 {
for px in px0..px1 {
let a = shadow_coverage(
(x, y, x + width, y + height),
(px as f32 + 0.5, py as f32 + 0.5),
sigma,
radius,
) * paint.alpha;
if a > 1.0 / 512.0 {
let i = (py as usize * self.width as usize + px as usize) * 4;
self.blend_linear(i, paint.linear, a);
}
}
}
}
/// A wavy line, as under a misspelt word: from `x0` to `x1` along `y`,
/// rising and falling `amplitude` pixels every `period` pixels, in the
/// stroke colour and weight.
///
/// Every pixel near it is evaluated (no tiles skipped): the distance to
/// a wave is only approximate, too steep near its crests for skipping
/// a tile by its centre to be safe.
pub fn wavy_line(&mut self, x0: f32, y: f32, x1: f32, amplitude: f32, period: f32) {
let Some(paint) = self.stroke else { return };
let half = self.stroke_weight * 0.5;
let (a, k) = (amplitude, std::f32::consts::TAU / period.max(1e-3));
let reach = a + 2.0 * half + 1.0;
let (px0, py0) = (
(x0 - reach).floor().max(0.0) as u32,
(y - reach).floor().max(0.0) as u32,
);
let px1 = ((x1 + reach).ceil().max(0.0) as u32).min(self.width);
let py1 = ((y + reach).ceil().max(0.0) as u32).min(self.height);
if px0 >= px1 || py0 >= py1 || paint.alpha <= 0.0 {
return;
}
self.mark_rows(py0, py1);
for py in py0..py1 {
for px in px0..px1 {
let c = wave_coverage(px as f32 + 0.5, py as f32 + 0.5, x0, x1, y, a, k, half);
if c > 0.0 {
let i = (py as usize * self.width as usize + px as usize) * 4;
self.blend_linear(i, paint.linear, paint.alpha * c);
}
}
}
}
/// An axis-aligned rectangle with its top-left corner at `(x, y)`.
pub fn rect(&mut self, x: f32, y: f32, width: f32, height: f32) {
self.rounded_rect(x, y, width, height, 0.0);
}
/// A rectangle with corners rounded by `radius` pixels.
pub fn rounded_rect(&mut self, x: f32, y: f32, width: f32, height: f32, radius: f32) {
let (hx, hy) = (width * 0.5, height * 0.5);
let (cx, cy) = (x + hx, y + hy);
let r = radius.clamp(0.0, hx.abs().min(hy.abs()));
let half = Vector2::new(hx.abs(), hy.abs());
let sdf = move |px: f32, py: f32| d2::round_rect(Vector2::new(px - cx, py - cy), half, r);
self.shape(
cx - hx.abs(),
cy - hy.abs(),
cx + hx.abs(),
cy + hy.abs(),
sdf,
);
}
/// A rectangle with corners rounded by `radius` pixels, cut to the
/// rectangle `clip` (`[x, y, width, height]`): the part inside it, its
/// own corners still round.
#[allow(clippy::too_many_arguments)]
pub fn rounded_rect_clipped(
&mut self,
x: f32,
y: f32,
width: f32,
height: f32,
radius: f32,
clip: [f32; 4],
) {
let (hx, hy) = (width.abs() * 0.5, height.abs() * 0.5);
let (cx, cy) = (x.min(x + width) + hx, y.min(y + height) + hy);
let r = radius.clamp(0.0, hx.min(hy));
let half = Vector2::new(hx, hy);
let (chx, chy) = (clip[2].abs() * 0.5, clip[3].abs() * 0.5);
let (ccx, ccy) = (clip[0] + chx, clip[1] + chy);
let clip_half = Vector2::new(chx, chy);
// inside both: the farther of the two distances
let sdf = move |px: f32, py: f32| {
d2::round_rect(Vector2::new(px - cx, py - cy), half, r)
.max(d2::rect(Vector2::new(px - ccx, py - ccy), clip_half))
};
let (x0, y0) = ((cx - hx).max(ccx - chx), (cy - hy).max(ccy - chy));
let (x1, y1) = ((cx + hx).min(ccx + chx), (cy + hy).min(ccy + chy));
if x1 > x0 && y1 > y0 {
self.shape(x0, y0, x1, y1, sdf);
}
}
/// A circle of `radius` centred on `(cx, cy)`.
pub fn circle(&mut self, cx: f32, cy: f32, radius: f32) {
self.ellipse(cx, cy, radius, radius);
}
/// An axis-aligned ellipse centred on `(cx, cy)`.
///
/// The distance field is the cheap radial approximation, exact for a circle
/// and slightly off for a very eccentric ellipse — where it shows up as
/// anti-aliasing a fraction of a pixel soft on the flatter sides, not as a
/// misplaced edge.
pub fn ellipse(&mut self, cx: f32, cy: f32, rx: f32, ry: f32) {
let (rx, ry) = (rx.abs().max(1e-6), ry.abs().max(1e-6));
let sdf = move |px: f32, py: f32| {
let (dx, dy) = ((px - cx) / rx, (py - cy) / ry);
((dx * dx + dy * dy).sqrt() - 1.0) * rx.min(ry)
};
self.shape(cx - rx, cy - ry, cx + rx, cy + ry, sdf);
}
/// A line from `(x0, y0)` to `(x1, y1)`, in the stroke colour and width.
///
/// Unlike the closed shapes this has no inside, so it ignores the fill and
/// draws nothing when there is no stroke. A weight under a pixel draws a
/// line of that weight — fainter, not wider — that keeps its weight as it
/// moves between pixels.
pub fn line(&mut self, x0: f32, y0: f32, x1: f32, y1: f32) {
let (a, b) = (Vector2::new(x0, y0), Vector2::new(x1, y1));
let half = self.stroke_weight * 0.5;
self.stroke_centre(
x0.min(x1),
y0.min(y1),
x0.max(x1),
y0.max(y1),
half,
|px, py| d2::segment(Vector2::new(px, py), a, b),
);
}
/// A connected run of line segments, open — the last point is not joined
/// back to the first. The shape for a plot or an axis.
///
/// Drawn as one stroke, so the joints are covered once: segments drawn
/// one by one blend their shared end pixels twice, which leaves a dark
/// bead at every vertex of a thin or translucent line.
pub fn polyline(&mut self, points: &[Vector2]) {
if points.len() < 2 {
return;
}
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
for p in points {
x0 = x0.min(p.x);
y0 = y0.min(p.y);
x1 = x1.max(p.x);
y1 = y1.max(p.y);
}
let half = self.stroke_weight * 0.5;
if points.len() < 9 {
self.stroke_centre(x0, y0, x1, y1, half, |px, py| {
let p = Vector2::new(px, py);
points
.windows(2)
.map(|w| d2::segment(p, w[0], w[1]))
.fold(f32::MAX, f32::min)
});
return;
}
// Every pixel against every segment is the whole bounding box times the
// whole line: a map outline of a hundred and fifty points took two
// milliseconds. So the segments are filed by the tiles they come near,
// and a pixel looks only at its tile's. Far from any, the distance is
// just "far", which is all the coverage needs to know.
const TILE: f32 = 8.0;
let pad = half + 3.0;
let (gx, gy) = (x0 - pad, y0 - pad);
let cols = ((x1 - x0 + 2.0 * pad) / TILE) as usize + 1;
let rows = ((y1 - y0 + 2.0 * pad) / TILE) as usize + 1;
let mut tiles: Vec<Vec<u32>> = vec![Vec::new(); cols * rows];
for (i, w) in points.windows(2).enumerate() {
let tile = |v: f32, origin: f32, most: usize| {
(((v - origin) / TILE).max(0.0) as usize).min(most - 1)
};
let (c0, c1) = (
tile(w[0].x.min(w[1].x) - pad, gx, cols),
tile(w[0].x.max(w[1].x) + pad, gx, cols),
);
let (r0, r1) = (
tile(w[0].y.min(w[1].y) - pad, gy, rows),
tile(w[0].y.max(w[1].y) + pad, gy, rows),
);
for r in r0..=r1 {
for c in c0..=c1 {
tiles[r * cols + c].push(i as u32);
}
}
}
let far = pad * 4.0;
self.stroke_centre(x0, y0, x1, y1, half, |px, py| {
let (c, r) = ((px - gx) / TILE, (py - gy) / TILE);
if c < 0.0 || r < 0.0 || c >= cols as f32 || r >= rows as f32 {
return far;
}
let p = Vector2::new(px, py);
tiles[r as usize * cols + c as usize]
.iter()
.map(|&i| d2::segment(p, points[i as usize], points[i as usize + 1]))
.fold(far, f32::min)
});
}
/// A closed polygon, filled and stroked. Winding does not matter.
///
/// Hand it a [`voronoi_cells`](crate::math::voronoi_cells) cell or a
/// [`convex_hull`](crate::math::convex_hull) outline directly.
pub fn polygon(&mut self, points: &[Vector2]) {
if points.len() < 3 {
// Two points are a line and one is nothing; neither has an inside,
// and silently drawing half of what was asked for would be worse.
if points.len() == 2 {
self.line(points[0].x, points[0].y, points[1].x, points[1].y);
}
return;
}
let (mut x0, mut y0) = (f32::MAX, f32::MAX);
let (mut x1, mut y1) = (f32::MIN, f32::MIN);
for p in points {
x0 = x0.min(p.x);
y0 = y0.min(p.y);
x1 = x1.max(p.x);
y1 = y1.max(p.y);
}
// Borrowed, not copied into the closure: `shape` does not outlive this
// call, and a `move` here was an allocation per polygon per frame.
self.shape(x0, y0, x1, y1, |px, py| {
d2::polygon(Vector2::new(px, py), points)
});
}
/// Any signed distance field, filled and stroked in the current style —
/// the rasteriser behind `rect`, `circle` and `polygon`, opened up.
///
/// `sdf` takes a pixel position and returns the distance to the edge in
/// pixels, negative inside; build it from [`crate::sdf`]. Only the box
/// `(x0, y0)`–`(x1, y1)` is evaluated, so it has to contain the shape (the
/// stroke's padding is added for you). The field may underestimate the
/// distance — smooth unions do — but must never overestimate it: whole
/// tiles are skipped on the strength of one sample.
///
/// ```
/// use threers::math::{Color, Vector2};
/// use threers::overlay::Overlay;
/// use threers::sdf::{self, d2};
///
/// let mut o = Overlay::new(64, 64);
/// o.fill(Color::WHITE);
/// // Two discs melted into one blob.
/// o.distance_field(0.0, 0.0, 64.0, 64.0, |p| {
/// let a = d2::circle(p - Vector2::new(22.0, 32.0), 12.0);
/// let b = d2::circle(p - Vector2::new(42.0, 32.0), 12.0);
/// sdf::smooth_union(a, b, 8.0)
/// });
/// assert!(o.touched());
/// ```
pub fn distance_field<F>(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, sdf: F)
where
F: Fn(Vector2) -> f32,
{
self.shape(x0, y0, x1, y1, |px, py| sdf(Vector2::new(px, py)));
}
/// A stroke around any centre line, in the stroke colour at the stroke
/// weight — what `line` and `polyline` are, opened up.
///
/// `centre` takes a pixel position and returns the unsigned distance to
/// the line, in pixels: a curve, a spiral, the union of many segments
/// (`min` of their [`d2::segment`]s). Only the box is evaluated; the
/// stroke's padding is added for you.
///
/// Thin strokes are where this differs from drawing the stroke as a
/// [`distance_field`](Self::distance_field): the coverage is the share of
/// each pixel the stroke really covers, so a 0.3-pixel hairline draws as a
/// faint line one pixel wide rather than a dark one two pixels wide, and
/// it does not shimmer or bead as it crosses pixels at an angle.
///
/// ```
/// use threers::math::{Color, Vector2};
/// use threers::overlay::Overlay;
///
/// let mut o = Overlay::new(64, 64);
/// o.stroke(Color::WHITE);
/// o.stroke_weight(0.4);
/// // a hairline circle
/// o.stroke_field(0.0, 0.0, 64.0, 64.0, |p| ((p - Vector2::new(32.0, 32.0)).length() - 20.0).abs());
/// assert!(o.touched());
/// ```
pub fn stroke_field<F>(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, centre: F)
where
F: Fn(Vector2) -> f32,
{
let half = self.stroke_weight * 0.5;
self.stroke_centre(x0, y0, x1, y1, half, |px, py| centre(Vector2::new(px, py)));
}
/// [`stroke_field`](Self::stroke_field) with a width that varies along the
/// line: `field` returns the distance to the centre line and the stroke's
/// half-width there — a brush mark, a tapering strand (the radius
/// [`d2::tapered_capsule_radius`] reports). The stroke weight is not used.
/// The distance minus the half-width must not overestimate the distance
/// to the stroke's edge, and the box must hold the whole stroke, its
/// widest point included.
pub fn stroke_field_with_width<F>(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, field: F)
where
F: Fn(Vector2) -> (f32, f32),
{
let Some(paint) = self.stroke else {
return;
};
self.paint(x0 - 1.0, y0 - 1.0, x1 + 1.0, y1 + 1.0, &paint, |px, py| {
let (u, half) = field(Vector2::new(px, py));
(u - half, half.max(0.0))
});
}
/// A string with its top-left corner at `(x, y)`, in the fill colour at the
/// current [`text_size`](Overlay::text_size).
///
/// A stroke, if set, becomes an outline around the glyphs — which is what
/// makes small text readable over a busy render, and the reason this takes
/// the stroke at all.
///
/// Returns whether anything was drawn: `false` for an empty string or one
/// placed entirely off-canvas.
#[cfg(feature = "captions")]
pub fn text(&mut self, x: f32, y: f32, text: &str) -> bool {
self.draw_text(x, y, text, crate::captions::CaptionAlign::Left)
}
/// A string with its **right** edge at `x`, and its top at `y`.
///
/// What a numeric read-out wants: the digits grow leftwards from a fixed
/// edge instead of pushing the rest of the line around as the value
/// changes. The alternative at the call site is
/// [`measure_text`](Overlay::measure_text) and a subtraction, which is what
/// this does and what every HUD ends up writing twice.
#[cfg(feature = "captions")]
pub fn text_right(&mut self, x: f32, y: f32, text: &str) -> bool {
self.draw_text(x, y, text, crate::captions::CaptionAlign::Right)
}
/// A string centred horizontally on `x`, with its top at `y`.
#[cfg(feature = "captions")]
pub fn text_centered(&mut self, x: f32, y: f32, text: &str) -> bool {
self.draw_text(x, y, text, crate::captions::CaptionAlign::Center)
}
/// A string turned by `quarter_turns` × 90° counter-clockwise (1: read
/// from the bottom up, as a chart's vertical axis label), the rotated
/// block's top-left corner at `(x, y)`.
///
/// Drawn as [`text`](Overlay::text) draws it, then turned and laid over
/// the canvas (source-over), so the style, font and outline are the same.
/// Returns whether anything was drawn.
#[cfg(feature = "captions")]
pub fn text_rotated(&mut self, x: f32, y: f32, text: &str, quarter_turns: i32) -> bool {
let q = quarter_turns.rem_euclid(4);
if q == 0 {
return self.text(x, y, text);
}
let (tw, th) = self.measure_text(text);
// with a margin for the outline
let (w, h) = (tw.ceil() as u32 + 4, th.ceil() as u32 + 4);
if w > self.width || h > self.height {
return false;
}
// drawn upright in a corner of the canvas cleared for it, taken out,
// and the corner put back as it was
let (cw, row) = (self.width as usize, w as usize * 4);
let saved: Vec<u8> = (0..h as usize)
.flat_map(|r| self.pixels[r * cw * 4..r * cw * 4 + row].to_vec())
.collect();
for r in 0..h as usize {
self.pixels[r * cw * 4..r * cw * 4 + row].fill(0);
}
let (touched, dirty, content) = (self.touched, self.dirty.clone(), self.content.clone());
let drawn = self.text(2.0, 2.0, text);
let upright: Vec<u8> = (0..h as usize)
.flat_map(|r| self.pixels[r * cw * 4..r * cw * 4 + row].to_vec())
.collect();
for r in 0..h as usize {
self.pixels[r * cw * 4..r * cw * 4 + row]
.copy_from_slice(&saved[r * row..(r + 1) * row]);
}
(self.touched, self.dirty, self.content) = (touched, dirty, content);
if !drawn {
return false;
}
// turned: (u, v) upright to (i, j) on the canvas
let (rw, rh) = if q % 2 == 1 { (h, w) } else { (w, h) };
let (x0, y0) = (x.round() as i32, y.round() as i32);
let mut any = false;
for j in 0..rh {
for i in 0..rw {
let (u, v) = match q {
1 => (w - 1 - j, i),
2 => (w - 1 - i, h - 1 - j),
_ => (j, h - 1 - i),
};
let s = &upright[(v as usize * w as usize + u as usize) * 4..][..4];
let sa = s[3] as f32 / 255.0;
let (px, py) = (x0 + i as i32, y0 + j as i32);
if sa == 0.0
|| px < 0
|| py < 0
|| px >= self.width as i32
|| py >= self.height as i32
{
continue;
}
let d = &mut self.pixels[(py as usize * cw + px as usize) * 4..][..4];
let da = d[3] as f32 / 255.0;
let oa = sa + da * (1.0 - sa);
for c in 0..3 {
d[c] = ((s[c] as f32 * sa + d[c] as f32 * da * (1.0 - sa)) / oa).round() as u8;
}
d[3] = (oa * 255.0).round() as u8;
any = true;
}
}
if any {
self.touched = true;
self.mark_rows(
y0.max(0) as u32,
((y0 + rh as i32).max(0) as u32).min(self.height),
);
}
any
}
/// The one implementation behind [`text`](Overlay::text),
/// [`text_right`](Overlay::text_right) and
/// [`text_centered`](Overlay::text_centered).
///
/// `set_style` then draw, rather than a helper handing back a styled
/// painter: the draw needs `self.painter` and `self.pixels` borrowed mutably
/// at once, which the compiler allows for two fields of `self` named in the
/// same body and not for a method that borrows all of it.
#[cfg(feature = "captions")]
fn draw_text(
&mut self,
x: f32,
y: f32,
text: &str,
align: crate::captions::CaptionAlign,
) -> bool {
use crate::captions::CaptionAlign;
let style = self.text_style();
let (w, h) = (self.width, self.height);
self.apply_text_style();
let painter = self
.painter
.get_or_insert_with(crate::captions::CaptionPainter::new);
painter.set_style(style);
let pixels = &mut self.pixels;
let drawn = match align {
CaptionAlign::Left => painter.draw_text_at(pixels, w, h, x, y, text),
CaptionAlign::Right => painter.draw_text_at_right(pixels, w, h, x, y, text),
CaptionAlign::Center => painter.draw_text_at_center(pixels, w, h, x, y, text),
};
// Asked, not guessed: the painter re-wraps against the space left of
// the anchor and slides the block up off the bottom edge, so the rows a
// string lands on are not `y..y + measured height`.
let rows = painter.last_rows();
self.touched |= drawn;
if let Some((y0, y1)) = rows {
self.mark_rows(y0, y1);
}
drawn
}
/// Width and height of `text` in pixels, without drawing it — for
/// right-aligning a read-out or sizing a box behind a label.
#[cfg(feature = "captions")]
pub fn measure_text(&mut self, text: &str) -> (f32, f32) {
let style = self.text_style();
let w = self.width;
self.apply_text_style();
let painter = self
.painter
.get_or_insert_with(crate::captions::CaptionPainter::new);
painter.set_style(style);
let laid = painter.measure(text, w);
(laid.width, laid.height)
}
/// The size of `text` as one line, however wide: [`measure_text`]
/// (Self::measure_text) lays it out as a caption, which wraps it inside
/// the frame's safe width — a UI's line of text wider than that came out
/// narrower than it is drawn (so mis-wrapped and mis-centred).
#[cfg(feature = "captions")]
pub fn measure_line(&mut self, text: &str) -> (f32, f32) {
let style = self.text_style();
self.apply_text_style();
let painter = self
.painter
.get_or_insert_with(crate::captions::CaptionPainter::new);
painter.set_style(style);
let laid = painter.measure(text, 1 << 24);
(laid.width, laid.height)
}
/// The current fill, stroke and type size as a caption style. Text with no
/// fill set would be invisible rather than absent, so it falls back to
/// white — `no_fill` is about shapes, and a `text` call is an instruction to
/// draw something.
#[cfg(feature = "captions")]
fn text_style(&self) -> crate::captions::CaptionStyle {
let rgba = |p: &Paint| {
[
p.encoded[0],
p.encoded[1],
p.encoded[2],
(p.alpha * 255.0 + 0.5) as u8,
]
};
let fill = self.fill.unwrap_or_else(|| Paint::new(Color::WHITE, 1.0));
crate::captions::CaptionStyle {
font_size: self.text_size,
color: rgba(&fill),
// No box and no shadow: this is a drawing primitive, and anything
// behind the text is a `rect` the caller can place themselves.
background: [0, 0, 0, 0],
shadow_color: [0, 0, 0, 0],
outline_color: self.stroke.as_ref().map_or([0, 0, 0, 0], rgba),
outline_width: match self.stroke {
Some(_) => self.stroke_weight * 0.5,
None => 0.0,
},
padding: 0.0,
margin: 0.0,
..Default::default()
}
}
/// Fill then stroke one distance field — the shared body of every closed
/// primitive. `sdf` is negative inside, in pixels.
fn shape<F>(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, sdf: F)
where
F: Fn(f32, f32) -> f32,
{
if let Some(paint) = self.fill {
self.paint(x0 - 1.0, y0 - 1.0, x1 + 1.0, y1 + 1.0, &paint, |px, py| {
(sdf(px, py), f32::INFINITY)
});
}
if let Some(paint) = self.stroke {
let half = self.stroke_weight * 0.5;
// The outline is a stroke whose centre line is the edge: the
// distance to it is the field folded about zero.
let pad = half + 1.0;
self.paint(x0 - pad, y0 - pad, x1 + pad, y1 + pad, &paint, |px, py| {
(sdf(px, py).abs() - half, half)
});
}
}
/// A stroke `half` either side of a centre line, in the stroke colour.
/// `centre` is the unsigned distance to the line.
fn stroke_centre<F>(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, half: f32, centre: F)
where
F: Fn(f32, f32) -> f32,
{
let Some(paint) = self.stroke else {
return;
};
let pad = half + 1.0;
self.paint(x0 - pad, y0 - pad, x1 + pad, y1 + pad, &paint, |px, py| {
(centre(px, py) - half, half)
});
}
/// Rasterise one field over a bounding box.
///
/// `field` gives, at a pixel centre, the distance outside the shape's edge
/// (negative inside) and the half-width of the stroke the shape is —
/// `f32::INFINITY` for a filled shape, which has an edge and no centre
/// line. A stroke's coverage is the box-filtered share of the pixel it
/// covers ([`sdf::coverage_stroke`]), which is what keeps a line thinner
/// than a pixel at its own weight instead of drawing it dark and two
/// pixels wide.
fn paint<F>(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, paint: &Paint, field: F)
where
F: Fn(f32, f32) -> (f32, f32),
{
if paint.alpha <= 0.0 {
return;
}
let lo_x = x0.floor().max(0.0) as u32;
let lo_y = y0.floor().max(0.0) as u32;
let hi_x = (x1.ceil().max(0.0) as u32 + 1).min(self.width);
let hi_y = (y1.ceil().max(0.0) as u32 + 1).min(self.height);
if lo_x >= hi_x || lo_y >= hi_y {
return;
}
// Once per primitive, from its bounding box, rather than per pixel in
// the loop below. Conservative by at most a row of coverage either side
// of the shape, which is a row of upload and not a wrong picture.
self.mark_rows(lo_y, hi_y);
let table = srgb_decode_table();
// How far either side of an edge a pixel can be partly covered: half
// the widest footprint a pixel has across an edge, at 45 degrees.
const BAND: f32 = std::f32::consts::FRAC_1_SQRT_2;
let outer = |px: f32, py: f32| field(px, py).0;
// Walked in tiles so whole tiles can be settled from one evaluation.
// A signed distance field is 1-Lipschitz — moving a pixel changes it by
// at most a pixel — so if the centre of a tile is further than the
// tile's own radius from the edge, every sample in it is on the same
// side and none of them needs evaluating. Coverage ramps over
// `d` in `-BAND..BAND`, so that is the margin to clear.
//
// This is most of the cost of a large shape. `polygon` measures the
// distance to every edge at every pixel, and a Voronoi cell covering an
// eighth of a 1000x640 view is 80,000 pixels of which perhaps 3,000 are
// near an edge. Eight such cells, filled and stroked, with the Delaunay
// edges over the top: 96 ms a frame before tiling, 5 ms after. A
// read-out and a gradient legend — which is what most frames draw — is
// 183 us either way, so this costs nothing in the common case.
const TILE: u32 = 8;
for ty in (lo_y..hi_y).step_by(TILE as usize) {
let ty1 = (ty + TILE).min(hi_y);
for tx in (lo_x..hi_x).step_by(TILE as usize) {
let tx1 = (tx + TILE).min(hi_x);
// Furthest a sample centre in this tile can be from its middle.
// The tile may be clipped, so this is measured and not assumed.
let rx = (tx1 - tx) as f32 * 0.5 - 0.5;
let ry = (ty1 - ty) as f32 * 0.5 - 0.5;
let radius = (rx * rx + ry * ry).sqrt();
let middle = outer((tx + tx1) as f32 * 0.5, (ty + ty1) as f32 * 0.5);
if middle - radius >= BAND {
continue; // wholly outside
}
// Wholly inside, so every sample is fully covered and the
// field never has to be asked again. A stroke thinner than
// the band never gets here: its outer distance is at least
// minus its half-width.
let solid = middle + radius <= -BAND;
for py in ty..ty1 {
let row = py as usize * self.width as usize;
for px in tx..tx1 {
let alpha = if solid {
paint.alpha
} else {
let (cx, cy) = (px as f32 + 0.5, py as f32 + 0.5);
let (d, half) = field(cx, cy);
let coverage = if d >= BAND {
0.0
} else if d <= -BAND {
1.0
} else {
// In the band: how wide the pixel is across the
// edge here sets how wide the ramp is. Forward
// differences for an edge. A stroke's distance is
// folded about its centre line, and a step across
// that crease shortens the difference on its
// axis — so per axis the larger of the forward
// and backward one, which a crease cannot shorten
// both of.
let e = 0.5;
let mut gx = (outer(cx + e, cy) - d) / e;
let mut gy = (outer(cx, cy + e) - d) / e;
if half.is_finite() {
gx = gx.abs().max(((d - outer(cx - e, cy)) / e).abs());
gy = gy.abs().max(((d - outer(cx, cy - e)) / e).abs());
}
let w = sdf::footprint(Vector2::new(gx, gy));
if half.is_finite() {
sdf::coverage_stroke(d + half, half, w)
} else {
sdf::coverage_edge(d, w)
}
};
if coverage <= 0.0 {
continue;
}
paint.alpha * coverage
};
let i = (row + px as usize) * 4;
let dst = &mut self.pixels[i..i + 4];
let da = dst[3] as f32 / 255.0;
if da <= 0.0 {
// Nothing underneath, so there is nothing to mix
// with and the encoded colour goes straight down.
// The common case on a cleared canvas, and it skips
// both transfer functions.
dst[0] = paint.encoded[0];
dst[1] = paint.encoded[1];
dst[2] = paint.encoded[2];
dst[3] = (alpha * 255.0 + 0.5) as u8;
} else {
let out_a = alpha + da * (1.0 - alpha);
for c in 0..3 {
let under = table[dst[c] as usize];
let mixed =
(paint.linear[c] * alpha + under * da * (1.0 - alpha)) / out_a;
dst[c] = srgb_encode(mixed);
}
dst[3] = (out_a * 255.0 + 0.5) as u8;
}
self.touched = true;
}
}
}
}
}
}
/// Grow a row band to cover `y0..y1`.
/// Row ranges, half-open, sorted and apart from each other.
#[derive(Debug, Clone, Default, PartialEq)]
struct Bands(Vec<(u32, u32)>);
impl Bands {
/// Rows closer than this are one band: an upload has a cost of its own.
const JOIN: u32 = 16;
/// More bands than this become fewer, joining the closest, so a frame of
/// scattered text does not turn into hundreds of uploads.
const MOST: usize = 8;
fn add(&mut self, y0: u32, y1: u32) {
if y0 >= y1 {
return;
}
let (mut a, mut b) = (y0, y1);
let mut kept = Vec::with_capacity(self.0.len() + 1);
for &(c, d) in &self.0 {
if d + Self::JOIN < a || b + Self::JOIN < c {
kept.push((c, d));
} else {
a = a.min(c);
b = b.max(d);
}
}
kept.push((a, b));
kept.sort_unstable();
while kept.len() > Self::MOST {
let closest = (1..kept.len())
.min_by_key(|&i| kept[i].0 - kept[i - 1].1)
.unwrap();
kept[closest - 1].1 = kept[closest].1;
kept.remove(closest);
}
self.0 = kept;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "captions")]
#[test]
fn rotated_text_is_tall_and_leaves_the_rest() {
let mut o = Overlay::new(200, 200);
o.fill(Color::WHITE);
o.text_size(16.0);
let (tw, _) = o.measure_text("Voltage");
assert!(o.text_rotated(10.0, 20.0, "Voltage", 1));
// ink only inside the turned block: narrow and tall
let (mut x0, mut x1, mut y0, mut y1) = (u32::MAX, 0, u32::MAX, 0);
for y in 0..200 {
for x in 0..200 {
if o.pixels()[(y * 200 + x) as usize * 4 + 3] > 0 {
(x0, x1, y0, y1) = (x0.min(x), x1.max(x), y0.min(y), y1.max(y));
}
}
}
assert!(x0 >= 10 && y0 >= 20, "inside the block: {x0},{y0}");
assert!(
y1 - y0 > x1 - x0,
"taller than wide: {}x{}",
x1 - x0,
y1 - y0
);
assert!((y1 - y0) as f32 >= tw * 0.8, "as tall as the text is long");
// the corner used to draw it upright put back (transparent)
assert_eq!(o.pixels()[3], 0);
}
#[test]
fn put_image_data_copies_clipped_and_marks_the_rows() {
let mut o = Overlay::new(4, 3);
o.mark_uploaded();
// A 2 × 2 image hanging off the right edge at (3, 1): one column lands.
let img = [
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160,
];
o.put_image_data(3, 1, 2, 2, &img);
assert!(o.touched());
assert_eq!(o.dirty_rows(), Some((1, 3)));
assert_eq!(at(&o, 3, 1), [10, 20, 30, 40]);
assert_eq!(at(&o, 3, 2), [90, 100, 110, 120]);
assert_eq!(at(&o, 2, 1), [0, 0, 0, 0]);
// Replaces rather than blends: transparent pixels erase.
o.put_image_data(3, 1, 1, 1, &[0, 0, 0, 0]);
assert_eq!(at(&o, 3, 1), [0, 0, 0, 0]);
// Wholly outside: nothing.
o.put_image_data(-5, 0, 2, 2, &img);
assert_eq!(at(&o, 0, 0), [0, 0, 0, 0]);
}
/// Straight-alpha RGBA at a pixel.
fn at(o: &Overlay, x: u32, y: u32) -> [u8; 4] {
let (w, _) = o.size();
let i = (y as usize * w as usize + x as usize) * 4;
let p = o.pixels();
[p[i], p[i + 1], p[i + 2], p[i + 3]]
}
/// The table has to give the same byte as the curve it replaces, not a
/// close one — every pixel of every overlapping shape goes through it, and
/// an off-by-one would be a banding artefact nobody could trace back here.
/// Swept finely enough to land either side of all 255 switchover points.
#[test]
fn the_encode_table_matches_the_curve_it_replaces() {
let mut differing = Vec::new();
const STEPS: u32 = 200_000;
for i in 0..=STEPS {
let v = i as f32 / STEPS as f32;
if srgb_encode(v) != srgb_encode_by_curve(v) {
differing.push(v);
}
}
// Then every switchover and the representable value either side of it,
// which is where the two can actually disagree and which a sweep of any
// density will mostly step over.
for &t in srgb_encode_thresholds().iter() {
for v in [
f32::from_bits(t.to_bits().saturating_sub(1)),
t,
f32::from_bits(t.to_bits() + 1),
] {
if srgb_encode(v) != srgb_encode_by_curve(v) {
differing.push(v);
}
}
}
assert!(
differing.is_empty(),
"{} values encode differently, e.g. {:?} -> {} by table, {} by curve",
differing.len(),
differing[0],
srgb_encode(differing[0]),
srgb_encode_by_curve(differing[0])
);
// And the ends, which a sweep can miss.
assert_eq!(srgb_encode(0.0), 0);
assert_eq!(srgb_encode(1.0), 255);
assert_eq!(srgb_encode(-5.0), 0, "clamped");
assert_eq!(srgb_encode(5.0), 255, "clamped");
// Round trip against the decode table, which is the other half of the
// pair: every byte must encode back to itself.
let decode = srgb_decode_table();
for b in 0..=255u8 {
assert_eq!(
srgb_encode(decode[b as usize]),
b,
"byte {b} did not survive decode then encode"
);
}
}
/// Where the 2.29 ns against 6.00 ns in [`srgb_encode`]'s own docs comes
/// from. Ignored by default rather than asserted: the ratio is stable but
/// the absolute numbers are not, and a timing assertion in a test suite
/// fails for reasons that have nothing to do with the code.
#[test]
#[ignore]
fn the_encode_table_is_faster_than_the_curve() {
let vals: Vec<f32> = (0..1 << 16)
.map(|i| (i as f32) / ((1 << 16) as f32))
.collect();
let reps = 200;
for (label, f) in [
("table", srgb_encode as fn(f32) -> u8),
("curve", srgb_encode_by_curve as fn(f32) -> u8),
] {
let mut best = f64::MAX;
for _ in 0..7 {
let t = std::time::Instant::now();
let mut acc = 0u64;
for _ in 0..reps {
for &v in &vals {
acc += f(v) as u64;
}
}
let ns = t.elapsed().as_secs_f64() * 1e9 / (reps * vals.len()) as f64;
best = best.min(ns);
std::hint::black_box(acc);
}
eprintln!("{label}: {best:.2} ns/call");
}
}
#[test]
fn a_new_overlay_is_transparent_and_untouched() {
let o = Overlay::new(8, 4);
assert_eq!(o.size(), (8, 4));
assert_eq!(o.pixels().len(), 8 * 4 * 4);
assert!(o.pixels().iter().all(|&b| b == 0));
assert!(!o.touched());
}
#[test]
fn a_filled_rect_is_opaque_inside_and_untouched_outside() {
let mut o = Overlay::new(32, 32);
o.fill(Color::WHITE);
o.no_stroke();
o.rect(8.0, 8.0, 16.0, 16.0);
assert!(o.touched());
assert_eq!(at(&o, 16, 16), [255, 255, 255, 255], "centre");
assert_eq!(at(&o, 2, 2), [0, 0, 0, 0], "outside stays clear");
assert_eq!(at(&o, 30, 30), [0, 0, 0, 0], "outside stays clear");
}
/// The reason the rasteriser is a distance field: a half-pixel offset has
/// to land as half coverage, not as a snapped edge.
#[test]
fn edges_are_anti_aliased_rather_than_snapped() {
let mut o = Overlay::new(16, 16);
o.fill(Color::WHITE);
o.no_stroke();
// Left edge exactly through the centre of column 4.
o.rect(4.5, 0.0, 8.0, 16.0);
let a = at(&o, 4, 8)[3];
assert!(
(a as i32 - 128).abs() <= 4,
"an edge through a pixel centre should be about half covered, got {a}"
);
assert_eq!(at(&o, 6, 8)[3], 255, "well inside");
assert_eq!(at(&o, 2, 8)[3], 0, "well outside");
}
/// Alpha has to be straight (non-premultiplied) and the colour has to
/// survive at low alpha, because the compositing pass assumes both.
#[test]
fn alpha_is_straight_so_colour_survives_transparency() {
let mut o = Overlay::new(8, 8);
o.no_stroke();
o.fill_alpha(Color::WHITE, 0.25);
o.rect(0.0, 0.0, 8.0, 8.0);
let p = at(&o, 4, 4);
assert_eq!(
[p[0], p[1], p[2]],
[255, 255, 255],
"colour not premultiplied"
);
assert!(
(p[3] as i32 - 64).abs() <= 2,
"alpha {} should be ~64",
p[3]
);
}
/// Overlapping half-transparent fills must mix in linear light. Two 50%
/// mid-greys over each other land on a different byte in each space, so
/// this distinguishes them rather than just asserting the implementation.
#[test]
fn overlapping_fills_mix_in_linear_light() {
let mut o = Overlay::new(8, 8);
o.no_stroke();
o.fill_alpha(Color::WHITE, 0.5);
o.rect(0.0, 0.0, 8.0, 8.0);
let under = at(&o, 4, 4);
o.fill_alpha(Color::BLACK, 0.5);
o.rect(0.0, 0.0, 8.0, 8.0);
let got = at(&o, 4, 4);
// The first layer's alpha is already a byte by the time the second one
// reads it, and 0.5 rounds up to 128/255, so the stack lands a shade
// above three quarters. Derived from what is actually in the buffer
// rather than from the nominal halves, or this is off by one.
let da = under[3] as f32 / 255.0;
let out_a = 0.5 + da * 0.5;
assert_eq!(got[3], (out_a * 255.0 + 0.5) as u8, "two 50% layers stack");
// Black at 0.5 over white at `da`, mixed in linear light.
let want = srgb_encode((0.0 * 0.5 + 1.0 * da * 0.5) / out_a);
assert_eq!(got[0], want, "linear mix");
// And it is not the answer sRGB-space blending would give, so the
// assertion above is testing the space and not just the arithmetic.
let naive = (0.0 * 0.5 + under[0] as f32 * da * 0.5) / out_a;
assert!(
(got[0] as f32 - naive).abs() > 8.0,
"linear {} should differ from the sRGB-space mix {naive:.1}",
got[0]
);
}
#[test]
fn a_circle_is_round_and_centred() {
let mut o = Overlay::new(64, 64);
o.fill(Color::WHITE);
o.no_stroke();
o.circle(32.0, 32.0, 20.0);
assert_eq!(at(&o, 32, 32)[3], 255, "centre");
for (x, y) in [(32u32, 14u32), (32, 50), (14, 32), (50, 32)] {
assert_eq!(at(&o, x, y)[3], 255, "inside at ({x}, {y})");
}
for (x, y) in [(32u32, 8u32), (32, 56), (8, 32), (56, 32), (16, 16)] {
assert_eq!(at(&o, x, y)[3], 0, "outside at ({x}, {y})");
}
// Area, as a check that the radius is a radius and not a diameter.
let covered: f32 = o.pixels().chunks(4).map(|p| p[3] as f32 / 255.0).sum();
let want = std::f32::consts::PI * 20.0 * 20.0;
assert!(
(covered - want).abs() < want * 0.02,
"covered {covered:.1} against pi*r^2 = {want:.1}"
);
}
#[test]
fn an_unfilled_shape_draws_only_its_outline() {
let mut o = Overlay::new(64, 64);
o.no_fill();
o.stroke(Color::WHITE);
o.stroke_weight(4.0);
o.circle(32.0, 32.0, 20.0);
assert_eq!(at(&o, 32, 32)[3], 0, "the middle stays clear");
assert_eq!(at(&o, 32, 12)[3], 255, "on the ring");
assert_eq!(at(&o, 32, 2)[3], 0, "outside the ring");
// A ring of width w at radius r has area 2*pi*r*w.
let covered: f32 = o.pixels().chunks(4).map(|p| p[3] as f32 / 255.0).sum();
let want = std::f32::consts::TAU * 20.0 * 4.0;
assert!(
(covered - want).abs() < want * 0.05,
"covered {covered:.1} against 2*pi*r*w = {want:.1}"
);
}
#[test]
fn a_line_needs_a_stroke_and_ignores_the_fill() {
let mut o = Overlay::new(32, 32);
o.fill(Color::WHITE);
o.no_stroke();
o.line(2.0, 16.0, 30.0, 16.0);
assert!(!o.touched(), "no stroke means no line");
o.stroke(Color::WHITE);
o.stroke_weight(2.0);
o.line(2.0, 16.0, 30.0, 16.0);
assert!(o.touched());
assert_eq!(at(&o, 16, 16)[3], 255, "on the line");
assert_eq!(at(&o, 16, 24)[3], 0, "off the line");
}
/// Alpha across column `x`, as coverage.
fn column(o: &Overlay, x: u32) -> Vec<f32> {
(0..o.size().1)
.map(|y| at(o, x, y)[3] as f32 / 255.0)
.collect()
}
/// A line thinner than a pixel draws at its own weight: its alpha peaks at
/// its width and sums across it to its width, wherever it falls between
/// pixel centres. The edge rule it replaced drew a 0.4-pixel line at 0.9
/// alpha over two pixels — more than twice its ink.
#[test]
fn a_hairline_keeps_its_weight_between_pixels() {
for k in 0..8 {
let y = 16.0 + k as f32 / 8.0;
let mut o = Overlay::new(32, 32);
o.stroke(Color::WHITE);
o.stroke_weight(0.4);
o.line(2.0, y, 30.0, y);
let col = column(&o, 16);
let total: f32 = col.iter().sum();
let peak = col.iter().cloned().fold(0.0, f32::max);
assert!(
(total - 0.4).abs() < 0.02,
"at y {y}: {total} of ink for a 0.4 line"
);
assert!(peak <= 0.41, "at y {y}: peak {peak}");
}
}
/// Along a thin diagonal the ink per column stays even: no beads where the
/// line passes close to pixel centres and gaps where it does not.
#[test]
fn a_thin_diagonal_does_not_bead() {
let mut o = Overlay::new(64, 64);
o.stroke(Color::WHITE);
o.stroke_weight(0.6);
o.line(4.0, 4.3, 60.0, 60.3);
let sums: Vec<f32> = (10..54).map(|x| column(&o, x).iter().sum()).collect();
let mean = sums.iter().sum::<f32>() / sums.len() as f32;
let spread = sums.iter().map(|s| (s - mean).abs()).fold(0.0, f32::max);
// a 0.6-wide line at 45 degrees crosses each column over 0.6·√2
assert!(
(mean - 0.6 * std::f32::consts::SQRT_2).abs() < 0.03,
"mean ink per column {mean}"
);
assert!(
spread < 0.03,
"ink per column varies by {spread} along the line"
);
}
/// A translucent polyline covers its joints once: drawn segment by
/// segment, the shared end pixels were blended twice and showed as beads.
#[test]
fn a_polyline_covers_its_joints_once() {
let mut o = Overlay::new(48, 48);
o.stroke_alpha(Color::WHITE, 0.5);
o.stroke_weight(3.0);
let pts = [
Vector2::new(4.0, 24.0),
Vector2::new(24.0, 24.0),
Vector2::new(44.0, 24.0),
];
o.polyline(&pts);
let joint = at(&o, 24, 24)[3];
let along = at(&o, 14, 24)[3];
assert_eq!(joint, along, "the joint is no darker than the run");
assert!((along as i32 - 128).abs() <= 1, "{along}");
}
#[test]
fn a_polygon_fills_its_inside_whichever_way_it_is_wound() {
let square = [
Vector2::new(8.0, 8.0),
Vector2::new(24.0, 8.0),
Vector2::new(24.0, 24.0),
Vector2::new(8.0, 24.0),
];
let mut reversed: Vec<Vector2> = square.to_vec();
reversed.reverse();
for pts in [square.to_vec(), reversed] {
let mut o = Overlay::new(32, 32);
o.fill(Color::WHITE);
o.no_stroke();
o.polygon(&pts);
assert_eq!(at(&o, 16, 16)[3], 255, "inside");
assert_eq!(at(&o, 2, 2)[3], 0, "outside");
let covered: f32 = o.pixels().chunks(4).map(|p| p[3] as f32 / 255.0).sum();
assert!(
(covered - 256.0).abs() < 8.0,
"a 16x16 square should cover ~256 px, got {covered:.1}"
);
}
}
/// A concave polygon is where a winding-sign distance field and a crossing
/// count disagree, so the notch has to come out empty.
#[test]
fn a_concave_polygon_keeps_its_notch_empty() {
// An L, 20x20 with a 10x10 bite out of the bottom-right.
let l = [
Vector2::new(4.0, 4.0),
Vector2::new(24.0, 4.0),
Vector2::new(24.0, 14.0),
Vector2::new(14.0, 14.0),
Vector2::new(14.0, 24.0),
Vector2::new(4.0, 24.0),
];
let mut o = Overlay::new(32, 32);
o.fill(Color::WHITE);
o.no_stroke();
o.polygon(&l);
assert_eq!(at(&o, 8, 8)[3], 255, "the top-left arm");
assert_eq!(at(&o, 20, 8)[3], 255, "the top-right arm");
assert_eq!(at(&o, 8, 20)[3], 255, "the bottom-left arm");
assert_eq!(at(&o, 20, 20)[3], 0, "the notch stays empty");
let covered: f32 = o.pixels().chunks(4).map(|p| p[3] as f32 / 255.0).sum();
assert!(
(covered - 300.0).abs() < 10.0,
"20x20 less 10x10 is 300 px, got {covered:.1}"
);
}
#[test]
fn drawing_off_canvas_is_clipped_rather_than_a_panic() {
let mut o = Overlay::new(16, 16);
o.fill(Color::WHITE);
o.stroke(Color::BLACK);
o.rect(-100.0, -100.0, 40.0, 40.0);
o.rect(1e6, 1e6, 10.0, 10.0);
o.circle(-5.0, 8.0, 4.0);
o.line(-50.0, -50.0, 500.0, 500.0);
o.polygon(&[
Vector2::new(-10.0, -10.0),
Vector2::new(-20.0, -10.0),
Vector2::new(-15.0, -20.0),
]);
// Negative and zero sizes have no inside and must not wrap around.
o.rect(4.0, 4.0, 0.0, 8.0);
o.rect(4.0, 4.0, -8.0, -8.0);
o.circle(8.0, 8.0, 0.0);
o.polygon(&[Vector2::new(1.0, 1.0)]);
assert_eq!(o.pixels().len(), 16 * 16 * 4);
}
/// The upload band has to describe the difference between the buffer and
/// the texture, which is not the same as "what this frame drew": erasing a
/// panel changes rows without drawing on them.
/// A long polyline drawn tile by tile is the picture every segment at
/// every pixel gives.
#[test]
fn a_long_polyline_draws_as_the_slow_way_does() {
let points: Vec<Vector2> = (0..=60)
.map(|i| {
let a = i as f32 / 60.0 * std::f32::consts::TAU;
Vector2::new(
60.0 + 40.0 * a.cos() + (i % 3) as f32,
60.0 + 30.0 * a.sin(),
)
})
.collect();
let draw = |o: &mut Overlay| {
o.no_fill();
o.stroke(Color::WHITE);
o.stroke_weight(3.0);
};
let mut fast = Overlay::new(128, 128);
draw(&mut fast);
fast.polyline(&points);
let mut slow = Overlay::new(128, 128);
draw(&mut slow);
slow.stroke_centre(0.0, 0.0, 128.0, 128.0, 1.5, |px, py| {
let p = Vector2::new(px, py);
points
.windows(2)
.map(|w| d2::segment(p, w[0], w[1]))
.fold(f32::MAX, f32::min)
});
let differ = fast
.pixels()
.iter()
.zip(slow.pixels())
.filter(|(a, b)| a != b)
.count();
assert_eq!(differ, 0);
assert!(fast.pixels().iter().any(|&p| p > 0));
}
/// A panel at the top and one at the bottom are two bands, and clearing
/// zeroes their rows and nothing else.
#[test]
fn far_apart_drawing_is_two_bands_and_clearing_is_only_theirs() {
let mut o = Overlay::new(64, 400);
o.no_stroke();
o.rect(0.0, 10.0, 20.0, 20.0);
o.rect(0.0, 350.0, 20.0, 20.0);
let bands = o.dirty_bands();
assert_eq!(bands.len(), 2, "{bands:?}");
let upload: u32 = bands.iter().map(|(a, b)| b - a).sum();
assert!(upload < 60, "{bands:?}");
assert_eq!(
o.dirty_rows().map(|(a, b)| (a <= 10, b >= 370)),
Some((true, true))
);
o.mark_uploaded();
o.clear();
assert!(o.pixels().iter().all(|&p| p == 0));
assert_eq!(
o.dirty_bands(),
bands,
"the cleared rows still have to reach the texture"
);
// Rows near each other join, and a scatter of many stays a few.
let mut o = Overlay::new(64, 4000);
for i in 0..40 {
o.rect(0.0, i as f32 * 90.0, 5.0, 5.0);
}
assert!(o.dirty_bands().len() <= 8);
o.rect(0.0, 3990.0, 5.0, 5.0);
let rows: u32 = o.dirty_bands().iter().map(|(a, b)| b - a).sum();
assert!(rows < 4000);
}
#[test]
fn the_dirty_band_tracks_what_the_texture_is_missing() {
let mut o = Overlay::new(64, 200);
assert_eq!(o.dirty_rows(), None, "nothing has happened yet");
o.no_stroke();
o.fill(Color::WHITE);
o.rect(0.0, 20.0, 64.0, 20.0);
let (a, b) = o.dirty_rows().expect("the rect is outstanding");
assert!(a <= 20 && b >= 40, "rows {a}..{b} should cover 20..40");
assert!(b - a < 30, "rows {a}..{b} is far more than the rect");
o.mark_uploaded();
assert_eq!(o.dirty_rows(), None, "acknowledged");
// Erasing is a change. Without this the panel would stay on screen: the
// buffer goes to zero and nothing would tell the texture.
o.clear();
let (a, b) = o.dirty_rows().expect("the cleared rows are outstanding");
assert!(
a <= 20 && b >= 40,
"rows {a}..{b} should still cover 20..40"
);
// Drawing somewhere else unions with it, because both bands differ from
// the texture.
o.rect(0.0, 150.0, 64.0, 20.0);
let (a, b) = o.dirty_rows().expect("both");
assert!(a <= 20 && b >= 170, "rows {a}..{b} should span 20..170");
o.mark_uploaded();
o.clear();
let (a, b) = o.dirty_rows().expect("the second rect's rows");
assert!(
a >= 140 && b >= 170,
"rows {a}..{b} should be the second rect only — the first was \
already erased and acknowledged"
);
// A frame that draws nothing leaves the erase outstanding rather than
// dropping it, so skipping a composite cannot lose it.
o.clear();
assert!(o.dirty_rows().is_some(), "still outstanding");
}
/// A stroke outlines text, as `text` says it does. The positioned-line
/// path used to zero the outline, so a stroked label came out bare.
#[cfg(feature = "captions")]
#[test]
fn a_stroke_outlines_text() {
let red = |stroke: bool| {
let mut o = Overlay::new(240, 48);
o.set_font(crate::captions::CaptionFont::builtin());
o.text_size(20.0);
o.fill(Color::WHITE);
if stroke {
o.stroke(Color::new(1.0, 0.0, 0.0));
o.stroke_weight(3.0);
}
assert!(o.text(8.0, 8.0, "Outlined"));
o.pixels()
.chunks(4)
.filter(|p| p[3] > 128 && p[0] > 200 && p[1] < 60)
.count()
};
assert_eq!(red(false), 0);
assert!(red(true) > 100, "only {} outline pixels", red(true));
}
/// A variable face draws bold as its bold instance: heavier than the
/// regular, and no wider than the font's own bold advances make it —
/// not the regular struck twice. Skipped without SF Compact.
#[cfg(all(feature = "captions", target_os = "macos"))]
#[test]
fn bold_is_the_fonts_bold() {
let Some(font) = crate::captions::CaptionFont::try_sf_compact() else {
return;
};
let ink = |weight: u16| {
let mut o = Overlay::new(400, 48);
o.set_font(
font.with_weight(400)
.unwrap_or_else(|| crate::captions::CaptionFont::try_sf_compact().unwrap()),
);
o.text_size(18.0);
o.fill(Color::WHITE);
assert!(o.text_weight(weight), "the face has weight {weight}");
assert!(o.text(4.0, 8.0, "Hamburgefonstiv"));
let alpha: f32 = o.pixels().chunks(4).map(|p| p[3] as f32 / 255.0).sum();
(alpha, o.measure_text("Hamburgefonstiv").0)
};
let (regular, regular_width) = ink(400);
let (bold, bold_width) = ink(700);
assert!(
bold > regular * 1.3,
"bold ink {bold} against regular {regular}"
);
assert!(
bold_width > regular_width,
"bold is set wider by its own advances"
);
// And back: the regular face again, from the overlay's cache.
assert_eq!(ink(400).0, regular);
}
/// Italic is a style of its own, and leaning: the ink's top rows sit
/// right of where the upright's do, its bottom rows about where they
/// did. The bitmap face has none to give.
#[cfg(feature = "captions")]
#[test]
fn italic_text_leans() {
let centre = |italic: bool, rows: std::ops::Range<u32>| -> f32 {
let mut o = Overlay::new(240, 48);
o.set_font(
crate::captions::CaptionFont::from_ttf_bytes(include_bytes!(
"openscad/DejaVuSans.ttf"
))
.unwrap(),
);
o.text_size(24.0);
o.fill(Color::WHITE);
assert!(o.text_italic(italic));
assert!(o.text(8.0, 8.0, "llll"));
let (mut sum, mut w) = (0.0f32, 0.0f32);
for (i, p) in o.pixels().chunks(4).enumerate() {
let (x, y) = ((i % 240) as u32, (i / 240) as u32);
if rows.contains(&y) {
sum += x as f32 * p[3] as f32;
w += p[3] as f32;
}
}
sum / w
};
let (top, foot) = (10..16, 26..30);
let lean = centre(true, top.clone()) - centre(false, top);
assert!(lean > 2.0, "top rows moved {lean}");
assert!((centre(true, foot.clone()) - centre(false, foot)).abs() < 1.5);
let mut bitmap = Overlay::new(40, 20);
bitmap.set_font(crate::captions::CaptionFont::builtin());
assert!(!bitmap.text_italic(true));
}
/// Text is drawn by the caption painter straight into the buffer, so the
/// overlay has to ask it which rows it used rather than guess.
#[cfg(feature = "captions")]
#[test]
fn text_marks_the_rows_it_actually_landed_on() {
let mut o = Overlay::new(300, 200);
o.text_size(20.0);
o.fill(Color::WHITE);
assert!(o.text(10.0, 80.0, "a label"));
let (a, b) = o.dirty_rows().expect("the text is outstanding");
// Found by scanning the buffer, which is the ground truth.
let (mut first, mut last) = (u32::MAX, 0u32);
for (i, px) in o.pixels().chunks(4).enumerate() {
if px[3] > 0 {
let row = i as u32 / 300;
first = first.min(row);
last = last.max(row);
}
}
assert!(first != u32::MAX, "no ink");
assert!(
a <= first && b > last,
"band {a}..{b} should contain the ink, which is in {first}..={last}"
);
assert!(b - a < 60, "band {a}..{b} is much wider than the line");
}
#[test]
fn clear_and_resize_reset_the_canvas() {
let mut o = Overlay::new(16, 16);
o.fill(Color::WHITE);
o.rect(0.0, 0.0, 16.0, 16.0);
assert!(o.touched());
o.clear();
assert!(!o.touched());
assert!(o.pixels().iter().all(|&b| b == 0));
o.rect(0.0, 0.0, 16.0, 16.0);
o.resize(8, 32);
assert_eq!(o.size(), (8, 32));
assert_eq!(o.pixels().len(), 8 * 32 * 4);
assert!(o.pixels().iter().all(|&b| b == 0));
assert!(!o.touched());
// Same size is a no-op and keeps the contents.
o.fill(Color::WHITE);
o.rect(0.0, 0.0, 8.0, 32.0);
o.resize(8, 32);
assert!(o.touched(), "resizing to the same size should not clear");
}
/// Each alignment has to put the ink somewhere different, and in the right
/// direction. Measured as the horizontal centre of mass of the ink, which
/// needs no assumption about the font.
#[cfg(feature = "captions")]
#[test]
fn text_alignment_moves_the_ink_the_right_way() {
let centre_of_ink = |o: &Overlay| {
let (w, _) = o.size();
let (mut sum, mut weight) = (0.0f64, 0.0f64);
for (i, px) in o.pixels().chunks(4).enumerate() {
let a = px[3] as f64;
if a > 0.0 {
sum += (i % w as usize) as f64 * a;
weight += a;
}
}
assert!(weight > 0.0, "no ink");
sum / weight
};
let draw = |f: &dyn Fn(&mut Overlay) -> bool| {
let mut o = Overlay::new(400, 48);
o.text_size(20.0);
o.fill(Color::WHITE);
assert!(f(&mut o));
centre_of_ink(&o)
};
let anchor = 200.0f32;
let left = draw(&|o| o.text(anchor, 8.0, "measure me"));
let centre = draw(&|o| o.text_centered(anchor, 8.0, "measure me"));
let right = draw(&|o| o.text_right(anchor, 8.0, "measure me"));
assert!(
right < centre && centre < left,
"right {right:.1} should sit left of centred {centre:.1}, which sits \
left of left-aligned {left:.1}"
);
// Left-aligned starts at the anchor, right-aligned ends at it, and
// centred straddles it — so the centred one is about the midpoint of
// the other two.
assert!(
((left + right) * 0.5 - centre).abs() < 6.0,
"centred {centre:.1} should be near the midpoint of {left:.1} and {right:.1}"
);
let anchor = anchor as f64;
assert!(
centre > anchor - 60.0 && centre < anchor + 60.0,
"centred {centre:.1}"
);
}
#[cfg(feature = "captions")]
#[test]
fn text_marks_ink_and_measures_without_drawing() {
let mut o = Overlay::new(256, 64);
o.text_size(24.0);
o.fill(Color::WHITE);
let (w, h) = o.measure_text("Frame 120");
assert!(w > 0.0 && h > 0.0, "measured {w}x{h}");
assert!(!o.touched(), "measuring must not draw");
assert!(o.text(8.0, 8.0, "Frame 120"));
assert!(o.touched());
let ink: usize = o.pixels().chunks(4).filter(|p| p[3] > 0).count();
assert!(ink > 20, "only {ink} pixels of ink");
// An empty string is not an error and leaves no ink.
let mut blank = Overlay::new(64, 32);
assert!(!blank.text(0.0, 0.0, " "));
assert!(!blank.touched());
}
}