frust-engine 0.6.2

Sparse-strip GPU render pipeline for Frust: compiles a scene display list into strips and records the draw passes on wgpu.
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
//! The `glifo` backend the engine draws a glyph run through, and the draw sink
//! it drives.
//!
//! Two types, because `glifo` splits the work in two. [`EngineTextBackend`] is
//! the [`GlyphRunBackend`] a [`GlyphRunBuilder`](glifo::GlyphRunBuilder) is
//! parameterised on: it is consumed once per run and its only job is to hand
//! `glifo` the caches it prepares glyphs against and the sink it draws them
//! into. [`EngineGlyphSink`] is that sink — the [`DrawSink`]/[`GlyphRenderer`]
//! pair `glifo` issues per-glyph drawing commands to, which is where a glyph
//! actually becomes engine strips.
//!
//! The split is forced by borrowing, not chosen: `glifo` borrows the
//! preparation caches for as long as the run's renderer lives and borrows the
//! sink mutably *inside* that lifetime, so the two cannot be fields of one
//! struct the backend method owns. `vello_hybrid` and `vello_cpu` divide
//! themselves the same way.
//!
//! # What a glyph becomes
//!
//! With the atlas cacher disabled, an outline glyph reaches the sink as a
//! `save_state` / `set_transform` / `set_paint_transform` / `fill_path` /
//! `restore_state` sequence, and the sink answers it by generating that path's
//! coverage through the compiler's own [`StripGenerator`] under the run's
//! active clip and recording one [`EngineDraw`]. Every glyph in a run is one
//! draw at its own painter-order depth, exactly as one small filled path per
//! glyph would be, so nothing downstream — scheduling, clipping, depth testing
//! — has to learn that text exists.
//!
//! # A cached glyph is an image draw
//!
//! With the cacher *enabled* — which is what [`crate::text::atlas_policy`]
//! routes a settled run to — the same glyph arrives as a `set_tint` /
//! `set_transform` / `set_paint_image` / `set_paint_transform` / `fill_rect`
//! sequence instead: `glifo` has resolved (or just allocated) an atlas slot for
//! it, and asks the sink to draw that slot's rectangle. The sink answers it the
//! way the compiler answers a `Command::Image` — one [`EncodedPaint::Image`]
//! naming the slot's [`ImageId`](vello_common::paint::ImageId), the same
//! rectangle coverage every other draw produces, and one [`EngineDraw`]. The
//! slot travels alongside in [`CompiledFrame::glyph_slots`] because only the
//! sink is ever handed it, and the renderer needs the atlas rectangle it names
//! to lower the paint.
//!
//! The **tint** is the whole of the colour-glyph split, and it is `glifo`'s to
//! decide rather than this sink's: an outline glyph is a coverage mask, so it
//! arrives with [`TintMode::AlphaMask`](vello_common::paint::TintMode) and the
//! run's own colour, and the shader fills the covered texels with that colour;
//! a COLR or bitmap glyph carries its own pixels and arrives with *no* tint,
//! which the paint records as the identity multiply, so nothing multiplies a
//! colour emoji by the text colour. Passing the tint through unexamined is what
//! keeps those two cases one code path here.
//!
//! Only `fill_rect` draws from the atlas. `glifo` never issues an atlas paint
//! under `fill_path`, and a sink that honoured one there would be inventing a
//! mapping from an arbitrary path into a slot rectangle.
//!
//! # A settled run is quads
//!
//! The image draw above is general — any transform, any rectangle — and it pays
//! for that generality per glyph: an encoded record with its own inverse
//! transform, and coverage generated by flattening and tiling a rectangle. A
//! cached *outline* glyph never needs it. `glifo` places one at
//! `floor(origin) + bearing` over its slot's own whole-pixel extent, with the
//! run's subpixel offset already rasterized into the slot, so its rectangle
//! always lands on whole device pixels and each covered pixel samples exactly
//! one slot texel. Such a glyph is a *glyph quad*: one rect instance whose
//! payload names the atlas texel under its corner ([`GlyphQuad`]), painted by
//! one record the whole run shares per atlas layer (its layer and tint), and
//! no generated coverage at all outside an isolated layer
//! ([`EngineGlyphSink::draw_quad`]).
//!
//! Only a run every glyph of which was already resident is drawn that way. A
//! run that missed — rasterized a glyph into the atlas this frame — is drawn the
//! general way, exactly as before quads existed, so the frame that first shows
//! a page of text and every frame that draws text the atlas cannot hold are
//! unchanged. The answer is only known once `glifo` has finished the run, so a
//! quad candidate is held back ([`GlyphQuadScratch`]) and the run's draws are
//! recorded once the caller has compared the atlas's miss count across it
//! ([`EngineGlyphSink::finish_quads`]). A draw that cannot be a quad arriving
//! mid-run — a bitmap glyph, an outline the atlas had no room for — first
//! records everything held back the general way, so painter order never
//! changes. A run under a coverage-mask clip never collects at all: a quad's
//! rectangle can be trimmed to a scissor but cannot carry a mask.
//!
//! A run the glyph-atlas policy remembers as resident skips `glifo` and the
//! holding area both: [`EngineGlyphSink::draw_resident`] rebuilds each glyph's
//! quad from its remembered slot and the origin `glifo` would compute for it,
//! and records it exactly as the held-back candidate would have been.
//!
//! # The run's paint, encoded once
//!
//! A run carries one brush, and `glifo` hands the sink a per-glyph *relative*
//! paint transform whose product with the glyph's own draw transform is, by
//! construction, the run's scene paint transform again — the same value for
//! every glyph in the run. The engine therefore encodes the brush once, before
//! the first glyph, and paints every glyph of the run with that one
//! [`Paint`]. A gradient-brushed run costs one encoded-paint entry and one
//! colour ramp rather than one per glyph, and the round trip through a
//! per-glyph inverse is skipped rather than paid and then undone.
//!
//! # A colour glyph's own paint
//!
//! A COLR glyph is the one case where the run's paint is *not* what a draw
//! carries: its layers bring their own palette colours and gradients, and the
//! run's brush reaches it only as the context colour a layer may ask for.
//! Those layers do not arrive as glyphs either — they arrive as a bracketed
//! stream of clips and rectangle fills, which [`color`](crate::text::color)
//! recombines into one shape and one brush per layer. This module encodes each
//! of those brushes into the frame's own paint table, exactly as the compiler
//! encodes a shape's, and records one draw per layer.
//!
//! # What is not drawn
//!
//! An *uncached* bitmap-strike glyph reaches the sink as a pixmap image paint,
//! which is pixels travelling with the draw rather than a handle into the
//! atlas, and the engine has no encoding for one: the sink records nothing for
//! it and counts it, which keeps a bitmap-emoji run to missing glyphs rather
//! than wrongly-coloured ones. `glifo`'s `png` feature is deliberately left off
//! — the workspace decodes PNG in one place already — so a PNG strike is
//! refused by `glifo` before it ever reaches here, and the other two strike
//! encodings it never decodes at all.
//!
//! Stroked glyphs are refused on the same terms: the display list has no
//! stroked-glyph command, so the sink carries no stroke state to widen an
//! outline with and will not invent one.

use core::cell::Cell;
use core::ops::RangeInclusive;

use glifo::{
    AtlasCacher, AtlasPaint, AtlasSlot, DrawSink, GLYPH_PADDING, Glyph, GlyphPrepCache,
    GlyphRenderer, GlyphRun, GlyphRunBackend,
};
use kurbo::{Affine, BezPath, Rect, Shape};
use peniko::color::palette::css::BLACK;
use peniko::color::{AlphaColor, Srgb};
use peniko::{BlendMode, Extend, ImageQuality, ImageSampler};
use peniko::{Brush, Fill};
use vello_common::clip::PathDataRef;
use vello_common::encode::{EncodedImage, EncodedPaint};
use vello_common::geometry::RectU16;
use vello_common::paint::{Image, ImageSource, IndexedPaint, Paint, PaintType, Tint, TintMode};
use vello_common::strip_generator::{StripGenerator, StripStorage};

use crate::cache::images::AtlasRegion;
use crate::compile::clip::ClipStack;
use crate::compile::cull::generate_fill;
use crate::compile::paint::{encode_brush, encode_glyph_run_record};
use crate::compile::{
    CompiledFrame, DepthCounter, EngineDraw, FLATTEN_TOLERANCE, GlyphQuad, GlyphSlot,
};
use crate::gpu::atlas::x_y_advances;
use crate::text::ResidentPlan;
use crate::text::atlas_policy::{AtlasPolicy, PlacedGlyph, ResidentAnswer, subpixel_bucket};
use crate::text::color::{ColorGlyph, ColorLayer, LayerShape};

/// What one glyph run cost the frame.
///
/// Purely observational, in the same spirit as [`CompiledFrame`]'s own
/// counters: nothing downstream branches on either number, and they exist so
/// "a glyph the engine cannot paint is a missing glyph, not a wrong one" is
/// measurable from outside the sink rather than asserted about it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct GlyphRunOutcome {
    /// Glyphs that became a recorded draw.
    ///
    /// One per *glyph*, not per draw: a colour glyph costs one draw per layer
    /// and still counts once here, which is what keeps this bounded by the
    /// run's own glyph count.
    pub(crate) drawn: u32,
    /// Glyphs the sink refused to draw — a bitmap glyph, a stroked one, or a
    /// colour glyph whose layers have no exact engine spelling.
    pub(crate) skipped: u32,
    /// Whether the run was drawn out of the resident-run cache, without
    /// reaching `glifo` at all (see [`EngineGlyphSink::draw_resident`]).
    pub(crate) resident: bool,
}

/// The paint a drawing command arriving at the sink is painted with.
#[derive(Debug, Clone)]
enum SinkPaint {
    /// The run's own brush, as encoded once by the compiler.
    Run,
    /// A COLR layer's own palette colour or gradient, which the layer it
    /// paints is encoded from when the glyph closes.
    Layer(Brush),
    /// A glyph resolved out of the atlas: the image `glifo` built from the
    /// slot, whose source is the handle [`EngineGlyphSink::atlas_image_source`]
    /// answered with.
    Atlas(Image),
    /// A paint set by `glifo` that this backend has no encoding for — an
    /// uncached bitmap glyph's pixmap.
    Unsupported,
}

/// The sink state `glifo` saves and restores around each glyph.
///
/// `glifo` brackets every glyph it draws in a `save_state`/`restore_state`
/// pair, so the transform, paint transform and paint it sets inside the
/// bracket must not leak into the next glyph. Restoring is a whole-value
/// assignment rather than a field-by-field undo, which is what makes that
/// impossible to get half-right.
#[derive(Debug, Clone)]
pub(crate) struct GlyphSinkState {
    /// Maps the drawing command's geometry into device space.
    transform: Affine,
    /// The paint transform relative to [`Self::transform`], as `glifo`
    /// computes it per glyph.
    paint_transform: Affine,
    /// Which paint the next drawing command is painted with.
    paint: SinkPaint,
    /// The tint an atlas-sampled glyph is drawn through, as `glifo` set it.
    ///
    /// Part of the saved state rather than a bare field because `glifo` sets it
    /// *inside* the save/restore bracket it draws a cached glyph in, so a
    /// restore has to take it back with everything else — the same rule the
    /// transform and the paint follow.
    tint: Option<Tint>,
}

/// One cached glyph held back while its run is still being drawn, carrying
/// everything either lowering needs: a [quad](GlyphQuad) if the whole run
/// turns out resident, the general image draw otherwise.
#[derive(Debug, Clone)]
pub(crate) struct PendingGlyphQuad {
    /// The atlas paint `glifo` set for the glyph.
    image: Image,
    /// The rectangle `glifo` filled, in the space of [`Self::transform`].
    area: Rect,
    /// The draw transform `glifo` set for the glyph.
    transform: Affine,
    /// The paint transform relative to [`Self::transform`].
    paint_transform: Affine,
    /// The tint the glyph is drawn through.
    tint: Option<Tint>,
    /// The slot the paint names.
    slot: AtlasSlot,
}

impl PendingGlyphQuad {
    /// The device rectangle `[x0, y0, x1, y1]` this glyph covers when it can be
    /// a quad, or `None` when only the general image draw paints it exactly.
    ///
    /// A quad samples slot texel `k` at device pixel `x0 + k` with no transform
    /// and no extend mode, which is the general draw's own answer exactly when:
    /// the paint samples nearest (a bilinear or bicubic one blends texels); the
    /// draw transform is a translation by whole pixels with no relative paint
    /// transform on top (anything else moves texel centres off pixel centres);
    /// and the rectangle is the slot's own extent from its origin (so no pixel
    /// reaches past the slot, where the general draw's pad extend would clamp).
    /// `glifo` draws every cached outline glyph that way; a bitmap glyph samples
    /// bilinearly and a COLR one is placed fractionally, and both take the
    /// general draw.
    fn quad_rect(&self) -> Option<[i64; 4]> {
        if self.image.sampler.quality != ImageQuality::Low
            || self.paint_transform != Affine::IDENTITY
        {
            return None;
        }
        let [a, b, c, d, tx, ty] = self.transform.as_coeffs();
        if a != 1.0 || b != 0.0 || c != 0.0 || d != 1.0 || !whole_pixel(tx) || !whole_pixel(ty) {
            return None;
        }
        let width = f64::from(self.slot.width);
        let height = f64::from(self.slot.height);
        if self.area != Rect::new(0.0, 0.0, width, height) {
            return None;
        }
        // Exact: both are whole numbers well inside `i64` (see `whole_pixel`).
        let (x0, y0) = (tx as i64, ty as i64);
        Some([
            x0,
            y0,
            x0 + i64::from(self.slot.width),
            y0 + i64::from(self.slot.height),
        ])
    }
}

/// Whether `value` is a whole pixel coordinate a device rectangle can start at.
///
/// Bounded far outside any device grid so the conversion to `i64` is exact;
/// a glyph that far away is culled either way.
fn whole_pixel(value: f64) -> bool {
    value.fract() == 0.0 && on_quad_grid(value)
}

/// Whether `value` lies inside the bound [`whole_pixel`] holds a quad corner
/// to — the half of it a coordinate already known to be whole still has to
/// pass.
fn on_quad_grid(value: f64) -> bool {
    value.is_finite() && value.abs() <= f64::from(1_u32 << 30)
}

/// The record one run's quads on one atlas layer share, by tint.
#[derive(Debug, Clone, Copy)]
struct RunRecord {
    /// The atlas layer the record's slot is on.
    page: u32,
    /// The tint the record carries.
    tint: Option<Tint>,
    /// The record's index in the frame's encoded-paint table.
    paint_index: usize,
}

/// The compiler's retained scratch for glyph quads, kept across runs and
/// frames for its allocations alone — it carries nothing between runs.
#[derive(Debug, Default)]
pub(crate) struct GlyphQuadScratch {
    /// The run's quad candidates, in the order `glifo` drew them.
    pending: Vec<PendingGlyphQuad>,
    /// The run's shared records, one per atlas layer and tint drawn.
    records: Vec<RunRecord>,
    /// A resident run's glyphs with this frame's subpixel buckets.
    placed: Vec<PlacedGlyph>,
    /// A resident run's glyph origins in device space, as `glifo` places them.
    origins: Vec<(f64, f64)>,
    /// The slots a resident run's glyphs resolved to.
    slots: Vec<AtlasSlot>,
    /// A resident run's quads — device rectangle and slot — once every one of
    /// them is known to be one.
    quads: Vec<([i64; 4], AtlasSlot)>,
}

/// What a run may draw glyph quads through: the retained scratch, and the
/// device window a quad is trimmed to — the viewport intersected with every
/// scissor on the clip stack, which is exactly what the general draw's
/// coverage is culled and scissored to.
#[derive(Debug)]
pub(crate) struct GlyphQuadTargets<'a> {
    /// Where candidates wait for the run to finish.
    pub(crate) scratch: &'a mut GlyphQuadScratch,
    /// The device window a quad is trimmed to.
    pub(crate) window: RectU16,
}

/// The [`DrawSink`]/[`GlyphRenderer`] `glifo` draws a run's glyphs into.
///
/// Holds the pieces of a compile in progress a glyph draw needs, borrowed
/// disjointly from the compiler and the frame it is building: the retained
/// [`StripGenerator`], the active [`ClipStack`], the [`CompiledFrame`] being
/// filled, and the frame's [`DepthCounter`]. Everything else is per-run state
/// set up once by [`crate::text::lower_glyph_run`].
#[derive(Debug)]
pub(crate) struct EngineGlyphSink<'a> {
    /// The compiler's retained strip generator.
    generator: &'a mut StripGenerator,
    /// The clip stack the run is drawn under.
    clips: &'a mut ClipStack,
    /// The frame being compiled.
    frame: &'a mut CompiledFrame,
    /// The frame's painter-order depth counter.
    depth: &'a mut DepthCounter,
    /// The run's brush, encoded once (see this module's doc).
    run_paint: Paint,
    /// The run's brush in `glifo`'s own paint vocabulary, which it reads to
    /// resolve a COLR glyph's context colour and to decide whether a glyph is
    /// cacheable.
    context_paint: PaintType,
    /// The current, save/restore-scoped drawing state.
    state: GlyphSinkState,
    /// The slot the atlas paint about to be set names.
    ///
    /// `glifo` hands the slot to [`Self::atlas_image_source`] and then throws
    /// it away, keeping only the [`ImageSource`](vello_common::paint::ImageSource)
    /// that answer returned — but the engine's paint record needs the slot's
    /// *rectangle* as well, and nothing downstream carries it. So the one call
    /// that is given it stashes it here for the `fill_rect` two commands later.
    /// A [`Cell`] because that call takes `&self`: the trait asks a question,
    /// and the answer is what the drawing command that follows is built from.
    atlas_slot: Cell<Option<AtlasSlot>>,
    /// The colour glyph currently being replayed into layers, if any.
    color: ColorGlyph,
    /// What the run cost so far.
    outcome: GlyphRunOutcome,
    /// Where quad candidates are held, or `None` for a run that may not draw
    /// quads at all.
    quads: Option<GlyphQuadTargets<'a>>,
    /// Whether atlas draws are still being held back as quad candidates —
    /// cleared for good the first time a draw that cannot be one arrives.
    collecting: bool,
}

impl<'a> EngineGlyphSink<'a> {
    /// A sink drawing into `frame` with `run_paint`, under `clips`.
    ///
    /// `context_paint` is the same brush `run_paint` was encoded from, in the
    /// vocabulary `glifo` reads it back through. `quads` is where the run's
    /// glyph quads are held back, or `None` for a run that draws none.
    pub(crate) fn new(
        generator: &'a mut StripGenerator,
        clips: &'a mut ClipStack,
        frame: &'a mut CompiledFrame,
        depth: &'a mut DepthCounter,
        run_paint: Paint,
        context_paint: PaintType,
        mut quads: Option<GlyphQuadTargets<'a>>,
    ) -> Self {
        if let Some(targets) = quads.as_mut() {
            targets.scratch.pending.clear();
            targets.scratch.records.clear();
        }
        let collecting = quads.is_some();
        Self {
            generator,
            clips,
            frame,
            depth,
            run_paint,
            context_paint,
            // A decoration's rectangles arrive in scene space with no
            // `set_transform` ahead of them, and the run transform is already
            // baked into every transform `glifo` derives, so the identity is
            // the right starting state rather than merely a neutral one.
            state: GlyphSinkState {
                transform: Affine::IDENTITY,
                paint_transform: Affine::IDENTITY,
                paint: SinkPaint::Run,
                tint: None,
            },
            atlas_slot: Cell::new(None),
            color: ColorGlyph::default(),
            outcome: GlyphRunOutcome::default(),
            quads,
            collecting,
        }
    }

    /// What this sink drew and refused.
    ///
    /// Takes `&mut self` because it also closes the one state a run can end
    /// in that is not a finished glyph: a colour glyph whose brackets `glifo`
    /// never balanced (a cyclic paint graph in a malformed face is the way
    /// that happens). Its layers are dropped rather than drawn under a clip
    /// nothing closed, and it is counted as the missing glyph it is.
    pub(crate) fn outcome(&mut self) -> GlyphRunOutcome {
        if self.color.is_open() {
            self.color.reset();
            self.outcome.skipped = self.outcome.skipped.saturating_add(1);
        }

        self.outcome
    }

    /// Run `generate` under the active clip and record whatever strips
    /// survived as one draw painted with the run's paint, counting the glyph
    /// it drew.
    ///
    /// The whole of an outline glyph's path through this sink. A colour
    /// glyph's layers go through [`record_draw`](Self::record_draw) instead:
    /// they carry their own paints and are counted once for the glyph rather
    /// than once per draw.
    fn record<F>(&mut self, generate: F)
    where
        F: FnOnce(&mut StripGenerator, &mut StripStorage, Option<PathDataRef<'_>>),
    {
        // An outline mid-run: whatever the run held back is drawn first, so
        // the draws stay in the order `glifo` issued them.
        self.abandon_quads();
        if !matches!(self.state.paint, SinkPaint::Run) {
            self.outcome.skipped = self.outcome.skipped.saturating_add(1);
            return;
        }

        let paint = self.run_paint.clone();
        if self.record_draw(paint, generate) {
            self.outcome.drawn = self.outcome.drawn.saturating_add(1);
        }
    }

    /// Run `generate` under the active clip and record whatever strips
    /// survived as one draw painted with `paint`, answering whether a draw was
    /// recorded at all.
    ///
    /// The same shape [`crate::compile::SceneCompiler`]'s own draw recording
    /// takes, minus the paint encoding: the paint is resolved by the caller,
    /// so there is nothing to roll back and a culled glyph simply records
    /// nothing and consumes no depth.
    fn record_draw<F>(&mut self, paint: Paint, generate: F) -> bool
    where
        F: FnOnce(&mut StripGenerator, &mut StripStorage, Option<PathDataRef<'_>>),
    {
        if self.clips.blocks_everything() {
            return false;
        }

        let start = self.frame.strips.strips.len();
        let alpha_start = self.frame.strips.alphas.len();
        generate(self.generator, &mut self.frame.strips, self.clips.mask());
        self.clips
            .clip_run(&mut self.frame.strips, start, alpha_start);
        let strip_range = start..self.frame.strips.strips.len();

        if strip_range.is_empty() {
            return false;
        }

        let draw = EngineDraw::new(paint, self.depth.advance(), strip_range.clone());
        self.frame
            .recorder
            .push_draw(draw, &self.frame.strips.strips[strip_range]);
        true
    }

    /// Draw a run straight out of the resident-run cache, as quads, without
    /// `glifo`.
    ///
    /// What `glifo`'s own walk would hand this sink for a run whose every glyph
    /// hits the atlas, rebuilt from the remembered slots: per glyph, the device
    /// origin `glifo` computes ([`ResidentPlan::origin`]), the subpixel bucket
    /// it keys that origin under, the slot that bucket resolved to, and the
    /// rectangle `glifo` fills over it — `floor(origin) + bearing`, the slot's
    /// own extent, sampled nearest through the run colour's alpha-mask tint.
    /// Those are exactly the quad candidates [`Self::draw_atlas_glyph`] holds
    /// back, and each is recorded by the same [`Self::emit_quad`] a fully
    /// resident `glifo` run's quads end in: same draws, same depths, same
    /// shared records, same slots reported. Only the candidate itself is
    /// skipped — its rectangle is computed directly rather than re-derived from
    /// a transform and an area built to be checked.
    ///
    /// Anything but [`ResidentAnswer::Resolved`] draws nothing and leaves the
    /// sink as it was, for the run to go to `glifo`: a glyph the cache could
    /// not resolve, a glyph whose rectangle cannot be a quad, or a sink that
    /// may not draw quads at all.
    pub(crate) fn draw_resident(
        &mut self,
        policy: &mut AtlasPolicy,
        plan: &ResidentPlan<'_>,
    ) -> ResidentAnswer {
        if !self.collecting {
            return ResidentAnswer::Bypassed;
        }
        let Some(targets) = self.quads.as_mut() else {
            return ResidentAnswer::Bypassed;
        };
        let scratch = &mut *targets.scratch;
        scratch.placed.clear();
        scratch.origins.clear();
        for glyph in plan.glyphs() {
            let origin = plan.origin(glyph);
            scratch.placed.push(PlacedGlyph {
                id: glyph.id,
                // `glifo` keys the fraction of the f64 origin, narrowed.
                bucket: subpixel_bucket(origin.0.fract() as f32),
            });
            scratch.origins.push(origin);
        }

        let answer =
            policy.resolve_resident_run(plan.identity(), &scratch.placed, &mut scratch.slots);
        if answer != ResidentAnswer::Resolved {
            return answer;
        }

        let tint = Some(Tint {
            color: plan.color(),
            mode: TintMode::AlphaMask,
        });
        let sampler = ImageSampler {
            x_extend: Extend::Pad,
            y_extend: Extend::Pad,
            quality: ImageQuality::Low,
            alpha: 1.0,
        };
        scratch.quads.clear();
        for (&(x, y), &slot) in scratch.origins.iter().zip(&scratch.slots) {
            if slot.width == 0 || slot.height == 0 {
                // A glyph with no ink, skipped exactly as `draw_atlas_glyph`
                // skips it.
                continue;
            }
            // The corner `glifo` translates the slot's rectangle to. Whole by
            // construction — a floor plus an integer bearing — so of
            // `quad_rect`'s questions only the grid bound is left to ask.
            let left = x.floor() + f64::from(slot.bearing_x);
            let top = y.floor() + f64::from(slot.bearing_y);
            if !on_quad_grid(left) || !on_quad_grid(top) {
                // Off the grid a quad can address: `glifo` draws it the
                // general way, and so does the rest of the run.
                return ResidentAnswer::Bypassed;
            }
            // Exact: whole numbers inside the bound just checked.
            let (x0, y0) = (left as i64, top as i64);
            scratch.quads.push((
                [
                    x0,
                    y0,
                    x0 + i64::from(slot.width),
                    y0 + i64::from(slot.height),
                ],
                slot,
            ));
        }

        // Taken out and put back so the loop can borrow the sink mutably; the
        // allocation travels back with it.
        let window = targets.window;
        let quads = std::mem::take(&mut scratch.quads);
        self.collecting = false;
        for &(rect, slot) in &quads {
            let source = ImageSource::opaque_id(slot.image_id);
            self.emit_quad(rect, slot, tint, &source, sampler, window);
        }
        if let Some(targets) = self.quads.as_mut() {
            targets.scratch.quads = quads;
        }
        self.outcome.resident = true;
        ResidentAnswer::Resolved
    }

    /// Draw one glyph out of the atlas: `area`, the slot's own rectangle,
    /// under the current transform, painted from the slot.
    ///
    /// Held back as a quad candidate while the run is still collecting and
    /// the glyph can be one ([`PendingGlyphQuad::quad_rect`]); drawn the
    /// general way at once otherwise, after whatever the run held back (see
    /// this module's doc).
    fn draw_atlas_glyph(&mut self, image: &Image, area: Rect) {
        let Some(slot) = self.atlas_slot.get() else {
            // `glifo` sets an atlas image paint only after asking this sink for
            // the slot's source, so this is unreachable on its own path; a
            // stream that reached it would be one this backend cannot place.
            self.outcome.skipped = self.outcome.skipped.saturating_add(1);
            return;
        };
        if slot.width == 0 || slot.height == 0 {
            // A glyph with no ink — a space, whose outline bounds are empty and
            // whose slot is therefore a degenerate rectangle. Counted as
            // neither drawn nor skipped, exactly as the outline path counts one
            // whose fill produced no strips: it is not a glyph the engine
            // failed to paint, it is a glyph with nothing to paint.
            return;
        }

        let glyph = PendingGlyphQuad {
            image: image.clone(),
            area,
            transform: self.state.transform,
            paint_transform: self.state.paint_transform,
            tint: self.state.tint,
            slot,
        };
        if self.collecting
            && glyph.quad_rect().is_some()
            && let Some(targets) = self.quads.as_mut()
        {
            targets.scratch.pending.push(glyph);
            return;
        }
        self.abandon_quads();
        self.draw_atlas_image(&glyph);
    }

    /// Stop collecting quad candidates for the rest of the run, drawing every
    /// one held so far the general way, in order.
    ///
    /// What a draw that cannot be a quad calls before it records itself, so
    /// that nothing the run drew earlier lands after it.
    fn abandon_quads(&mut self) {
        if self.collecting {
            self.collecting = false;
            self.flush_pending(false);
        }
    }

    /// Record the quad candidates the run held back, now that the caller knows
    /// whether every glyph of it was already resident.
    ///
    /// `all_resident` — the atlas counted no miss across the run — draws them
    /// as [quads](GlyphQuad); otherwise they are drawn the general way, which
    /// is exactly what a run that rasterized into the atlas this frame drew
    /// before quads existed. Call once, after `glifo` has drawn the whole run
    /// and before [`Self::outcome`].
    pub(crate) fn finish_quads(&mut self, all_resident: bool) {
        if self.collecting {
            self.collecting = false;
            self.flush_pending(all_resident);
        }
    }

    /// Draw every held candidate in order — as quads when `as_quads`, the
    /// general way otherwise — and empty the holding area.
    fn flush_pending(&mut self, as_quads: bool) {
        let Some(targets) = self.quads.as_mut() else {
            return;
        };
        let window = targets.window;
        // Taken out and put back so the loop can borrow the sink mutably; the
        // allocation travels back with it.
        let mut pending = std::mem::take(&mut targets.scratch.pending);
        for glyph in &pending {
            if as_quads {
                self.draw_quad(glyph, window);
            } else {
                self.draw_atlas_image(glyph);
            }
        }
        pending.clear();
        if let Some(targets) = self.quads.as_mut() {
            targets.scratch.pending = pending;
        }
    }

    /// Draw `glyph` as one [quad](GlyphQuad) trimmed to `window`: painted by
    /// the run's shared record for its atlas layer and tint, and reported —
    /// rectangle and atlas texel — for the renderer's one rect instance.
    ///
    /// Outside every isolated layer the draw owns no coverage strips at all:
    /// the renderer draws a quad from [`GlyphQuad`] alone, and generating the
    /// rectangle's coverage only to have nothing read it was most of what a
    /// quad would otherwise still cost. Inside one, the recorder folds each
    /// draw's strip bounds into the layer's own bounds, which the layer's page
    /// is sized from — so there the draw carries its rectangle's coverage,
    /// written by the fast rectangle path: full inside, nothing outside, the
    /// same pixels the general draw's flatten-and-tile of that rectangle
    /// covers. Trimmed away entirely, the glyph records nothing and consumes no
    /// depth, as the general draw does for a glyph clipped out of sight.
    fn draw_quad(&mut self, glyph: &PendingGlyphQuad, window: RectU16) {
        let Some(rect) = glyph.quad_rect() else {
            // Only candidates that are quads are ever held back.
            self.draw_atlas_image(glyph);
            return;
        };
        self.emit_quad(
            rect,
            glyph.slot,
            glyph.tint,
            &glyph.image.image,
            glyph.image.sampler,
            window,
        );
    }

    /// Record one quad over device rectangle `[x0, y0, x1, y1]` sampling
    /// `slot` from its corner, trimmed to `window` — the whole of
    /// [`Self::draw_quad`] once a candidate is known to be a quad, shared with
    /// [`Self::draw_resident`]. `source` and `sampler` are the atlas paint the
    /// run's shared record is encoded from on the layer's first quad.
    fn emit_quad(
        &mut self,
        [x0, y0, x1, y1]: [i64; 4],
        slot: AtlasSlot,
        tint: Option<Tint>,
        source: &ImageSource,
        sampler: ImageSampler,
        window: RectU16,
    ) {
        let left = x0.max(i64::from(window.x0));
        let top = y0.max(i64::from(window.y0));
        let right = x1.min(i64::from(window.x1));
        let bottom = y1.min(i64::from(window.y1));
        if left >= right || top >= bottom || self.clips.blocks_everything() {
            return;
        }
        // Inside the window, which is inside the `u16` device grid.
        let narrow = |value: i64| u16::try_from(value).unwrap_or(u16::MAX);

        let start = self.frame.strips.strips.len();
        if self.frame.recorder.has_layers() {
            let alpha_start = self.frame.strips.alphas.len();
            let device = Rect::new(left as f64, top as f64, right as f64, bottom as f64);
            // No mask: a run under one never collects (see this module's
            // doc), and the scissor is already applied by the trim.
            self.generator
                .generate_filled_rect_fast(&device, &mut self.frame.strips, None);
            if self.frame.strips.strips.len() - start < 2 {
                self.frame.strips.strips.truncate(start);
                self.frame.strips.alphas.truncate(alpha_start);
                return;
            }
            self.frame.fast_rect_draws = self.frame.fast_rect_draws.saturating_add(1);
        }
        let strip_range = start..self.frame.strips.strips.len();

        let paint_index = self.run_record(slot.page_index, tint, source, sampler);
        let depth = self.depth.advance();
        let draw = EngineDraw::new(
            Paint::Indexed(IndexedPaint::new(paint_index)),
            depth,
            strip_range.clone(),
        );
        self.frame
            .recorder
            .push_draw(draw, &self.frame.strips.strips[strip_range]);

        self.frame.glyph_quads.push(GlyphQuad {
            depth,
            x: narrow(left),
            y: narrow(top),
            width: narrow(right - left),
            height: narrow(bottom - top),
            // The trim moves the corner into the slot by exactly as much as it
            // moves it on the device.
            atlas_x: narrow(i64::from(slot.x) + (left - x0)),
            atlas_y: narrow(i64::from(slot.y) + (top - y0)),
        });
        self.note_atlas_draw(slot);
    }

    /// The index of the record the run shares on atlas layer `page` at
    /// `tint`, encoding it from `source` and `sampler` on first use.
    ///
    /// Encoded at the first quad that is actually drawn on that layer, so the
    /// slot the record names is always one the frame reports — which is what
    /// resolves the record to its layer.
    fn run_record(
        &mut self,
        page: u32,
        tint: Option<Tint>,
        source: &ImageSource,
        sampler: ImageSampler,
    ) -> usize {
        if let Some(record) = self.quads.as_ref().and_then(|targets| {
            targets
                .scratch
                .records
                .iter()
                .find(|record| record.page == page && record.tint == tint)
        }) {
            return record.paint_index;
        }
        let paint_index = encode_glyph_run_record(
            source.clone(),
            sampler,
            tint,
            &mut self.frame.encoded_paints,
        );
        self.frame.glyph_run_paints.push(paint_index);
        if let Some(targets) = self.quads.as_mut() {
            targets.scratch.records.push(RunRecord {
                page,
                tint,
                paint_index,
            });
        }
        paint_index
    }

    /// Report a drawn atlas glyph: its slot, for the renderer to resolve the
    /// paint naming it, and the counts.
    ///
    /// The slot is reported into [`CompiledFrame::glyph_slots`] on every draw
    /// rather than once per allocation. That is what makes a recycled handle
    /// safe: `glifo` frees a slot's [`ImageId`](vello_common::paint::ImageId)
    /// back to the shared allocator when it evicts, and the next occupant of
    /// that id — a glyph or an image — may hold a different rectangle, so the
    /// rectangle a draw *names* is the one that has to travel with it.
    fn note_atlas_draw(&mut self, slot: AtlasSlot) {
        self.frame.glyph_slots.push(GlyphSlot {
            id: slot.image_id,
            region: AtlasRegion {
                layer: slot.page_index,
                offset: [u32::from(slot.x), u32::from(slot.y)],
                size: [u32::from(slot.width), u32::from(slot.height)],
            },
            padding: u32::from(GLYPH_PADDING),
        });
        self.frame.atlas_glyph_draws = self.frame.atlas_glyph_draws.saturating_add(1);
        self.outcome.drawn = self.outcome.drawn.saturating_add(1);
    }

    /// Draw `glyph` the general way: `area`, the slot's own rectangle, painted
    /// by an image paint naming the slot.
    ///
    /// The two transforms are the ones every image draw in this crate is built
    /// from, and they are *not* the same value. The coverage is `area` under
    /// the glyph's draw transform — where the glyph lands on the surface. The
    /// paint is placed by that transform composed with `glifo`'s relative
    /// paint transform, which is the absolute mapping this backend is
    /// documented to reconstruct that way; the encoded entry stores its
    /// inverse, because device-to-image is the direction the shader applies.
    fn draw_atlas_image(&mut self, glyph: &PendingGlyphQuad) {
        let transform = glyph.transform;
        let paint_transform = transform * glyph.paint_transform;
        let inverse = paint_transform.inverse();
        if !inverse.as_coeffs().iter().all(|coeff| coeff.is_finite()) {
            self.outcome.skipped = self.outcome.skipped.saturating_add(1);
            return;
        }

        let (x_advance, y_advance) = x_y_advances(inverse);
        let paint_index = self.frame.encoded_paints.len();
        self.frame
            .encoded_paints
            .push(EncodedPaint::Image(EncodedImage {
                // A glyph slot is an anti-aliased coverage mask (an outline) or a
                // colour glyph with its own alpha; neither is opaque, and claiming
                // otherwise would route it into the depth-writing opaque pass.
                may_have_transparency: true,
                source: glyph.image.image.clone(),
                sampler: glyph.image.sampler,
                transform: inverse,
                x_advance,
                y_advance,
                tint: glyph.tint,
            }));

        let area = glyph.area;
        let paint = Paint::Indexed(IndexedPaint::new(paint_index));
        let drawn = self.record_draw(paint, |generator, storage, clip| {
            generator.generate_filled_path(
                area.path_elements(FLATTEN_TOLERANCE),
                Fill::NonZero,
                transform,
                None,
                storage,
                clip,
            );
        });

        if drawn {
            self.note_atlas_draw(glyph.slot);
        } else {
            // The same roll-back the compiler's own `record` keeps: a glyph
            // clipped away leaves no orphan entry in the frame's paint table.
            // The entry just pushed is the last one, so this is exact.
            self.frame.encoded_paints.truncate(paint_index);
        }
    }

    /// Draw the colour glyph whose last bracket just closed, or count it
    /// skipped when it turned out to be inexpressible.
    ///
    /// Every layer is drawn under the glyph's own transform with its own
    /// brush, encoded into the frame's paint table the same way a shape's is.
    /// A glyph whose layers all culled away counts as neither drawn nor
    /// skipped, exactly as an outline glyph with no ink does.
    fn flush_color_glyph(&mut self) {
        self.abandon_quads();
        let transform = self.color.transform();
        let Some(layers) = self.color.take() else {
            self.outcome.skipped = self.outcome.skipped.saturating_add(1);
            return;
        };

        let mut drew = false;
        for layer in layers {
            drew |= self.draw_color_layer(&layer, transform);
        }
        if drew {
            self.outcome.drawn = self.outcome.drawn.saturating_add(1);
        }
    }

    /// Draw one colour layer, answering whether it recorded a draw.
    fn draw_color_layer(&mut self, layer: &ColorLayer, transform: Affine) -> bool {
        let encoding = encode_brush(
            &layer.brush,
            transform * layer.paint_transform,
            &mut self.frame.encoded_paints,
        );
        self.frame.lut_requests.extend(encoding.lut_request);

        // Pushed only for a layer whose outline the rectangle would actually
        // cut, which a well-formed face never has (see [`crate::text::color`]).
        let clipped = layer.clip.is_some();
        if let Some(clip) = layer.clip {
            self.clips.push_rect(clip, transform, self.generator);
        }

        let drawn = match &layer.shape {
            LayerShape::Rect(rect) => {
                let rect = *rect;
                self.record_draw(encoding.paint, |generator, storage, clip| {
                    generator.generate_filled_path(
                        rect.path_elements(FLATTEN_TOLERANCE),
                        Fill::NonZero,
                        transform,
                        None,
                        storage,
                        clip,
                    );
                })
            }
            LayerShape::Path(path) => {
                self.record_draw(encoding.paint, |generator, storage, clip| {
                    generate_fill(generator, path.iter(), transform, storage, clip);
                })
            }
        };

        if clipped {
            self.clips.pop();
        }

        drawn
    }
}

impl DrawSink for EngineGlyphSink<'_> {
    fn set_transform(&mut self, t: Affine) {
        self.state.transform = t;
    }

    fn set_paint(&mut self, paint: AtlasPaint) {
        // Only a COLR layer sets one, and it is the layer's own paint rather
        // than anything derived from the run's brush.
        self.state.paint = SinkPaint::Layer(match paint {
            AtlasPaint::Solid(color) => Brush::Solid(color),
            AtlasPaint::Gradient(gradient) => Brush::Gradient(gradient),
        });
    }

    fn set_paint_transform(&mut self, t: Affine) {
        self.state.paint_transform = t;
    }

    fn fill_path(&mut self, path: &BezPath) {
        if self.color.is_open() {
            // A colour glyph's layers arrive as rectangle fills through a
            // clip; a path fill inside one is a shape this sink has no place
            // to put, so the glyph goes missing rather than landing wrong.
            self.color.refuse();
            return;
        }

        let transform = self.state.transform;
        self.record(|generator, storage, clip| {
            generate_fill(generator, path.iter(), transform, storage, clip);
        });
    }

    fn fill_rect(&mut self, rect: &Rect) {
        let rect = *rect;
        if self.color.is_open() {
            match &self.state.paint {
                SinkPaint::Layer(brush) => {
                    let brush = brush.clone();
                    let paint_transform = self.state.paint_transform;
                    self.color.fill(rect, brush, paint_transform);
                }
                // A colour layer always sets its own paint before filling, so
                // a fill without one is a stream this sink does not recognise.
                SinkPaint::Run | SinkPaint::Atlas(_) | SinkPaint::Unsupported => {
                    self.color.refuse();
                }
            }
            return;
        }

        // A cached glyph is a rectangle of the atlas, and this is the only
        // command `glifo` draws one with.
        if let SinkPaint::Atlas(image) = &self.state.paint {
            let image = image.clone();
            self.draw_atlas_glyph(&image, rect);
            return;
        }

        let transform = self.state.transform;
        self.record(|generator, storage, clip| {
            generator.generate_filled_path(
                rect.path_elements(FLATTEN_TOLERANCE),
                Fill::NonZero,
                transform,
                None,
                storage,
                clip,
            );
        });
    }

    fn push_clip_layer(&mut self, _clip: &BezPath) {
        // An *isolated* clip layer, which `glifo` asks for only around a
        // colour glyph whose paint graph blends non-destructively — the one
        // thing the engine's own layer scheduling refuses too.
        self.color.push_refused(self.state.transform);
    }

    fn push_clip_path(&mut self, clip: &BezPath) {
        self.color.push_clip(clip, self.state.transform);
    }

    fn push_blend_layer(&mut self, _blend_mode: BlendMode) {
        self.color.push_refused(self.state.transform);
    }

    fn pop_layer(&mut self) {
        if self.color.pop() {
            self.flush_color_glyph();
        }
    }

    fn pop_clip_path(&mut self) {
        if self.color.pop() {
            self.flush_color_glyph();
        }
    }

    fn width(&self) -> u16 {
        self.generator.width()
    }

    fn height(&self) -> u16 {
        self.generator.height()
    }
}

impl GlyphRenderer for EngineGlyphSink<'_> {
    type SavedState = GlyphSinkState;

    fn save_state(&mut self) -> Self::SavedState {
        self.state.clone()
    }

    fn restore_state(&mut self, state: Self::SavedState) {
        self.state = state;
    }

    fn stroke_path(&mut self, _path: &BezPath) {
        // The display list carries no stroked-glyph command, so the sink holds
        // no stroke width to widen this outline by. Counted rather than
        // guessed at: a stroke drawn at an invented width would be wrong
        // pixels, and this is a glyph that goes missing instead — or, inside a
        // colour glyph, the whole glyph it is a layer of.
        if self.color.is_open() {
            self.color.refuse();
            return;
        }

        self.outcome.skipped = self.outcome.skipped.saturating_add(1);
    }

    fn set_paint_image(&mut self, image: Image) {
        // The source is what tells the two apart, and it is this sink's own
        // answer coming back: a glyph resolved out of the atlas carries the
        // handle `atlas_image_source` returned, while an uncached bitmap strike
        // carries its pixmap inline — pixels the engine has nowhere to put on
        // this path.
        self.state.paint = match &image.image {
            ImageSource::OpaqueId { .. } => SinkPaint::Atlas(image),
            ImageSource::Pixmap(_) => SinkPaint::Unsupported,
        };
    }

    fn set_tint(&mut self, tint: Option<vello_common::paint::Tint>) {
        // Carried, not interpreted: `glifo` sets the alpha-mask tint that
        // colours an outline glyph and leaves it unset for a COLR or bitmap
        // one, which is exactly the split the encoded paint has to record (see
        // this module's doc).
        self.state.tint = tint;
    }

    fn get_context_color(&self) -> AlphaColor<Srgb> {
        match &self.context_paint {
            PaintType::Solid(color) => *color,
            _ => BLACK,
        }
    }

    fn current_paint(&self) -> &PaintType {
        &self.context_paint
    }

    fn atlas_image_source(&self, atlas_slot: &AtlasSlot) -> ImageSource {
        // The one call handed the slot, so it is where the slot is kept for
        // the draw that follows (see [`EngineGlyphSink::atlas_slot`]).
        self.atlas_slot.set(Some(*atlas_slot));
        ImageSource::opaque_id(atlas_slot.image_id)
    }

    fn atlas_paint_transform(&self, _atlas_slot: &AtlasSlot) -> Affine {
        // The identity, because this engine addresses an atlas paint by its
        // own *region* — the layer, offset and extent travel in the lowered
        // record — rather than by sampling the whole page and shifting into
        // the slot. A renderer that bound the page would need the slot's
        // negative offset here; one whose record already carries the offset
        // would be applying it twice.
        Affine::IDENTITY
    }
}

/// The [`GlyphRunBackend`] a run's [`GlyphRunBuilder`](glifo::GlyphRunBuilder)
/// is built on.
///
/// Consumed by whichever of its three drawing methods the builder ends in, so
/// it holds the two borrows a run needs and nothing else: the sink the glyphs
/// are drawn into, and the preparation caches `glifo` resolves outlines and
/// hinting instances against.
#[derive(Debug)]
pub(crate) struct EngineTextBackend<'a, 's> {
    /// Where the run's glyphs are drawn.
    sink: &'a mut EngineGlyphSink<'s>,
    /// The compiler's retained outline/hinting caches.
    prep: &'a mut GlyphPrepCache,
    /// The glyph atlas this run's glyphs may be cached in, or
    /// [`AtlasCacher::Disabled`] for a run the policy routed to outlines.
    cacher: AtlasCacher<'a>,
}

impl<'a, 's> EngineTextBackend<'a, 's> {
    /// A backend drawing into `sink`, preparing glyphs against `prep`, caching
    /// through `cacher`.
    ///
    /// `cacher` is the policy's answer for this run already made: the caller
    /// classified the run before building this, so nothing here re-decides it.
    pub(crate) fn new(
        sink: &'a mut EngineGlyphSink<'s>,
        prep: &'a mut GlyphPrepCache,
        cacher: AtlasCacher<'a>,
    ) -> Self {
        Self { sink, prep, cacher }
    }
}

impl<'a> GlyphRunBackend<'a> for EngineTextBackend<'a, '_> {
    /// Turn atlas-backed glyph caching off for this run.
    ///
    /// One-way on purpose. The cacher this backend was built with is already
    /// the policy's answer for the run — the *only* place that decides whether
    /// a run may be cached (see [`crate::text::atlas_policy`]) — so a caller
    /// asking for caching cannot conjure a cache the policy withheld, while a
    /// caller asking to go without is always honoured. The engine's own
    /// lowering asks for neither.
    fn atlas_cache(mut self, enabled: bool) -> Self {
        if !enabled {
            self.cacher = AtlasCacher::Disabled;
        }
        self
    }

    fn fill_glyphs<Glyphs>(self, run: GlyphRun<'a>, glyphs: Glyphs)
    where
        Glyphs: Iterator<Item = Glyph> + Clone,
    {
        let Self { sink, prep, cacher } = self;
        let mut renderer = run.build(glyphs, prep.as_mut(), cacher);
        renderer.fill_glyphs(sink);
    }

    fn stroke_glyphs<Glyphs>(self, run: GlyphRun<'a>, glyphs: Glyphs)
    where
        Glyphs: Iterator<Item = Glyph> + Clone,
    {
        let Self { sink, prep, cacher } = self;
        let mut renderer = run.build(glyphs, prep.as_mut(), cacher);
        // No stroke width is scaled by `stroke_adjustment` on the way in, the
        // way a renderer holding stroke state would: the sink has none, and
        // refuses the stroked outline when it arrives (see
        // [`EngineGlyphSink::stroke_path`]).
        renderer.stroke_glyphs(sink);
    }

    fn render_decoration<Glyphs>(
        self,
        run: GlyphRun<'a>,
        glyphs: Glyphs,
        x_range: RangeInclusive<f32>,
        baseline_y: f32,
        offset: f32,
        size: f32,
        buffer: f32,
    ) where
        Glyphs: Iterator<Item = Glyph> + Clone,
    {
        let Self { sink, prep, cacher } = self;
        let mut renderer = run.build(glyphs, prep.as_mut(), cacher);
        renderer.render_decoration(x_range, baseline_y, offset, size, buffer, sink);
    }
}

/// A display-list brush in the paint vocabulary `glifo` reads back through.
///
/// `glifo` asks the sink what it is painting with for two reasons — a COLR
/// glyph's context colour, and whether a glyph may be atlas-cached — and both
/// answers come from the run's own brush rather than from anything the sink
/// derives. An image brush has no counterpart in that vocabulary (its image
/// type is the renderer's, not `peniko`'s), and answers black, the same
/// fallback the CPU reference renderer gives for every non-solid paint.
pub(crate) fn context_paint(brush: &Brush) -> PaintType {
    match brush {
        Brush::Solid(color) => PaintType::Solid(*color),
        Brush::Gradient(gradient) => PaintType::Gradient(gradient.clone()),
        Brush::Image(_) => PaintType::Solid(BLACK),
    }
}