teksilo-render 0.9.1

wgpu renderer for Teksilo — rect, SDF and path pipelines with a glyph atlas.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Path atlas: CPU rasterizes paths with tiny-skia, caches results in a texture atlas with LRU eviction.

use std::collections::HashMap;
use std::hash::{Hash, Hasher};

use teksilo_canvas::paint::{FillRule, LineCap, LineJoin, StrokeSpace, StrokeStyle};
use teksilo_canvas::path::{Path, PathCommand};

/// Upper bound on a cosmetic path's rasterized dimension (device px). At
/// extreme zoom the body would otherwise exceed the atlas; beyond this the
/// body softens and the stroke drifts slightly off-cosmetic — an accepted
/// degradation far past normal zoom. Kept well under [`PathAtlas::max_size`]
/// (4096) to leave room for shelf packing.
const MAX_COSMETIC_RASTER_DIM: f32 = 2048.0;

/// Free vertical headroom (device px) below which `begin_frame` treats the
/// atlas as near-full and compacts. Roughly one tall shelf — enough that a
/// frame rarely runs out of room mid-walk (where reclaiming is unsafe).
const COMPACT_SLACK_PX: u32 = 256;

/// A region within the atlas texture.
#[derive(Debug, Clone, Copy)]
pub struct AtlasRegion {
    pub x: u32,
    pub y: u32,
    pub w: u32,
    pub h: u32,
    /// Frame when this region was last used.
    last_used_frame: u64,
}

/// Cache key derived from path geometry + stroke style + rasterized size.
///
/// Deliberately does **not** include color: the atlas now always
/// rasterizes an opaque-white AA coverage mask (see [`rasterize_path`]),
/// so a solid fill and a gradient fill of identical geometry share one
/// atlas entry — the color/gradient tint is applied by the GPU at draw
/// time, not baked into the bitmap.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PathCacheKey(u64);

impl PathCacheKey {
    fn new(path: &Path, style: &StrokeStyle, fill_rule: FillRule, w: u32, h: u32) -> Self {
        let mut hasher = std::hash::DefaultHasher::new();
        // Hash path commands
        for cmd in &path.commands {
            std::mem::discriminant(cmd).hash(&mut hasher);
            match cmd {
                PathCommand::MoveTo(p) | PathCommand::LineTo(p) => {
                    p.x.to_bits().hash(&mut hasher);
                    p.y.to_bits().hash(&mut hasher);
                }
                PathCommand::QuadTo { control, to } => {
                    control.x.to_bits().hash(&mut hasher);
                    control.y.to_bits().hash(&mut hasher);
                    to.x.to_bits().hash(&mut hasher);
                    to.y.to_bits().hash(&mut hasher);
                }
                PathCommand::CubicTo {
                    control1,
                    control2,
                    to,
                } => {
                    control1.x.to_bits().hash(&mut hasher);
                    control1.y.to_bits().hash(&mut hasher);
                    control2.x.to_bits().hash(&mut hasher);
                    control2.y.to_bits().hash(&mut hasher);
                    to.x.to_bits().hash(&mut hasher);
                    to.y.to_bits().hash(&mut hasher);
                }
                PathCommand::ArcTo {
                    rect,
                    start_angle,
                    sweep_angle,
                } => {
                    rect.x.to_bits().hash(&mut hasher);
                    rect.y.to_bits().hash(&mut hasher);
                    rect.width.to_bits().hash(&mut hasher);
                    rect.height.to_bits().hash(&mut hasher);
                    start_angle.to_bits().hash(&mut hasher);
                    sweep_angle.to_bits().hash(&mut hasher);
                }
                PathCommand::Close => {}
            }
        }
        // Hash stroke style
        style.width.to_bits().hash(&mut hasher);
        std::mem::discriminant(&style.line_cap).hash(&mut hasher);
        std::mem::discriminant(&style.line_join).hash(&mut hasher);
        if let Some(ref pattern) = style.dash_pattern {
            for &v in pattern {
                v.to_bits().hash(&mut hasher);
            }
        }
        style.dash_offset.to_bits().hash(&mut hasher);
        style.miter_limit.to_bits().hash(&mut hasher);
        // Cosmetic vs logical strokes bake differently (constant device width
        // vs zoom-scaled), so they must not share a cache entry.
        std::mem::discriminant(&style.space).hash(&mut hasher);
        // Winding vs even-odd fill produce different pixels for the same path.
        std::mem::discriminant(&fill_rule).hash(&mut hasher);
        // Hash rasterized dimensions
        w.hash(&mut hasher);
        h.hash(&mut hasher);
        PathCacheKey(hasher.finish())
    }
}

/// Shelf-packed atlas for rasterized paths with LRU eviction.
pub struct PathAtlas {
    /// Atlas pixel data (RGBA).
    pixels: Vec<u8>,
    width: u32,
    height: u32,
    /// Maximum atlas dimension.
    max_size: u32,
    /// Cache from path key to atlas region.
    cache: HashMap<PathCacheKey, AtlasRegion>,
    /// Current frame counter for LRU.
    current_frame: u64,
    /// Whether the atlas texture needs re-uploading.
    dirty: bool,
    // Shelf-packing state
    /// Current Y position of the next shelf.
    shelf_y: u32,
    /// Current X position within the current shelf.
    shelf_x: u32,
    /// Height of the current shelf (tallest entry in this row).
    shelf_height: u32,
    /// How many paths have been skipped because they could never fit the atlas.
    ///
    /// Such a path is simply not drawn. That is a silent hole in the frame, so it is
    /// counted rather than swallowed: a non-zero value means some geometry is being
    /// asked to rasterize larger than [`max_size`](Self::max_size), which is almost
    /// always a layout bug upstream (see [`Self::lookup_or_rasterize`]).
    oversize_skips: u64,
}

impl PathAtlas {
    /// Create a new path atlas with the given initial dimensions.
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            pixels: vec![0; (width * height * 4) as usize],
            width,
            height,
            max_size: 4096,
            cache: HashMap::new(),
            current_frame: 0,
            dirty: false,
            shelf_y: 0,
            shelf_x: 0,
            shelf_height: 0,
            oversize_skips: 0,
        }
    }

    /// How many paths have been skipped for being too large to ever fit the atlas.
    ///
    /// Each one is a path that simply was not drawn. Non-zero means some geometry is
    /// rasterizing bigger than `max_size` — upstream, that is a
    /// layout that has run away (an overlay spanning a whole scrolled document, a
    /// shape scaled by a runaway transform), and it is worth chasing rather than
    /// leaving as a hole in the frame.
    pub fn oversize_skips(&self) -> u64 {
        self.oversize_skips
    }

    /// Call at the start of each frame to advance the LRU counter.
    ///
    /// This is also the only point at which the atlas may safely **repack**
    /// itself: no `AtlasRegion` has been handed out for the new frame yet, so
    /// moving surviving entries to fresh coordinates cannot invalidate any
    /// region the renderer is still holding from the current frame. When the
    /// atlas is near-full and there are stale entries (not touched on the last
    /// completed frame), we compact — dropping the stale entries and repacking
    /// the rest tightly — so steady-state reclamation never has to happen
    /// mid-frame (which would corrupt already-placed paths).
    pub fn begin_frame(&mut self) {
        self.current_frame += 1;

        // Only the just-completed frame's working set is worth keeping
        // (temporal locality); anything older is fragmentation to reclaim.
        let keep_from = self.current_frame - 1;
        let near_full =
            self.shelf_y.saturating_add(self.shelf_height) + COMPACT_SLACK_PX >= self.height;
        let has_stale = self.cache.values().any(|r| r.last_used_frame < keep_from);
        if near_full && has_stale {
            self.compact(keep_from);
        }
    }

    /// Current atlas dimensions.
    pub fn size(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Whether the atlas texture needs re-uploading to the GPU.
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// Raw pixel data (RGBA).
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }

    /// Mark the atlas as uploaded.
    pub fn mark_clean(&mut self) {
        self.dirty = false;
    }

    /// Look up or rasterize a path, returning its atlas region.
    ///
    /// The rasterized bitmap is always an **opaque-white AA coverage
    /// mask** — color is applied by the GPU at draw time (solid fills tint
    /// it via the quad pipeline; gradients sample an analytic gradient in
    /// `path_gradient.wgsl` and modulate by the mask's alpha channel), so
    /// this function takes no color and two fills of identical geometry
    /// share one atlas entry regardless of their paint.
    ///
    /// `zoom` is the uniform scale of the view transform active where the path
    /// is drawn. For a **cosmetic** stroke ([`StrokeSpace::Device`]) the body
    /// is rasterized at the current zoom (so it stays sharp, matching the
    /// transform-scaled display quad 1:1) while the stroke is baked at a
    /// zoom-independent device width — the border holds a constant
    /// device-pixel thickness at any zoom. **Logical** strokes ignore `zoom`
    /// (the body bitmap is stretched by the display quad, as before).
    #[allow(clippy::too_many_arguments)] // rasterization params; bundling adds no clarity
    pub fn lookup_or_rasterize(
        &mut self,
        path: &Path,
        style: &StrokeStyle,
        fill_rule: FillRule,
        bounds: [f32; 4],
        scale_factor: f32,
        zoom: f32,
    ) -> Option<AtlasRegion> {
        // Cosmetic paths rasterize the body at the current zoom (so it stays
        // sharp 1:1 with the transform-scaled display quad). Cost: the zoom is
        // baked into the raster dimensions, which are part of the cache key,
        // so a CONTINUOUS zoom gesture is a cache miss every frame — each
        // visible cosmetic path is re-rasterized per frame while zooming (the
        // per-frame LRU keeps current-frame entries and evicts the rest, so
        // the atlas stays bounded, but CPU rasterization scales with the
        // visible cosmetic-path count). Cache hits resume once the zoom
        // settles. This is the cost of "full-fidelity" cosmetic paths; coarse
        // zoom-quantization would cut the re-raster rate but reintroduce the
        // sub-pixel width drift the zoom-aware path was chosen to avoid.
        let (geom_scale, stroke_scale) = if style.space == StrokeSpace::Device {
            let mut g = scale_factor * zoom.max(1e-3);
            // Keep the bitmap under the atlas budget at extreme zoom.
            let cap = MAX_COSMETIC_RASTER_DIM / bounds[2].max(bounds[3]).max(1.0);
            if g > cap {
                g = cap;
            }
            (g, scale_factor)
        } else {
            (scale_factor, scale_factor)
        };

        let raster_w = (bounds[2] * geom_scale).ceil() as u32;
        let raster_h = (bounds[3] * geom_scale).ceil() as u32;
        if raster_w == 0 || raster_h == 0 {
            return None;
        }

        // A path that can never fit the atlas must never be rasterized.
        //
        // Growth is capped at `max_size`, so `allocate_and_write` is guaranteed to
        // fail for anything larger — meaning the bitmap would be built, thrown away,
        // and rebuilt from scratch on the very next frame, forever. That is not a
        // slow frame, it is a permanent freeze: a single 7573x7563 path (one hazard
        // stripe painted across a tall overflow strip) is a 229 MB rasterization,
        // and redoing it every frame pinned the UI thread at 100% CPU for as long as
        // the path stayed on screen.
        //
        // Returning `None` here is not a new failure mode — it is the one the caller
        // already handled (and already reached, just hundreds of megabytes later):
        // the path is skipped for this frame. Bailing out *before* the raster turns
        // an unbounded stall into a dropped draw.
        if raster_w > self.max_size || raster_h > self.max_size {
            self.oversize_skips += 1;
            return None;
        }

        let key = PathCacheKey::new(path, style, fill_rule, raster_w, raster_h);

        // Cache hit
        if let Some(region) = self.cache.get_mut(&key) {
            region.last_used_frame = self.current_frame;
            return Some(*region);
        }

        // Rasterize — always opaque white; see PathCacheKey and this
        // function's doc comment for why color is not a parameter.
        let pixels = rasterize_path(path, style, fill_rule, bounds, geom_scale, stroke_scale)?;
        let region = self.allocate_and_write(key, raster_w, raster_h, &pixels)?;
        Some(region)
    }

    /// Try to allocate space in the atlas via shelf packing.
    ///
    /// Strategy, in order:
    ///   1. Try the current shelf / a new shelf at the existing size.
    ///   2. Grow the atlas (doubles up to `max_size`). Growth preserves
    ///      every existing entry's `(x, y)` so any `AtlasRegion` values
    ///      handed out earlier in the same render pass stay valid.
    ///   3. Last resort, evict. Eviction never moves entries already handed
    ///      out this frame (that would invalidate `AtlasRegion`s the caller
    ///      cached earlier in the same render walk → wrong-pixel sampling). It
    ///      can only reclaim space when nothing has been handed out yet this
    ///      frame; otherwise the allocation fails and the path is skipped for
    ///      this frame. Steady-state reclamation happens safely in
    ///      [`PathAtlas::begin_frame`] (compaction) before any region is
    ///      handed out.
    fn allocate_and_write(
        &mut self,
        key: PathCacheKey,
        w: u32,
        h: u32,
        pixels: &[u8],
    ) -> Option<AtlasRegion> {
        if let Some(region) = self.try_allocate(w, h) {
            self.blit(region.x, region.y, w, h, pixels);
            self.cache.insert(key, region);
            self.dirty = true;
            return Some(region);
        }

        // Grow first — keeps every existing entry at the same coordinates.
        while self.try_grow() {
            if let Some(region) = self.try_allocate(w, h) {
                self.blit(region.x, region.y, w, h, pixels);
                self.cache.insert(key, region);
                self.dirty = true;
                return Some(region);
            }
        }

        // Atlas at max size and still no room. Try eviction — but it will
        // refuse to move any entry already handed out this frame, so if the
        // frame's live working set already fills a max-size atlas this is a
        // no-op and we return `None` (the path is skipped this frame, which is
        // correct: it genuinely doesn't fit). It never corrupts placed paths.
        self.evict_lru();
        if let Some(region) = self.try_allocate(w, h) {
            self.blit(region.x, region.y, w, h, pixels);
            self.cache.insert(key, region);
            self.dirty = true;
            return Some(region);
        }

        None
    }

    /// Try to allocate a region using shelf packing.
    fn try_allocate(&mut self, w: u32, h: u32) -> Option<AtlasRegion> {
        // Does it fit on the current shelf?
        if self.shelf_x + w <= self.width && self.shelf_y + h.max(self.shelf_height) <= self.height
        {
            let region = AtlasRegion {
                x: self.shelf_x,
                y: self.shelf_y,
                w,
                h,
                last_used_frame: self.current_frame,
            };
            self.shelf_x += w;
            self.shelf_height = self.shelf_height.max(h);
            return Some(region);
        }

        // Start a new shelf
        let new_y = self.shelf_y + self.shelf_height;
        if w <= self.width && new_y + h <= self.height {
            self.shelf_y = new_y;
            self.shelf_x = w;
            self.shelf_height = h;
            let region = AtlasRegion {
                x: 0,
                y: new_y,
                w,
                h,
                last_used_frame: self.current_frame,
            };
            return Some(region);
        }

        None
    }

    /// Mid-frame, last-resort space reclamation.
    ///
    /// Eviction must **never** move an entry that has already been handed out
    /// this frame: the renderer's pre-pass caches each path's `AtlasRegion` in
    /// `path_regions[..]` and reads it back later in the same frame, so moving
    /// those pixels makes the cached region sample the wrong location (flicker
    /// / wrong-pixel rendering on path-heavy widgets like LineChart and
    /// PieChart). A shelf packer cannot reclaim the fragmented space held by
    /// older entries without repacking the live ones, so:
    ///
    /// * If **no** region has been handed out this frame, clearing the whole
    ///   atlas is safe — do it (the next lookups re-rasterize from a clean
    ///   atlas, and `try_grow` already ran).
    /// * If **any** region is live this frame, we leave the atlas untouched.
    ///   `allocate_and_write` then returns `None` and the path is skipped for
    ///   one frame — never corrupted.
    ///
    /// Steady-state reclamation that *does* repack happens in
    /// [`PathAtlas::begin_frame`], where no region is live yet.
    fn evict_lru(&mut self) {
        if self.cache.is_empty() {
            return;
        }

        let current = self.current_frame;
        let any_live = self.cache.values().any(|r| r.last_used_frame == current);
        if any_live {
            // Can't reclaim without moving a live entry — bail out.
            return;
        }

        // No live entries — safe to clear everything.
        self.cache.clear();
        self.pixels.fill(0);
        self.shelf_x = 0;
        self.shelf_y = 0;
        self.shelf_height = 0;
        self.dirty = true;
    }

    /// Drop every entry not used on or after `keep_from_frame` and repack the
    /// survivors tightly from the top of the atlas.
    ///
    /// This **moves** surviving entries, so it is only sound when no
    /// `AtlasRegion` has been handed out for the current frame yet — i.e. it
    /// must be called only from [`PathAtlas::begin_frame`].
    fn compact(&mut self, keep_from_frame: u64) {
        // Read survivors out before we wipe the backing pixels. `read_region`
        // and `cache.iter()` both borrow `&self` immutably, so this is fine.
        let mut survivors: Vec<(PathCacheKey, AtlasRegion, Vec<u8>)> = self
            .cache
            .iter()
            .filter(|(_, r)| r.last_used_frame >= keep_from_frame)
            .map(|(k, r)| (*k, *r, self.read_region(*r)))
            .collect();

        self.cache.clear();
        self.pixels.fill(0);
        self.shelf_x = 0;
        self.shelf_y = 0;
        self.shelf_height = 0;
        self.dirty = true;

        // Repack tallest-first to limit shelf wastage.
        survivors.sort_by_key(|(_, r, _)| std::cmp::Reverse(r.h));
        for (key, old_region, pixels) in survivors {
            if let Some(new_region) = self.try_allocate(old_region.w, old_region.h) {
                self.blit(
                    new_region.x,
                    new_region.y,
                    new_region.w,
                    new_region.h,
                    &pixels,
                );
                self.cache.insert(
                    key,
                    AtlasRegion {
                        x: new_region.x,
                        y: new_region.y,
                        w: new_region.w,
                        h: new_region.h,
                        last_used_frame: old_region.last_used_frame,
                    },
                );
            }
        }
    }

    /// Read a region's pixels back out of the atlas (for repacking
    /// survivors during eviction). Returns an RGBA buffer of `w*h*4` bytes.
    fn read_region(&self, region: AtlasRegion) -> Vec<u8> {
        let mut out = vec![0u8; (region.w * region.h * 4) as usize];
        for row in 0..region.h {
            let src_start = ((region.y + row) * self.width * 4 + region.x * 4) as usize;
            let src_end = src_start + (region.w * 4) as usize;
            let dst_start = (row * region.w * 4) as usize;
            let dst_end = dst_start + (region.w * 4) as usize;
            if src_end <= self.pixels.len() && dst_end <= out.len() {
                out[dst_start..dst_end].copy_from_slice(&self.pixels[src_start..src_end]);
            }
        }
        out
    }

    /// Try to grow the atlas (double dimensions up to max_size).
    fn try_grow(&mut self) -> bool {
        let new_w = (self.width * 2).min(self.max_size);
        let new_h = (self.height * 2).min(self.max_size);
        if new_w == self.width && new_h == self.height {
            return false; // Already at max
        }
        let mut new_pixels = vec![0u8; (new_w * new_h * 4) as usize];
        // Copy existing data row by row
        for y in 0..self.height {
            let src_start = (y * self.width * 4) as usize;
            let src_end = src_start + (self.width * 4) as usize;
            let dst_start = (y * new_w * 4) as usize;
            new_pixels[dst_start..dst_start + (self.width * 4) as usize]
                .copy_from_slice(&self.pixels[src_start..src_end]);
        }
        self.pixels = new_pixels;
        self.width = new_w;
        self.height = new_h;
        self.dirty = true;
        true
    }

    /// Write pixels into the atlas at the given position.
    fn blit(&mut self, x: u32, y: u32, w: u32, h: u32, pixels: &[u8]) {
        for row in 0..h {
            let src_start = (row * w * 4) as usize;
            let src_end = src_start + (w * 4) as usize;
            let dst_start = ((y + row) * self.width * 4 + x * 4) as usize;
            let dst_end = dst_start + (w * 4) as usize;
            if src_end <= pixels.len() && dst_end <= self.pixels.len() {
                self.pixels[dst_start..dst_end].copy_from_slice(&pixels[src_start..src_end]);
            }
        }
    }
}

/// Rasterize a path to RGBA pixels using tiny-skia, always as an
/// **opaque-white AA coverage mask** (RGB = white, alpha = coverage).
/// Color is intentionally not a parameter — see [`PathAtlas::lookup_or_rasterize`]:
/// the mask is tinted/gradient-sampled by the GPU at draw time (matching
/// `quad.wgsl`'s `flags = 0` monochrome-mask convention), so rasterization
/// only needs to bake the geometry's AA coverage, letting solid and
/// gradient fills of the same path share one atlas entry. This also fixes
/// a pre-existing double-alpha bug: baking a translucent color into the
/// bitmap AND multiplying by that same color's alpha again at draw time
/// squared the effective alpha.
///
/// `geom_scale` scales the path **geometry** into the bitmap (= `scale_factor`
/// for logical strokes, `scale_factor × zoom` for cosmetic ones so the body is
/// sharp at the current zoom). `stroke_scale` scales the **stroke width** (=
/// `scale_factor` always; for cosmetic strokes this bakes a zoom-independent
/// device-pixel thickness). The two are equal for the logical/fill path.
fn rasterize_path(
    path: &Path,
    style: &StrokeStyle,
    fill_rule: FillRule,
    bounds: [f32; 4],
    geom_scale: f32,
    stroke_scale: f32,
) -> Option<Vec<u8>> {
    let w = (bounds[2] * geom_scale).ceil() as u32;
    let h = (bounds[3] * geom_scale).ceil() as u32;
    if w == 0 || h == 0 {
        return None;
    }

    let mut pixmap = tiny_skia::Pixmap::new(w, h)?;

    // Build tiny-skia path, translating from bounds origin
    let mut pb = tiny_skia::PathBuilder::new();
    for cmd in &path.commands {
        match *cmd {
            PathCommand::MoveTo(p) => {
                pb.move_to(
                    (p.x - bounds[0]) * geom_scale,
                    (p.y - bounds[1]) * geom_scale,
                );
            }
            PathCommand::LineTo(p) => {
                pb.line_to(
                    (p.x - bounds[0]) * geom_scale,
                    (p.y - bounds[1]) * geom_scale,
                );
            }
            PathCommand::QuadTo { control, to } => {
                pb.quad_to(
                    (control.x - bounds[0]) * geom_scale,
                    (control.y - bounds[1]) * geom_scale,
                    (to.x - bounds[0]) * geom_scale,
                    (to.y - bounds[1]) * geom_scale,
                );
            }
            PathCommand::CubicTo {
                control1,
                control2,
                to,
            } => {
                pb.cubic_to(
                    (control1.x - bounds[0]) * geom_scale,
                    (control1.y - bounds[1]) * geom_scale,
                    (control2.x - bounds[0]) * geom_scale,
                    (control2.y - bounds[1]) * geom_scale,
                    (to.x - bounds[0]) * geom_scale,
                    (to.y - bounds[1]) * geom_scale,
                );
            }
            PathCommand::ArcTo {
                rect,
                start_angle,
                sweep_angle,
            } => {
                // Approximate arc with cubic Bézier segments
                arc_to_cubics(
                    &mut pb,
                    rect.x - bounds[0],
                    rect.y - bounds[1],
                    rect.width,
                    rect.height,
                    start_angle,
                    sweep_angle,
                    geom_scale,
                );
            }
            PathCommand::Close => {
                pb.close();
            }
        }
    }

    let sk_path = pb.finish()?;

    // Always opaque white — a pure AA coverage mask. Color/gradient tint
    // is applied by the GPU at draw time (see this function's doc comment).
    let paint = tiny_skia::Paint {
        shader: tiny_skia::Shader::SolidColor(tiny_skia::Color::from_rgba(1.0, 1.0, 1.0, 1.0)?),
        anti_alias: true,
        ..Default::default()
    };

    if style.width > 0.0 {
        // Stroke
        let line_cap = match style.line_cap {
            LineCap::Butt => tiny_skia::LineCap::Butt,
            LineCap::Round => tiny_skia::LineCap::Round,
            LineCap::Square => tiny_skia::LineCap::Square,
        };
        let line_join = match style.line_join {
            LineJoin::Miter => tiny_skia::LineJoin::Miter,
            LineJoin::Round => tiny_skia::LineJoin::Round,
            LineJoin::Bevel => tiny_skia::LineJoin::Bevel,
        };
        let dash = style
            .dash_pattern
            .as_ref()
            .and_then(|pattern| tiny_skia::StrokeDash::new(pattern.clone(), style.dash_offset));
        let stroke = tiny_skia::Stroke {
            width: style.width * stroke_scale,
            line_cap,
            line_join,
            miter_limit: style.miter_limit,
            dash,
        };
        pixmap.stroke_path(
            &sk_path,
            &paint,
            &stroke,
            tiny_skia::Transform::identity(),
            None,
        );
    } else {
        // Fill
        let sk_rule = match fill_rule {
            FillRule::Winding => tiny_skia::FillRule::Winding,
            FillRule::EvenOdd => tiny_skia::FillRule::EvenOdd,
        };
        pixmap.fill_path(
            &sk_path,
            &paint,
            sk_rule,
            tiny_skia::Transform::identity(),
            None,
        );
    }

    Some(pixmap.data().to_vec())
}

/// Approximate an elliptical arc with cubic Bézier segments.
/// Each 90° sweep is one cubic; smaller sweeps use one cubic.
///
/// `start_angle` and `sweep_angle` are in **degrees** (matching the
/// public `Path::arc_to` API and existing call sites like
/// `Path::circle` and `Path::rounded_rect`). They are converted to
/// radians internally before being fed to `f32::cos`/`f32::sin`.
#[allow(clippy::too_many_arguments)]
fn arc_to_cubics(
    pb: &mut tiny_skia::PathBuilder,
    cx: f32,
    cy: f32,
    w: f32,
    h: f32,
    start_angle: f32,
    sweep_angle: f32,
    scale_factor: f32,
) {
    let rx = w * 0.5;
    let ry = h * 0.5;
    let center_x = (cx + rx) * scale_factor;
    let center_y = (cy + ry) * scale_factor;
    let rx_s = rx * scale_factor;
    let ry_s = ry * scale_factor;

    let mut remaining = sweep_angle.to_radians();
    let mut angle = start_angle.to_radians();
    let sign = if remaining >= 0.0 { 1.0 } else { -1.0 };

    while remaining.abs() > 0.001 {
        let chunk = sign * remaining.abs().min(std::f32::consts::FRAC_PI_2);
        let half = chunk * 0.5;
        let k = (4.0 / 3.0) * (1.0 - half.cos()) / half.sin();

        let cos_a = angle.cos();
        let sin_a = angle.sin();
        let cos_b = (angle + chunk).cos();
        let sin_b = (angle + chunk).sin();

        let p1x = center_x + rx_s * cos_a;
        let p1y = center_y + ry_s * sin_a;
        let p2x = center_x + rx_s * (cos_a - k * sin_a);
        let p2y = center_y + ry_s * (sin_a + k * cos_a);
        let p3x = center_x + rx_s * (cos_b + k * sin_b);
        let p3y = center_y + ry_s * (sin_b - k * cos_b);
        let p4x = center_x + rx_s * cos_b;
        let p4y = center_y + ry_s * sin_b;

        if (remaining - sweep_angle).abs() < 0.001 && pb.is_empty() {
            // First segment of a subpath that opens with an arc (e.g. a bare
            // `<circle>`): move_to its start point. tiny-skia would otherwise
            // insert an implicit move_to(0,0) before this line_to and draw a
            // stray line from the origin to the arc.
            pb.move_to(p1x, p1y);
        } else {
            // Connect to the arc's start from the current point (a shared
            // vertex on rounded rects / continued subpaths; a zero-length
            // no-op when a move_to already placed us there).
            pb.line_to(p1x, p1y);
        }
        pb.cubic_to(p2x, p2y, p3x, p3y, p4x, p4y);

        angle += chunk;
        remaining -= chunk;
    }
}

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

    /// A path larger than the atlas can ever hold must be rejected **before** it is
    /// rasterized — not after.
    ///
    /// The atlas grows only up to `max_size`, so `allocate_and_write` could never
    /// store such a path: it was rasterized, discarded, and rasterized again on the
    /// next frame, forever. The geometry below is the one that actually shipped the
    /// freeze — a single 45° hazard band across a 7563px-tall overflow strip, whose
    /// bounding box is a 229 MB bitmap. Redoing that every frame pinned the UI thread
    /// at 100% CPU and the app never recovered.
    ///
    /// If this test ever hangs rather than fails, the guard is gone.
    #[test]
    fn a_path_too_big_for_the_atlas_is_never_rasterized() {
        let mut atlas = PathAtlas::new(256, 256);

        // The exact parallelogram from the freeze: height 7563, width 7563 + PITCH.
        let (h, pitch) = (7563.0_f32, 10.0_f32);
        let w = h + pitch;
        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(pitch, 0.0)));
        path.commands.push(PathCommand::LineTo(Point::new(w, h)));
        path.commands.push(PathCommand::LineTo(Point::new(h, h)));
        path.commands.push(PathCommand::Close);

        let before = atlas.cache.len();
        let region = atlas.lookup_or_rasterize(
            &path,
            &StrokeStyle::solid(0.0),
            FillRule::Winding,
            [0.0, 0.0, w, h],
            1.0,
            1.0,
        );

        assert!(
            region.is_none(),
            "a {w}x{h} path cannot fit an atlas capped at {} — it must be skipped, \
             not rasterized into a 229 MB bitmap that is then thrown away",
            atlas.max_size
        );
        assert_eq!(
            atlas.cache.len(),
            before,
            "the rejected path must not leave a cache entry behind"
        );
        // `is_none()` alone proves nothing: BEFORE the guard existed the call also
        // returned None — it just rasterized 229 MB and failed to allocate first,
        // which is precisely the bug. What must be asserted is that we bailed out
        // *early*, so pin the counter that only the pre-raster guard increments.
        assert_eq!(
            atlas.oversize_skips(),
            1,
            "the path must be rejected BEFORE rasterizing; without the early guard \
             this call still returns None, but only after building and discarding a \
             229 MB bitmap — every frame, forever"
        );
    }

    /// The guard rejects only what genuinely cannot fit: a path right at the limit
    /// still rasterizes, so the bail-out cannot quietly swallow legitimate art.
    #[test]
    fn a_path_that_still_fits_the_atlas_is_rasterized() {
        let mut atlas = PathAtlas::new(256, 256);
        let side = atlas.max_size as f32; // exactly at the cap

        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(side, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(side, side)));
        path.commands
            .push(PathCommand::LineTo(Point::new(0.0, side)));
        path.commands.push(PathCommand::Close);

        let region = atlas.lookup_or_rasterize(
            &path,
            &StrokeStyle::solid(0.0),
            FillRule::Winding,
            [0.0, 0.0, side, side],
            1.0,
            1.0,
        );
        assert!(
            region.is_some(),
            "a path exactly at max_size ({side}) must still be rasterized — the guard \
             is for paths that can NEVER fit, not for merely large ones"
        );
        assert_eq!(
            atlas.oversize_skips(),
            0,
            "the guard must not fire on a path that fits"
        );
    }

    #[test]
    fn rasterize_simple_rect_path() {
        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 10.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(0.0, 10.0)));
        path.commands.push(PathCommand::Close);

        let style = StrokeStyle::solid(0.0);
        let bounds = [0.0, 0.0, 10.0, 10.0];
        let pixels = rasterize_path(&path, &style, FillRule::Winding, bounds, 1.0, 1.0);
        assert!(pixels.is_some());
        let px = pixels.unwrap();
        assert_eq!(px.len(), 10 * 10 * 4);
        // Center pixel should be opaque white (a pure coverage mask —
        // color is no longer baked into the bitmap, see C3).
        let center = (5 * 10 + 5) * 4;
        assert!(px[center] > 200); // R
        assert!(px[center + 1] > 200); // G
        assert!(px[center + 2] > 200); // B
        assert!(px[center + 3] > 200); // A (coverage)
    }

    #[test]
    fn rasterize_stroke_path() {
        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(1.0, 5.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(9.0, 5.0)));

        let style = StrokeStyle::solid(2.0);
        let bounds = [0.0, 0.0, 10.0, 10.0];
        let pixels = rasterize_path(&path, &style, FillRule::Winding, bounds, 1.0, 1.0);
        assert!(pixels.is_some());
    }

    #[test]
    fn cache_key_distinguishes_line_join() {
        // Two strokes identical except for line join must NOT share a
        // cache entry — otherwise the atlas serves the first's pixels
        // for the second (the bug: line_join was honored in the
        // rasterizer but absent from the key).
        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 10.0)));

        let miter = StrokeStyle {
            line_join: LineJoin::Miter,
            ..StrokeStyle::solid(2.0)
        };
        let round = StrokeStyle {
            line_join: LineJoin::Round,
            ..StrokeStyle::solid(2.0)
        };
        assert_ne!(
            PathCacheKey::new(&path, &miter, FillRule::Winding, 12, 12),
            PathCacheKey::new(&path, &round, FillRule::Winding, 12, 12),
            "miter and round joins must hash to different cache keys"
        );
    }

    #[test]
    fn cache_key_distinguishes_fill_rule() {
        // Winding vs even-odd produce different pixels for the same path, so
        // they must not share an atlas entry.
        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 10.0)));
        path.commands.push(PathCommand::Close);
        let style = StrokeStyle::solid(0.0);
        assert_ne!(
            PathCacheKey::new(&path, &style, FillRule::Winding, 12, 12),
            PathCacheKey::new(&path, &style, FillRule::EvenOdd, 12, 12),
            "winding and even-odd fills must hash to different cache keys"
        );
    }

    #[test]
    fn atlas_cache_hit() {
        let mut atlas = PathAtlas::new(256, 256);
        atlas.begin_frame();

        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 10.0)));
        path.commands.push(PathCommand::Close);

        let style = StrokeStyle::solid(0.0);
        let bounds = [0.0, 0.0, 10.0, 10.0];

        let r1 = atlas
            .lookup_or_rasterize(&path, &style, FillRule::Winding, bounds, 1.0, 1.0)
            .unwrap();
        let r2 = atlas
            .lookup_or_rasterize(&path, &style, FillRule::Winding, bounds, 1.0, 1.0)
            .unwrap();

        // Same region (cache hit)
        assert_eq!(r1.x, r2.x);
        assert_eq!(r1.y, r2.y);
    }

    #[test]
    fn cache_hit_is_independent_of_color() {
        // C3: color is no longer part of the rasterization or the cache
        // key — two lookups with identical geometry/stroke/size but
        // DIFFERENT colors (as the caller would pass via the paint,
        // before this refactor) must now hit the SAME atlas entry, since
        // `lookup_or_rasterize` no longer takes a color at all. This is
        // what lets a solid fill and a gradient fill of the same path
        // share one atlas entry.
        let mut atlas = PathAtlas::new(256, 256);
        atlas.begin_frame();

        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(10.0, 10.0)));
        path.commands.push(PathCommand::Close);

        let style = StrokeStyle::solid(0.0);
        let bounds = [0.0, 0.0, 10.0, 10.0];

        // Simulate two draw calls that would previously have carried
        // different colors — the API no longer distinguishes them, so
        // both lookups are for the exact same cache key.
        let r1 = atlas
            .lookup_or_rasterize(&path, &style, FillRule::Winding, bounds, 1.0, 1.0)
            .expect("first lookup rasterizes and caches");
        let r2 = atlas
            .lookup_or_rasterize(&path, &style, FillRule::Winding, bounds, 1.0, 1.0)
            .expect("second lookup hits the same cache entry");

        assert_eq!(r1.x, r2.x, "cache hit: same region x");
        assert_eq!(r1.y, r2.y, "cache hit: same region y");
        assert_eq!(r1.w, r2.w);
        assert_eq!(r1.h, r2.h);
        assert_eq!(atlas.cache.len(), 1, "only one atlas entry for both calls");
    }

    #[test]
    fn atlas_begin_frame_advances() {
        let mut atlas = PathAtlas::new(256, 256);
        assert_eq!(atlas.current_frame, 0);
        atlas.begin_frame();
        assert_eq!(atlas.current_frame, 1);
        atlas.begin_frame();
        assert_eq!(atlas.current_frame, 2);
    }

    #[test]
    fn atlas_eviction_clears_stale() {
        let mut atlas = PathAtlas::new(64, 64);

        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(8.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(8.0, 8.0)));
        path.commands.push(PathCommand::Close);
        let style = StrokeStyle::solid(0.0);
        let bounds = [0.0, 0.0, 8.0, 8.0];

        atlas.begin_frame(); // frame 1
        atlas.lookup_or_rasterize(&path, &style, FillRule::Winding, bounds, 1.0, 1.0);

        // Advance well past the entry
        atlas.begin_frame(); // frame 2
        atlas.begin_frame(); // frame 3
        atlas.begin_frame(); // frame 4

        // Eviction should clear it
        atlas.evict_lru();
        assert!(atlas.cache.is_empty());
    }

    #[test]
    fn evict_preserves_current_frame_entries() {
        // Regression: previously `evict_lru` cleared the entire cache,
        // so a second path inserted in the same frame could displace
        // the first — `path_regions[0]` ended up pointing at pixels
        // that now belonged to path #2. LineChart and PieChart hit this
        // routinely because their paths cover most of the plot area.
        let mut atlas = PathAtlas::new(64, 64);
        atlas.begin_frame();

        let mut p1 = Path::new();
        p1.commands.push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        p1.commands.push(PathCommand::LineTo(Point::new(40.0, 0.0)));
        p1.commands
            .push(PathCommand::LineTo(Point::new(40.0, 40.0)));
        p1.commands.push(PathCommand::Close);

        let mut p2 = Path::new();
        p2.commands.push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        p2.commands.push(PathCommand::LineTo(Point::new(50.0, 0.0)));
        p2.commands
            .push(PathCommand::LineTo(Point::new(50.0, 50.0)));
        p2.commands.push(PathCommand::Close);

        let style = StrokeStyle::solid(0.0);
        let r1 = atlas
            .lookup_or_rasterize(
                &p1,
                &style,
                FillRule::Winding,
                [0.0, 0.0, 40.0, 40.0],
                1.0,
                1.0,
            )
            .expect("p1 fits");

        // p2 doesn't fit in the remaining space → eviction triggers.
        // After the fix, p1 (current-frame) survives and gets repacked.
        let _r2 = atlas.lookup_or_rasterize(
            &p2,
            &style,
            FillRule::Winding,
            [0.0, 0.0, 50.0, 50.0],
            1.0,
            1.0,
        );

        // Looking up p1 again must still hit cache (with possibly a new
        // region, but stable across the lookup).
        let r1b = atlas
            .lookup_or_rasterize(
                &p1,
                &style,
                FillRule::Winding,
                [0.0, 0.0, 40.0, 40.0],
                1.0,
                1.0,
            )
            .expect("p1 still cached after eviction");
        // The repacked region may have moved, but lookup_or_rasterize
        // must return a non-None region for p1 — i.e. it wasn't lost.
        let _ = (r1, r1b);
        assert!(atlas.cache.contains_key(&PathCacheKey::new(
            &p1,
            &style,
            FillRule::Winding,
            40,
            40,
        )));
    }

    #[test]
    fn evict_never_moves_live_entry_when_full() {
        // Core invariant for the stale-UV fix: once a region is handed out
        // this frame it is frozen. If a later path can't fit and the atlas is
        // already at max size, the new path is skipped (returns None) — the
        // live entry must NOT be repacked, or `path_regions[..]` would sample
        // the wrong pixels later in the same frame.
        let mut atlas = PathAtlas::new(64, 64);
        atlas.max_size = 64; // forbid growth so eviction is the only path
        atlas.begin_frame();

        let mut p1 = Path::new();
        p1.commands.push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        p1.commands.push(PathCommand::LineTo(Point::new(60.0, 0.0)));
        p1.commands
            .push(PathCommand::LineTo(Point::new(60.0, 60.0)));
        p1.commands.push(PathCommand::Close);

        let mut p2 = Path::new();
        p2.commands.push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        p2.commands.push(PathCommand::LineTo(Point::new(62.0, 0.0)));
        p2.commands
            .push(PathCommand::LineTo(Point::new(62.0, 62.0)));
        p2.commands.push(PathCommand::Close);

        let style = StrokeStyle::solid(0.0);
        let r1 = atlas
            .lookup_or_rasterize(
                &p1,
                &style,
                FillRule::Winding,
                [0.0, 0.0, 60.0, 60.0],
                1.0,
                1.0,
            )
            .expect("p1 fits");

        // p2 can't fit, can't grow → must be skipped, not placed by moving p1.
        let r2 = atlas.lookup_or_rasterize(
            &p2,
            &style,
            FillRule::Winding,
            [0.0, 0.0, 62.0, 62.0],
            1.0,
            1.0,
        );
        assert!(
            r2.is_none(),
            "an unfittable path is skipped, never placed by evicting a live entry"
        );

        // p1's region is byte-for-byte unchanged.
        let r1b = atlas
            .lookup_or_rasterize(
                &p1,
                &style,
                FillRule::Winding,
                [0.0, 0.0, 60.0, 60.0],
                1.0,
                1.0,
            )
            .expect("p1 still cached");
        assert_eq!(r1.x, r1b.x, "live entry must not move");
        assert_eq!(r1.y, r1b.y, "live entry must not move");
    }

    #[test]
    fn begin_frame_compacts_stale_entries() {
        // `begin_frame` is the safe point to repack: nothing is handed out
        // for the new frame yet. A near-full atlas with entries not used on
        // the last completed frame compacts them away.
        let mut atlas = PathAtlas::new(64, 64);
        atlas.begin_frame(); // frame 1

        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(8.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(8.0, 8.0)));
        path.commands.push(PathCommand::Close);
        let style = StrokeStyle::solid(0.0);
        atlas
            .lookup_or_rasterize(
                &path,
                &style,
                FillRule::Winding,
                [0.0, 0.0, 8.0, 8.0],
                1.0,
                1.0,
            )
            .expect("entry fits");
        assert_eq!(atlas.cache.len(), 1);

        atlas.begin_frame(); // frame 2 — keep_from = 1, entry (used f1) kept
        assert_eq!(
            atlas.cache.len(),
            1,
            "entry from the last completed frame is kept"
        );

        atlas.begin_frame(); // frame 3 — keep_from = 2, entry (used f1) is stale
        assert!(
            atlas.cache.is_empty(),
            "stale entry compacted away on begin_frame"
        );
    }

    #[test]
    fn atlas_grow() {
        let mut atlas = PathAtlas::new(16, 16);
        assert!(atlas.try_grow());
        assert_eq!(atlas.width, 32);
        assert_eq!(atlas.height, 32);
    }

    #[test]
    fn growth_preserves_earlier_frame_regions() {
        // Regression: when a single frame inserts more paths than fit in
        // the initial atlas, we must grow rather than evict — eviction
        // repacks current-frame survivors at fresh coordinates,
        // invalidating any AtlasRegion the renderer already cached for
        // them earlier in the same frame. With grow-first, the first
        // entry's region stays valid throughout the frame.
        let mut atlas = PathAtlas::new(64, 64);
        atlas.begin_frame();

        let mut p1 = Path::new();
        p1.commands.push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        p1.commands.push(PathCommand::LineTo(Point::new(50.0, 0.0)));
        p1.commands
            .push(PathCommand::LineTo(Point::new(50.0, 50.0)));
        p1.commands.push(PathCommand::Close);

        let mut p2 = Path::new();
        p2.commands.push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        p2.commands.push(PathCommand::LineTo(Point::new(60.0, 0.0)));
        p2.commands
            .push(PathCommand::LineTo(Point::new(60.0, 60.0)));
        p2.commands.push(PathCommand::Close);

        let style = StrokeStyle::solid(0.0);
        let r1 = atlas
            .lookup_or_rasterize(
                &p1,
                &style,
                FillRule::Winding,
                [0.0, 0.0, 50.0, 50.0],
                1.0,
                1.0,
            )
            .expect("p1 fits");

        // p2 doesn't fit alongside p1 in 64×64 → atlas should grow,
        // not evict. After growth, p1's region must still be at the
        // same coordinates we got back the first time.
        let _r2 = atlas
            .lookup_or_rasterize(
                &p2,
                &style,
                FillRule::Winding,
                [0.0, 0.0, 60.0, 60.0],
                1.0,
                1.0,
            )
            .expect("p2 fits after grow");

        let r1_after = atlas
            .lookup_or_rasterize(
                &p1,
                &style,
                FillRule::Winding,
                [0.0, 0.0, 50.0, 50.0],
                1.0,
                1.0,
            )
            .expect("p1 still cached");
        assert_eq!(r1.x, r1_after.x, "p1 must not move when atlas grows");
        assert_eq!(r1.y, r1_after.y, "p1 must not move when atlas grows");
    }

    #[test]
    fn cosmetic_path_raster_is_zoom_aware_logical_is_not() {
        // A cosmetic stroke rasterizes its body at the view zoom (so it stays
        // sharp and matches the transform-scaled display quad 1:1) — the
        // raster dimensions scale with zoom. A logical stroke ignores zoom
        // (one bitmap, stretched by the quad), so its raster size and cache
        // entry are zoom-independent.
        let mut atlas = PathAtlas::new(512, 512);
        atlas.begin_frame();
        let mut path = Path::new();
        path.commands
            .push(PathCommand::MoveTo(Point::new(0.0, 0.0)));
        path.commands
            .push(PathCommand::LineTo(Point::new(40.0, 0.0)));
        let bounds = [0.0, 0.0, 40.0, 4.0];

        let cosmetic = StrokeStyle::hairline(2.0);
        let r1 = atlas
            .lookup_or_rasterize(&path, &cosmetic, FillRule::Winding, bounds, 1.0, 1.0)
            .unwrap();
        let r2 = atlas
            .lookup_or_rasterize(&path, &cosmetic, FillRule::Winding, bounds, 1.0, 2.0)
            .unwrap();
        assert_eq!(r1.w, 40, "cosmetic body at zoom 1: 40·sf1·zoom1");
        assert_eq!(
            r2.w, 80,
            "cosmetic body at zoom 2: 40·sf1·zoom2 (zoom-aware)"
        );

        let logical = StrokeStyle::solid(2.0);
        let l1 = atlas
            .lookup_or_rasterize(&path, &logical, FillRule::Winding, bounds, 1.0, 1.0)
            .unwrap();
        let l2 = atlas
            .lookup_or_rasterize(&path, &logical, FillRule::Winding, bounds, 1.0, 4.0)
            .unwrap();
        assert_eq!(l1.w, l2.w, "logical raster size ignores zoom");
        assert_eq!(
            (l1.x, l1.y),
            (l2.x, l2.y),
            "logical hits the same cache entry"
        );

        // Same width/dims but different stroke space must not collide.
        let k_cos = PathCacheKey::new(&path, &cosmetic, FillRule::Winding, 40, 4);
        let k_log = PathCacheKey::new(&path, &logical, FillRule::Winding, 40, 4);
        assert_ne!(
            k_cos, k_log,
            "cache key must distinguish cosmetic vs logical"
        );
    }
}