ribir_gpu 0.4.0-alpha.65

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

use ahash::HashMap;
use guillotiere::euclid::Vector2D;
use ribir_algo::Resource;
use ribir_painter::{
  Color, ColorFormat, ColorMatrix, CommandBrush, FaceId, FilterComposite, FilterLayer, FilterOp,
  GlyphId, GlyphRasterSource, LineCap, LineJoin, PaintCommand, PaintPath, PaintPathAction,
  PainterBackend, PaintingStyle, Path, PathCommand, PathKind, PixelImage, RasterBitmapFormat,
  StrokeOptions, Svg, TextCommand, Vertex, VertexBuffers, color::ColorFilterMatrix,
};
use ribir_types::{
  DevicePoint, DeviceRect, DeviceSize, Point, Transform, Vector, rect_corners,
  transform_to_device_rect,
};

use crate::{
  ColorAttr, FilterPrimitive, GPUBackendImpl, GradientStopPrimitive, ImagePrimIndex, ImgPrimitive,
  LinearGradientPrimIndex, LinearGradientPrimitive, MaskKind, MaskLayer, RadialGradientPrimIndex,
  RadialGradientPrimitive, TexturePrimIndex, TexturePrimitive,
};

mod atlas;

mod textures_mgr;
use textures_mgr::*;

type RasterImageGlyphs = HashMap<(FaceId, u16, u16), Option<(Resource<PixelImage>, Point)>>;

struct GlyphDrawCtx<'a, T> {
  glyph_provider: &'a dyn GlyphRasterSource,
  brush: &'a CommandBrush,
  text_matrix: &'a Transform,
  output_tex_size: DeviceSize,
  output: &'a mut T,
}

pub struct GPUBackend<Impl: GPUBackendImpl> {
  gpu_impl: Impl,
  tex_mgr: TexturesMgr<Impl::Texture>,
  color_vertices_buffer: VertexBuffers<ColorAttr>,
  img_vertices_buffer: VertexBuffers<ImagePrimIndex>,
  filter_vertices_buffer: VertexBuffers<()>,
  img_prims: Vec<ImgPrimitive>,
  radial_gradient_vertices_buffer: VertexBuffers<RadialGradientPrimIndex>,
  radial_gradient_stops: Vec<GradientStopPrimitive>,
  radial_gradient_prims: Vec<RadialGradientPrimitive>,
  linear_gradient_prims: Vec<LinearGradientPrimitive>,
  linear_gradient_stops: Vec<GradientStopPrimitive>,
  linear_gradient_vertices_buffer: VertexBuffers<LinearGradientPrimIndex>,
  texture_vertices_buffer: VertexBuffers<TexturePrimIndex>,
  current_phase: CurrentPhase,
  tex_ids_map: TextureIdxMap,
  viewport: DeviceRect,
  mask_layers: Vec<MaskLayer>,
  clip_layer_stack: Vec<ClipLayer>,
  skip_clip_cnt: usize,
  surface_color: Option<Color>,
  frame_no: u64,
  raster_image_glyphs: RasterImageGlyphs,
  svg_glyphs: HashMap<(FaceId, u16), Option<Svg>>,
}

#[derive(Clone, Debug)]
enum CurrentPhase {
  None,
  Color,
  Img,
  RadialGradient,
  LinearGradient,
  Filter(Box<FilterPhase>),
}

#[derive(Clone, Debug)]
struct FilterPhase {
  view_rect: DeviceRect,
  mask_head: i32,
  filters: Vec<FilterLayer>,
}

struct ClipLayer {
  viewport: DeviceRect,
  mask_head: i32,
}

/// Texture use to display.
pub trait Texture {
  type Host;
  /// clear a list of areas in the texture with zero.
  fn clear_areas(&mut self, areas: &[DeviceRect], backend: &mut Self::Host);

  /// write data to the texture.
  fn write_data(&mut self, dist: &DeviceRect, data: &[u8], host: &mut Self::Host);

  /// Return a image future of the texture area.
  /// - you should poll the image future after the `end_frame` is called to
  ///   ensure all content had been submitted, because the PainterBackend does
  ///   not be required to draw synchronization
  fn copy_as_image(
    &self, rect: &DeviceRect, host: &mut Self::Host,
  ) -> impl std::future::Future<Output = Result<PixelImage, Box<dyn Error>>> + 'static;

  fn color_format(&self) -> ColorFormat;

  fn size(&self) -> DeviceSize;
}

#[derive(Default)]
struct TextureIdxMap {
  texture_map: ahash::HashMap<TextureID, u32>,
  textures: Vec<TextureID>,
}

impl<Impl> PainterBackend for GPUBackend<Impl>
where
  Impl: GPUBackendImpl,
  Impl::Texture: Texture<Host = Impl>,
{
  type Texture = Impl::Texture;

  fn begin_frame(&mut self, surface: Color) {
    self.surface_color = Some(surface);
    self.gpu_impl.begin_frame();
  }

  fn draw_commands(
    &mut self, viewport: DeviceRect, commands: &[PaintCommand], global_matrix: &Transform,
    output: &mut Self::Texture, glyph_provider: &dyn GlyphRasterSource,
  ) {
    let clips = self.clip_layer_stack.len();
    self.viewport = viewport;
    self.begin_draw_phase();
    let output_size = output.size();
    for cmd in commands {
      self.draw_command(cmd, global_matrix, output_size, output, glyph_provider);
    }
    self.draw_triangles(output);
    self.end_draw_phase();

    assert_eq!(self.clip_layer_stack.len(), clips);
  }

  fn end_frame(&mut self) {
    self.frame_no += 1;
    self.mask_layers.clear();
    if self.tex_mgr.end_frame(&mut self.gpu_impl) {
      self.gpu_impl.flush_draw_commands();
    }
    self.gpu_impl.end_frame();
  }
}

impl<Impl: GPUBackendImpl> GPUBackend<Impl>
where
  Impl::Texture: Texture<Host = Impl>,
{
  fn support_sdf_stroke(style: &StrokeOptions) -> bool {
    style.width > 0.0
      && style.width.is_finite()
      && style.miter_limit.is_finite()
      && matches!(style.line_cap, LineCap::Butt)
      && matches!(style.line_join, LineJoin::Miter | LineJoin::Bevel)
  }

  fn normalize_round_rect_radii(
    rect: &ribir_types::Rect, radius: &ribir_painter::Radius,
  ) -> [f32; 4] {
    let mut tl = radius.top_left;
    let mut tr = radius.top_right;
    let mut br = radius.bottom_right;
    let mut bl = radius.bottom_left;

    let w = rect.width().max(0.0);
    let h = rect.height().max(0.0);
    if w <= 0.0 || h <= 0.0 {
      return [0.0; 4];
    }

    let tl_pos = tl.max(0.0);
    let tr_pos = tr.max(0.0);
    let br_pos = br.max(0.0);
    let bl_pos = bl.max(0.0);

    let sx_top = if tl_pos + tr_pos > 0.0 { w / (tl_pos + tr_pos) } else { 1.0 };
    let sx_bottom = if bl_pos + br_pos > 0.0 { w / (bl_pos + br_pos) } else { 1.0 };
    let sy_left = if tl_pos + bl_pos > 0.0 { h / (tl_pos + bl_pos) } else { 1.0 };
    let sy_right = if tr_pos + br_pos > 0.0 { h / (tr_pos + br_pos) } else { 1.0 };
    let s = sx_top
      .min(sx_bottom)
      .min(sy_left)
      .min(sy_right)
      .min(1.0);

    if s < 1.0 {
      if tl > 0.0 {
        tl *= s;
      }
      if tr > 0.0 {
        tr *= s;
      }
      if br > 0.0 {
        br *= s;
      }
      if bl > 0.0 {
        bl *= s;
      }
    }

    [tl, tr, br, bl]
  }

  pub fn new(mut gpu_impl: Impl) -> Self {
    let tex_mgr = TexturesMgr::new(&mut gpu_impl);
    Self {
      gpu_impl,
      tex_mgr,
      tex_ids_map: <_>::default(),
      mask_layers: vec![],
      clip_layer_stack: vec![],
      skip_clip_cnt: 0,
      color_vertices_buffer: VertexBuffers::with_capacity(256, 512),
      img_vertices_buffer: VertexBuffers::with_capacity(256, 512),
      texture_vertices_buffer: VertexBuffers::with_capacity(256, 512),
      filter_vertices_buffer: VertexBuffers::with_capacity(16, 32),
      radial_gradient_vertices_buffer: VertexBuffers::with_capacity(256, 512),
      radial_gradient_prims: vec![],
      radial_gradient_stops: vec![],
      linear_gradient_vertices_buffer: VertexBuffers::with_capacity(256, 512),
      linear_gradient_stops: vec![],
      linear_gradient_prims: vec![],
      img_prims: vec![],
      current_phase: CurrentPhase::None,
      viewport: DeviceRect::zero(),
      surface_color: Some(Color::WHITE),
      frame_no: 0,
      raster_image_glyphs: <_>::default(),
      svg_glyphs: <_>::default(),
    }
  }

  #[inline]
  pub fn get_impl(&self) -> &Impl { &self.gpu_impl }

  #[inline]
  pub fn get_impl_mut(&mut self) -> &mut Impl { &mut self.gpu_impl }

  #[inline]
  pub fn into_impl(self) -> Impl { self.gpu_impl }

  pub fn composite_texture_to_output(
    &mut self, source: &Impl::Texture, output: &mut Impl::Texture,
  ) {
    debug_assert!(self.clip_layer_stack.is_empty());

    self.begin_draw_phase();
    self.texture_vertices_buffer.clear();
    add_full_texture_vertices(TexturePrimIndex(0), &mut self.texture_vertices_buffer);

    let prim = TexturePrimitive {
      transform: Transform::identity().to_array(),
      mask_head: -1,
      opacity: 1.0,
      is_premultiplied: 1,
      _padding: [0; 3],
    };
    let prims_offset = self
      .gpu_impl
      .load_texture_data(&[prim], &self.texture_vertices_buffer);
    let indices = 0..self.texture_vertices_buffer.indices.len() as u32;
    self.gpu_impl.draw_texture_triangles(
      output,
      indices,
      Some(Color::TRANSPARENT),
      source,
      0,
      prims_offset,
    );
    self.end_draw_phase();
  }

  fn draw_command(
    &mut self, cmd: &PaintCommand, global_matrix: &Transform, output_tex_size: DeviceSize,
    output: &mut Impl::Texture, glyph_provider: &dyn GlyphRasterSource,
  ) {
    match cmd {
      PaintCommand::Path(cmd @ PathCommand { path, paint_bounds, transform, action }) => {
        if self.skip_clip_cnt > 0 {
          if matches!(action, PaintPathAction::Clip) {
            self.skip_clip_cnt += 1;
          }
          // Skip the commands if the clip layer is not visible.
          return;
        }
        let bounds = transform_to_device_rect(paint_bounds, global_matrix);

        let Some(viewport) = self.viewport().intersection(&bounds) else {
          if matches!(action, PaintPathAction::Clip) {
            self.skip_clip_cnt += 1;
          }
          // Skip the command if it is not visible.
          return;
        };

        if !self.can_batch_path_command(cmd) {
          self.new_draw_phase(output);
        }

        let matrix = transform.then(global_matrix);
        let (rect, mask_head) = match action {
          PaintPathAction::Clip => {
            self.new_mask_layer(&viewport, &matrix, path, &PaintingStyle::Fill)
          }
          PaintPathAction::Paint { painting_style, .. } => {
            self.new_mask_layer(&viewport, &matrix, path, painting_style)
          }
        };
        match action {
          PaintPathAction::Clip => self
            .clip_layer_stack
            .push(ClipLayer { viewport, mask_head }),
          PaintPathAction::Paint { brush, .. } => match brush {
            CommandBrush::Color(color) => {
              let color = color.into_components();
              let color_attr = ColorAttr { color, mask_head };
              let buffer = &mut self.color_vertices_buffer;
              add_rect_vertices(rect, output_tex_size, color_attr, buffer);
              self.current_phase = CurrentPhase::Color;
            }
            CommandBrush::Image { img, color_filter } => {
              let slice = self.tex_mgr.store_image(img, &mut self.gpu_impl);
              let ts = matrix.inverse().unwrap();
              self.draw_img_slice(
                slice,
                &ts,
                mask_head,
                color_filter,
                output_tex_size,
                rect,
                false,
              );
            }
            CommandBrush::Radial(radial) => {
              let prim: RadialGradientPrimitive = RadialGradientPrimitive {
                transform: matrix.inverse().unwrap().to_array(),
                stop_start: self.radial_gradient_stops.len() as u32,
                stop_cnt: radial.stops.len() as u32,
                start_center: radial.start_center.to_array(),
                start_radius: radial.start_radius,
                end_center: radial.end_center.to_array(),
                end_radius: radial.end_radius,
                mask_head,
                spread: radial.spread_method as u32,
              };
              let stops = radial
                .stops
                .iter()
                .map(GradientStopPrimitive::new);
              self.radial_gradient_stops.extend(stops);
              let prim_idx = self.radial_gradient_prims.len() as u32;
              self.radial_gradient_prims.push(prim);
              let buffer = &mut self.radial_gradient_vertices_buffer;

              add_rect_vertices(rect, output_tex_size, RadialGradientPrimIndex(prim_idx), buffer);
              self.current_phase = CurrentPhase::RadialGradient;
            }
            CommandBrush::Linear(linear) => {
              let stop = (self.linear_gradient_stops.len() << 16 | linear.stops.len()) as u32;
              let mask_head_and_spread = mask_head << 16 | linear.spread_method as i32;
              let prim: LinearGradientPrimitive = LinearGradientPrimitive {
                transform: matrix.inverse().unwrap().to_array(),
                stop,
                start_position: linear.start.to_array(),
                end_position: linear.end.to_array(),
                mask_head_and_spread,
              };
              let stops = linear
                .stops
                .iter()
                .map(GradientStopPrimitive::new);
              self.linear_gradient_stops.extend(stops);
              let prim_idx = self.linear_gradient_prims.len() as u32;
              self.linear_gradient_prims.push(prim);
              let buffer = &mut self.linear_gradient_vertices_buffer;
              add_rect_vertices(rect, output_tex_size, LinearGradientPrimIndex(prim_idx), buffer);
              self.current_phase = CurrentPhase::LinearGradient;
            }
          },
        }
      }
      PaintCommand::PopClip => {
        if self.skip_clip_cnt > 0 {
          self.skip_clip_cnt -= 1;
        } else {
          self.clip_layer_stack.pop();
        }
      }
      PaintCommand::Bundle { transform, color_filter, bounds, cmds } => {
        let matrix = transform.then(global_matrix);
        let scale = self.tex_mgr.cache_scale(&bounds.size, &matrix);
        let cache_size = bounds.size * scale;

        let this = self as *mut Self;
        let (cache_scale, slice) = self.tex_mgr.store_commands(
          cache_size.to_i32().cast_unit(),
          cmds.clone().into_any(),
          scale,
          &mut self.gpu_impl,
          |slice, tex, _| {
            // SAFETY: We already hold a mut reference to the texture in the texture
            // manager, so we cant use `self` here, but this texture should always exist
            // within the frame, and no modifications will be made to the slice
            // that has already been allocated.
            let this = unsafe { &mut *this };

            // Initiate a new drawing phase to ensure a clean state for rendering in a new
            // texture.
            this.new_draw_phase(output);

            // store the viewport
            let viewport = self.viewport;
            // Overwrite the viewport to the slice bounds.
            self
              .clip_layer_stack
              .push(ClipLayer { viewport: *slice, mask_head: -1 });

            let matrix = Transform::translation(-bounds.origin.x, -bounds.origin.y)
              .then_scale(scale, scale)
              .then_translate(slice.origin.to_f32().cast_unit().to_vector());

            let surface_color = this.surface_color.take();
            this.surface_color = Some(Color::TRANSPARENT);
            this.draw_commands(*slice, cmds, &matrix, tex, glyph_provider);
            this.surface_color = surface_color;

            // restore the clip layer and viewport
            self.clip_layer_stack.pop();
            this.viewport = viewport;
          },
        );

        let mut points: [_; 4] = rect_corners(&bounds.to_f32().cast_unit());
        for p in points.iter_mut() {
          *p = matrix.transform_point(*p);
        }

        let view_to_slice = matrix
          // point back to the bundle commands axis.
          .inverse()
          .unwrap()
          // align to the zero point, draw image slice is start from zero.
          .then_translate(Vector2D::new(-bounds.origin.x, -bounds.origin.y))
          // scale to the cache size.
          .then_scale(cache_scale, cache_scale);

        if !self.can_batch_img_path() {
          self.new_draw_phase(output);
        }
        let mask_head = self
          .clip_layer_stack
          .last()
          .map_or(-1, |l| l.mask_head);
        self.draw_img_slice(
          slice,
          &view_to_slice,
          mask_head,
          color_filter,
          output_tex_size,
          points,
          true,
        );
      }
      PaintCommand::Filter { path, filter_bounds, transform, filters } => {
        let bounds = transform_to_device_rect(filter_bounds, global_matrix);
        let Some(view_rect) = self.viewport().intersection(&bounds) else {
          return;
        };

        self.new_draw_phase(output);

        let ts = transform.then(global_matrix);
        let (_, mask_head) = self.new_mask_layer(&view_rect, &ts, path, &PaintingStyle::Fill);

        self.current_phase = CurrentPhase::Filter(Box::new(FilterPhase {
          view_rect,
          mask_head,
          filters: filters
            .iter()
            .map(|f| FilterLayer {
              ops: f.ops.clone(),
              offset: global_matrix
                .transform_vector(f.offset.into())
                .into(),
              composite: f.composite,
            })
            .collect(),
        }));
      }
      PaintCommand::Text(text_cmd) => {
        self.draw_text_command(text_cmd, global_matrix, output_tex_size, output, glyph_provider);
      }
    }
  }

  fn draw_text_command(
    &mut self, text_cmd: &TextCommand, global_matrix: &Transform, output_tex_size: DeviceSize,
    output: &mut Impl::Texture, glyph_provider: &dyn GlyphRasterSource,
  ) {
    if self.skip_clip_cnt > 0 {
      return;
    }

    let text_matrix = text_cmd.transform.then(global_matrix);
    for run in text_cmd.payload.runs.iter() {
      let brush = run
        .brush
        .clone()
        .map(|brush| {
          let mut brush = CommandBrush::from(brush);
          brush.apply_color_filter(&text_cmd.color_filter);
          brush
        })
        .unwrap_or_else(|| text_cmd.default_brush.clone());
      self.draw_payload_run(
        glyph_provider,
        run,
        text_cmd.payload.origin_offset,
        &brush,
        &text_matrix,
        output_tex_size,
        output,
      );
    }

    for decoration in text_cmd.payload.decorations.iter() {
      let brush = decoration
        .brush
        .clone()
        .map(|brush| {
          let mut brush = CommandBrush::from(brush);
          brush.apply_color_filter(&text_cmd.color_filter);
          brush
        })
        .unwrap_or_else(|| text_cmd.default_brush.clone());
      let cmd = PaintCommand::Path(PathCommand {
        path: PaintPath::Share(Resource::new(Path::rect(&decoration.rect))),
        paint_bounds: text_matrix.outer_transformed_rect(&decoration.rect),
        transform: text_matrix,
        action: PaintPathAction::Paint { brush, painting_style: PaintingStyle::Fill },
      });
      self.draw_command(&cmd, &Transform::identity(), output_tex_size, output, glyph_provider);
    }
  }

  #[allow(clippy::too_many_arguments)]
  fn draw_payload_run(
    &mut self, glyph_provider: &dyn GlyphRasterSource, run: &ribir_painter::DrawGlyphRun,
    origin_offset: Vector, brush: &CommandBrush, text_matrix: &Transform,
    output_tex_size: DeviceSize, output: &mut Impl::Texture,
  ) {
    let mut ctx = GlyphDrawCtx { glyph_provider, brush, text_matrix, output_tex_size, output };
    for glyph in run.glyphs.iter() {
      self.draw_rasterized_glyph(
        &mut ctx,
        run.face_id,
        glyph.glyph_id,
        run.logical_font_size,
        Point::new(
          glyph.baseline_origin.x + origin_offset.x,
          glyph.baseline_origin.y + origin_offset.y,
        ),
      );
    }
  }

  fn draw_rasterized_glyph(
    &mut self, ctx: &mut GlyphDrawCtx<'_, Impl::Texture>, face_id: FaceId, glyph_id: GlyphId,
    font_size: f32, baseline_origin: Point,
  ) {
    let scale = ctx
      .text_matrix
      .m11
      .abs()
      .max(ctx.text_matrix.m22.abs());
    let physical_size = (font_size * scale).ceil().max(1.) as u16;

    if let Some(svg) = self.glyph_svg_image(ctx.glyph_provider, face_id, glyph_id) {
      let Some(metrics) = ctx.glyph_provider.face_metrics(face_id) else {
        return;
      };
      let unit = metrics.units_per_em as f32;
      let grid_scale = metrics
        .vertical_height
        .map(|h| h / unit)
        .unwrap_or(1.)
        .max(1.);
      let svg_size = svg.size();
      let s = font_size.min(font_size) / svg_size.height.max(1.) / grid_scale;
      let svg_matrix =
        Transform::new(s, 0., 0., s, baseline_origin.x, baseline_origin.y - font_size)
          .then(ctx.text_matrix);

      let brush = ribir_painter::Brush::from(ribir_painter::Color::BLACK);
      let commands = svg.commands(&brush, &brush);
      for cmd in commands.iter() {
        let cmd = match cmd.clone() {
          PaintCommand::Path(mut path) => {
            path.transform(&svg_matrix);
            PaintCommand::Path(path)
          }
          other => other,
        };
        self.draw_command(
          &cmd,
          &Transform::identity(),
          ctx.output_tex_size,
          ctx.output,
          ctx.glyph_provider,
        );
      }
      return;
    }

    if let Some((image, offset)) =
      self.glyph_raster_image(ctx.glyph_provider, face_id, glyph_id, physical_size)
    {
      let img_h = image.height() as f32;
      let img_w = image.width() as f32;
      let is_color = matches!(image.color_format(), ColorFormat::Rgba8);

      if is_color {
        let img_size_px = physical_size as f32;
        let s = font_size / img_size_px;
        let dst_h = img_h * s;
        let draw_x = baseline_origin.x + offset.x * s;
        let draw_y = baseline_origin.y + offset.y * s;
        let dst_size = ribir_types::Size::new(img_w * s, dst_h);
        let dst_rect = ribir_types::Rect::new(Point::new(draw_x, draw_y), dst_size);
        let img_matrix = Transform::new(
          dst_rect.width() / img_w,
          0.,
          0.,
          dst_rect.height() / img_h,
          dst_rect.min_x(),
          dst_rect.min_y(),
        )
        .then(ctx.text_matrix);
        self.draw_color_bitmap_glyph(&image, &img_matrix, ctx.output_tex_size, ctx.output);
      } else {
        let img_size_px = physical_size as f32;
        let s = font_size / img_size_px;
        let draw_x = baseline_origin.x + offset.x * s;
        let draw_y = baseline_origin.y + offset.y * s;
        let glyph_matrix = Transform::new(s, 0., 0., s, draw_x, draw_y).then(ctx.text_matrix);
        let path = PaintPath::PixelImage(image);
        let p_bounds = path.bounds(None);
        let device_bounds = transform_to_device_rect(&p_bounds, &glyph_matrix);

        if self
          .viewport()
          .intersection(&device_bounds)
          .is_some()
        {
          let path_cmd = PathCommand {
            path,
            paint_bounds: glyph_matrix.outer_transformed_rect(&p_bounds),
            transform: glyph_matrix,
            action: PaintPathAction::Paint {
              brush: ctx.brush.clone(),
              painting_style: PaintingStyle::Fill,
            },
          };
          let cmd = PaintCommand::Path(path_cmd);
          self.draw_command(
            &cmd,
            &Transform::identity(),
            ctx.output_tex_size,
            ctx.output,
            ctx.glyph_provider,
          );
        }
      }
    }
  }

  fn glyph_raster_image(
    &mut self, glyph_provider: &dyn GlyphRasterSource, face_id: ribir_painter::FaceId,
    glyph_id: GlyphId, img_size: u16,
  ) -> Option<(ribir_algo::Resource<PixelImage>, Point)> {
    let key = (face_id, glyph_id.0, img_size);
    self
      .raster_image_glyphs
      .entry(key)
      .or_insert_with(|| {
        glyph_provider
          .raster_bitmap(face_id, glyph_id, img_size)
          .map(|bitmap| {
            let format = match bitmap.format {
              RasterBitmapFormat::Rgba8 => ColorFormat::Rgba8,
              RasterBitmapFormat::Alpha8 => ColorFormat::Alpha8,
            };
            let image =
              PixelImage::new(Cow::Owned(bitmap.data), bitmap.width, bitmap.height, format);
            (Resource::new(image), bitmap.placement)
          })
      })
      .clone()
  }

  fn glyph_svg_image(
    &mut self, glyph_provider: &dyn GlyphRasterSource, face_id: ribir_painter::FaceId,
    glyph_id: GlyphId,
  ) -> Option<ribir_painter::Svg> {
    let key = (face_id, glyph_id.0);
    self
      .svg_glyphs
      .entry(key)
      .or_insert_with(|| {
        glyph_provider
          .raster_svg(face_id, glyph_id)
          .and_then(|svg| Svg::parse_from_bytes(svg.as_bytes(), true, false).ok())
      })
      .clone()
  }

  fn can_batch_img_path(&self) -> bool {
    let limits = self.gpu_impl.limits();
    matches!(self.current_phase, CurrentPhase::None)
      || (matches!(self.current_phase, CurrentPhase::Img)
        && self.tex_ids_map.len() < limits.max_tex_load - 1
        && self.img_prims.len() < limits.max_image_primitives)
  }

  // end current draw phase and start a new draw phase.
  fn new_draw_phase(&mut self, output: &mut Impl::Texture) {
    self.draw_triangles(output);
    self.end_draw_phase();
    self.begin_draw_phase();
  }

  fn begin_draw_phase(&mut self) {
    if !self.clip_layer_stack.is_empty() {
      // clear unused mask nodes and update mask index.
      let mut retain_masks = Vec::with_capacity(self.clip_layer_stack.len());
      let mut mask_new_idx = vec![-1; self.mask_layers.len()];
      for s in self.clip_layer_stack.iter_mut() {
        if s.mask_head != -1 {
          let old_idx = s.mask_head as usize;
          if mask_new_idx[old_idx] == -1 {
            retain_masks.push(self.mask_layers[old_idx].clone());
            mask_new_idx[old_idx] = retain_masks.len() as i32 - 1;
          }
          s.mask_head = mask_new_idx[old_idx];
        }
      }

      self.mask_layers = retain_masks;

      // update the texture index of atlas masks in new draw phase.
      let tex_map = self.tex_ids_map.textures.clone();
      self.tex_ids_map.reset();
      for mask in self.mask_layers.iter_mut() {
        if mask.prev_mask_idx != -1 {
          mask.prev_mask_idx = mask_new_idx[mask.prev_mask_idx as usize];
        }
        if mask.kind == MaskKind::Atlas as u32 {
          let tex_id = tex_map[mask.mask_tex_idx as usize];
          mask.mask_tex_idx = self.tex_ids_map.tex_idx(tex_id);
        }
      }
    } else {
      self.tex_ids_map.reset();
      self.mask_layers.clear();
    }
  }

  fn end_draw_phase(&mut self) {
    self.current_phase = CurrentPhase::None;
    self.color_vertices_buffer.vertices.clear();
    self.color_vertices_buffer.indices.clear();
    self.img_vertices_buffer.vertices.clear();
    self.img_vertices_buffer.indices.clear();
    self.img_prims.clear();
    self
      .radial_gradient_vertices_buffer
      .indices
      .clear();
    self
      .radial_gradient_vertices_buffer
      .vertices
      .clear();
    self.radial_gradient_prims.clear();
    self.radial_gradient_stops.clear();
    self.linear_gradient_prims.clear();
    self
      .linear_gradient_vertices_buffer
      .vertices
      .clear();
    self
      .linear_gradient_vertices_buffer
      .indices
      .clear();
    self.linear_gradient_stops.clear();
    self.filter_vertices_buffer.vertices.clear();
    self.filter_vertices_buffer.indices.clear();
  }

  /// Blit a pre-rasterized color bitmap (e.g. emoji) directly to the output.
  ///
  /// `img_matrix` maps from image pixel space (origin = top-left of image,
  /// size = pixel dimensions) to the output's logical coordinate space.
  /// Phase management and batching are handled internally.
  fn draw_color_bitmap_glyph(
    &mut self, image: &ribir_algo::Resource<PixelImage>, img_matrix: &Transform,
    output_tex_size: DeviceSize, output: &mut Impl::Texture,
  ) {
    let img_w = image.width() as f32;
    let img_h = image.height() as f32;
    let slice = self
      .tex_mgr
      .store_image(image, &mut self.gpu_impl);
    let ts = img_matrix.inverse().unwrap();

    if !self.can_batch_img_path() {
      self.new_draw_phase(output);
    }

    let mask_head = self.current_clip_mask_index();
    let device_rect = transform_to_device_rect(
      &ribir_types::Rect::from_size(ribir_types::Size::new(img_w, img_h)),
      img_matrix,
    );
    let points = rect_corners(&device_rect.to_f32().cast_unit());
    self.draw_img_slice(
      slice,
      &ts,
      mask_head,
      &ColorMatrix::default(),
      output_tex_size,
      points,
      false,
    );
  }

  #[allow(clippy::too_many_arguments)]
  fn draw_img_slice(
    &mut self, img_slice: TextureSlice, transform: &Transform, mask_head: i32,
    color_filter: &ColorMatrix, output_tex_size: DeviceSize, rect: [Point; 4], premultiplied: bool,
  ) {
    let img_start = img_slice.rect.origin.to_f32().to_array();
    let img_size = img_slice.rect.size.to_f32().to_array();
    let mask_head_and_tex_idx = mask_head << 16 | self.tex_ids_map.tex_idx(img_slice.tex_id) as i32;
    let prim_idx = self.img_prims.len() as u32;
    let ColorFilterMatrix { matrix, base_color } = color_filter.to_matrix();
    let base = base_color.map_or([0.; 4], |c| c.into_f32_components());

    let prim = ImgPrimitive {
      transform: transform.to_array(),
      img_start,
      img_size,
      mask_head_and_tex_idx,
      color_matrix: matrix,
      base_color: base,
      is_premultiplied: if premultiplied { 1 } else { 0 },
    };
    self.img_prims.push(prim);
    let buffer = &mut self.img_vertices_buffer;
    add_rect_vertices(rect, output_tex_size, ImagePrimIndex(prim_idx), buffer);
    self.current_phase = CurrentPhase::Img;
  }

  fn can_batch_path_command(&self, cmd: &PathCommand) -> bool {
    let limits = self.gpu_impl.limits();
    let tex_used = self.tex_ids_map.len();

    if matches!(self.current_phase, CurrentPhase::Filter(_)) {
      return false;
    }

    if self.mask_layers.len() >= limits.max_mask_layers {
      return false;
    }

    let PaintPathAction::Paint { brush, .. } = &cmd.action else {
      return tex_used < limits.max_tex_load;
    };

    match (&self.current_phase, brush) {
      (CurrentPhase::None, _) => true,
      (CurrentPhase::Filter(_), _) => false,
      (CurrentPhase::Color, CommandBrush::Color(_)) => tex_used < limits.max_tex_load,
      (CurrentPhase::Img, CommandBrush::Image { .. }) => {
        tex_used < limits.max_tex_load - 1 && self.img_prims.len() < limits.max_image_primitives
      }
      (CurrentPhase::RadialGradient, CommandBrush::Radial(_)) => {
        tex_used < limits.max_tex_load
          && self.radial_gradient_prims.len() < limits.max_radial_gradient_primitives
          && self.radial_gradient_stops.len() < limits.max_gradient_stop_primitives
      }
      (CurrentPhase::LinearGradient, CommandBrush::Linear(_)) => {
        tex_used < limits.max_tex_load
          && self.linear_gradient_prims.len() < limits.max_linear_gradient_primitives
          && self.linear_gradient_stops.len() < limits.max_gradient_stop_primitives
      }
      _ => false,
    }
  }

  fn current_clip_mask_index(&self) -> i32 {
    self
      .clip_layer_stack
      .last()
      .map_or(-1, |l| l.mask_head)
  }

  fn viewport(&self) -> &DeviceRect {
    self
      .clip_layer_stack
      .last()
      .map_or(&self.viewport, |l| &l.viewport)
  }

  fn new_mask_layer(
    &mut self, view: &DeviceRect, matrix: &Transform, path: &PaintPath, style: &PaintingStyle,
  ) -> ([Point; 4], i32) {
    let (paint_style, stroke_half_width) = match style {
      PaintingStyle::Fill => (0, 0.0),
      PaintingStyle::Stroke(opt) if Self::support_sdf_stroke(opt) => (1, opt.width * 0.5),
      _ => (0, -1.0),
    };

    if stroke_half_width >= 0.0 {
      let (kind, rect, p0) = match path.path_kind() {
        PathKind::Rect { rect } => (1, rect, [0.; 4]),
        PathKind::Circle { center, radius } => (
          3,
          ribir_types::Rect::new(
            Point::new(center.x - radius, center.y - radius),
            ribir_types::Size::new(radius * 2., radius * 2.),
          ),
          [center.x, center.y, radius, 0.],
        ),
        PathKind::RoundRect { rect, radius } => {
          (2, rect, Self::normalize_round_rect_radii(&rect, &radius))
        }
        PathKind::Complex => (0, ribir_types::Rect::zero(), [0.; 4]),
      };

      if kind > 0
        && let Some(inv) = matrix.inverse()
      {
        let prev_mask_idx = self.current_clip_mask_index();
        let node_idx = self.mask_layers.len() as i32;
        self.mask_layers.push(MaskLayer {
          transform: inv.to_array(),
          min: rect.origin.to_array(),
          max: Point::new(rect.max_x(), rect.max_y()).to_array(),
          mask_tex_idx: kind,
          prev_mask_idx,
          kind: MaskKind::Sdf as u32,
          paint_style,
          stroke_half_width,
          aa_epsilon: 1e-4,
          p0,
        });

        let points = rect_corners(&view.to_f32().cast_unit());
        return (points, node_idx);
      }
    }

    let (mask, mask_to_view) =
      self
        .tex_mgr
        .store_alpha_path(path, style, matrix, view, &mut self.gpu_impl);

    let mut points = rect_corners(&mask.rect.to_f32().cast_unit());
    for p in points.iter_mut() {
      *p = mask_to_view.transform_point(*p);
    }

    let prev_mask_idx = self.current_clip_mask_index();
    let min_max = mask.rect.to_box2d().to_f32();
    let node_idx = self.mask_layers.len() as i32;
    self.mask_layers.push(MaskLayer {
      // view to mask transform.
      transform: mask_to_view.inverse().unwrap().to_array(),
      min: min_max.min.to_array(),
      max: min_max.max.to_array(),
      mask_tex_idx: self.tex_ids_map.tex_idx(mask.tex_id),
      prev_mask_idx,
      kind: MaskKind::Atlas as u32,
      paint_style: 0,
      stroke_half_width: 0.,
      aa_epsilon: 0.,
      p0: [0.; 4],
    });
    (points, node_idx)
  }

  fn draw_triangles(&mut self, output: &mut Impl::Texture) {
    let mut color = self.surface_color.take();
    let gpu_impl = &mut self.gpu_impl;
    self.tex_mgr.draw_alpha_textures(gpu_impl);
    let mask_offset =
      if !self.mask_layers.is_empty() { gpu_impl.load_mask_layers(&self.mask_layers) } else { 0 };

    let textures = self.tex_ids_map.all_textures();
    let max_textures = gpu_impl.limits().max_tex_load;
    let mut tex_buffer = Vec::with_capacity(max_textures);
    if textures.is_empty() {
      tex_buffer.push(self.tex_mgr.texture(TextureID::Alpha(0)));
    } else {
      textures.iter().take(max_textures).for_each(|id| {
        tex_buffer.push(self.tex_mgr.texture(*id));
      });
    }
    gpu_impl.load_textures(&tex_buffer);

    let current_phase = std::mem::replace(&mut self.current_phase, CurrentPhase::None);
    match current_phase {
      CurrentPhase::None => {
        if color.is_some() {
          gpu_impl.draw_color_triangles(output, 0..0, color.take(), mask_offset)
        }
      }
      CurrentPhase::Color if !self.color_vertices_buffer.indices.is_empty() => {
        gpu_impl.load_color_vertices(&self.color_vertices_buffer);
        let rg = 0..self.color_vertices_buffer.indices.len() as u32;
        gpu_impl.draw_color_triangles(output, rg, color.take(), mask_offset)
      }
      CurrentPhase::Img if !self.img_vertices_buffer.indices.is_empty() => {
        let prims_offset = gpu_impl.load_img_data(&self.img_prims, &self.img_vertices_buffer);
        let rg = 0..self.img_vertices_buffer.indices.len() as u32;
        gpu_impl.draw_img_triangles(output, rg, color.take(), mask_offset, prims_offset)
      }
      CurrentPhase::RadialGradient
        if !self
          .radial_gradient_vertices_buffer
          .indices
          .is_empty() =>
      {
        let (prims_offset, stops_offset) = gpu_impl.load_radial_gradient_data(
          &self.radial_gradient_prims,
          &self.radial_gradient_stops,
          &self.radial_gradient_vertices_buffer,
        );
        let rg = 0..self.radial_gradient_vertices_buffer.indices.len() as u32;
        gpu_impl.draw_radial_gradient_triangles(
          output,
          rg,
          color.take(),
          mask_offset,
          prims_offset,
          stops_offset,
        )
      }
      CurrentPhase::LinearGradient
        if !self
          .linear_gradient_vertices_buffer
          .indices
          .is_empty() =>
      {
        let (prims_offset, stops_offset) = gpu_impl.load_linear_gradient_data(
          &self.linear_gradient_prims,
          &self.linear_gradient_stops,
          &self.linear_gradient_vertices_buffer,
        );
        let rg = 0..self.linear_gradient_vertices_buffer.indices.len() as u32;
        gpu_impl.draw_linear_gradient_triangles(
          output,
          rg,
          color.take(),
          mask_offset,
          prims_offset,
          stops_offset,
        )
      }
      CurrentPhase::Filter(filters) => {
        self.draw_filter(&filters, output, mask_offset);
      }
      _ => {}
    }
  }

  fn draw_filter(&mut self, filter: &FilterPhase, output: &mut Impl::Texture, mask_offset: u32) {
    let mask_origin: DevicePoint = filter.view_rect.origin.cast().cast_unit();
    let size = filter.view_rect.size;

    // 1. Initialize temporary textures
    let mut tex_a = self
      .gpu_impl
      .new_texture(size, ColorFormat::Rgba8);
    let mut tex_b = self
      .gpu_impl
      .new_texture(size, ColorFormat::Rgba8);

    // flush explicitly to ensure WGPU synchronizes draw commands to the output
    // texture before copying
    self.gpu_impl.flush_draw_commands();

    // Initial Copy: Output -> tex_a
    self.gpu_impl.copy_texture_from_texture(
      &mut tex_a,
      DevicePoint::zero(),
      output,
      &filter.view_rect.cast_unit(),
    );

    let p_a = &mut tex_a as *mut Impl::Texture;
    let p_b = &mut tex_b as *mut Impl::Texture;
    let mut p_src = p_a;
    let mut p_dst = p_b;

    for layer in &filter.filters {
      // Prepare Ops Iterator
      // Handle case where ops are empty but offset exists (e.g. strict shift)
      let mut ops_vec: Vec<(FilterOp, [f32; 2])> = layer
        .ops
        .iter()
        .map(|op| (op.clone(), [0.; 2]))
        .collect();

      if ops_vec.is_empty() && layer.offset != [0., 0.] {
        ops_vec.push((FilterOp::Color(ColorMatrix::identity().to_matrix()), [0.; 2]));
      }

      // Apply Offset to Last Op
      if let Some(last) = ops_vec.last_mut() {
        last.1 = layer.offset;
      } else {
        // Layer effectively empty/no-op
        continue;
      }

      // Execute Ops (Ping-Pong)
      // p_src holds Input (Source for this layer).
      for (op, offset) in ops_vec {
        let (color_matrix, base_color, matrix) = match &op {
          FilterOp::Color(m) => (
            m.matrix,
            m.base_color
              .map_or([0.; 4], |c| c.into_f32_components()),
            vec![1.0],
          ),
          FilterOp::Convolution(m) => {
            (ColorMatrix::identity().to_matrix().matrix, [0.; 4], m.matrix.clone())
          }
        };

        let width = if let FilterOp::Convolution(m) = &op { m.width as i32 } else { 1 };
        let height = if let FilterOp::Convolution(m) = &op { m.height as i32 } else { 1 };

        let prim = FilterPrimitive {
          sample_offset: [0.; 2],
          offset,
          mask_offset: mask_origin.to_vector().cast().into(),
          kernel_size: [width, height],
          mask_head: filter.mask_head,
          composite: 0, // Ops strictly Replace
          dummy: [0.; 2],
          base_color,
          color_matrix,
        };

        self.filter_vertices_buffer.clear();
        add_full_texture_vertices((), &mut self.filter_vertices_buffer);

        let src_tex = unsafe { &*p_src };
        let dst_tex = unsafe { &mut *p_dst };

        // mask_offset is passed from draw_triangles and remains valid during
        // the filter pass thanks to wgpu_impl not clearing it mid-draw.
        let prims_offset =
          self
            .gpu_impl
            .load_filter_data(&prim, &matrix, &self.filter_vertices_buffer);
        let indices = 0..self.filter_vertices_buffer.indices.len() as u32;

        // Draw Op, clearing dst first
        self.gpu_impl.draw_filter_triangles(
          dst_tex,
          src_tex,
          indices,
          Some(Color::TRANSPARENT),
          mask_offset,
          prims_offset,
        );

        std::mem::swap(&mut p_src, &mut p_dst);
      }

      // If ExcludeSource: We want Source OVER Filter.
      if layer.composite == FilterComposite::ExcludeSource {
        // 1. Copy Source (Output) -> p_dst
        self.gpu_impl.copy_texture_from_texture(
          unsafe { &mut *p_dst },
          DevicePoint::zero(),
          output,
          &filter.view_rect,
        );

        // 2. Swap so p_src=Source(Back), p_dst=Filter(Front/Dest)
        std::mem::swap(&mut p_src, &mut p_dst);

        // 3. Draw Source (p_src) OVER Filter (p_dst)
        // Composite Mode = ExcludeSource (passed to shader/backend)
        // We use TexturePrimitive via draw_texture_triangles to handle composition
        let transform = Transform::identity().to_array();
        let prim = TexturePrimitive {
          transform,
          mask_head: filter.mask_head,
          opacity: 1.0,
          is_premultiplied: 1,
          _padding: [0; 3],
        };

        self.texture_vertices_buffer.clear();
        add_full_texture_vertices(TexturePrimIndex(0), &mut self.texture_vertices_buffer);

        let src_tex = unsafe { &*p_src };
        let dst_tex = unsafe { &mut *p_dst };

        // mask_offset remains valid for the composite draw as well.
        let prims_offset = self
          .gpu_impl
          .load_texture_data(&[prim], &self.texture_vertices_buffer);
        let indices = 0..self.texture_vertices_buffer.indices.len() as u32;

        // Draw src_tex OVER dst_tex with composition.
        self.gpu_impl.draw_texture_triangles(
          dst_tex,
          indices,
          None,
          src_tex,
          mask_offset,
          prims_offset,
        );

        // 4. Swap back so p_src holds the Final Result
        std::mem::swap(&mut p_src, &mut p_dst);
      }

      // Update Output (Source for next layer)
      self.gpu_impl.copy_texture_from_texture(
        output,
        filter.view_rect.origin.cast().cast_unit(),
        unsafe { &*p_src },
        &DeviceRect::from_size(size),
      );
    }
  }
}

impl TextureIdxMap {
  fn tex_idx(&mut self, id: TextureID) -> u32 {
    *self.texture_map.entry(id).or_insert_with(|| {
      let idx = self.textures.len();
      self.textures.push(id);
      idx as u32
    })
  }

  fn all_textures(&self) -> &[TextureID] { &self.textures }

  fn reset(&mut self) {
    self.texture_map.clear();
    self.textures.clear();
  }

  fn len(&self) -> usize { self.textures.len() }
}

pub fn vertices_coord(pos: Point, tex_size: DeviceSize) -> [f32; 2] {
  [pos.x / tex_size.width as f32, pos.y / tex_size.height as f32]
}

pub fn add_rect_vertices<Attr: Copy>(
  [lt, rt, rb, lb]: [Point; 4], tex_size: DeviceSize, attr: Attr, buffer: &mut VertexBuffers<Attr>,
) {
  let VertexBuffers { vertices, indices } = buffer;

  let vertex_start = vertices.len() as u32;
  vertices.push(Vertex::new(vertices_coord(lt, tex_size), attr));
  vertices.push(Vertex::new(vertices_coord(rt, tex_size), attr));
  vertices.push(Vertex::new(vertices_coord(rb, tex_size), attr));
  vertices.push(Vertex::new(vertices_coord(lb, tex_size), attr));

  indices.push(vertex_start);
  indices.push(vertex_start + 3);
  indices.push(vertex_start + 2);
  indices.push(vertex_start + 2);
  indices.push(vertex_start + 1);
  indices.push(vertex_start);
}

pub fn add_full_texture_vertices<Attr: Copy>(attr: Attr, buffer: &mut VertexBuffers<Attr>) {
  let VertexBuffers { vertices, indices } = buffer;

  let vertex_start = vertices.len() as u32;
  vertices.push(Vertex::new([0., 0.], attr));
  vertices.push(Vertex::new([1., 0.], attr));
  vertices.push(Vertex::new([1., 1.], attr));
  vertices.push(Vertex::new([0., 1.], attr));

  indices.push(vertex_start);
  indices.push(vertex_start + 3);
  indices.push(vertex_start + 2);
  indices.push(vertex_start + 2);
  indices.push(vertex_start + 1);
  indices.push(vertex_start);
}

#[cfg(feature = "wgpu")]
#[cfg(test)]
mod tests {
  use ribir_algo::Resource;
  use ribir_core::prelude::AppCtx;
  use ribir_dev_helper::*;
  use ribir_painter::{Brush, LineCap, LineJoin, Painter, Path, Radius, StrokeOptions, Svg};
  use ribir_types::*;

  use super::*;

  fn painter(bounds: Size) -> Painter { Painter::new(Rect::from_size(bounds)) }
  fn webp_image(bytes: &'static [u8]) -> PixelImage { PixelImage::from_webp(bytes).unwrap() }

  painter_backend_eq_image_test!(smoke, comparison = 0.001);
  fn smoke() -> Painter {
    fn draw_arrow_path(painter: &mut Painter) {
      painter
        .begin_path((0., 70.).into())
        .line_to((100.0, 70.0).into())
        .line_to((100.0, 0.0).into())
        .line_to((250.0, 100.0).into())
        .line_to((100.0, 200.0).into())
        .line_to((100.0, 130.0).into())
        .line_to((0.0, 130.0).into())
        .end_path(true);
    }

    let mut painter = painter(Size::new(512., 512.));

    let img = webp_image(include_bytes!("../imgs/leaves.webp"));
    let share_img = Resource::new(img);

    let img_brush = Brush::Image(share_img);

    draw_arrow_path(&mut painter);
    painter.set_fill_brush(Color::RED).fill();

    painter.translate(260., 0.);
    draw_arrow_path(&mut painter);
    painter
      .set_stroke_brush(Color::RED)
      .set_line_width(5.)
      .stroke();

    painter.translate(-260., 250.);
    draw_arrow_path(&mut painter);
    painter.set_fill_brush(img_brush.clone()).fill();

    painter.translate(260., 0.);
    draw_arrow_path(&mut painter);
    painter
      .set_stroke_brush(img_brush)
      .set_line_width(5.)
      .stroke();

    painter
  }

  painter_backend_eq_image_test!(transform_img_brush, comparison = 0.001);
  fn transform_img_brush() -> Painter {
    let mut painter = painter(Size::new(800., 250.));

    let transform = Transform::new(1., 1., 2., 1., 0., 0.);
    let rect: Rect = Rect::new(Point::new(10., 10.), Size::new(100., 100.));
    painter
      .set_fill_brush(Color::RED)
      .set_transform(transform)
      .rect(&rect, true)
      .fill();

    let leaves_brush = Resource::new(webp_image(include_bytes!("../imgs/leaves.webp")));

    painter
      .set_fill_brush(leaves_brush)
      .set_transform(transform.then_translate((400., 0.).into()))
      .rect(&rect, true)
      .fill();

    painter
  }

  painter_backend_eq_image_test!(clip_layers, comparison = 0.0065);
  fn clip_layers() -> Painter {
    let mut painter = painter(Size::new(120., 340.));
    let rect_100x100 = Rect::from_size(Size::new(100., 100.));
    painter
      .set_fill_brush(Color::RED)
      .translate(10., 20.)
      .rect(&rect_100x100, true)
      .fill()
      .translate(0., 200.)
      .clip(Path::circle(Point::new(50., 50.), 50.).into())
      .rect(&rect_100x100, true)
      .fill();

    painter
  }

  #[test]
  fn normalize_round_rect_radii_clamps_and_scales() {
    let rect = Rect::from_size(Size::new(100., 60.));
    let radii = Radius::new(80., 80., 50., -2.);
    let [tl, tr, br, bl] = GPUBackend::<crate::WgpuImpl>::normalize_round_rect_radii(&rect, &radii);

    assert_eq!(br, -2.); // Negative offsets are perfectly forwarded
    assert!(tl + tr <= rect.width() + 1e-4);
    assert!(bl + br <= rect.width() + 1e-4);
    assert!(tl + bl <= rect.height() + 1e-4);
    assert!(tr + br <= rect.height() + 1e-4);
  }

  #[test]
  fn sdf_stroke_gate_rules() {
    let base = StrokeOptions {
      width: 2.0,
      miter_limit: 4.0,
      line_cap: LineCap::Butt,
      line_join: LineJoin::Miter,
    };
    assert!(GPUBackend::<crate::WgpuImpl>::support_sdf_stroke(&base));

    let round_cap = StrokeOptions { line_cap: LineCap::Round, ..base.clone() };
    assert!(!GPUBackend::<crate::WgpuImpl>::support_sdf_stroke(&round_cap));

    let round_join = StrokeOptions { line_join: LineJoin::Round, ..base.clone() };
    assert!(!GPUBackend::<crate::WgpuImpl>::support_sdf_stroke(&round_join));

    let zero_width = StrokeOptions { width: 0.0, ..base };
    assert!(!GPUBackend::<crate::WgpuImpl>::support_sdf_stroke(&zero_width));
  }

  painter_backend_eq_image_test!(stroke_include_border, comparison = 0.0004);
  fn stroke_include_border() -> Painter {
    let mut painter = painter(Size::new(100., 100.));
    painter
      .set_stroke_brush(Color::RED)
      .begin_path(Point::new(50., 5.))
      .line_to(Point::new(95., 50.))
      .line_to(Point::new(50., 95.))
      .line_to(Point::new(5., 50.))
      .end_path(true)
      .set_line_width(10.)
      .stroke();
    painter
  }

  painter_backend_eq_image_test!(two_img_brush, comparison = 0.006);
  fn two_img_brush() -> Painter {
    let mut painter = painter(Size::new(200., 100.));

    let brush1 = webp_image(include_bytes!("../imgs/leaves.webp"));
    let brush2 = webp_image(include_bytes!("../../examples/attachments/3DDD-1.webp"));
    let rect = rect(0., 0., 100., 100.);
    painter
      .set_fill_brush(brush1)
      .rect(&rect, true)
      .fill()
      .set_fill_brush(brush2)
      .translate(100., 0.)
      .clip(Path::circle(Point::new(50., 50.), 50.).into())
      .rect(&rect, true)
      .fill();

    painter
  }

  painter_backend_eq_image_test!(draw_partial_img, comparison = 0.0015);
  fn draw_partial_img() -> Painter {
    let img = Resource::new(webp_image(include_bytes!("../imgs/leaves.webp")));
    let m_width = img.width() as f32;
    let m_height = img.height() as f32;
    let mut painter = painter(Size::new(m_width * 2., m_height * 2.));

    painter.draw_img(
      img,
      &Rect::new(Point::new(m_width, m_height), Size::new(m_width, m_height)),
      &Some(Rect::new(
        Point::new(m_width / 2., m_height / 2.),
        Size::new(m_width / 2., m_height / 2.),
      )),
    );

    painter
  }

  painter_backend_eq_image_test!(draw_svg_gradient, comparison = 0.0025);
  fn draw_svg_gradient() -> Painter {
    let mut painter = painter(Size::new(64., 64.));
    let svg = Svg::parse_from_bytes(
      include_bytes!("../../tests/assets/fill_with_gradient.svg"),
      true,
      false,
    )
    .unwrap();

    painter.draw_svg(&svg);
    painter
  }

  // This test is disabled on Windows as it fails in the CI environment (exit code
  // 2173), although it passes on a physical Windows machine.
  #[cfg(not(target_os = "windows"))]
  fn multi_draw_phase() -> Painter {
    let mut painter = painter(Size::new(1048., 1048.));

    let rect = Rect::from_size(Size::new(1024., 1024.));
    for i in 0..100 {
      let mut painter = painter.save_guard();
      painter.translate(i as f32 * 10., i as f32 * 10.);
      let color = if i % 2 == 0 { Color::GREEN } else { Color::RED };
      painter
        .set_fill_brush(color)
        .rect_round(&rect, &ribir_painter::Radius::all(i as f32), true)
        .fill();
    }
    painter
  }
  #[cfg(not(target_os = "windows"))]
  painter_backend_eq_image_test!(multi_draw_phase, comparison = 0.001);

  fn draw_bundle_svg() -> Painter {
    let mut painter = painter(Size::new(512., 512.));
    let circle = Resource::new(Path::circle(Point::new(4., 4.), 100.));
    let commands = (0..64)
      .map(|i| {
        let color = if i % 2 == 0 { Color::GREEN } else { Color::RED };
        PaintCommand::Path(PathCommand::new(
          circle.clone().into(),
          PaintPathAction::Paint {
            brush: CommandBrush::Color(color),
            painting_style: PaintingStyle::Fill,
          },
          Transform::translation(i as f32 * 8., i as f32 * 8.),
        ))
      })
      .collect();

    painter.draw_bundle_commands(Rect::from_size(Size::new(512., 512.)), Resource::new(commands));
    painter
  }
  painter_backend_eq_image_test!(draw_bundle_svg, comparison = 0.001);
}