mgui-runtime 0.9.0

mgui 运行时:AppRunner、GPU/软件渲染后端、窗口/无障碍/异步任务集成
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
use mgui_core::paint::{BlendMode, TextureMode};
use mgui_core::Rect;
use mgui_core::{
    effect_flags, CacheInvalidationReason, CacheStats, FramePaint, LayerEffect, LayerId, LayerPaint, PaintCommand,
    PaintList, RRectDef, Size,
};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use wgpu::util::DeviceExt;

/// GPU 增量失效实验开关。默认关闭:0.6 只有在 L2 A/B 给出 GO 后才切换默认值。
/// 打开后,被标脏但内容 key 未变的 layer 跳过 Pass 1 重画。
static INCREMENTAL_LAYER_CACHE: AtomicBool = AtomicBool::new(false);

/// 打开/关闭 layer 内容 key 增量失效。仅用于实验与回归,不改变 DT-06 采集口径。
pub fn set_incremental_layer_cache_enabled(on: bool) {
    INCREMENTAL_LAYER_CACHE.store(on, Ordering::SeqCst);
}

/// 当前是否启用 layer 内容 key 增量失效。
pub fn incremental_layer_cache_enabled() -> bool {
    INCREMENTAL_LAYER_CACHE.load(Ordering::SeqCst)
}

/// 阶段 B1:rect 批处理 — batch header(per-layer 共享)
/// 屏幕逻辑尺寸 + instance 数量;**16-align**:`vec2` 后接 `u32` + `vec2 pad` 凑齐 16 字节。
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct RectBatchUniform {
    screen_size: [f32; 2], // 0..8
    count: u32,            // 8..12
    _pad: [f32; 1],        // 12..16 (整体 16-align)
}

/// 阶段 B1:rect 批处理 — 每实例数据
/// size = 5 × vec4 = 80 字节(WGSL 16-align 兼容)。
///
/// - 普通 Rect:from = to = color,params[1] = 0
/// - BoxShadow:params[2] = blur_radius
/// - LinearGradient:grad = (start.xy, end.xy),params[1] = 1
/// - RadialGradient:grad = (center.xy, radius, 0),params[1] = 2
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct RectInstance {
    rect: [f32; 4],
    from: [f32; 4],
    to: [f32; 4],
    grad: [f32; 4],
    /// [corner_radius, kind, blur_radius, pad]
    params: [f32; 4],
}

/// 阶段 B2:text 批处理 — batch header
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct TextBatchUniform {
    screen_size: [f32; 2], // 0..8
    count: u32,            // 8..12
    _pad: [f32; 1],        // 12..16 (整体 16-align)
}

/// 阶段 B2:text 批处理 — 每实例数据
/// size = 16(rect vec4) + 16(color vec4) + 16(uv vec4) + 16(mode vec4) = 64 字节
/// 16-align OK。
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct TextInstance {
    rect: [f32; 4],  // 0..16
    color: [f32; 4], // 16..32
    uv: [f32; 4],    // 32..48
    /// 纹理采样模式(vec4.x):0.0 = Mask(alpha 在纹理 R 通道,glyph/SVG tint),
    /// 1.0 = Color(straight RGBA 全彩纹理,SVG 全彩 / PNG 图片)
    mode: f32, // 48..52
    _pad: [f32; 3],  // 52..64
}

// 阶段 B2:被 TextInstance + TextBatchUniform 替代(批处理)
// 旧 TextUniform 已删除(deprecated by B2,见 commit log)

/// 阶段 4-B + 4-D:blit uniform(全屏 blit 用,带 layer offset/size)
///
/// 阶段 5:扩展为携带 effect 字段:
/// - effect_flags: bit field(HAS_TRANSFORM / HAS_OPACITY / HAS_CLIP)
/// - opacity / rotation / scale / translate_x / translate_y / clip_radius
///
/// **WGSL 对齐**: u32 4 字节,f32 4 字节;WGSL 会按 16-align 整体 struct。
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct BlitUniform {
    offset: [f32; 2], // 0..8    layer 在父 layer 内的 logical 位置
    size: [f32; 2],   // 8..16   layer 的 logical size
    screen: [f32; 2], // 16..24  surface logical 尺寸
    // ========== 阶段 5:effect 字段 ==========
    effect_flags: u32, // 24..28  bit field
    opacity: f32,      // 28..32
    rotation: f32,     // 32..36
    scale_x: f32,      // 36..40  HAS_TRANSFORM:x 轴缩放
    translate_x: f32,  // 40..44
    translate_y: f32,  // 44..48
    clip_radius: f32,  // 48..52
    scale_y: f32,      // 52..56  HAS_TRANSFORM:y 轴缩放(布局为 16-align 的填充位)
    // bugfix(Transform 旋转被裁):quad 覆盖区域。无旋转时 = offset/size;
    // HAS_TRANSFORM 时 = 旋转+缩放后的 AABB(中心不变,尺寸按 |cos|/|sin| 扩大),
    // 否则旋转超出原矩形的部分会被 quad 光栅化裁掉。
    quad_offset: [f32; 2], // 56..64
    quad_size: [f32; 2],   // 64..72
    phys_screen: [f32; 2], // 72..80 surface 物理像素尺寸
    // ========== 嵌套 layer 合成:局部坐标 → surface 的完整仿射 ==========
    /// [a, b, c, d]:x' = a*x + b*y + tx;y' = c*x + d*y + ty
    affine: [f32; 4], // 80..96
    affine_translate: [f32; 2], // 96..104
    _affine_pad: [f32; 2],      // 104..112(16-align)
    /// 两层裁剪(祖先 + 自己的内两层),surface 逻辑坐标 AABB
    clip_rect0: [f32; 4], // 112..128
    clip_rect1: [f32; 4],       // 128..144
    /// [radius0, radius1, count, unused]
    clip_params: [f32; 4], // 144..160
}
// struct size = 160 bytes (16-aligned)

/// 阶段 4-B:每个 layer 的 GPU cache(MSAA texture + resolve texture)
struct LayerGpuCache {
    /// resolve target texture(单采样;blit 采样 + 背景模糊 snapshot 复制源)
    resolve_texture: wgpu::Texture,
    /// resolve target view(sample_count=1,blit 采样这里)
    resolve_view: wgpu::TextureView,
    /// 创建时的物理尺寸;resize 时重建
    cached_size: (u32, u32),
    /// 上次真正画进这张 texture 的内容 key。增量开关打开时用于判定
    /// 「标脏但像素输入未变」;关闭时保持 0,不参与决策。
    content_key: u64,
}

/// 可跨窗口复用的 Renderer GPU 资源(pipeline / bind group layout / blit sampler /
/// glyph atlas / 图片纹理缓存)。
///
/// layer 缓存与 batch buffer 仍由各窗口 Renderer 独立持有(LayerId 只在单树内唯一)。
#[derive(Clone)]
pub struct RendererShared {
    /// Normal / Multiply / Screen / Add 各一个矩形 pipeline
    rect_pipelines: [wgpu::RenderPipeline; 4],
    rect_bgl: wgpu::BindGroupLayout,
    text_pipeline: wgpu::RenderPipeline,
    text_bgl: wgpu::BindGroupLayout,
    /// 纹理 mask(destination-in)
    text_pipeline_mask: wgpu::RenderPipeline,
    text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
    tri_pipeline: wgpu::RenderPipeline,
    tri_bgl: wgpu::BindGroupLayout,
    /// ClipPath stencil mask 写入(推入 +1 / 弹出 -1,front/back 同步)
    tri_pipeline_stencil_inc: wgpu::RenderPipeline,
    tri_pipeline_stencil_dec: wgpu::RenderPipeline,
    rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
    text_pipeline_stencil_test: wgpu::RenderPipeline,
    tri_pipeline_stencil_test: wgpu::RenderPipeline,
    blit_pipeline: wgpu::RenderPipeline,
    blit_bgl: wgpu::BindGroupLayout,
    blit_sampler: wgpu::Sampler,
    /// P2-1.4b:背景模糊(圆角遮罩 + 13-tap,复用 blit_sampler)
    backdrop_pipeline: wgpu::RenderPipeline,
    backdrop_bgl: wgpu::BindGroupLayout,
    format: wgpu::TextureFormat,
    atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
    image_cache: Rc<RefCell<ImageTextureCache>>,
}

/// 跨窗口共享的图片纹理缓存。
#[derive(Default)]
pub(crate) struct ImageTextureCache {
    textures: HashMap<u32, ImageTextureEntry>,
    clock: u64,
    /// 每个 texture_id 的内容代数;UpdateContent/Recreate 时递增。
    /// 增量 layer key 用它隔离「命令没变但纹理换帧」的情况。
    generations: HashMap<u32, u64>,
    /// 多窗口共享模式下由 host 统一管理预算,暂不做单帧 eviction。
    evict_enabled: bool,
}

impl RendererShared {
    pub fn format(&self) -> wgpu::TextureFormat {
        self.format
    }

    /// 多窗口 host 在一个渲染周期后调用:保护所有窗口最近一帧使用的纹理,
    /// 超预算时淘汰其余最旧纹理。
    pub fn evict_images(&self, protected: &std::collections::HashSet<u32>) {
        self.image_cache.borrow_mut().evict_to_budget(protected);
    }
}

impl ImageTextureCache {
    /// 某 texture_id 当前的内容代数;未注册过按 0 处理。
    pub(crate) fn generation(&self, texture_id: u32) -> u64 {
        self.generations.get(&texture_id).copied().unwrap_or(0)
    }

    fn evict_to_budget(&mut self, protected: &std::collections::HashSet<u32>) {
        let budget = IMAGE_TEXTURE_BUDGET_BYTES;
        let mut total: u64 = self.textures.values().map(|e| e.bytes).sum();
        if total <= budget {
            return;
        }
        let mut candidates: Vec<(u32, u64, u64)> = self
            .textures
            .iter()
            .filter(|(id, _)| !protected.contains(id))
            .map(|(&id, e)| (id, e.last_used, e.bytes))
            .collect();
        candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
        for (id, _, bytes) in candidates {
            if total <= budget {
                break;
            }
            self.textures.remove(&id);
            total = total.saturating_sub(bytes);
        }
        if total > budget {
            log::warn!(
                target: "mgui_startup",
                "shared image cache uses {} MiB (budget {} MiB); all remaining textures are in use",
                total / (1024 * 1024),
                budget / (1024 * 1024)
            );
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PresentStats {
    /// 真 present 出去的帧数(被 `Outdated` / `Occluded` / 校验错误挡掉的那些**不占号**:
    /// 那几种情况下屏幕上没有新内容,把它们算进"节奏"就是把失败读成正常)。
    pub presents: u64,
    /// 累计"等 vsync"的时间(`get_current_texture` 阻塞那一段)。这是 FIFO 呈现的**配额**:
    /// 它涨说明我们在等显示,而不是在等 GPU。
    pub wait_ns: u64,
    /// 累计 `queue.present` 调用本身的时间。
    pub submit_ns: u64,
    /// 记过多少个"相邻两次 present 的间隔"。语义与 `mgui_video::StageCounters::frames_measured`
    /// 同源:**没有前驱的那一次不许编出一个间隔**,所以它最多等于 `presents − 1`。
    pub gaps: u64,
    pub gap_sum_ns: u64,
    pub gap_max_ns: u64,
    /// 最近一个间隔(给"每帧读一次并自己组分布"的工具用,例如 showcase 的 cadence 运行器)。
    pub last_gap_ns: u64,
    /// 呈现模式的**实际生效值**(从 `SurfaceConfiguration` 读,不是文档里的默认)。
    /// 之所以回显它:节奏这件事的全部解释都依赖"到底是 FIFO 还是 IMMEDIATE、队列允许几深",
    /// 读数与配置分两处写就一定分叉(本仓为这类分叉付过学费)。
    ///
    /// **空串的含义是"这一路没接线"**(软件回退、或多窗口宿主的 slot 还没接上共享 context),
    /// 而不是"这台机器一次都没 present"。接线之后它一定是 `Fifo` / `Mailbox` 这类实际模式名,
    /// 所以 `presents == 0` 与 `present_mode == ""` 一起读才分得开"没量到"与"量了但没帧"。
    pub present_mode: &'static str,
    /// `desired_maximum_frame_latency` 的实际值(同上)。
    pub max_frame_latency: u32,
    /// 累计 `present_gpu_frame` 入口 → `queue.present` 返回的 CPU 耗时(纳秒)。
    /// **不是完整端到端**:不含 `app.frame()` / CPU paint / `about_to_wait` / 事件循环调度。
    pub present_path_cpu_ns: u64,
    /// 累计 `redraw` 入口 → present 返回的 CPU 耗时(纳秒)。多窗口未接线时为 0。
    pub redraw_cpu_ns: u64,
    /// 最近一次的两个耗时(给 cadence 逐帧采样用)。
    pub last_present_path_cpu_ns: u64,
    pub last_redraw_cpu_ns: u64,
    /// A/B 2 必测项 1:累计 frame_start(`redraw` 入口)→ acquire 完成。
    /// 实验组这一格**包含**提前上传,机械变长不是退化,只作调用顺序的自证;
    /// CPU paint 与 vsync 等待在两组里都落在这一段,口径一致。
    pub frame_to_acquire_ns: u64,
    /// A/B 2 必测项 2:累计 acquire 完成 → `queue.present` 返回(含 Pass1/Pass2 submit)。
    /// 实验组上传被移出这一段,机械变短没有判别力(规格明确),不能单独拿来判胜负。
    pub acquire_to_submit_ns: u64,
    pub last_frame_to_acquire_ns: u64,
    pub last_acquire_to_submit_ns: u64,
}

impl PresentStats {
    /// 记一次成功的 present。`gap` = 与上一次 present 的间隔;第一次传 `None`。
    ///
    /// 分成这个方法而不是让调用方自己加字段,是为了把"第一帧不产生样本"这条家规放在**一处**
    /// 实现(另一处是 `mgui_video::timing`),调用方只需要回答"有没有前驱"。
    pub fn record(&mut self, wait_ns: u64, submit_ns: u64, gap: Option<Duration>, mode: &'static str, latency: u32) {
        self.presents = self.presents.saturating_add(1);
        self.wait_ns = self.wait_ns.saturating_add(wait_ns);
        self.submit_ns = self.submit_ns.saturating_add(submit_ns);
        self.present_mode = mode;
        self.max_frame_latency = latency;
        if let Some(gap) = gap {
            let ns = gap.as_nanos() as u64;
            self.gaps = self.gaps.saturating_add(1);
            self.gap_sum_ns = self.gap_sum_ns.saturating_add(ns);
            self.gap_max_ns = self.gap_max_ns.max(ns);
            self.last_gap_ns = ns;
        }
    }

    /// 间隔均值(纳秒)。没有样本时给 0 —— 调用方要读 [`Self::gaps`],不是读这个数。
    pub fn mean_gap_ns(&self) -> u64 {
        self.gap_sum_ns.checked_div(self.gaps).unwrap_or(0)
    }
}

/// 一条 `pending_texture` 声明的**处置记录**:三种 outcome 全部记录。
///
/// `Reuse` 也必须留下记录:`register_outcome(seq)` 是四段序号链路的第四段。只记真实
/// 上传时,取到 N 帧却只传了 N/10 帧的运行里那 9 成声明没有落点,
/// 「dirty layer 重画了但声明旧像素」与「根本没进 PaintList」两种坏法分不开。
/// 字节数刻意分两栏:`source_bytes` 是按 `stride`/layout 实际参与读取的字节
/// (`ImageData::min_len()`),`active_bytes` 是 `width * height * 4` 的有效像素规模。
pub(crate) struct TextureUploadRecord {
    pub outcome: mgui_core::image::TextureUpdate,
    /// `Reuse` / 上传失败时为 0:只有真实上传才计字节与 `upload_count`。
    pub source_bytes: u64,
    pub active_bytes: u64,
    /// 只包 `queue.write_texture` 那一段,不含 drain 遍历与 create_texture/view/sampler。
    pub write_ns: u64,
    /// `write_texture` 的 Extent3d 宽高。A/B 1 的**生效校验**靠它:实验组必须等于
    /// 显式给定的目标尺寸,光看 `source_bytes` 下降还可能被帧数变化蒙混过去。
    pub width: u32,
    pub height: u32,
    pub meta: Option<mgui_core::paint::TextureFrameMeta>,
}

impl TextureUploadRecord {
    /// 日志里的 outcome 编号:0=无 / 1=Reuse / 2=UpdateContent / 3=Recreate。
    pub(crate) fn outcome_code(&self) -> u8 {
        use mgui_core::image::TextureUpdate;
        match self.outcome {
            TextureUpdate::Reuse => 1,
            TextureUpdate::UpdateContent => 2,
            TextureUpdate::Recreate => 3,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RenderStats {
    /// 本帧实际重画的 layer 数
    pub layers_painted: u32,
    /// 0.6 M3 / DT-06:layer cache hit/miss、失效归因、显存高水位与恢复耗时。
    /// 采集关闭时整块恒 0(读成「未量到」,不是「没有失效」)。
    pub cache: CacheStats,
    /// 实际提交的 scissor 段数
    pub segments: u32,
    /// paint pass + stencil mask + layer blit 的 draw 总数
    pub draw_calls: u32,
    /// 跨 layer 复用 scratch 的总字节(MSAA + stencil + snapshot)
    pub scratch_bytes: u64,
    /// 持久 layer resolve texture 的总字节
    pub layer_texture_bytes: u64,
    /// **纹理上传段**的耗时(纳秒):`drain_pending_textures` 那一步,也就是图片/SVG 纹理
    /// 首次注册、内容更新(`queue.write_texture`)与重建(`device.create_texture`)的全部成本。
    ///
    /// 为什么要单独一段而不是并进 `paint_ns`:视频每一帧都走 `UpdateContent`(同一张
    /// texture_id 换内容),所以这一段是"逐帧像素进 GPU 的过路费",与画多少 layer 无关;
    /// 2026-11-10 之前它在产品里完全不可读,于是"上传贵不贵"只能靠现场搭探针回答。
    /// 口径与 `mgui_core::frame::FrameStats::COLLECTING` 绑定:`profiling` 关着时它恒 0
    /// (`Lap` 不读表),那种时候**不许**把 0 读成"上传不要钱"。
    pub upload_ns: u64,
    /// 只累计真实上传分支里的 `queue.write_texture`(`Reuse` 遍历不算进单次上传成本)。
    pub upload_write_ns: u64,
    /// 最近一次真实上传的 `write_texture` 尺寸(A/B 1 生效校验:实验组应等于目标尺寸)。
    pub last_upload_width: u32,
    pub last_upload_height: u32,
    /// 本帧真实上传的源缓冲字节数(按 stride/layout 实际参与读取的量)
    pub upload_source_bytes: u64,
    /// 本帧真实上传的有效像素字节数(width * height * 4)
    pub upload_active_bytes: u64,
    /// 本帧真实上传次数
    pub upload_count: u32,
    /// 本帧带视频帧元数据的声明数 / 三种 outcome 各多少次。
    pub texture_decl_count: u32,
    pub texture_reuse_count: u32,
    pub texture_update_count: u32,
    pub texture_recreate_count: u32,
    /// 声明的 `sequence` 落后于 paint 时共享格最新序号的次数 ——
    /// 「PaintList 重新生成了但携带旧像素」的直接计数。
    pub stale_decl_count: u32,
    /// 声明的元数据 `synced_seq == 0` 的次数(RO 从未同步过这一帧)。
    pub unsynced_decl_count: u32,
    /// 最近一次带帧元数据的**声明**:sequence / generation / 帧年龄(ns)。
    /// 帧年龄只在真实上传那一次落样本(`last_frame_encoder != 0`)。
    pub last_frame_sequence: u64,
    pub last_frame_generation: u64,
    pub last_frame_age_ns: u64,
    /// 四段序号链路的第 2 / 3 / 4 段(第 1 段就是 `last_frame_sequence` 声明的帧号)。
    pub last_frame_synced_seq: u64,
    pub last_frame_latest_seq: u64,
    /// 1=Reuse / 2=UpdateContent / 3=Recreate / 0=本帧无带元数据的声明。
    pub last_frame_outcome: u8,
    /// 承载这次上传 copy 的 submit:1 = Pass1,2 = Pass2,0 = 本帧无真实上传
    pub last_frame_encoder: u8,
}

pub struct Renderer {
    /// Normal / Multiply / Screen / Add 各一个矩形 pipeline
    rect_pipelines: [wgpu::RenderPipeline; 4],
    rect_bgl: wgpu::BindGroupLayout,
    text_pipeline: wgpu::RenderPipeline,
    text_bgl: wgpu::BindGroupLayout,
    /// 纹理 mask(destination-in)
    text_pipeline_mask: wgpu::RenderPipeline,
    text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
    /// Stage T1: triangle pipeline(PathBuilder.fill → earcut → vertex/index buffer)
    tri_pipeline: wgpu::RenderPipeline,
    tri_bgl: wgpu::BindGroupLayout,
    /// **ClipPath GPU stencil** — 4 个测试变体 + 2 个 mask 写入变体:
    /// 1. `tri_pipeline_stencil_inc/dec`:只写 stencil,color=NONE(推入 +1 / 弹出 -1)
    /// 2. `rect/text/tri_pipeline_stencil_test`:stencil Equal(当前嵌套深度)
    tri_pipeline_stencil_inc: wgpu::RenderPipeline,
    tri_pipeline_stencil_dec: wgpu::RenderPipeline,
    rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
    text_pipeline_stencil_test: wgpu::RenderPipeline,
    tri_pipeline_stencil_test: wgpu::RenderPipeline,
    /// 缓存的 GPU glyph atlas(多窗口共享同一 texture/view/sampler)
    atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
    /// 阶段 4-B:layer → GPU texture cache(每 layer 一张全屏 texture)
    layer_cache: HashMap<LayerId, LayerGpuCache>,
    /// P2:frame 内活跃 layer id 复用集合(避免每帧分配 HashSet)
    active_layer_ids: std::collections::HashSet<LayerId>,
    /// P2:frame 内 layer 逻辑尺寸复用表(composition 用)
    frame_layer_sizes: HashMap<LayerId, Size>,
    /// P2:跨帧复用的 composition scratch(by_id/memo/visiting 容器)
    composition_scratch: mgui_core::CompositionScratch,
    /// 阶段 4-B:blit pipeline(把 layer texture 画到 surface)
    blit_pipeline: wgpu::RenderPipeline,
    blit_bgl: wgpu::BindGroupLayout,
    blit_sampler: wgpu::Sampler,
    /// P2-1.4b:背景模糊(圆角遮罩 + 13-tap,复用 blit_sampler)
    backdrop_pipeline: wgpu::RenderPipeline,
    backdrop_bgl: wgpu::BindGroupLayout,
    /// 阶段 2-E:surface 格式(layer texture 与 pipeline render target 保持一致)
    format: wgpu::TextureFormat,
    /// 阶段 B4:GPU 端 timestamp profiler(None = 设备不支持 TIMESTAMP_QUERY)
    pub gpu_profiler: Option<crate::gpu_profiler::GpuProfiler>,
    /// 阶段 B1.5:**per-layer** batch buffer pool
    ///
    /// **关键**:每个 layer 独立 buffer — **不能所有 layer 共享一个 pool buffer**!
    /// wgpu 的 `queue.write_buffer` 是 staged + 下次 submit 时执行;
    /// 同一 submit 内多个 layer 依次 write_buffer 同一 buffer → 后写覆盖先写,
    /// 所有 layer 的 draw 都用最后一个 layer 的数据 → UI 错乱(元素放大/错位)。
    /// 阶段 6(图片):value 同 LayerBatchPool;key = (LayerId, texture_id) —
    /// text 用 texture_id 0,每张图片一个独立 key(纹理不同 buffer 必须隔离)
    batch_pools: HashMap<(LayerId, u32), LayerBatchPool>,
    /// 阶段 6(图片):图片纹理缓存(多窗口共享;按 ImageWidget 的 texture_id 索引)
    image_cache: Rc<RefCell<ImageTextureCache>>,
    /// P2-1.5:跨 layer 复用的临时纹理(按物理尺寸 key;view 持有 texture 引用)
    msaa_scratch: HashMap<(u32, u32), wgpu::TextureView>,
    stencil_scratch: HashMap<(u32, u32), wgpu::TextureView>,
    snapshot_scratch: HashMap<(u32, u32), (wgpu::Texture, wgpu::TextureView)>,
    /// P2-1.5:上一帧的绘制统计(draw calls / scratch / layer texture)
    last_stats: RenderStats,
    /// DT-06:本帧尚未结算的失效归因;`render()` 开头摘走并清零
    pending_invalidations: [u32; 9],
    /// DT-06:最近一次失效的时间锚点;帧末结算恢复时间
    pending_invalidation_start: Option<Instant>,
    /// DT-06:会话内显存高水位
    cache_high_watermark_bytes: u64,
    /// A/B 2:提前上传的记录 `(处置记录, 整段 drain 耗时 ns)`。
    /// `upload_pending()` 在 acquire 前写入,`render()` 消费;`None` = 走原来的
    /// render 内 drain(对照组,与实验前逐字节一致)。两组都用同一份记录填 `RenderStats`,
    /// 所以上传统计、四段序号、帧年龄的口径不随调用位置漂移。
    pending_upload: Option<(Vec<TextureUploadRecord>, u64)>,
}

/// 单张图片纹理的 GPU 缓存条目
pub(crate) struct ImageTextureEntry {
    /// 仅用于保持 GPU 纹理存活(view 是否持有引用不应依赖)
    pub _texture: wgpu::Texture,
    pub view: wgpu::TextureView,
    pub sampler: wgpu::Sampler,
    /// 最近一次被 PaintList 声明使用的时钟
    pub last_used: u64,
    /// 纹理字节数(width * height * 4),用于预算淘汰
    pub bytes: u64,
    /// 源数据的 **`Rc` 身份**(0.4 V-P0-1)。必须把 `Rc` 本身留住:只存地址会让
    /// 释放后被复用的地址把"另一张图"误判成"同一帧"。
    pub source: Rc<mgui_core::image::ImageData>,
    /// 纹理当前尺寸;`plan_texture_update` 据此判 `UpdateContent` 还是 `Recreate`。
    pub size: (u32, u32),
}

/// 图片纹理预算(256 MiB)
pub const IMAGE_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;

/// 单窗口所有 layer resolve texture 的总预算(256 MiB)。
pub use setup::LAYER_TEXTURE_BUDGET_BYTES;

pub use mgui_core::inspect::ImageTextureStats;

impl Renderer {
    /// P2-1.5:上一帧绘制统计(draw calls / segment / scratch 内存)
    pub fn last_stats(&self) -> RenderStats {
        self.last_stats
    }

    /// DT-06:宿主在主题/DPR/atlas/图片/设备丢失/窗口重建等外部失效发生时调用。
    /// 同一帧多次调用会累加归因,恢复时间从最早一次算到本帧提交完成。
    pub fn note_cache_invalidation(&mut self, reason: CacheInvalidationReason) {
        if !mgui_core::frame::cache_stats_collecting() {
            return;
        }
        let now = Instant::now();
        if self.pending_invalidation_start.is_none() {
            self.pending_invalidation_start = Some(now);
        }
        let slot = reason as usize;
        self.pending_invalidations[slot] = self.pending_invalidations[slot].saturating_add(1);
    }

    /// 当前图片纹理数量/字节数与预算
    pub fn image_texture_stats(&self) -> ImageTextureStats {
        let cache = self.image_cache.borrow();
        ImageTextureStats {
            count: cache.textures.len(),
            bytes: cache.textures.values().map(|e| e.bytes).sum(),
            budget_bytes: IMAGE_TEXTURE_BUDGET_BYTES,
        }
    }
}

/// 阶段 B1.5:单 layer 的 batch buffer pool(9 个 buffer — 含 tri + stencil mask)
struct LayerBatchPool {
    rect_header: Option<wgpu::Buffer>,
    rect_instances: Option<wgpu::Buffer>,
    text_header: Option<wgpu::Buffer>,
    text_instances: Option<wgpu::Buffer>,
    /// Stage T1:tri buffers(vertex + index + uniform)
    tri_vertex: Option<wgpu::Buffer>,
    tri_index: Option<wgpu::Buffer>,
    tri_uniform: Option<wgpu::Buffer>,
    /// **T0-1.5:ClipPath stencil** — PushClipPath path triangles 的 vertex/index buffer
    /// 每帧 write_buffer 覆盖内容;grow-only 容量够就复用
    stencil_vertex: Option<wgpu::Buffer>,
    stencil_index: Option<wgpu::Buffer>,
}

/// GPU atlas 资源 + 缓存的 size
pub(crate) struct AtlasGpu {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
    sampler: wgpu::Sampler,
    /// 创建时的 atlas 尺寸;尺寸变化时重建
    cached_size: (u32, u32),
}

pub(crate) struct RectBatch {
    bg: wgpu::BindGroup,
}

/// Stage T1:triangle pipeline — 每 layer 一个批次(所有 PathBuilder.fill 合并画)
pub(crate) struct TriBatch {
    bg: wgpu::BindGroup,
}

/// Stage T1:triangle uniform(跟 RectBatchUniform 同样的 16 bytes pattern)
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct TriUniform {
    screen_size: [f32; 2],
    _pad0: u32,
    _pad1: u32,
}

/// P2-1.4b:背景模糊 uniform(64 bytes)
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct BackdropUniform {
    screen: [f32; 2],
    _pad: [f32; 2],
    rect: [f32; 4],
    /// [corner_radius, blur_radius, 0, 0]
    params: [f32; 4],
    /// tint rgb + mix alpha
    tint: [f32; 4],
}

/// 阶段 B2:text 批处理结果(pub(crate):ImageBatchDraw::batch 字段引用)
pub(crate) struct TextBatch {
    bg: wgpu::BindGroup,
    count: u32,
}

// ============================================================
// 阶段 B2+B3:clip 分段收集 + GPU scissor 裁剪
// ============================================================

/// PushClipPath 的 earcut 三角形(扁平 vertices + indices)
#[derive(Debug, Clone, Default)]
pub(crate) struct StencilDraw {
    /// [x, y, r, g, b, a, ...]
    pub vertices: Vec<f32>,
    pub indices: Vec<u32>,
}

/// 进入/退出一个 ClipPath 时对 stencil 覆盖计数的操作。
///
/// 推入时 +1、弹出时 -1;内容段用 `Equal(level)` 测试,
/// 因此嵌套 clip 的交集会自动生效(只有每个 mask 都覆盖到的像素计数 = depth)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct StencilAction {
    /// `StencilDraw` 下标
    pub draw: u32,
    /// 操作时的嵌套深度(从 1 开始)
    pub level: u32,
    pub increment: bool,
}

/// 合并后的 ClipPath mask GPU 资源;`ranges[draw]` = (first_index, index_count)
pub(crate) struct StencilGpu {
    pub vertex: wgpu::Buffer,
    pub index: wgpu::Buffer,
    pub ranges: Vec<(u32, u32)>,
    pub bg: wgpu::BindGroup,
}

/// 背景模糊命令参数(圆角遮罩 + 13-tap blur + tint)
#[derive(Debug, Clone, Copy)]
pub(crate) struct BackdropBlurSpec {
    pub rect: Rect,
    pub radius: f32,
    pub blur_radius: f32,
    pub tint: [f32; 4],
}

/// 段内的一次绘制操作(按 PaintList 命令顺序记录,保留跨类型 z-order)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DrawOp {
    /// rect instance 半开区间 [start, end) + 混合模式
    Rect(u32, u32, BlendMode),
    /// text instance 半开区间 [start, end)
    Text(u32, u32),
    /// 图片组下标
    Image(u32),
    /// 纹理 alpha mask(destination-in),引用图片组下标
    Mask(u32),
    /// 背景模糊(引用 BackdropBlurSpec 下标)
    BackdropBlur(u32),
    /// tri index 半开区间 [start, end)(index 进合并后的 tri index buffer)
    Tri(u32, u32),
}

/// 阶段 B3:一个 scissor 段 — 相邻 clip 边界(PushClip/PopClip)之间的绘制区间
///
/// Pass 1 里每段一次 `set_scissor_rect`,再按 `ops` 顺序逐条 draw —— 这样
/// rect/text/图片/三角形都保持 PaintList 的原始绘制顺序,而不是被类型分组
/// 重排(旧实现固定 rect→image→text→tri,后画的 rect 会盖不住先画的文字)。
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct ClipSegment {
    /// scissor 矩形物理像素 [x, y, w, h];`None` = 本段无裁剪(整个 target)
    pub scissor: Option<[u32; 4]>,
    /// 本段实际 draw 的顺序列表
    pub ops: Vec<DrawOp>,
    /// 段内 rect/text/图片组的总范围(测试/诊断兼容字段)
    pub rect_range: (u32, u32),
    pub text_range: (u32, u32),
    pub image_range: (u32, u32),
    /// 本段生效的 ClipPath 嵌套深度(0 = 无 path 裁剪,>0 时用 stencil Equal(level))
    pub stencil_level: u32,
    /// 本段绘制前要执行的 stencil mask 操作(推入/弹出,按顺序)
    pub stencil_actions: Vec<StencilAction>,
}

/// 阶段 6(图片):一个 texture_id 的连续图片组(paint 命令顺序里相邻的同图
/// TexturedRect 合为一组 — 同一 ImageWidget 只产 1 条命令,组数 = 层内图片数)
pub(crate) struct ImageGroup {
    pub texture_id: u32,
    pub instances: Vec<TextInstance>,
}

/// 阶段 6(图片):一个图片组的可绘制批次(bind group 已绑定该组纹理)。
///
/// 在 `Vec<Option<ImageBatchDraw>>` 里**下标 = ImageGroup 下标**:
/// 未注册纹理的组是 `None` 占位,这样段的 `image_range`(组下标区间)
/// 不因跳过而错位。
pub(crate) struct ImageBatchDraw {
    pub(crate) batch: TextBatch,
}

/// 矩形求交(负宽高 clamp 为 0 — 退化矩形与任何东西都不相交)
fn intersect_rect(a: Rect, b: Rect) -> Rect {
    let x1 = a.x.max(b.x);
    let y1 = a.y.max(b.y);
    let x2 = (a.x + a.width).min(b.x + b.width);
    let y2 = (a.y + a.height).min(b.y + b.height);
    Rect::new(x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0))
}

/// 计算 path triangles 的 bounding box(用于 PushClipPath → scissor 近似)
fn path_bounding_box(vertices: &[mgui_core::paint::Vertex]) -> Rect {
    if vertices.is_empty() {
        return Rect::new(0.0, 0.0, 0.0, 0.0);
    }
    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for v in vertices {
        min_x = min_x.min(v.x);
        min_y = min_y.min(v.y);
        max_x = max_x.max(v.x);
        max_y = max_y.max(v.y);
    }
    Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
}

/// instance 矩形是否与当前 clip 相交(CPU 粗剔除;精确裁剪交给 GPU scissor)
fn rect_intersects_clip(r: &Rect, clip: Option<Rect>) -> bool {
    match clip {
        None => true,
        // 退化 clip(宽或高 = 0)与任何东西都不相交
        Some(c) => {
            c.width > 0.0
                && c.height > 0.0
                && r.x < c.x + c.width
                && r.x + r.width > c.x
                && r.y < c.y + c.height
                && r.y + r.height > c.y
        }
    }
}

/// 圆角矩形三角扇(凸多边形,中心 + 周边点即可精确覆盖)。
///
/// 用于 `PushClipRRect` 的 stencil mask;每角 8 段二次近似圆,
/// 顶点格式与 `StencilDraw` 一致([x,y,r,g,b,a])。
fn rounded_rect_stencil_mesh(rect: Rect, radius: f32) -> (Vec<f32>, Vec<u32>) {
    if rect.width <= 0.0 || rect.height <= 0.0 {
        return (Vec::new(), Vec::new());
    }
    let (x, y, w, h) = (rect.x, rect.y, rect.width, rect.height);
    let r = radius.max(0.0).min(w.min(h) * 0.5);

    let mut pts: Vec<(f32, f32)> = Vec::new();
    if r <= 0.0 {
        pts.extend_from_slice(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
    } else {
        const SEG: u32 = 8;
        // 顺时针(屏幕 y 向下):右上 → 右下 → 左下 → 左上
        let arcs = [
            (x + w - r, y + r, -std::f32::consts::FRAC_PI_2, 0.0),
            (x + w - r, y + h - r, 0.0, std::f32::consts::FRAC_PI_2),
            (x + r, y + h - r, std::f32::consts::FRAC_PI_2, std::f32::consts::PI),
            (x + r, y + r, std::f32::consts::PI, 3.0 * std::f32::consts::FRAC_PI_2),
        ];
        for &(cx, cy, a0, a1) in &arcs {
            for i in 0..=SEG {
                let a = a0 + (a1 - a0) * (i as f32 / SEG as f32);
                pts.push((cx + r * a.cos(), cy + r * a.sin()));
            }
        }
        // 最后一角回到起点(首尾重复),去掉
        if pts.len() > 1 && pts.first() == pts.last() {
            pts.pop();
        }
    }
    pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5);

    let n = pts.len();
    if n < 3 {
        return (Vec::new(), Vec::new());
    }
    let mut verts = Vec::with_capacity((n + 1) * 6);
    for &(px, py) in &pts {
        verts.extend_from_slice(&[px, py, 1.0, 1.0, 1.0, 1.0]);
    }
    verts.extend_from_slice(&[x + w * 0.5, y + h * 0.5, 1.0, 1.0, 1.0, 1.0]);
    let center = n as u32;
    let mut indices = Vec::with_capacity(n * 3);
    for i in 0..n as u32 {
        indices.extend_from_slice(&[center, i, (i + 1) % n as u32]);
    }
    (verts, indices)
}

/// clip 逻辑坐标 → scissor 物理像素 [x, y, w, h](floor/ceil 取整,clamp 到 texture 尺寸)
fn clip_to_scissor_px(r: Rect, dpr: f32, tex: (u32, u32)) -> [u32; 4] {
    let d = dpr.max(0.0);
    let (tw, th) = (tex.0 as f32, tex.1 as f32);
    // 近边也必须 clamp 到 target 尺寸,否则完全落在 target 右侧/下方的 clip
    // 会产出 x/y 越界的 scissor → wgpu validation error。
    let x0 = (r.x * d).floor().clamp(0.0, tw);
    let y0 = (r.y * d).floor().clamp(0.0, th);
    let x1 = ((r.x + r.width) * d).ceil().clamp(0.0, tw).max(x0);
    let y1 = ((r.y + r.height) * d).ceil().clamp(0.0, th).max(y0);
    let x = x0 as u32;
    let y = y0 as u32;
    let w = (x1 as u32).saturating_sub(x);
    let h = (y1 as u32).saturating_sub(y);
    [x, y, w, h]
}

/// 阶段 B2+B3:一次遍历 paint_list → rect/text instances + scissor 分段
///
/// - `PushClip`/`PopClip` 是段边界;`PushClip` 与外层 clip 求交(嵌套 clip)
/// - instance 与当前 clip 相交才收集(CPU 粗剔除),溢出边缘交给 GPU scissor
/// - 空段(无 instance)不产出 — 不浪费 draw call
///
/// Stage T1:Triangles — 合并所有 PaintCommand::Triangles(vertices,indices)
/// 进一个 Vec<f32>(vertex flat) + Vec<u32>(index merged + offset by base vertex count)
/// **不分 clip 分段**(简化:path fill 的三角形通常不需要 clip 分段;
/// 未来需要时加 tri_range 进 ClipSegment)
///
/// **ClipPath stencil** — 最后一个返回值:
/// 所有 PushClipPath 的 earcut 三角形(供 renderer 在段间写 stencil mask);
/// 每个 `ClipSegment.stencil_actions` 用下标引用它。
type CollectedInstances = (
    Vec<RectInstance>,
    Vec<TextInstance>,
    Vec<ImageGroup>,
    Vec<ClipSegment>,
    // Stage T1:triangle data(所有 PaintCommand::Triangles 合并)
    Vec<f32>, // vertex flat data: [x,y,r,g,b,a, x,y,r,g,b,a, ...]
    Vec<u32>, // merged index data(offset per command)
    // ClipPath mask triangles(按 PushClipPath 顺序)
    Vec<StencilDraw>,
    // 背景模糊参数
    Vec<BackdropBlurSpec>,
);

pub(crate) fn collect_instances_segmented(
    paint_list: &PaintList,
    dpr: f32,
    tex_size: (u32, u32),
) -> CollectedInstances {
    let mut rects: Vec<RectInstance> = Vec::new();
    let mut texts: Vec<TextInstance> = Vec::new();
    let mut image_groups: Vec<ImageGroup> = Vec::new();
    let mut segments: Vec<ClipSegment> = Vec::new();
    // Stage T1:triangles
    let mut tri_vertices: Vec<f32> = Vec::new(); // 扁平化后的顶点
    let mut tri_indices: Vec<u32> = Vec::new(); // 合并后的 index(加偏移)
    let mut tri_base_vertex: u32 = 0; // 当前 command 的顶点在全局数组里的 base offset
                                      // **ClipPath stencil** — 每个 PushClipPath 的 mask 三角形 + 待执行的 +1/-1 操作
    let mut stencil_draws: Vec<StencilDraw> = Vec::new();
    let mut pending_stencil: Vec<StencilAction> = Vec::new();
    let mut backdrop_blurs: Vec<BackdropBlurSpec> = Vec::new();
    let mut path_draw_stack: Vec<Option<u32>> = Vec::new();
    let mut clip_depth: u32 = 0;
    // 混合模式栈:作用于后续矩形族命令,不产生段边界
    let mut blend_stack: Vec<BlendMode> = Vec::new();
    let mut cur_blend = BlendMode::Normal;
    // clip 栈:每层保存"压入前的外层 clip" + 是否为 stencil mask 裁剪
    let mut stack: Vec<(Option<Rect>, bool)> = Vec::new();
    let mut cur_clip: Option<Rect> = None;
    let (mut seg_r, mut seg_t, mut seg_i): (u32, u32, u32) = (0, 0, 0);
    // 段内绘制顺序(rect/text/image/tri 交错,保留 painter's order)
    let mut ops: Vec<DrawOp> = Vec::new();

    // 关闭当前段(有绘制操作才记录;重置段起点)
    macro_rules! close_segment {
        () => {
            let r_end = rects.len() as u32;
            let t_end = texts.len() as u32;
            let i_end = image_groups.len() as u32;
            if !ops.is_empty() {
                segments.push(ClipSegment {
                    scissor: cur_clip.map(|c| clip_to_scissor_px(c, dpr, tex_size)),
                    ops: ops.clone(),
                    rect_range: (seg_r, r_end),
                    text_range: (seg_t, t_end),
                    image_range: (seg_i, i_end),
                    stencil_level: clip_depth,
                    // 边界上的 mask 操作属于"下一段内容";空段不消费它们,
                    // 留到下一个有绘制的段(净效果仍然正确)。
                    stencil_actions: std::mem::take(&mut pending_stencil),
                });
                ops.clear();
            }
            seg_r = r_end;
            seg_t = t_end;
            seg_i = i_end;
        };
    }

    fn push_range_op(ops: &mut Vec<DrawOp>, op: DrawOp) {
        match op {
            DrawOp::Rect(s, e, mode) => {
                if let Some(DrawOp::Rect(_, last_end, last_mode)) = ops.last_mut() {
                    if *last_end == s && *last_mode == mode {
                        *last_end = e;
                        return;
                    }
                }
            }
            DrawOp::Text(s, e) => {
                if let Some(DrawOp::Text(_, last_end)) = ops.last_mut() {
                    if *last_end == s {
                        *last_end = e;
                        return;
                    }
                }
            }
            DrawOp::Tri(s, e) => {
                if let Some(DrawOp::Tri(_, last_end)) = ops.last_mut() {
                    if *last_end == s {
                        *last_end = e;
                        return;
                    }
                }
            }
            DrawOp::Image(_) => {}
            DrawOp::Mask(_) => {}
            DrawOp::BackdropBlur(_) => {}
        }
        ops.push(op);
    }

    // ClipPath / ClipRRect 共用:压入一层 stencil mask + bbox scissor
    macro_rules! push_mask_clip {
        ($flat:expr, $idxs:expr, $bbox:expr) => {{
            clip_depth += 1;
            let flat_verts: Vec<f32> = $flat;
            let idxs: &[u32] = $idxs;
            let draw_index = if !flat_verts.is_empty() && !idxs.is_empty() {
                let idx = stencil_draws.len() as u32;
                stencil_draws.push(StencilDraw { vertices: flat_verts, indices: idxs.to_vec() });
                pending_stencil.push(StencilAction { draw: idx, level: clip_depth, increment: true });
                Some(idx)
            } else {
                None
            };
            path_draw_stack.push(draw_index);

            let bbox: Rect = $bbox;
            stack.push((cur_clip, true));
            cur_clip = Some(match cur_clip {
                Some(outer) => intersect_rect(outer, bbox),
                None => bbox,
            });
        }};
    }

    // 弹出 mask clip:深度的 -1 操作 + 恢复外层 scissor
    macro_rules! pop_mask_clip {
        () => {{
            if let Some(Some(draw)) = path_draw_stack.pop() {
                // 弹出时 -1,恢复外层的覆盖计数(兄弟 clip 不会互相污染)
                pending_stencil.push(StencilAction { draw, level: clip_depth, increment: false });
            }
            clip_depth = clip_depth.saturating_sub(1);
        }};
    }

    for cmd in &paint_list.commands {
        match cmd {
            PaintCommand::PushBlendMode(mode) => {
                blend_stack.push(cur_blend);
                cur_blend = *mode;
            }
            PaintCommand::PopBlendMode => {
                cur_blend = blend_stack.pop().unwrap_or(BlendMode::Normal);
            }
            PaintCommand::PushClip(r) => {
                close_segment!();
                stack.push((cur_clip, false));
                cur_clip = Some(match cur_clip {
                    Some(outer) => intersect_rect(outer, *r),
                    None => *r,
                });
            }
            PaintCommand::PushClipRRect { rect, radius } => {
                close_segment!();
                let (flat_verts, idxs) = rounded_rect_stencil_mesh(*rect, *radius);
                push_mask_clip!(flat_verts, &idxs, *rect);
            }
            PaintCommand::PopClip => {
                close_segment!();
                let (prev, is_mask) = stack.pop().unwrap_or((None, false));
                if is_mask {
                    pop_mask_clip!();
                }
                cur_clip = prev;
            }
            // PushClipPath — 路径裁剪(scissor 用 bbox 粗裁,GPU stencil 精确 mask)
            PaintCommand::PushClipPath { vertices, indices } => {
                close_segment!();
                let mut flat_verts: Vec<f32> = Vec::with_capacity(vertices.len() * 6);
                for v in vertices {
                    flat_verts.push(v.x);
                    flat_verts.push(v.y);
                    flat_verts.push(v.color.r);
                    flat_verts.push(v.color.g);
                    flat_verts.push(v.color.b);
                    flat_verts.push(v.color.a);
                }
                push_mask_clip!(flat_verts, indices, path_bounding_box(vertices));
            }
            PaintCommand::PopClipPath => {
                close_segment!();
                let (prev, is_mask) = stack.pop().unwrap_or((None, false));
                if is_mask {
                    pop_mask_clip!();
                }
                cur_clip = prev;
            }
            PaintCommand::Rect { rect, color, radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let start = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [color.r, color.g, color.b, color.a],
                        to: [color.r, color.g, color.b, color.a],
                        grad: [0.0; 4],
                        params: [*radius, 0.0, 0.0, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
                }
            }
            // **T0-2:BoxShadow** — 走同一条 Rect pipeline,shader 根据 blur_radius 做 SDF blur
            PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let start = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [color.r, color.g, color.b, color.a],
                        to: [color.r, color.g, color.b, color.a],
                        grad: [0.0; 4],
                        params: [*radius, 0.0, *blur_radius, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
                }
            }
            // **P2-1.4:InsetShadow** — 同一 rect pipeline,shader kind=3 做内侧 SDF 衰减
            PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let idx = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [color.r, color.g, color.b, color.a],
                        to: [color.r, color.g, color.b, color.a],
                        grad: [0.0; 4],
                        params: [*radius, 3.0, *blur_radius, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
                }
            }
            PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let idx = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [from.r, from.g, from.b, from.a],
                        to: [to.r, to.g, to.b, to.a],
                        grad: [start.x, start.y, end.x, end.y],
                        params: [*corner_radius, 1.0, 0.0, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
                }
            }
            PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let idx = rects.len() as u32;
                    rects.push(RectInstance {
                        rect: [rect.x, rect.y, rect.width, rect.height],
                        from: [from.r, from.g, from.b, from.a],
                        to: [to.r, to.g, to.b, to.a],
                        grad: [center.x, center.y, *radial_radius, 0.0],
                        params: [*corner_radius, 2.0, 0.0, 0.0],
                    });
                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
                }
            }
            // **P2-1.4b:背景模糊** — 在命令处切 pass,模糊此前已绘制内容
            PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
                if rect_intersects_clip(rect, cur_clip) {
                    let idx = backdrop_blurs.len() as u32;
                    backdrop_blurs.push(BackdropBlurSpec {
                        rect: *rect,
                        radius: *radius,
                        blur_radius: *blur_radius,
                        tint: [tint.r, tint.g, tint.b, tint.a],
                    });
                    ops.push(DrawOp::BackdropBlur(idx));
                }
            }
            // **P2-1.3:纹理 mask** — destination-in,只保留纹理 alpha 覆盖的区域
            PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
                if *alpha > 0.0 && rect_intersects_clip(rect, cur_clip) {
                    let gi = image_groups.len() as u32;
                    image_groups.push(ImageGroup {
                        texture_id: *texture_id,
                        instances: vec![TextInstance {
                            rect: [rect.x, rect.y, rect.width, rect.height],
                            // mode 2.0 = Alpha:alpha 取纹理 A 通道 × color.a
                            color: [1.0, 1.0, 1.0, alpha.clamp(0.0, 1.0)],
                            uv: *uv,
                            mode: 2.0,
                            _pad: [0.0; 3],
                        }],
                    });
                    ops.push(DrawOp::Mask(gi));
                }
            }
            PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
                if rect_intersects_clip(rect, cur_clip) {
                    // **像素对齐**:text glyph atlas 按物理分辨率栅格化(每个 glyph 一个 texel=一个物理像素),
                    // rect 在逻辑坐标上做 round(x*dpr)/dpr → 确保 UV 采样 1:1 对齐 atlas texel → 文字锐
                    let snap = |v: f32| (v * dpr).round() / dpr;
                    let inst = TextInstance {
                        rect: [
                            snap(rect.x),
                            snap(rect.y),
                            snap(rect.x + rect.width) - snap(rect.x),
                            snap(rect.y + rect.height) - snap(rect.y),
                        ],
                        color: [color.r, color.g, color.b, color.a],
                        uv: *uv,
                        mode: match mode {
                            TextureMode::Mask => 0.0,
                            TextureMode::Color => 1.0,
                        },
                        _pad: [0.0; 3],
                    };
                    if *texture_id == 0 {
                        let start = texts.len() as u32;
                        texts.push(inst);
                        push_range_op(&mut ops, DrawOp::Text(start, start + 1));
                    } else {
                        // 阶段 6(图片):texture_id != 0 = ImageWidget 的全图 quad。
                        // 只有「紧邻的上一笔也是同纹理图片」才合并成组 —— 中间插入
                        // rect/text 后必须新开一组,否则绘制顺序无法恢复。
                        let reuse_group = ops
                            .last()
                            .and_then(|op| match op {
                                DrawOp::Image(gi) => Some(*gi),
                                _ => None,
                            })
                            .filter(|&gi| image_groups[gi as usize].texture_id == *texture_id);
                        if let Some(gi) = reuse_group {
                            image_groups[gi as usize].instances.push(inst);
                        } else {
                            let gi = image_groups.len() as u32;
                            image_groups.push(ImageGroup { texture_id: *texture_id, instances: vec![inst] });
                            ops.push(DrawOp::Image(gi));
                        }
                    }
                }
            }
            // Stage T1:Triangles — 合并所有 path fill 的 earcut 输出
            // 每个 command 的 indices 加 base offset(避免不同 PathBuilder 的 triangles 互相引用)
            PaintCommand::Triangles { vertices, indices } => {
                let idx_start = tri_indices.len() as u32;
                // vertices 扁平化为 [x, y, r, g, b, a]
                for v in vertices {
                    tri_vertices.push(v.x);
                    tri_vertices.push(v.y);
                    tri_vertices.push(v.color.r);
                    tri_vertices.push(v.color.g);
                    tri_vertices.push(v.color.b);
                    tri_vertices.push(v.color.a);
                }
                // indices 加 base(让每个 command 的顶点全局唯一)
                for &idx in indices {
                    tri_indices.push(tri_base_vertex + idx);
                }
                tri_base_vertex += vertices.len() as u32;
                if !vertices.is_empty() && !indices.is_empty() {
                    push_range_op(&mut ops, DrawOp::Tri(idx_start, tri_indices.len() as u32));
                }
            }
            // Stage T2:PaintCommand::Text — core 层 Widget 要画文字的高层命令
            // 让 paint_text_line 展开成 TexturedRect → 逐个收集
            PaintCommand::Text { text, range, font_size, color, position, max_width } => {
                let mut temp_list = PaintList::new();
                crate::text::paint_text_span(text, *range, *font_size, *color, *position, &mut temp_list, *max_width);
                // 展开后的 TexturedRect 逐个收集
                let snap = |v: f32| (v * dpr).round() / dpr;
                let start = texts.len() as u32;
                for cmd in temp_list.commands {
                    if let PaintCommand::TexturedRect { rect, color, uv, texture_id: 0, .. } = cmd {
                        if rect_intersects_clip(&rect, cur_clip) {
                            texts.push(TextInstance {
                                rect: [
                                    snap(rect.x),
                                    snap(rect.y),
                                    snap(rect.x + rect.width) - snap(rect.x),
                                    snap(rect.y + rect.height) - snap(rect.y),
                                ],
                                color: [color.r, color.g, color.b, color.a],
                                uv,
                                // glyph atlas 永远走 mask 采样
                                mode: 0.0,
                                _pad: [0.0; 3],
                            });
                        }
                    }
                }
                if texts.len() as u32 > start {
                    push_range_op(&mut ops, DrawOp::Text(start, texts.len() as u32));
                }
            }
        }
    }
    // 尾段
    close_segment!();
    let _ = (seg_r, seg_t, seg_i); // 尾段关闭后不再读 — 显式消费消除 unused_assignments

    // P2-1.5:合并相邻且 scissor/stencil 状态相同的段。
    // 常见于 PopClip 后立刻 PushClip 同一矩形(虚拟列表/滚动容器),
    // 合并后减少 set_scissor / pipeline 状态切换;跨 mask 操作的段不合并。
    let mut merged: Vec<ClipSegment> = Vec::with_capacity(segments.len());
    for seg in segments.drain(..) {
        let can_merge = merged.last().is_some_and(|prev: &ClipSegment| {
            prev.scissor == seg.scissor && prev.stencil_level == seg.stencil_level && seg.stencil_actions.is_empty()
        });
        if can_merge {
            let prev = merged.last_mut().expect("checked non-empty");
            for op in &seg.ops {
                push_range_op(&mut prev.ops, *op);
            }
            prev.rect_range.1 = seg.rect_range.1;
            prev.text_range.1 = seg.text_range.1;
            prev.image_range.1 = seg.image_range.1;
        } else {
            merged.push(seg);
        }
    }

    (rects, texts, image_groups, merged, tri_vertices, tri_indices, stencil_draws, backdrop_blurs)
}

/// 阶段 B1:helper — 构造 rect batch bind group(0 rect → None)
///
/// 阶段 B1.5:**per-layer buffer pool** — header(16B 固定)永驻,instances(grow-only)
/// 容量够就复用,只 `queue.write_buffer` 覆盖。稳态 0 alloc/帧/layer。
///
/// **关键教训**:**不能所有 layer 共享一个 pool buffer** — wgpu 的
// `queue.write_buffer` 是 staged + 下次 submit 执行;同一 submit 内多个 layer
// 依次 write_buffer 同一 buffer → 后写覆盖先写 → 所有 layer 的 draw 都用
// 最后一个 layer 的数据 → UI 元素放大/错乱。
// =================================================================
// 子模块
// =================================================================
mod batches;
mod composition;
mod render;
mod setup;
#[cfg(test)]
mod tests;

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

    fn ms(v: u64) -> Duration {
        Duration::from_millis(v)
    }

    /// 第一帧不许编出一个间隔:这条与 `mgui_video::timing` 那一格是同一条家规的两个入口,
    /// 而它坏了的形式很难查 —— 起始那一次会话启动成本会被读成"节奏里有一个慢帧",
    /// 而那恰恰是本轮唯一还活着的 >60ms 事件(起始成批),不能被假样本冒充。
    #[test]
    fn the_first_present_invents_no_gap() {
        let mut s = PresentStats::default();
        s.record(1_000, 2_000, None, "Fifo", 2);
        assert_eq!(s.presents, 1, "present 本身要记上:屏幕上确实出新内容了");
        assert_eq!(s.gaps, 0, "没有前驱就不许有间隔");
        assert_eq!((s.last_gap_ns, s.gap_sum_ns, s.gap_max_ns), (0, 0, 0));
        assert_eq!(s.mean_gap_ns(), 0, "均值给 0 只允许配着 gaps == 0 读");

        s.record(1_000, 2_000, Some(ms(33)), "Fifo", 2);
        assert_eq!(s.gaps, 1, "第二个 present 才产生第一个间隔");
        assert_eq!(s.last_gap_ns, 33_000_000);
    }

    /// 间隔的三件事(个数 / 最大 / 均值)必须各自独立:只报均值会把"每 8 帧一顿"读成完美。
    #[test]
    fn gap_stats_tally_count_max_and_mean_separately() {
        let mut s = PresentStats::default();
        s.record(0, 0, None, "Fifo", 2);
        for gap in [ms(16), ms(33), ms(99)] {
            s.record(0, 0, Some(gap), "Fifo", 2);
        }
        assert_eq!(s.presents, 4);
        assert_eq!(s.gaps, 3);
        assert_eq!(s.gap_max_ns, 99_000_000, "最坏那一顿必须单独看得见,不能被均值抹平");
        assert_eq!(s.mean_gap_ns(), (16 + 33 + 99) * 1_000_000 / 3);
    }

    /// "等 vsync"与"提交"是两问:前者是显示配额(FIFO 下正常就该有),后者是我们自己的成本。
    /// 合成一个字段就会得到"present 很慢"这种无法归因的读数。
    #[test]
    fn waiting_for_the_display_and_submitting_are_two_different_numbers() {
        let mut s = PresentStats::default();
        s.record(4_000_000, 300_000, None, "Fifo", 2);
        s.record(3_000_000, 200_000, Some(ms(33)), "Fifo", 2);
        assert_eq!(s.wait_ns, 7_000_000);
        assert_eq!(s.submit_ns, 500_000);
        assert_ne!(s.wait_ns, s.submit_ns, "两问合一之后,任何一条归因都无从下手");
    }

    /// 空串 = 这一路**没接线**,不是"这台机器一次都没 present"。这条区分是给读表的工具用的:
    /// 多窗口宿主的 slot 与软件回退都会给全零,而那两种"零"的含义不同。
    #[test]
    fn an_unwired_path_says_so_instead_of_looking_idle() {
        let unwired = PresentStats::default();
        assert_eq!(unwired.present_mode, "", "没接线的形式必须是可识别的,而不是恰好等于一个合法的零");
        assert_eq!(unwired.presents, 0);
        let mut wired = PresentStats::default();
        wired.record(1, 1, None, "Mailbox", 1);
        assert_eq!((wired.present_mode, wired.max_frame_latency), ("Mailbox", 1));
        assert_ne!(PresentStats::default().present_mode, wired.present_mode);
    }
}