lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
//! Flattened group opacity and layer blur.
//!
//! A node with `opacity < 1` fades its subtree as one flattened layer, like
//! CSS `opacity` and design tools: the subtree is painted into an offscreen
//! layer, which is then composited once at the node's opacity. Content inside
//! the group blends only with other content of the group, so a label over a
//! faded fill keeps its contrast against that fill, and a border drawn over
//! the fill's anti-aliased edge does not leave a lighter ring.
//!
//! A node with a blur is a layer too, like CSS `filter: blur()`: its subtree
//! is painted into the layer, and the layer is blurred as it is composited
//! ([`LayerBlur`]). A blurred layer is painted for more pixels than it shows,
//! because what lies just outside the visible part still bleeds into it. The
//! radius is in the node's own units: under a transform that scales the node
//! it scales with it.
//!
//! Layout records each group as a range of quads (`OpacityGroup`). A faded
//! group whose content paints a single primitive gives the same pixels either
//! way, so layout folds its opacity into that quad instead and no layer is
//! made. The runtime turns the remaining groups into [`LayerCmd`]s with pixel
//! bounds, and render engines walk a `LayerPlan` to paint each layer into
//! its own target before compositing it into its parent.

use std::ops::Range;

use crate::layout::{
  backdrop::BackdropCmd,
  quad::{ClipRect, MAX_ROUNDED_CLIPS},
  render_list::{GlyphCmd, RectCmd},
};

/// Anti-aliasing reach of the quad pipelines past a primitive's box, in
/// physical pixels (their vertex stages grow each quad by 2 px).
const AA_REACH: f32 = 2.0;

/// Largest blur radius of a node, in logical pixels. A layer is painted for
/// its blur's reach past the window, so an unbounded radius is an unbounded
/// texture.
pub const MAX_BLUR_RADIUS: f32 = 256.0;

/// A blur below this many physical pixels of deviation changes no pixel.
const MIN_BLUR_SIGMA: f32 = 0.05;
/// The widest Gaussian one pass samples directly, in texels of its source.
/// Wider blurs run on a reduced copy of the layer.
const MAX_PASS_SIGMA: f32 = 8.0;
/// Most the layer is reduced by for a wide blur, per axis.
const MAX_BLUR_REDUCTION: u32 = 64;

/// The Gaussian's standard deviation for a blur radius: half of it, as for
/// box and text shadows and the canvas's `Filter::Blur`.
pub(crate) fn blur_sigma(radius: f32) -> f32 {
  radius * 0.5
}

/// How far a blur of `radius` moves colour, in the radius's units: three
/// standard deviations, past which a Gaussian has under 0.3 % of its weight.
pub(crate) fn blur_reach(radius: f32) -> f32 {
  (blur_sigma(radius) * 3.0).ceil()
}

/// A subtree painted as one layer: a node with `opacity < 1` that paints more
/// than one primitive, or a node with a blur. Its quads are `start..end`
/// (quad indices, which are also the render orders).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct OpacityGroup {
  pub start: usize,
  pub end: usize,
  pub opacity: f32,
  /// The node's blur radius in logical pixels; 0 without a blur.
  pub blur: f32,
  /// With a blur: the clip the node itself is under, in logical pixels,
  /// rounded clips included. The blurred layer shows only inside it; its
  /// content is clipped further out (see `LayoutEngine::collect_quads`).
  pub clip: Option<ClipRect>,
}

/// An offscreen layer: the draws whose `order` lies in `start_order..end_order`
/// are painted into a transparent layer covering `bounds`, which is then
/// composited over what was painted before `start_order` at `opacity`.
///
/// Layers nest: a layer inside another lies within its order range, and
/// [`RenderList::layers`](crate::layout::render_list::RenderList::layers) lists
/// them in paint order, an outer layer before the layers inside it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayerCmd {
  pub start_order: usize,
  pub end_order: usize,
  /// The group's opacity, in `0.0..1.0`.
  pub opacity: f32,
  /// Where the layer shows, in whole physical pixels of the window. Without
  /// a blur this is also where its content can paint, and the layer's pixels
  /// map one to one onto the window's, so compositing never resamples.
  pub bounds: LayerBounds,
  /// Blurs the layer as it is composited. `None` composites it as painted.
  pub blur: Option<LayerBlur>,
}

impl LayerCmd {
  /// Whether compositing the layer changes any pixel. An invisible layer is
  /// skipped with everything inside it.
  pub fn is_visible(&self) -> bool {
    self.opacity > 0.0 && !self.bounds.is_empty() && self.blur.is_none_or(|blur| blur.width > 0 && blur.height > 0)
  }

  /// The window pixels the layer's content is painted for, as an origin and
  /// a size: `bounds`, or a blurred layer's larger rectangle.
  pub fn painted(&self) -> ([i32; 2], [u32; 2]) {
    match self.blur {
      Some(blur) => ([blur.x, blur.y], [blur.width, blur.height]),
      None => (
        [self.bounds.x as i32, self.bounds.y as i32],
        [self.bounds.width, self.bounds.height],
      ),
    }
  }
}

/// A Gaussian blur of a layer, like CSS `filter: blur()`.
///
/// The layer's content is painted for the rectangle here, which reaches past
/// [`LayerCmd::bounds`] by as far as the blur moves colour and may lie partly
/// outside the window: content there is not shown, but it bleeds into what
/// is. Its pixels are whole physical pixels of the window, as `bounds` are.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayerBlur {
  /// Standard deviation of the Gaussian, in physical pixels.
  pub sigma: f32,
  pub x: i32,
  pub y: i32,
  pub width: u32,
  pub height: u32,
  /// The rounded clips the blurred layer is cut to as it is composited:
  /// those of the clip its node is under (see [`rounded_clip_boxes`]). A
  /// clip's rectangle is in [`LayerCmd::bounds`] already.
  pub clips: RoundedClipBoxes,
}

/// The rounded clips of a [`ClipRect`] as boxes, innermost first.
pub type RoundedClipBoxes = [Option<RoundedBox>; MAX_ROUNDED_CLIPS];

/// The rounded clips of `clip` (in physical pixels of the window) as upright
/// [`RoundedBox`]es, which is what the blur passes cut by.
pub(crate) fn rounded_clip_boxes(clip: ClipRect) -> RoundedClipBoxes {
  if !clip.active {
    return [None; MAX_ROUNDED_CLIPS];
  }
  clip.rounded.map(|rounded| {
    rounded.map(|rounded| {
      let limit = (rounded.width.min(rounded.height) * 0.5).max(0.0);
      RoundedBox::rect(
        rounded.x,
        rounded.y,
        rounded.width,
        rounded.height,
        rounded.radius.to_array().map(|radius| radius.clamp(0.0, limit)),
      )
    })
  })
}

/// How much of the pixel whose centre is (`x`, `y`) all of `clips` cover.
#[cfg(feature = "devtools")]
pub(crate) fn rounded_clips_coverage(clips: &RoundedClipBoxes, x: f32, y: f32) -> f32 {
  clips.iter().flatten().map(|clip| clip.coverage(x, y)).product()
}

/// A box with rounded corners in the window, possibly turned or scaled: what
/// a blur is cut to. The shaders and [`Self::coverage`] take a pixel's
/// offset from `center` into the box's own axes with `inverse` and measure
/// its distance to the rounded edge there.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RoundedBox {
  /// The box's centre, in physical pixels of the window.
  pub center: [f32; 2],
  /// Half the box's width and height, along its own axes.
  pub half: [f32; 2],
  /// Corner radii along its own axes: top left, top right, bottom right,
  /// bottom left.
  pub radii: [f32; 4],
  /// The 2x2 matrix (`[a, b, c, d]`, as a
  /// [`RectCmd`]'s transform) from an
  /// offset in window pixels to the box's own axes. The identity for an
  /// upright box.
  pub inverse: [f32; 4],
  /// Window pixels per unit of the box's own axes: 1 for an upright box.
  pub scale: f32,
}

impl RoundedBox {
  /// An upright box.
  pub fn rect(x: f32, y: f32, width: f32, height: f32, radii: [f32; 4]) -> Self {
    Self {
      center: [x + width * 0.5, y + height * 0.5],
      half: [width * 0.5, height * 0.5],
      radii,
      inverse: [1.0, 0.0, 0.0, 1.0],
      scale: 1.0,
    }
  }

  /// A `width` x `height` box at (`x`, `y`) under the 2x2 `transform` around
  /// `origin` (relative to the box), as a
  /// [`RectCmd`] is placed. `None` for
  /// a transform that flattens the box.
  pub fn transformed(
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    radii: [f32; 4],
    transform: [f32; 4],
    origin: [f32; 2],
  ) -> Option<Self> {
    let [a, b, c, d] = transform;
    let determinant = a * d - b * c;
    if !(determinant.is_finite() && determinant.abs() > 1.0e-6) {
      return None;
    }
    let (dx, dy) = (width * 0.5 - origin[0], height * 0.5 - origin[1]);
    Some(Self {
      center: [x + origin[0] + a * dx + c * dy, y + origin[1] + b * dx + d * dy],
      half: [width * 0.5, height * 0.5],
      radii,
      inverse: [d / determinant, -b / determinant, -c / determinant, a / determinant],
      scale: determinant.abs().sqrt(),
    })
  }

  /// The box's axis-aligned bounds in the window: x0, y0, x1, y1.
  pub fn extent(&self) -> [f32; 4] {
    // The forward matrix is the inverse of `inverse`.
    let [ia, ib, ic, id] = self.inverse;
    let determinant = ia * id - ib * ic;
    let (a, b, c, d) = (id / determinant, -ib / determinant, -ic / determinant, ia / determinant);
    let reach_x = (a * self.half[0]).abs() + (c * self.half[1]).abs();
    let reach_y = (b * self.half[0]).abs() + (d * self.half[1]).abs();
    [
      self.center[0] - reach_x,
      self.center[1] - reach_y,
      self.center[0] + reach_x,
      self.center[1] + reach_y,
    ]
  }

  /// How much of the pixel whose centre is (`x`, `y`) the box covers, from
  /// the centre's distance to the rounded edge, as the blur shaders take it.
  pub fn coverage(&self, x: f32, y: f32) -> f32 {
    let (dx, dy) = (x - self.center[0], y - self.center[1]);
    let [a, b, c, d] = self.inverse;
    let p = [a * dx + c * dy, b * dx + d * dy];
    let radius = match (p[0] >= 0.0, p[1] >= 0.0) {
      (false, false) => self.radii[0],
      (true, false) => self.radii[1],
      (true, true) => self.radii[2],
      (false, true) => self.radii[3],
    };
    let q = [p[0].abs() - self.half[0] + radius, p[1].abs() - self.half[1] + radius];
    let distance = q[0].max(0.0).hypot(q[1].max(0.0)) + q[0].max(q[1]).min(0.0) - radius;
    (0.5 - distance * self.scale).clamp(0.0, 1.0)
  }
}

/// How a render engine blurs a layer: wide blurs first reduce the layer by
/// `reduction` per axis (a box filter), then both run a horizontal and a
/// vertical Gaussian pass between intermediate targets of the (reduced)
/// layer's size, and the result is read once per pixel as the layer is
/// composited, scaled back up. The box filter and the resampling on the way
/// back up widen the result, so the Gaussian's `sigma` is narrowed to keep
/// the total at the blur asked for.
#[cfg_attr(not(feature = "render"), allow(dead_code))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct BlurPlan {
  /// 1, or a power of two the layer is reduced by before the Gaussian.
  pub reduction: u32,
  /// The Gaussian's deviation in texels of the (reduced) layer.
  pub sigma: f32,
  /// Size of the reduced layer with its border; the layer's own size when
  /// `reduction` is 1.
  pub size: [u32; 2],
  /// Texels around the reduced layer, on every side, that hold what lies
  /// just past the layer (its edge, repeated): 1 for a reduced layer, whose
  /// outermost pixels are read between its edge texel and that one as it is
  /// scaled back up, and 0 for a layer that is not reduced.
  pub border: u32,
}

#[cfg_attr(not(feature = "render"), allow(dead_code))]
impl BlurPlan {
  pub(crate) fn new(blur: &LayerBlur) -> Self {
    let reduction = blur_reduction(blur.sigma);
    if reduction == 1 {
      return Self {
        reduction,
        sigma: blur.sigma,
        size: [blur.width, blur.height],
        border: 0,
      };
    }
    let r = reduction as f32;
    // Variances add: a box of `r` texels has (r^2 - 1) / 12, and the
    // bilinear resampling back up is a tent of half-width `r`, r^2 / 6.
    let widened = (r * r - 1.0) / 12.0 + r * r / 6.0;
    let sigma = (blur.sigma * blur.sigma - widened).max(0.25).sqrt() / r;
    Self {
      reduction,
      sigma: sigma.min(MAX_PASS_SIGMA * 1.25),
      size: [
        blur.width.div_ceil(reduction).max(1) + 2,
        blur.height.div_ceil(reduction).max(1) + 2,
      ],
      border: 1,
    }
  }
}

/// How far past the pixels a blur of `sigma` shows the pixels it reads lie,
/// in whole physical pixels: the blur's reach, and what the passes' sampling
/// adds (a reduced texel on either side, and the bilinear taps' neighbour).
pub(crate) fn blur_pad(sigma: f32) -> i32 {
  (sigma * 3.0).ceil() as i32 + 2 * blur_reduction(sigma) as i32 + 1
}

fn blur_reduction(sigma: f32) -> u32 {
  let mut reduction = 1;
  while sigma / reduction as f32 > MAX_PASS_SIGMA && reduction < MAX_BLUR_REDUCTION {
    reduction *= 2;
  }
  reduction
}

/// A rectangle of whole physical pixels.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LayerBounds {
  pub x: u32,
  pub y: u32,
  pub width: u32,
  pub height: u32,
}

impl LayerBounds {
  pub fn is_empty(&self) -> bool {
    self.width == 0 || self.height == 0
  }
}

/// A step of painting one target (the window or a layer): a run of ordered
/// draws, or compositing a finished inner layer.
#[cfg_attr(not(any(feature = "render", feature = "devtools")), allow(dead_code))]
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum LayerStep {
  /// Indices into the sorted draw list.
  Draws(Range<usize>),
  /// Composite the layer painted by `LayerPlan::targets()[index]`.
  Composite(usize),
  /// Blur what the target holds so far for the backdrop blur `index` of the
  /// frame (see [`crate::layout::backdrop`]).
  Backdrop(usize),
}

/// One target to paint: a layer (`Some(index into RenderList::layers)`) or,
/// last, the window itself (`None`).
#[cfg_attr(not(any(feature = "render", feature = "devtools")), allow(dead_code))]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LayerTarget {
  pub layer: Option<usize>,
  steps: Range<usize>,
}

/// The order in which a render engine paints a frame with layers: every
/// layer's target before the target it is composited into, the window last.
/// Without layers the plan is the window's draws in one step, so opacity 1
/// costs nothing.
#[cfg_attr(not(any(feature = "render", feature = "devtools")), allow(dead_code))]
#[derive(Default)]
pub(crate) struct LayerPlan {
  targets: Vec<LayerTarget>,
  steps: Vec<LayerStep>,
  pending: Vec<LayerStep>,
  /// The next backdrop blur to place while a plan is built.
  backdrop_cursor: usize,
  backdrop_steps: usize,
}

#[cfg_attr(not(any(feature = "render", feature = "devtools")), allow(dead_code))]
impl LayerPlan {
  /// Plans `draw_count` draws sorted by order (`order_of(index)`), grouped by
  /// `layers`, with the frame's backdrop blurs at `backdrops` (their orders,
  /// ascending) between them. Invisible layers drop their draws and the
  /// layers and backdrop blurs inside them.
  pub(crate) fn build(
    &mut self,
    draw_count: usize,
    order_of: impl Fn(usize) -> usize,
    layers: &[LayerCmd],
    backdrops: &[BackdropCmd],
  ) {
    self.targets.clear();
    self.steps.clear();
    self.pending.clear();
    self.backdrop_cursor = 0;
    self.backdrop_steps = 0;
    let mut cursor = 0;
    self.plan_target(
      None,
      0..draw_count,
      usize::MAX,
      &order_of,
      layers,
      backdrops,
      &mut cursor,
    );
  }

  /// Whether the frame has any backdrop blur to run.
  #[cfg_attr(not(feature = "render"), allow(dead_code))]
  pub(crate) fn has_backdrops(&self) -> bool {
    self.backdrop_steps > 0
  }

  /// Queues the draws `*next..draw_end` of the target being planned, split
  /// at the backdrop blurs whose order is below `order_limit`.
  fn plan_draws(
    &mut self,
    next: &mut usize,
    draw_end: usize,
    order_limit: usize,
    order_of: &impl Fn(usize) -> usize,
    backdrops: &[BackdropCmd],
  ) {
    while let Some(backdrop) = backdrops.get(self.backdrop_cursor)
      && backdrop.order < order_limit
    {
      let at = first_at_or_after(*next..draw_end, backdrop.order, order_of);
      if at > *next {
        self.pending.push(LayerStep::Draws(*next..at));
        *next = at;
      }
      self.pending.push(LayerStep::Backdrop(self.backdrop_cursor));
      self.backdrop_cursor += 1;
      self.backdrop_steps += 1;
    }
    if draw_end > *next {
      self.pending.push(LayerStep::Draws(*next..draw_end));
      *next = draw_end;
    }
  }

  /// The targets in paint order; the window is last.
  pub(crate) fn targets(&self) -> &[LayerTarget] {
    &self.targets
  }

  pub(crate) fn steps(&self, target: &LayerTarget) -> &[LayerStep] {
    &self.steps[target.steps.clone()]
  }

  /// Whether the frame has any layer to paint.
  #[cfg_attr(not(feature = "render"), allow(dead_code))]
  pub(crate) fn has_layers(&self) -> bool {
    self.targets.len() > 1
  }

  #[allow(clippy::too_many_arguments)]
  fn plan_target(
    &mut self,
    layer: Option<usize>,
    draws: Range<usize>,
    end_order: usize,
    order_of: &impl Fn(usize) -> usize,
    layers: &[LayerCmd],
    backdrops: &[BackdropCmd],
    cursor: &mut usize,
  ) -> usize {
    // Steps of this target wait on `pending` while inner targets are planned.
    let pending_start = self.pending.len();
    let mut next = draws.start;
    while *cursor < layers.len() && layers[*cursor].start_order < end_order {
      let index = *cursor;
      *cursor += 1;
      let inner = layers[index];
      let start = first_at_or_after(next..draws.end, inner.start_order, order_of);
      let end = first_at_or_after(start..draws.end, inner.end_order, order_of);
      self.plan_draws(&mut next, start, inner.start_order, order_of, backdrops);
      if inner.is_visible() && end > start {
        let target = self.plan_target(
          Some(index),
          start..end,
          inner.end_order,
          order_of,
          layers,
          backdrops,
          cursor,
        );
        self.pending.push(LayerStep::Composite(target));
      } else {
        while *cursor < layers.len() && layers[*cursor].start_order < inner.end_order {
          *cursor += 1;
        }
      }
      // Nothing of a layer that is not painted is blurred either.
      while backdrops
        .get(self.backdrop_cursor)
        .is_some_and(|backdrop| backdrop.order < inner.end_order)
      {
        self.backdrop_cursor += 1;
      }
      next = end;
    }
    self.plan_draws(&mut next, draws.end, end_order, order_of, backdrops);
    let steps_start = self.steps.len();
    self.steps.extend(self.pending.drain(pending_start..));
    self.targets.push(LayerTarget {
      layer,
      steps: steps_start..self.steps.len(),
    });
    self.targets.len() - 1
  }
}

/// The pixel space a render pass draws in: the window, or a layer texture
/// whose texel (0, 0) is window pixel `origin`. Draws keep window
/// coordinates; shaders subtract `origin` (the `zw` of their globals'
/// `viewport`), and clips are moved into the target with [`Self::clip`].
#[cfg(feature = "render")]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct TargetSpace {
  /// Size of the render target in pixels.
  pub width: f32,
  pub height: f32,
  pub origin: [f32; 2],
  /// The layer's own size within its (possibly larger, pooled) texture.
  layer_size: Option<[f32; 2]>,
}

#[cfg(feature = "render")]
impl TargetSpace {
  pub(crate) fn window(width: f32, height: f32) -> Self {
    Self {
      width,
      height,
      origin: [0.0; 2],
      layer_size: None,
    }
  }

  /// The pixels `layer` is painted for, in the top-left corner of a
  /// `texture_width` x `texture_height` texture.
  pub(crate) fn layer(layer: &LayerCmd, texture_width: u32, texture_height: u32) -> Self {
    let (origin, size) = layer.painted();
    Self {
      width: texture_width as f32,
      height: texture_height as f32,
      origin: [origin[0] as f32, origin[1] as f32],
      layer_size: Some([size[0] as f32, size[1] as f32]),
    }
  }

  /// An intermediate target of a blur: `size` texels in the top-left corner
  /// of a `texture_width` x `texture_height` texture.
  #[cfg_attr(not(feature = "dx12"), allow(dead_code))]
  pub(crate) fn blur_target(size: [u32; 2], texture_width: u32, texture_height: u32) -> Self {
    Self {
      width: texture_width as f32,
      height: texture_height as f32,
      origin: [0.0; 2],
      layer_size: Some([size[0] as f32, size[1] as f32]),
    }
  }

  #[cfg_attr(not(feature = "wgpu"), allow(dead_code))]
  pub(crate) fn is_window(&self) -> bool {
    self.layer_size.is_none()
  }

  /// The `viewport` of the shaders' globals: target size, then origin.
  pub(crate) fn viewport(&self) -> [f32; 4] {
    [self.width, self.height, self.origin[0], self.origin[1]]
  }

  /// `clip` (window pixels) in this target's pixels. In a layer, drawing
  /// without a clip is limited to the layer's bounds.
  pub(crate) fn clip(&self, clip: ClipRect) -> ClipRect {
    let Some([width, height]) = self.layer_size else {
      return clip;
    };
    if !clip.active {
      return ClipRect::rect(0.0, 0.0, width, height);
    }
    clip.translated(-self.origin[0], -self.origin[1])
  }

  /// Where `layer` sits in this target, as a clip in this target's pixels.
  pub(crate) fn layer_rect(&self, layer: LayerBounds) -> ClipRect {
    ClipRect::rect(
      layer.x as f32 - self.origin[0],
      layer.y as f32 - self.origin[1],
      layer.width as f32,
      layer.height as f32,
    )
  }
}

/// Uniforms of the layer-composite shaders (`layer.wgsl`, `layer.hlsl`).
#[cfg(feature = "render")]
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct LayerComposite {
  /// The layer's rect in the parent target's pixels: x, y, width, height.
  pub rect: [f32; 4],
  /// The parent target's size, then the offset from a parent pixel to the
  /// layer texel it shows.
  pub target: [f32; 4],
  /// `x`: the layer's opacity.
  pub opacity: [f32; 4],
}

#[cfg(feature = "render")]
impl LayerComposite {
  pub(crate) fn new(layer: &LayerCmd, parent: &TargetSpace) -> Self {
    let rect = parent.layer_rect(layer.bounds);
    Self {
      rect: [rect.x, rect.y, rect.width, rect.height],
      target: [
        parent.width,
        parent.height,
        parent.origin[0] - layer.bounds.x as f32,
        parent.origin[1] - layer.bounds.y as f32,
      ],
      opacity: [layer.opacity, 0.0, 0.0, 0.0],
    }
  }
}

/// Uniforms of one pass of the layer-blur shaders (`layer_blur.wgsl`,
/// `layer_blur.hlsl`). A pass draws `rect` of its target; each pixel reads
/// the source texture around `(pixel + offset) * scale`, in source texels.
#[cfg(feature = "render")]
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct LayerBlurPass {
  /// The rect drawn, in the target's pixels: x, y, width, height.
  pub rect: [f32; 4],
  /// The target's size, then the offset added to a target pixel.
  pub target: [f32; 4],
  /// The scale from offset target pixels to source texels, then one over the
  /// source texture's size.
  pub source: [f32; 4],
  /// The Gaussian's axis in source texels, its deviation in source texels,
  /// and the opacity the result is multiplied by.
  pub kernel: [f32; 4],
  /// `x`: 0 for a Gaussian pass; otherwise the pass is a box reduction that
  /// averages this many bilinear taps per axis (half the reduction). `y`:
  /// the mask's [`RoundedBox::scale`]; `z`: the clip's. `w`: 1 for the pass
  /// that composites a finished blur, which reads its source once per pixel.
  pub mode: [f32; 4],
  /// The source texels a tap may read, as the lowest and the highest texel
  /// centre: taps past them read the edge texel. The texture around them
  /// holds whatever it was last used for.
  pub limit: [f32; 4],
  /// For the pass that puts a blurred backdrop back: the [`RoundedBox`] it
  /// fills, as its centre in the target's pixels and its half size, its
  /// `inverse` matrix and its corner radii. A box that covers everything
  /// otherwise.
  pub mask: [f32; 4],
  pub mask_inverse: [f32; 4],
  pub radii: [f32; 4],
  /// For the last pass of a blur: the innermost rounded clip its result is
  /// cut to, in the same form. A box that covers everything without one.
  pub clip: [f32; 4],
  pub clip_inverse: [f32; 4],
  pub clip_radii: [f32; 4],
  /// And the rounded clip outside that one, as centre and half size, then
  /// radii. Clips are upright boxes, so it has no matrix, and `mode.z` is
  /// its scale too.
  pub outer_clip: [f32; 4],
  pub outer_clip_radii: [f32; 4],
}

#[cfg(feature = "render")]
impl LayerBlurPass {
  /// Reduces the painted layer `blur` (in a `source` sized texture) into
  /// the top-left corner of a `target` sized one.
  pub(crate) fn reduce(blur: &LayerBlur, plan: &BlurPlan, source: [u32; 2], target: [u32; 2]) -> Self {
    let r = plan.reduction as f32;
    // The reduced layer starts `border` texels in: the texels before it read
    // past the layer's edge, which repeats.
    let border = plan.border as f32;
    Self {
      rect: [0.0, 0.0, plan.size[0] as f32, plan.size[1] as f32],
      target: [target[0] as f32, target[1] as f32, -border, -border],
      source: [r, r, 1.0 / source[0] as f32, 1.0 / source[1] as f32],
      kernel: [0.0, 0.0, 0.0, 1.0],
      mode: [(plan.reduction / 2) as f32, 1.0, 1.0, 0.0],
      limit: texel_limit([blur.width, blur.height]),
      ..Self::UNCUT
    }
  }

  /// The horizontal Gaussian, between two textures holding the (reduced)
  /// layer in their top-left corners.
  pub(crate) fn horizontal(plan: &BlurPlan, source: [u32; 2], target: [u32; 2]) -> Self {
    Self::gaussian(plan, [1.0, 0.0], source, target)
  }

  /// The vertical Gaussian, over what the horizontal one painted.
  pub(crate) fn vertical(plan: &BlurPlan, source: [u32; 2], target: [u32; 2]) -> Self {
    Self::gaussian(plan, [0.0, 1.0], source, target)
  }

  /// A Gaussian along `axis`, texel for texel between two textures holding
  /// the (reduced) layer in their top-left corners.
  fn gaussian(plan: &BlurPlan, axis: [f32; 2], source: [u32; 2], target: [u32; 2]) -> Self {
    Self {
      rect: [0.0, 0.0, plan.size[0] as f32, plan.size[1] as f32],
      target: [target[0] as f32, target[1] as f32, 0.0, 0.0],
      source: [1.0, 1.0, 1.0 / source[0] as f32, 1.0 / source[1] as f32],
      kernel: [axis[0], axis[1], plan.sigma, 1.0],
      mode: [0.0, 1.0, 1.0, 0.0],
      limit: texel_limit(plan.size),
      ..Self::UNCUT
    }
  }

  /// The finished blur, composited into `parent` over `layer`'s bounds at
  /// its opacity and scaled back up from a reduced layer: one read per
  /// pixel. `source` is the size of the texture the vertical pass painted.
  pub(crate) fn composite(layer: &LayerCmd, plan: &BlurPlan, parent: &TargetSpace, source: [u32; 2]) -> Self {
    let rect = parent.layer_rect(layer.bounds);
    let (origin, _) = layer.painted();
    let scale = 1.0 / plan.reduction as f32;
    // The offset is in the parent's pixels: the border's texels are
    // `reduction` of them each.
    let border = (plan.border * plan.reduction) as f32;
    let clips = layer.blur.map_or([None; MAX_ROUNDED_CLIPS], |blur| blur.clips);
    let (clip, clip_inverse, clip_radii, clip_scale) = box_uniforms(clips[0], parent);
    let (outer_clip, _, outer_clip_radii, _) = box_uniforms(clips[1], parent);
    Self {
      clip,
      clip_inverse,
      clip_radii,
      outer_clip,
      outer_clip_radii,
      rect: [rect.x, rect.y, rect.width, rect.height],
      target: [
        parent.width,
        parent.height,
        parent.origin[0] - origin[0] as f32 + border,
        parent.origin[1] - origin[1] as f32 + border,
      ],
      source: [scale, scale, 1.0 / source[0] as f32, 1.0 / source[1] as f32],
      kernel: [0.0, 0.0, 0.0, layer.opacity],
      mode: [0.0, 1.0, clip_scale, 1.0],
      limit: texel_limit(plan.size),
      ..Self::UNCUT
    }
  }

  /// The finished blur of a backdrop, put back into `parent` inside the
  /// region's box. `source` is the size of the texture the vertical pass
  /// painted.
  pub(crate) fn backdrop(
    region: &crate::layout::backdrop::BackdropRegion,
    plan: &BlurPlan,
    parent: &TargetSpace,
    source: [u32; 2],
  ) -> Self {
    let composite = Self::composite(&region.layer, plan, parent, source);
    let (mask, mask_inverse, radii, mask_scale) = box_uniforms(Some(region.mask), parent);
    Self {
      mask,
      mask_inverse,
      radii,
      mode: [composite.mode[0], mask_scale, composite.mode[2], composite.mode[3]],
      ..composite
    }
  }

  /// A pass that is cut to nothing: both boxes cover everything.
  const UNCUT: Self = Self {
    rect: [0.0; 4],
    target: [0.0; 4],
    source: [0.0; 4],
    kernel: [0.0; 4],
    mode: [0.0, 1.0, 1.0, 0.0],
    limit: [0.0; 4],
    mask: [0.0, 0.0, EVERYWHERE, EVERYWHERE],
    mask_inverse: [1.0, 0.0, 0.0, 1.0],
    radii: [0.0; 4],
    clip: [0.0, 0.0, EVERYWHERE, EVERYWHERE],
    clip_inverse: [1.0, 0.0, 0.0, 1.0],
    clip_radii: [0.0; 4],
    outer_clip: [0.0, 0.0, EVERYWHERE, EVERYWHERE],
    outer_clip_radii: [0.0; 4],
  };
}

/// The half size of a box that covers every pixel of any target.
#[cfg(feature = "render")]
const EVERYWHERE: f32 = 1.0e9;

/// A [`RoundedBox`] as a pass's uniforms in `parent`'s pixels: centre and
/// half size, inverse matrix, radii and scale. A box that covers everything
/// for `None`.
#[cfg(feature = "render")]
fn box_uniforms(rounded: Option<RoundedBox>, parent: &TargetSpace) -> ([f32; 4], [f32; 4], [f32; 4], f32) {
  match rounded {
    Some(rounded) => (
      [
        rounded.center[0] - parent.origin[0],
        rounded.center[1] - parent.origin[1],
        rounded.half[0],
        rounded.half[1],
      ],
      rounded.inverse,
      rounded.radii,
      rounded.scale,
    ),
    None => ([0.0, 0.0, EVERYWHERE, EVERYWHERE], [1.0, 0.0, 0.0, 1.0], [0.0; 4], 1.0),
  }
}

/// The lowest and the highest texel centre of a `size` texel region at a
/// texture's origin.
#[cfg(feature = "render")]
fn texel_limit(size: [u32; 2]) -> [f32; 4] {
  [
    0.5,
    0.5,
    (size[0] as f32 - 0.5).max(0.5),
    (size[1] as f32 - 0.5).max(0.5),
  ]
}

/// The first index in `range` whose order is at least `order` (`range.end`
/// when there is none); draws are sorted by order.
fn first_at_or_after(range: Range<usize>, order: usize, order_of: &impl Fn(usize) -> usize) -> usize {
  let (mut low, mut high) = (range.start, range.end);
  while low < high {
    let mid = low + (high - low) / 2;
    if order_of(mid) < order {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  low
}

/// Resolves `groups` into `layers` (cleared first) from the draws a frame
/// built for its `orders` quads, over a `viewport` of physical pixels, each
/// logical pixel `scale` of them.
#[allow(clippy::too_many_arguments)]
pub(crate) fn resolve_layers(
  groups: &[OpacityGroup],
  orders: usize,
  viewport: [f32; 2],
  scale: f32,
  rects: &[RectCmd],
  glyphs: &[GlyphCmd],
  #[cfg(feature = "raster")] images: &[crate::images::ImageCmd],
  layers: &mut Vec<LayerCmd>,
) {
  layers.clear();
  if groups.is_empty() {
    return;
  }
  let mut bounds = LayerBoundsBuilder::new(orders);
  rects.iter().for_each(|rect| bounds.add_rect(rect));
  glyphs.iter().for_each(|glyph| bounds.add_glyph(glyph));
  #[cfg(feature = "raster")]
  images.iter().for_each(|image| bounds.add_image(image));
  bounds.build(groups, viewport, scale, layers);
}

/// Axis-aligned bounds `[x0, y0, x1, y1]` in physical pixels.
pub(crate) type Extent = [f32; 4];

const EMPTY_EXTENT: Extent = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];

/// The pixels a rect can paint: its box under its transform, as far as its
/// anti-aliasing, its shadow and its stroke reach, inside its clip.
pub(crate) fn rect_extent(rect: &RectCmd) -> Extent {
  let reach = AA_REACH + rect.shadow.map_or(0.0, |shadow| shadow.outset()) + rect.stroke_style.outset(rect.stroke);
  let extent = transformed_extent(
    rect.x,
    rect.y,
    rect.width,
    rect.height,
    rect.transform,
    rect.transform_origin,
    reach,
  );
  clipped(extent, rect.clip)
}

/// How far past its box a glyph can paint: its anti-aliasing, and its
/// blurred shadow.
pub(crate) fn glyph_reach(glyph: &GlyphCmd) -> f32 {
  // The glyph pipeline pads a blurred shadow by `ceil(2 * sigma) + 1`.
  if glyph.shadow_sigma > 0.0 {
    (glyph.shadow_sigma * 2.0).ceil() + 1.0 + AA_REACH
  } else {
    AA_REACH
  }
}

/// The pixels a glyph can paint, with its blurred shadow, inside its clip.
pub(crate) fn glyph_extent(glyph: &GlyphCmd) -> Extent {
  let reach = glyph_reach(glyph);
  let extent = transformed_extent(
    glyph.x,
    glyph.y,
    glyph.width,
    glyph.height,
    glyph.transform,
    glyph.transform_origin,
    reach,
  );
  clipped(extent, glyph.clip)
}

/// The pixels an image can paint, inside its clip.
#[cfg(feature = "raster")]
pub(crate) fn image_extent(image: &crate::images::ImageCmd) -> Extent {
  let extent = transformed_extent(
    image.x,
    image.y,
    image.width,
    image.height,
    image.transform,
    image.transform_origin,
    AA_REACH,
  );
  clipped(extent, image.clip)
}

fn union(a: Extent, b: Extent) -> Extent {
  [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]
}

/// Collects the painted extent of every render order, then turns `groups`
/// into layers over a `viewport` of physical pixels.
struct LayerBoundsBuilder {
  extents: Vec<Extent>,
}

impl LayerBoundsBuilder {
  /// `orders` is the number of quad orders (orders past it are overlays that
  /// no group contains).
  fn new(orders: usize) -> Self {
    Self {
      extents: vec![EMPTY_EXTENT; orders],
    }
  }

  fn add(&mut self, order: usize, extent: Extent) {
    let Some(slot) = self.extents.get_mut(order) else {
      return;
    };
    *slot = union(*slot, extent);
  }

  fn add_rect(&mut self, rect: &RectCmd) {
    self.add(rect.order, rect_extent(rect));
  }

  fn add_glyph(&mut self, glyph: &GlyphCmd) {
    self.add(glyph.order, glyph_extent(glyph));
  }

  #[cfg(feature = "raster")]
  fn add_image(&mut self, image: &crate::images::ImageCmd) {
    self.add(image.order, image_extent(image));
  }

  /// Layers for `groups`, outer layers first.
  fn build(&mut self, groups: &[OpacityGroup], viewport: [f32; 2], scale: f32, layers: &mut Vec<LayerCmd>) {
    // Groups close children first, so a group is resolved before the groups
    // around it.
    for group in groups {
      let end = group.end.min(self.extents.len());
      let start = group.start.min(end);
      let extent = self.extents[start..end].iter().copied().fold(EMPTY_EXTENT, union);
      let (bounds, blur) = blurred_bounds(group, extent, viewport, scale);
      // A blurred layer paints past its content, and a layer around it has
      // to cover that too.
      if blur.is_some() && start < end {
        let shown = [
          bounds.x as f32,
          bounds.y as f32,
          (bounds.x + bounds.width) as f32,
          (bounds.y + bounds.height) as f32,
        ];
        self.extents[start] = union(self.extents[start], shown);
      }
      layers.push(LayerCmd {
        start_order: group.start,
        end_order: group.end,
        opacity: group.opacity.clamp(0.0, 1.0),
        bounds,
        blur,
      });
    }
    // Groups close children first; paint order puts the outer layer first.
    layers.sort_by(|a, b| a.start_order.cmp(&b.start_order).then(b.end_order.cmp(&a.end_order)));
  }
}

/// The bounding box of a `width` x `height` box at (`x`, `y`) under the 2x2
/// `transform` applied around `origin` (relative to the box), grown by `reach`.
fn transformed_extent(
  x: f32,
  y: f32,
  width: f32,
  height: f32,
  transform: [f32; 4],
  origin: [f32; 2],
  reach: f32,
) -> Extent {
  let [a, b, c, d] = transform;
  let corners = [
    (-reach, -reach),
    (width + reach, -reach),
    (-reach, height + reach),
    (width + reach, height + reach),
  ];
  corners.iter().fold(EMPTY_EXTENT, |extent, &(local_x, local_y)| {
    let (dx, dy) = (local_x - origin[0], local_y - origin[1]);
    let px = x + origin[0] + a * dx + c * dy;
    let py = y + origin[1] + b * dx + d * dy;
    union(extent, [px, py, px, py])
  })
}

pub(crate) fn clipped(extent: Extent, clip: ClipRect) -> Extent {
  if !clip.active {
    return extent;
  }
  [
    extent[0].max(clip.x.floor()),
    extent[1].max(clip.y.floor()),
    extent[2].min((clip.x + clip.width).ceil()),
    extent[3].min((clip.y + clip.height).ceil()),
  ]
}

fn grown(extent: Extent, by: f32) -> Extent {
  [extent[0] - by, extent[1] - by, extent[2] + by, extent[3] + by]
}

fn intersection(a: Extent, b: Extent) -> Extent {
  [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]
}

/// Where a group painting `extent` shows, and its blur if it has one.
///
/// A blurred layer shows as far as its blur reaches past its content, inside
/// the node's clip and the window. It is painted for the visible part grown
/// by the blur's reach (and by what the passes' sampling adds): that holds
/// the content that can reach a visible pixel, and it is also where the
/// horizontal pass leaves its result, which spreads that far sideways. Past
/// the content the rectangle ends where no pass has anything left to read.
fn blurred_bounds(
  group: &OpacityGroup,
  extent: Extent,
  viewport: [f32; 2],
  scale: f32,
) -> (LayerBounds, Option<LayerBlur>) {
  let radius = if group.blur.is_finite() {
    group.blur.clamp(0.0, MAX_BLUR_RADIUS)
  } else {
    0.0
  };
  let sigma = blur_sigma(radius) * scale;
  if sigma < MIN_BLUR_SIGMA {
    return (pixel_bounds(extent, viewport), None);
  }
  let reach = (sigma * 3.0).ceil();
  let mut shown = grown(extent, reach);
  let mut clips = [None; MAX_ROUNDED_CLIPS];
  if let Some(clip) = group.clip {
    let clip = clip.scaled(scale);
    clips = rounded_clip_boxes(clip);
    let (x, y, width, height) = (clip.x, clip.y, clip.width, clip.height);
    shown = intersection(shown, [x.floor(), y.floor(), (x + width).ceil(), (y + height).ceil()]);
  }
  let bounds = pixel_bounds(shown, viewport);
  if bounds.is_empty() {
    return (bounds, None);
  }
  let pad = blur_pad(sigma) as f32;
  let visible = [
    bounds.x as f32,
    bounds.y as f32,
    (bounds.x + bounds.width) as f32,
    (bounds.y + bounds.height) as f32,
  ];
  let painted = intersection(grown(extent, pad), grown(visible, pad));
  let (x0, y0, x1, y1) = (
    painted[0].floor(),
    painted[1].floor(),
    painted[2].ceil(),
    painted[3].ceil(),
  );
  if !(x1 > x0 && y1 > y0) {
    return (LayerBounds::default(), None);
  }
  (
    bounds,
    Some(LayerBlur {
      sigma,
      x: x0 as i32,
      y: y0 as i32,
      width: (x1 - x0) as u32,
      height: (y1 - y0) as u32,
      clips,
    }),
  )
}

fn pixel_bounds(extent: Extent, viewport: [f32; 2]) -> LayerBounds {
  let x0 = extent[0].floor().max(0.0);
  let y0 = extent[1].floor().max(0.0);
  let x1 = extent[2].ceil().min(viewport[0].ceil());
  let y1 = extent[3].ceil().min(viewport[1].ceil());
  if !(x1 > x0 && y1 > y0) {
    return LayerBounds::default();
  }
  LayerBounds {
    x: x0 as u32,
    y: y0 as u32,
    width: (x1 - x0) as u32,
    height: (y1 - y0) as u32,
  }
}

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

  fn layer(start_order: usize, end_order: usize, opacity: f32) -> LayerCmd {
    LayerCmd {
      start_order,
      end_order,
      opacity,
      bounds: LayerBounds {
        x: 0,
        y: 0,
        width: 4,
        height: 4,
      },
      blur: None,
    }
  }

  fn plan(orders: &[usize], layers: &[LayerCmd]) -> Vec<(Option<usize>, Vec<LayerStep>)> {
    let mut plan = LayerPlan::default();
    plan.build(orders.len(), |index| orders[index], layers, &[]);
    plan
      .targets()
      .iter()
      .map(|target| (target.layer, plan.steps(target).to_vec()))
      .collect()
  }

  #[test]
  fn a_rounded_box_covers_what_is_inside_its_corners_under_any_transform() {
    let upright = RoundedBox::rect(10.0, 20.0, 40.0, 20.0, [8.0, 0.0, 0.0, 0.0]);
    assert_eq!(upright.extent(), [10.0, 20.0, 50.0, 40.0]);
    assert_eq!(upright.coverage(30.5, 30.5), 1.0);
    // An edge through a pixel's centre covers half of it.
    assert_eq!(upright.coverage(50.0, 30.5), 0.5);
    assert_eq!(upright.coverage(51.5, 30.5), 0.0);
    // The rounded corner is cut, the square one is not.
    assert_eq!(upright.coverage(11.0, 21.0), 0.0);
    assert_eq!(upright.coverage(49.0, 21.0), 1.0);

    // A quarter turn about the centre: 20 wide, 40 tall.
    let turned =
      RoundedBox::transformed(10.0, 20.0, 40.0, 20.0, [0.0; 4], [0.0, 1.0, -1.0, 0.0], [20.0, 10.0]).unwrap();
    let extent = turned.extent();
    assert!(
      (extent[0] - 20.0).abs() < 1e-4 && (extent[2] - 40.0).abs() < 1e-4,
      "{extent:?}"
    );
    assert!(
      (extent[1] - 10.0).abs() < 1e-4 && (extent[3] - 50.0).abs() < 1e-4,
      "{extent:?}"
    );
    assert_eq!(turned.coverage(30.5, 12.5), 1.0);
    assert_eq!(turned.coverage(15.5, 30.5), 0.0);

    // Twice the size about its top-left corner: the edge is still one
    // pixel wide.
    let doubled = RoundedBox::transformed(10.0, 20.0, 40.0, 20.0, [0.0; 4], [2.0, 0.0, 0.0, 2.0], [0.0, 0.0]).unwrap();
    assert_eq!(doubled.extent(), [10.0, 20.0, 90.0, 60.0]);
    assert_eq!((doubled.coverage(89.0, 40.0), doubled.coverage(90.0, 40.0)), (1.0, 0.5));

    assert!(RoundedBox::transformed(0.0, 0.0, 4.0, 4.0, [0.0; 4], [1.0, 2.0, 2.0, 4.0], [0.0, 0.0]).is_none());
  }

  #[test]
  fn a_narrow_blur_runs_on_the_layer_and_a_wide_one_on_a_reduced_copy() {
    let blur = |sigma: f32| LayerBlur {
      sigma,
      x: -10,
      y: 0,
      width: 201,
      height: 100,
      clips: [None; MAX_ROUNDED_CLIPS],
    };
    let narrow = BlurPlan::new(&blur(4.0));
    assert_eq!(
      (narrow.reduction, narrow.sigma, narrow.size, narrow.border),
      (1, 4.0, [201, 100], 0)
    );
    assert_eq!(BlurPlan::new(&blur(MAX_PASS_SIGMA)).reduction, 1);

    for sigma in [9.0, 20.0, 100.0, 384.0] {
      let plan = BlurPlan::new(&blur(sigma));
      let r = plan.reduction as f32;
      assert!(
        plan.reduction.is_power_of_two() && plan.reduction > 1,
        "sigma {sigma}: {plan:?}"
      );
      assert!(plan.sigma <= MAX_PASS_SIGMA, "sigma {sigma}: {plan:?}");
      // The reduced layer, and a texel around it for what lies past its edge.
      assert_eq!(plan.border, 1);
      assert_eq!(
        plan.size,
        [
          201_u32.div_ceil(plan.reduction) + 2,
          100_u32.div_ceil(plan.reduction) + 2
        ]
      );
      // The box, the Gaussian and the resampling together are the blur asked for.
      let total = ((r * r - 1.0) / 12.0 + r * r / 6.0 + (plan.sigma * r).powi(2)).sqrt();
      assert!((total - sigma).abs() < sigma * 0.01, "sigma {sigma}: {total}");
    }
  }

  #[test]
  fn a_blurred_group_shows_inside_its_clip_and_is_painted_past_it() {
    let group = OpacityGroup {
      start: 0,
      end: 1,
      opacity: 1.0,
      blur: 8.0,
      clip: Some(ClipRect::rect(10.0, 0.0, 50.0, 100.0)),
    };
    // Content from x 20 to 200, in a 100 x 100 window at scale 2.
    let (bounds, blur) = blurred_bounds(&group, [20.0, 30.0, 200.0, 60.0], [100.0, 100.0], 2.0);
    let blur = blur.expect("a blur");
    assert_eq!(blur.sigma, 8.0);
    // 24 pixels of reach: left to the clip at 20, right to the window's edge, up and down by the reach.
    assert_eq!(
      bounds,
      LayerBounds {
        x: 20,
        y: 6,
        width: 80,
        height: 78
      }
    );
    // Painted for the reach past what shows, and 3 pixels more for the passes' sampling: left of the clip and
    // right of the window. Above and below, what shows already ends where the content's spread does.
    assert_eq!((blur.x, blur.y), (20 - 27, 30 - 27));
    assert_eq!(
      (blur.x + blur.width as i32, blur.y + blur.height as i32),
      (100 + 27, 60 + 27)
    );

    assert_eq!(
      blur.clips, [None; MAX_ROUNDED_CLIPS],
      "a clip without corners is in the bounds"
    );
    // A rounded clip rides along, in physical pixels.
    let rounded = OpacityGroup {
      clip: Some(ClipRect::rounded_rect(
        10.0,
        0.0,
        50.0,
        100.0,
        Some(crate::node::border::BorderRadius::new(4.0, 0.0, 0.0, 0.0)),
      )),
      ..group
    };
    let (_, blur) = blurred_bounds(&rounded, [20.0, 30.0, 200.0, 60.0], [100.0, 100.0], 2.0);
    assert_eq!(
      blur.unwrap().clips,
      [
        Some(RoundedBox::rect(20.0, 0.0, 100.0, 200.0, [8.0, 0.0, 0.0, 0.0])),
        None
      ]
    );
    // Under two rounded clips, both ride along, the innermost first: a rail along the bottom of a rounded panel
    // is cut by the panel's corners, which are not the rail's.
    let panel = ClipRect::rounded_rect(
      0.0,
      0.0,
      50.0,
      100.0,
      Some(crate::node::border::BorderRadius::all(10.0)),
    );
    let rail = ClipRect::rounded_rect(
      0.0,
      80.0,
      50.0,
      20.0,
      Some(crate::node::border::BorderRadius::new(4.0, 4.0, 0.0, 0.0)),
    );
    let nested = OpacityGroup {
      clip: Some(panel.intersect(rail)),
      ..group
    };
    let (_, blur) = blurred_bounds(&nested, [0.0, 0.0, 100.0, 200.0], [100.0, 200.0], 2.0);
    assert_eq!(
      blur.unwrap().clips,
      [
        Some(RoundedBox::rect(0.0, 160.0, 100.0, 40.0, [8.0, 8.0, 0.0, 0.0])),
        Some(RoundedBox::rect(0.0, 0.0, 100.0, 200.0, [20.0; 4])),
      ]
    );

    let unblurred = OpacityGroup { blur: 0.0, ..group };
    let (bounds, blur) = blurred_bounds(&unblurred, [20.0, 30.0, 200.0, 60.0], [100.0, 100.0], 2.0);
    assert!(blur.is_none());
    assert_eq!((bounds.x, bounds.width), (20, 80));
  }

  fn backdrop(order: usize) -> BackdropCmd {
    BackdropCmd {
      order,
      x: 0.0,
      y: 0.0,
      width: 4.0,
      height: 4.0,
      radii: [0.0; 4],
      transform: [1.0, 0.0, 0.0, 1.0],
      transform_origin: [2.0, 2.0],
      clip: ClipRect::default(),
      sigma: 4.0,
      opacity: 1.0,
    }
  }

  #[test]
  fn backdrop_blurs_split_the_draws_of_the_target_they_are_in() {
    // Orders: 0 | B1 | 2 [ B3 4 (invisible: B5 6) ] | B7, B8 | 9.
    let orders = [0, 2, 4, 6, 9];
    let layers = [layer(3, 7, 0.5), layer(5, 7, 0.0)];
    let backdrops = [1, 3, 5, 7, 8].map(backdrop);
    let mut plan = LayerPlan::default();
    plan.build(orders.len(), |index| orders[index], &layers, &backdrops);
    let targets: Vec<_> = plan
      .targets()
      .iter()
      .map(|target| (target.layer, plan.steps(target).to_vec()))
      .collect();
    assert_eq!(
      targets,
      vec![
        // The blur at 3 sees the layer's own content only: nothing yet.
        (Some(0), vec![LayerStep::Backdrop(1), LayerStep::Draws(2..3)]),
        (
          None,
          vec![
            LayerStep::Draws(0..1),
            LayerStep::Backdrop(0),
            LayerStep::Draws(1..2),
            LayerStep::Composite(0),
            LayerStep::Backdrop(3),
            LayerStep::Backdrop(4),
            LayerStep::Draws(4..5),
          ]
        ),
      ]
    );
    assert!(plan.has_backdrops());

    plan.build(orders.len(), |index| orders[index], &layers, &[]);
    assert!(!plan.has_backdrops());
  }

  #[test]
  fn without_layers_the_window_paints_every_draw_in_one_step() {
    assert_eq!(plan(&[0, 1, 2], &[]), vec![(None, vec![LayerStep::Draws(0..3)])]);
  }

  #[test]
  fn nested_layers_are_painted_before_the_targets_they_composite_into() {
    // Orders: 0 | 1 [2 (3 4) 5] | 6, with a draw per order and two at 3.
    let orders = [0, 1, 2, 3, 3, 4, 5, 6];
    let layers = [layer(1, 6, 0.5), layer(3, 5, 0.4)];
    assert_eq!(
      plan(&orders, &layers),
      vec![
        (Some(1), vec![LayerStep::Draws(3..6)]),
        (
          Some(0),
          vec![LayerStep::Draws(1..3), LayerStep::Composite(0), LayerStep::Draws(6..7)]
        ),
        (
          None,
          vec![LayerStep::Draws(0..1), LayerStep::Composite(1), LayerStep::Draws(7..8)]
        ),
      ]
    );
  }

  #[test]
  fn an_invisible_layer_drops_its_draws_and_inner_layers() {
    let orders = [0, 1, 2, 3];
    let layers = [layer(1, 3, 0.0), layer(2, 3, 0.5)];
    assert_eq!(
      plan(&orders, &layers),
      vec![(None, vec![LayerStep::Draws(0..1), LayerStep::Draws(3..4)])]
    );
  }

  #[test]
  fn a_layer_without_draws_is_skipped() {
    // Its quads were culled: no draw has an order in 2..4.
    let orders = [0, 1, 5];
    let layers = [layer(2, 4, 0.5)];
    assert_eq!(
      plan(&orders, &layers),
      vec![(None, vec![LayerStep::Draws(0..2), LayerStep::Draws(2..3)])]
    );
  }

  #[test]
  fn bounds_cover_transformed_content_in_whole_pixels_within_clip_and_viewport() {
    let identity = [1.0, 0.0, 0.0, 1.0];
    let extent = transformed_extent(10.25, 20.5, 30.0, 10.0, identity, [15.0, 5.0], 0.0);
    assert_eq!(extent, [10.25, 20.5, 40.25, 30.5]);
    assert_eq!(
      pixel_bounds(extent, [100.0, 100.0]),
      LayerBounds {
        x: 10,
        y: 20,
        width: 31,
        height: 11
      }
    );
    // A quarter turn around the box's centre swaps its extent.
    let turned = transformed_extent(0.0, 0.0, 40.0, 10.0, [0.0, 1.0, -1.0, 0.0], [20.0, 5.0], 0.0);
    assert!((turned[0] - 15.0).abs() < 1e-4 && (turned[2] - 25.0).abs() < 1e-4);
    assert!((turned[1] + 15.0).abs() < 1e-4 && (turned[3] - 25.0).abs() < 1e-4);
    let clip = ClipRect::rect(12.0, 0.0, 8.0, 200.0);
    assert_eq!(clipped(extent, clip), [12.0, 20.5, 20.0, 30.5]);
    assert_eq!(pixel_bounds([90.0, 90.0, 120.0, 95.0], [100.0, 100.0]).width, 10);
    assert!(pixel_bounds([120.0, 0.0, 130.0, 10.0], [100.0, 100.0]).is_empty());
  }
}