Skip to main content

mgui_runtime/renderer/
mod.rs

1use mgui_core::paint::{BlendMode, TextureMode};
2use mgui_core::Rect;
3use mgui_core::{effect_flags, FramePaint, LayerEffect, LayerId, LayerPaint, PaintCommand, PaintList, RRectDef, Size};
4use std::cell::RefCell;
5use std::collections::HashMap;
6use std::rc::Rc;
7use std::time::Duration;
8
9use wgpu::util::DeviceExt;
10
11/// 阶段 B1:rect 批处理 — batch header(per-layer 共享)
12/// 屏幕逻辑尺寸 + instance 数量;**16-align**:`vec2` 后接 `u32` + `vec2 pad` 凑齐 16 字节。
13#[repr(C)]
14#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
15pub(crate) struct RectBatchUniform {
16    screen_size: [f32; 2], // 0..8
17    count: u32,            // 8..12
18    _pad: [f32; 1],        // 12..16 (整体 16-align)
19}
20
21/// 阶段 B1:rect 批处理 — 每实例数据
22/// size = 5 × vec4 = 80 字节(WGSL 16-align 兼容)。
23///
24/// - 普通 Rect:from = to = color,params[1] = 0
25/// - BoxShadow:params[2] = blur_radius
26/// - LinearGradient:grad = (start.xy, end.xy),params[1] = 1
27/// - RadialGradient:grad = (center.xy, radius, 0),params[1] = 2
28#[repr(C)]
29#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
30pub(crate) struct RectInstance {
31    rect: [f32; 4],
32    from: [f32; 4],
33    to: [f32; 4],
34    grad: [f32; 4],
35    /// [corner_radius, kind, blur_radius, pad]
36    params: [f32; 4],
37}
38
39/// 阶段 B2:text 批处理 — batch header
40#[repr(C)]
41#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
42pub(crate) struct TextBatchUniform {
43    screen_size: [f32; 2], // 0..8
44    count: u32,            // 8..12
45    _pad: [f32; 1],        // 12..16 (整体 16-align)
46}
47
48/// 阶段 B2:text 批处理 — 每实例数据
49/// size = 16(rect vec4) + 16(color vec4) + 16(uv vec4) + 16(mode vec4) = 64 字节
50/// 16-align OK。
51#[repr(C)]
52#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
53pub(crate) struct TextInstance {
54    rect: [f32; 4],  // 0..16
55    color: [f32; 4], // 16..32
56    uv: [f32; 4],    // 32..48
57    /// 纹理采样模式(vec4.x):0.0 = Mask(alpha 在纹理 R 通道,glyph/SVG tint),
58    /// 1.0 = Color(straight RGBA 全彩纹理,SVG 全彩 / PNG 图片)
59    mode: f32, // 48..52
60    _pad: [f32; 3],  // 52..64
61}
62
63// 阶段 B2:被 TextInstance + TextBatchUniform 替代(批处理)
64// 旧 TextUniform 已删除(deprecated by B2,见 commit log)
65
66/// 阶段 4-B + 4-D:blit uniform(全屏 blit 用,带 layer offset/size)
67///
68/// 阶段 5:扩展为携带 effect 字段:
69/// - effect_flags: bit field(HAS_TRANSFORM / HAS_OPACITY / HAS_CLIP)
70/// - opacity / rotation / scale / translate_x / translate_y / clip_radius
71///
72/// **WGSL 对齐**: u32 4 字节,f32 4 字节;WGSL 会按 16-align 整体 struct。
73#[repr(C)]
74#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
75pub(crate) struct BlitUniform {
76    offset: [f32; 2], // 0..8    layer 在父 layer 内的 logical 位置
77    size: [f32; 2],   // 8..16   layer 的 logical size
78    screen: [f32; 2], // 16..24  surface logical 尺寸
79    // ========== 阶段 5:effect 字段 ==========
80    effect_flags: u32, // 24..28  bit field
81    opacity: f32,      // 28..32
82    rotation: f32,     // 32..36
83    scale_x: f32,      // 36..40  HAS_TRANSFORM:x 轴缩放
84    translate_x: f32,  // 40..44
85    translate_y: f32,  // 44..48
86    clip_radius: f32,  // 48..52
87    scale_y: f32,      // 52..56  HAS_TRANSFORM:y 轴缩放(布局为 16-align 的填充位)
88    // bugfix(Transform 旋转被裁):quad 覆盖区域。无旋转时 = offset/size;
89    // HAS_TRANSFORM 时 = 旋转+缩放后的 AABB(中心不变,尺寸按 |cos|/|sin| 扩大),
90    // 否则旋转超出原矩形的部分会被 quad 光栅化裁掉。
91    quad_offset: [f32; 2], // 56..64
92    quad_size: [f32; 2],   // 64..72
93    phys_screen: [f32; 2], // 72..80 surface 物理像素尺寸
94    // ========== 嵌套 layer 合成:局部坐标 → surface 的完整仿射 ==========
95    /// [a, b, c, d]:x' = a*x + b*y + tx;y' = c*x + d*y + ty
96    affine: [f32; 4], // 80..96
97    affine_translate: [f32; 2], // 96..104
98    _affine_pad: [f32; 2],      // 104..112(16-align)
99    /// 两层裁剪(祖先 + 自己的内两层),surface 逻辑坐标 AABB
100    clip_rect0: [f32; 4], // 112..128
101    clip_rect1: [f32; 4],       // 128..144
102    /// [radius0, radius1, count, unused]
103    clip_params: [f32; 4], // 144..160
104}
105// struct size = 160 bytes (16-aligned)
106
107/// 阶段 4-B:每个 layer 的 GPU cache(MSAA texture + resolve texture)
108struct LayerGpuCache {
109    /// resolve target texture(单采样;blit 采样 + 背景模糊 snapshot 复制源)
110    resolve_texture: wgpu::Texture,
111    /// resolve target view(sample_count=1,blit 采样这里)
112    resolve_view: wgpu::TextureView,
113    /// 创建时的物理尺寸;resize 时重建
114    cached_size: (u32, u32),
115}
116
117/// 可跨窗口复用的 Renderer GPU 资源(pipeline / bind group layout / blit sampler /
118/// glyph atlas / 图片纹理缓存)。
119///
120/// layer 缓存与 batch buffer 仍由各窗口 Renderer 独立持有(LayerId 只在单树内唯一)。
121#[derive(Clone)]
122pub struct RendererShared {
123    /// Normal / Multiply / Screen / Add 各一个矩形 pipeline
124    rect_pipelines: [wgpu::RenderPipeline; 4],
125    rect_bgl: wgpu::BindGroupLayout,
126    text_pipeline: wgpu::RenderPipeline,
127    text_bgl: wgpu::BindGroupLayout,
128    /// 纹理 mask(destination-in)
129    text_pipeline_mask: wgpu::RenderPipeline,
130    text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
131    tri_pipeline: wgpu::RenderPipeline,
132    tri_bgl: wgpu::BindGroupLayout,
133    /// ClipPath stencil mask 写入(推入 +1 / 弹出 -1,front/back 同步)
134    tri_pipeline_stencil_inc: wgpu::RenderPipeline,
135    tri_pipeline_stencil_dec: wgpu::RenderPipeline,
136    rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
137    text_pipeline_stencil_test: wgpu::RenderPipeline,
138    tri_pipeline_stencil_test: wgpu::RenderPipeline,
139    blit_pipeline: wgpu::RenderPipeline,
140    blit_bgl: wgpu::BindGroupLayout,
141    blit_sampler: wgpu::Sampler,
142    /// P2-1.4b:背景模糊(圆角遮罩 + 13-tap,复用 blit_sampler)
143    backdrop_pipeline: wgpu::RenderPipeline,
144    backdrop_bgl: wgpu::BindGroupLayout,
145    format: wgpu::TextureFormat,
146    atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
147    image_cache: Rc<RefCell<ImageTextureCache>>,
148}
149
150/// 跨窗口共享的图片纹理缓存。
151#[derive(Default)]
152pub(crate) struct ImageTextureCache {
153    textures: HashMap<u32, ImageTextureEntry>,
154    clock: u64,
155    /// 多窗口共享模式下由 host 统一管理预算,暂不做单帧 eviction。
156    evict_enabled: bool,
157}
158
159impl RendererShared {
160    pub fn format(&self) -> wgpu::TextureFormat {
161        self.format
162    }
163
164    /// 多窗口 host 在一个渲染周期后调用:保护所有窗口最近一帧使用的纹理,
165    /// 超预算时淘汰其余最旧纹理。
166    pub fn evict_images(&self, protected: &std::collections::HashSet<u32>) {
167        self.image_cache.borrow_mut().evict_to_budget(protected);
168    }
169}
170
171impl ImageTextureCache {
172    fn evict_to_budget(&mut self, protected: &std::collections::HashSet<u32>) {
173        let budget = IMAGE_TEXTURE_BUDGET_BYTES;
174        let mut total: u64 = self.textures.values().map(|e| e.bytes).sum();
175        if total <= budget {
176            return;
177        }
178        let mut candidates: Vec<(u32, u64, u64)> = self
179            .textures
180            .iter()
181            .filter(|(id, _)| !protected.contains(id))
182            .map(|(&id, e)| (id, e.last_used, e.bytes))
183            .collect();
184        candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
185        for (id, _, bytes) in candidates {
186            if total <= budget {
187                break;
188            }
189            self.textures.remove(&id);
190            total = total.saturating_sub(bytes);
191        }
192        if total > budget {
193            log::warn!(
194                target: "mgui_startup",
195                "shared image cache uses {} MiB (budget {} MiB); all remaining textures are in use",
196                total / (1024 * 1024),
197                budget / (1024 * 1024)
198            );
199        }
200    }
201}
202
203#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
204pub struct PresentStats {
205    /// 真 present 出去的帧数(被 `Outdated` / `Occluded` / 校验错误挡掉的那些**不占号**:
206    /// 那几种情况下屏幕上没有新内容,把它们算进"节奏"就是把失败读成正常)。
207    pub presents: u64,
208    /// 累计"等 vsync"的时间(`get_current_texture` 阻塞那一段)。这是 FIFO 呈现的**配额**:
209    /// 它涨说明我们在等显示,而不是在等 GPU。
210    pub wait_ns: u64,
211    /// 累计 `queue.present` 调用本身的时间。
212    pub submit_ns: u64,
213    /// 记过多少个"相邻两次 present 的间隔"。语义与 `mgui_video::StageCounters::frames_measured`
214    /// 同源:**没有前驱的那一次不许编出一个间隔**,所以它最多等于 `presents − 1`。
215    pub gaps: u64,
216    pub gap_sum_ns: u64,
217    pub gap_max_ns: u64,
218    /// 最近一个间隔(给"每帧读一次并自己组分布"的工具用,例如 showcase 的 cadence 运行器)。
219    pub last_gap_ns: u64,
220    /// 呈现模式的**实际生效值**(从 `SurfaceConfiguration` 读,不是文档里的默认)。
221    /// 之所以回显它:节奏这件事的全部解释都依赖"到底是 FIFO 还是 IMMEDIATE、队列允许几深",
222    /// 读数与配置分两处写就一定分叉(本仓为这类分叉付过学费)。
223    ///
224    /// **空串的含义是"这一路没接线"**(软件回退、或多窗口宿主的 slot 还没接上共享 context),
225    /// 而不是"这台机器一次都没 present"。接线之后它一定是 `Fifo` / `Mailbox` 这类实际模式名,
226    /// 所以 `presents == 0` 与 `present_mode == ""` 一起读才分得开"没量到"与"量了但没帧"。
227    pub present_mode: &'static str,
228    /// `desired_maximum_frame_latency` 的实际值(同上)。
229    pub max_frame_latency: u32,
230    /// 累计 `present_gpu_frame` 入口 → `queue.present` 返回的 CPU 耗时(纳秒)。
231    /// **不是完整端到端**:不含 `app.frame()` / CPU paint / `about_to_wait` / 事件循环调度。
232    pub present_path_cpu_ns: u64,
233    /// 累计 `redraw` 入口 → present 返回的 CPU 耗时(纳秒)。多窗口未接线时为 0。
234    pub redraw_cpu_ns: u64,
235    /// 最近一次的两个耗时(给 cadence 逐帧采样用)。
236    pub last_present_path_cpu_ns: u64,
237    pub last_redraw_cpu_ns: u64,
238    /// A/B 2 必测项 1:累计 frame_start(`redraw` 入口)→ acquire 完成。
239    /// 实验组这一格**包含**提前上传,机械变长不是退化,只作调用顺序的自证;
240    /// CPU paint 与 vsync 等待在两组里都落在这一段,口径一致。
241    pub frame_to_acquire_ns: u64,
242    /// A/B 2 必测项 2:累计 acquire 完成 → `queue.present` 返回(含 Pass1/Pass2 submit)。
243    /// 实验组上传被移出这一段,机械变短没有判别力(规格明确),不能单独拿来判胜负。
244    pub acquire_to_submit_ns: u64,
245    pub last_frame_to_acquire_ns: u64,
246    pub last_acquire_to_submit_ns: u64,
247}
248
249impl PresentStats {
250    /// 记一次成功的 present。`gap` = 与上一次 present 的间隔;第一次传 `None`。
251    ///
252    /// 分成这个方法而不是让调用方自己加字段,是为了把"第一帧不产生样本"这条家规放在**一处**
253    /// 实现(另一处是 `mgui_video::timing`),调用方只需要回答"有没有前驱"。
254    pub fn record(&mut self, wait_ns: u64, submit_ns: u64, gap: Option<Duration>, mode: &'static str, latency: u32) {
255        self.presents = self.presents.saturating_add(1);
256        self.wait_ns = self.wait_ns.saturating_add(wait_ns);
257        self.submit_ns = self.submit_ns.saturating_add(submit_ns);
258        self.present_mode = mode;
259        self.max_frame_latency = latency;
260        if let Some(gap) = gap {
261            let ns = gap.as_nanos() as u64;
262            self.gaps = self.gaps.saturating_add(1);
263            self.gap_sum_ns = self.gap_sum_ns.saturating_add(ns);
264            self.gap_max_ns = self.gap_max_ns.max(ns);
265            self.last_gap_ns = ns;
266        }
267    }
268
269    /// 间隔均值(纳秒)。没有样本时给 0 —— 调用方要读 [`Self::gaps`],不是读这个数。
270    pub fn mean_gap_ns(&self) -> u64 {
271        self.gap_sum_ns.checked_div(self.gaps).unwrap_or(0)
272    }
273}
274
275/// 一条 `pending_texture` 声明的**处置记录**:三种 outcome 全部记录。
276///
277/// `Reuse` 也必须留下记录:`register_outcome(seq)` 是四段序号链路的第四段。只记真实
278/// 上传时,取到 N 帧却只传了 N/10 帧的运行里那 9 成声明没有落点,
279/// 「dirty layer 重画了但声明旧像素」与「根本没进 PaintList」两种坏法分不开。
280/// 字节数刻意分两栏:`source_bytes` 是按 `stride`/layout 实际参与读取的字节
281/// (`ImageData::min_len()`),`active_bytes` 是 `width * height * 4` 的有效像素规模。
282pub(crate) struct TextureUploadRecord {
283    pub outcome: mgui_core::image::TextureUpdate,
284    /// `Reuse` / 上传失败时为 0:只有真实上传才计字节与 `upload_count`。
285    pub source_bytes: u64,
286    pub active_bytes: u64,
287    /// 只包 `queue.write_texture` 那一段,不含 drain 遍历与 create_texture/view/sampler。
288    pub write_ns: u64,
289    /// `write_texture` 的 Extent3d 宽高。A/B 1 的**生效校验**靠它:实验组必须等于
290    /// 显式给定的目标尺寸,光看 `source_bytes` 下降还可能被帧数变化蒙混过去。
291    pub width: u32,
292    pub height: u32,
293    pub meta: Option<mgui_core::paint::TextureFrameMeta>,
294}
295
296impl TextureUploadRecord {
297    /// 日志里的 outcome 编号:0=无 / 1=Reuse / 2=UpdateContent / 3=Recreate。
298    pub(crate) fn outcome_code(&self) -> u8 {
299        use mgui_core::image::TextureUpdate;
300        match self.outcome {
301            TextureUpdate::Reuse => 1,
302            TextureUpdate::UpdateContent => 2,
303            TextureUpdate::Recreate => 3,
304        }
305    }
306}
307
308#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
309pub struct RenderStats {
310    /// 本帧实际重画的 layer 数
311    pub layers_painted: u32,
312    /// 实际提交的 scissor 段数
313    pub segments: u32,
314    /// paint pass + stencil mask + layer blit 的 draw 总数
315    pub draw_calls: u32,
316    /// 跨 layer 复用 scratch 的总字节(MSAA + stencil + snapshot)
317    pub scratch_bytes: u64,
318    /// 持久 layer resolve texture 的总字节
319    pub layer_texture_bytes: u64,
320    /// **纹理上传段**的耗时(纳秒):`drain_pending_textures` 那一步,也就是图片/SVG 纹理
321    /// 首次注册、内容更新(`queue.write_texture`)与重建(`device.create_texture`)的全部成本。
322    ///
323    /// 为什么要单独一段而不是并进 `paint_ns`:视频每一帧都走 `UpdateContent`(同一张
324    /// texture_id 换内容),所以这一段是"逐帧像素进 GPU 的过路费",与画多少 layer 无关;
325    /// 2026-11-10 之前它在产品里完全不可读,于是"上传贵不贵"只能靠现场搭探针回答。
326    /// 口径与 `mgui_core::frame::FrameStats::COLLECTING` 绑定:`profiling` 关着时它恒 0
327    /// (`Lap` 不读表),那种时候**不许**把 0 读成"上传不要钱"。
328    pub upload_ns: u64,
329    /// 只累计真实上传分支里的 `queue.write_texture`(`Reuse` 遍历不算进单次上传成本)。
330    pub upload_write_ns: u64,
331    /// 最近一次真实上传的 `write_texture` 尺寸(A/B 1 生效校验:实验组应等于目标尺寸)。
332    pub last_upload_width: u32,
333    pub last_upload_height: u32,
334    /// 本帧真实上传的源缓冲字节数(按 stride/layout 实际参与读取的量)
335    pub upload_source_bytes: u64,
336    /// 本帧真实上传的有效像素字节数(width * height * 4)
337    pub upload_active_bytes: u64,
338    /// 本帧真实上传次数
339    pub upload_count: u32,
340    /// 本帧带视频帧元数据的声明数 / 三种 outcome 各多少次。
341    pub texture_decl_count: u32,
342    pub texture_reuse_count: u32,
343    pub texture_update_count: u32,
344    pub texture_recreate_count: u32,
345    /// 声明的 `sequence` 落后于 paint 时共享格最新序号的次数 ——
346    /// 「PaintList 重新生成了但携带旧像素」的直接计数。
347    pub stale_decl_count: u32,
348    /// 声明的元数据 `synced_seq == 0` 的次数(RO 从未同步过这一帧)。
349    pub unsynced_decl_count: u32,
350    /// 最近一次带帧元数据的**声明**:sequence / generation / 帧年龄(ns)。
351    /// 帧年龄只在真实上传那一次落样本(`last_frame_encoder != 0`)。
352    pub last_frame_sequence: u64,
353    pub last_frame_generation: u64,
354    pub last_frame_age_ns: u64,
355    /// 四段序号链路的第 2 / 3 / 4 段(第 1 段就是 `last_frame_sequence` 声明的帧号)。
356    pub last_frame_synced_seq: u64,
357    pub last_frame_latest_seq: u64,
358    /// 1=Reuse / 2=UpdateContent / 3=Recreate / 0=本帧无带元数据的声明。
359    pub last_frame_outcome: u8,
360    /// 承载这次上传 copy 的 submit:1 = Pass1,2 = Pass2,0 = 本帧无真实上传
361    pub last_frame_encoder: u8,
362}
363
364pub struct Renderer {
365    /// Normal / Multiply / Screen / Add 各一个矩形 pipeline
366    rect_pipelines: [wgpu::RenderPipeline; 4],
367    rect_bgl: wgpu::BindGroupLayout,
368    text_pipeline: wgpu::RenderPipeline,
369    text_bgl: wgpu::BindGroupLayout,
370    /// 纹理 mask(destination-in)
371    text_pipeline_mask: wgpu::RenderPipeline,
372    text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
373    /// Stage T1: triangle pipeline(PathBuilder.fill → earcut → vertex/index buffer)
374    tri_pipeline: wgpu::RenderPipeline,
375    tri_bgl: wgpu::BindGroupLayout,
376    /// **ClipPath GPU stencil** — 4 个测试变体 + 2 个 mask 写入变体:
377    /// 1. `tri_pipeline_stencil_inc/dec`:只写 stencil,color=NONE(推入 +1 / 弹出 -1)
378    /// 2. `rect/text/tri_pipeline_stencil_test`:stencil Equal(当前嵌套深度)
379    tri_pipeline_stencil_inc: wgpu::RenderPipeline,
380    tri_pipeline_stencil_dec: wgpu::RenderPipeline,
381    rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
382    text_pipeline_stencil_test: wgpu::RenderPipeline,
383    tri_pipeline_stencil_test: wgpu::RenderPipeline,
384    /// 缓存的 GPU glyph atlas(多窗口共享同一 texture/view/sampler)
385    atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
386    /// 阶段 4-B:layer → GPU texture cache(每 layer 一张全屏 texture)
387    layer_cache: HashMap<LayerId, LayerGpuCache>,
388    /// P2:frame 内活跃 layer id 复用集合(避免每帧分配 HashSet)
389    active_layer_ids: std::collections::HashSet<LayerId>,
390    /// P2:frame 内 layer 逻辑尺寸复用表(composition 用)
391    frame_layer_sizes: HashMap<LayerId, Size>,
392    /// P2:跨帧复用的 composition scratch(by_id/memo/visiting 容器)
393    composition_scratch: mgui_core::CompositionScratch,
394    /// 阶段 4-B:blit pipeline(把 layer texture 画到 surface)
395    blit_pipeline: wgpu::RenderPipeline,
396    blit_bgl: wgpu::BindGroupLayout,
397    blit_sampler: wgpu::Sampler,
398    /// P2-1.4b:背景模糊(圆角遮罩 + 13-tap,复用 blit_sampler)
399    backdrop_pipeline: wgpu::RenderPipeline,
400    backdrop_bgl: wgpu::BindGroupLayout,
401    /// 阶段 2-E:surface 格式(layer texture 与 pipeline render target 保持一致)
402    format: wgpu::TextureFormat,
403    /// 阶段 B4:GPU 端 timestamp profiler(None = 设备不支持 TIMESTAMP_QUERY)
404    pub gpu_profiler: Option<crate::gpu_profiler::GpuProfiler>,
405    /// 阶段 B1.5:**per-layer** batch buffer pool
406    ///
407    /// **关键**:每个 layer 独立 buffer — **不能所有 layer 共享一个 pool buffer**!
408    /// wgpu 的 `queue.write_buffer` 是 staged + 下次 submit 时执行;
409    /// 同一 submit 内多个 layer 依次 write_buffer 同一 buffer → 后写覆盖先写,
410    /// 所有 layer 的 draw 都用最后一个 layer 的数据 → UI 错乱(元素放大/错位)。
411    /// 阶段 6(图片):value 同 LayerBatchPool;key = (LayerId, texture_id) —
412    /// text 用 texture_id 0,每张图片一个独立 key(纹理不同 buffer 必须隔离)
413    batch_pools: HashMap<(LayerId, u32), LayerBatchPool>,
414    /// 阶段 6(图片):图片纹理缓存(多窗口共享;按 ImageWidget 的 texture_id 索引)
415    image_cache: Rc<RefCell<ImageTextureCache>>,
416    /// P2-1.5:跨 layer 复用的临时纹理(按物理尺寸 key;view 持有 texture 引用)
417    msaa_scratch: HashMap<(u32, u32), wgpu::TextureView>,
418    stencil_scratch: HashMap<(u32, u32), wgpu::TextureView>,
419    snapshot_scratch: HashMap<(u32, u32), (wgpu::Texture, wgpu::TextureView)>,
420    /// P2-1.5:上一帧的绘制统计(draw calls / scratch / layer texture)
421    last_stats: RenderStats,
422    /// A/B 2:提前上传的记录 `(处置记录, 整段 drain 耗时 ns)`。
423    /// `upload_pending()` 在 acquire 前写入,`render()` 消费;`None` = 走原来的
424    /// render 内 drain(对照组,与实验前逐字节一致)。两组都用同一份记录填 `RenderStats`,
425    /// 所以上传统计、四段序号、帧年龄的口径不随调用位置漂移。
426    pending_upload: Option<(Vec<TextureUploadRecord>, u64)>,
427}
428
429/// 单张图片纹理的 GPU 缓存条目
430pub(crate) struct ImageTextureEntry {
431    /// 仅用于保持 GPU 纹理存活(view 是否持有引用不应依赖)
432    pub _texture: wgpu::Texture,
433    pub view: wgpu::TextureView,
434    pub sampler: wgpu::Sampler,
435    /// 最近一次被 PaintList 声明使用的时钟
436    pub last_used: u64,
437    /// 纹理字节数(width * height * 4),用于预算淘汰
438    pub bytes: u64,
439    /// 源数据的 **`Rc` 身份**(0.4 V-P0-1)。必须把 `Rc` 本身留住:只存地址会让
440    /// 释放后被复用的地址把"另一张图"误判成"同一帧"。
441    pub source: Rc<mgui_core::image::ImageData>,
442    /// 纹理当前尺寸;`plan_texture_update` 据此判 `UpdateContent` 还是 `Recreate`。
443    pub size: (u32, u32),
444}
445
446/// 图片纹理预算(256 MiB)
447pub const IMAGE_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
448
449/// 单窗口所有 layer resolve texture 的总预算(256 MiB)。
450pub use setup::LAYER_TEXTURE_BUDGET_BYTES;
451
452pub use mgui_core::inspect::ImageTextureStats;
453
454impl Renderer {
455    /// P2-1.5:上一帧绘制统计(draw calls / segment / scratch 内存)
456    pub fn last_stats(&self) -> RenderStats {
457        self.last_stats
458    }
459
460    /// 当前图片纹理数量/字节数与预算
461    pub fn image_texture_stats(&self) -> ImageTextureStats {
462        let cache = self.image_cache.borrow();
463        ImageTextureStats {
464            count: cache.textures.len(),
465            bytes: cache.textures.values().map(|e| e.bytes).sum(),
466            budget_bytes: IMAGE_TEXTURE_BUDGET_BYTES,
467        }
468    }
469}
470
471/// 阶段 B1.5:单 layer 的 batch buffer pool(9 个 buffer — 含 tri + stencil mask)
472struct LayerBatchPool {
473    rect_header: Option<wgpu::Buffer>,
474    rect_instances: Option<wgpu::Buffer>,
475    text_header: Option<wgpu::Buffer>,
476    text_instances: Option<wgpu::Buffer>,
477    /// Stage T1:tri buffers(vertex + index + uniform)
478    tri_vertex: Option<wgpu::Buffer>,
479    tri_index: Option<wgpu::Buffer>,
480    tri_uniform: Option<wgpu::Buffer>,
481    /// **T0-1.5:ClipPath stencil** — PushClipPath path triangles 的 vertex/index buffer
482    /// 每帧 write_buffer 覆盖内容;grow-only 容量够就复用
483    stencil_vertex: Option<wgpu::Buffer>,
484    stencil_index: Option<wgpu::Buffer>,
485}
486
487/// GPU atlas 资源 + 缓存的 size
488pub(crate) struct AtlasGpu {
489    texture: wgpu::Texture,
490    view: wgpu::TextureView,
491    sampler: wgpu::Sampler,
492    /// 创建时的 atlas 尺寸;尺寸变化时重建
493    cached_size: (u32, u32),
494}
495
496pub(crate) struct RectBatch {
497    bg: wgpu::BindGroup,
498}
499
500/// Stage T1:triangle pipeline — 每 layer 一个批次(所有 PathBuilder.fill 合并画)
501pub(crate) struct TriBatch {
502    bg: wgpu::BindGroup,
503}
504
505/// Stage T1:triangle uniform(跟 RectBatchUniform 同样的 16 bytes pattern)
506#[repr(C)]
507#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
508struct TriUniform {
509    screen_size: [f32; 2],
510    _pad0: u32,
511    _pad1: u32,
512}
513
514/// P2-1.4b:背景模糊 uniform(64 bytes)
515#[repr(C)]
516#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
517struct BackdropUniform {
518    screen: [f32; 2],
519    _pad: [f32; 2],
520    rect: [f32; 4],
521    /// [corner_radius, blur_radius, 0, 0]
522    params: [f32; 4],
523    /// tint rgb + mix alpha
524    tint: [f32; 4],
525}
526
527/// 阶段 B2:text 批处理结果(pub(crate):ImageBatchDraw::batch 字段引用)
528pub(crate) struct TextBatch {
529    bg: wgpu::BindGroup,
530    count: u32,
531}
532
533// ============================================================
534// 阶段 B2+B3:clip 分段收集 + GPU scissor 裁剪
535// ============================================================
536
537/// PushClipPath 的 earcut 三角形(扁平 vertices + indices)
538#[derive(Debug, Clone, Default)]
539pub(crate) struct StencilDraw {
540    /// [x, y, r, g, b, a, ...]
541    pub vertices: Vec<f32>,
542    pub indices: Vec<u32>,
543}
544
545/// 进入/退出一个 ClipPath 时对 stencil 覆盖计数的操作。
546///
547/// 推入时 +1、弹出时 -1;内容段用 `Equal(level)` 测试,
548/// 因此嵌套 clip 的交集会自动生效(只有每个 mask 都覆盖到的像素计数 = depth)。
549#[derive(Debug, Clone, Copy, PartialEq, Eq)]
550pub(crate) struct StencilAction {
551    /// `StencilDraw` 下标
552    pub draw: u32,
553    /// 操作时的嵌套深度(从 1 开始)
554    pub level: u32,
555    pub increment: bool,
556}
557
558/// 合并后的 ClipPath mask GPU 资源;`ranges[draw]` = (first_index, index_count)
559pub(crate) struct StencilGpu {
560    pub vertex: wgpu::Buffer,
561    pub index: wgpu::Buffer,
562    pub ranges: Vec<(u32, u32)>,
563    pub bg: wgpu::BindGroup,
564}
565
566/// 背景模糊命令参数(圆角遮罩 + 13-tap blur + tint)
567#[derive(Debug, Clone, Copy)]
568pub(crate) struct BackdropBlurSpec {
569    pub rect: Rect,
570    pub radius: f32,
571    pub blur_radius: f32,
572    pub tint: [f32; 4],
573}
574
575/// 段内的一次绘制操作(按 PaintList 命令顺序记录,保留跨类型 z-order)
576#[derive(Debug, Clone, Copy, PartialEq, Eq)]
577pub(crate) enum DrawOp {
578    /// rect instance 半开区间 [start, end) + 混合模式
579    Rect(u32, u32, BlendMode),
580    /// text instance 半开区间 [start, end)
581    Text(u32, u32),
582    /// 图片组下标
583    Image(u32),
584    /// 纹理 alpha mask(destination-in),引用图片组下标
585    Mask(u32),
586    /// 背景模糊(引用 BackdropBlurSpec 下标)
587    BackdropBlur(u32),
588    /// tri index 半开区间 [start, end)(index 进合并后的 tri index buffer)
589    Tri(u32, u32),
590}
591
592/// 阶段 B3:一个 scissor 段 — 相邻 clip 边界(PushClip/PopClip)之间的绘制区间
593///
594/// Pass 1 里每段一次 `set_scissor_rect`,再按 `ops` 顺序逐条 draw —— 这样
595/// rect/text/图片/三角形都保持 PaintList 的原始绘制顺序,而不是被类型分组
596/// 重排(旧实现固定 rect→image→text→tri,后画的 rect 会盖不住先画的文字)。
597#[derive(Debug, Clone, PartialEq)]
598pub(crate) struct ClipSegment {
599    /// scissor 矩形物理像素 [x, y, w, h];`None` = 本段无裁剪(整个 target)
600    pub scissor: Option<[u32; 4]>,
601    /// 本段实际 draw 的顺序列表
602    pub ops: Vec<DrawOp>,
603    /// 段内 rect/text/图片组的总范围(测试/诊断兼容字段)
604    pub rect_range: (u32, u32),
605    pub text_range: (u32, u32),
606    pub image_range: (u32, u32),
607    /// 本段生效的 ClipPath 嵌套深度(0 = 无 path 裁剪,>0 时用 stencil Equal(level))
608    pub stencil_level: u32,
609    /// 本段绘制前要执行的 stencil mask 操作(推入/弹出,按顺序)
610    pub stencil_actions: Vec<StencilAction>,
611}
612
613/// 阶段 6(图片):一个 texture_id 的连续图片组(paint 命令顺序里相邻的同图
614/// TexturedRect 合为一组 — 同一 ImageWidget 只产 1 条命令,组数 = 层内图片数)
615pub(crate) struct ImageGroup {
616    pub texture_id: u32,
617    pub instances: Vec<TextInstance>,
618}
619
620/// 阶段 6(图片):一个图片组的可绘制批次(bind group 已绑定该组纹理)。
621///
622/// 在 `Vec<Option<ImageBatchDraw>>` 里**下标 = ImageGroup 下标**:
623/// 未注册纹理的组是 `None` 占位,这样段的 `image_range`(组下标区间)
624/// 不因跳过而错位。
625pub(crate) struct ImageBatchDraw {
626    pub(crate) batch: TextBatch,
627}
628
629/// 矩形求交(负宽高 clamp 为 0 — 退化矩形与任何东西都不相交)
630fn intersect_rect(a: Rect, b: Rect) -> Rect {
631    let x1 = a.x.max(b.x);
632    let y1 = a.y.max(b.y);
633    let x2 = (a.x + a.width).min(b.x + b.width);
634    let y2 = (a.y + a.height).min(b.y + b.height);
635    Rect::new(x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0))
636}
637
638/// 计算 path triangles 的 bounding box(用于 PushClipPath → scissor 近似)
639fn path_bounding_box(vertices: &[mgui_core::paint::Vertex]) -> Rect {
640    if vertices.is_empty() {
641        return Rect::new(0.0, 0.0, 0.0, 0.0);
642    }
643    let mut min_x = f32::INFINITY;
644    let mut min_y = f32::INFINITY;
645    let mut max_x = f32::NEG_INFINITY;
646    let mut max_y = f32::NEG_INFINITY;
647    for v in vertices {
648        min_x = min_x.min(v.x);
649        min_y = min_y.min(v.y);
650        max_x = max_x.max(v.x);
651        max_y = max_y.max(v.y);
652    }
653    Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
654}
655
656/// instance 矩形是否与当前 clip 相交(CPU 粗剔除;精确裁剪交给 GPU scissor)
657fn rect_intersects_clip(r: &Rect, clip: Option<Rect>) -> bool {
658    match clip {
659        None => true,
660        // 退化 clip(宽或高 = 0)与任何东西都不相交
661        Some(c) => {
662            c.width > 0.0
663                && c.height > 0.0
664                && r.x < c.x + c.width
665                && r.x + r.width > c.x
666                && r.y < c.y + c.height
667                && r.y + r.height > c.y
668        }
669    }
670}
671
672/// 圆角矩形三角扇(凸多边形,中心 + 周边点即可精确覆盖)。
673///
674/// 用于 `PushClipRRect` 的 stencil mask;每角 8 段二次近似圆,
675/// 顶点格式与 `StencilDraw` 一致([x,y,r,g,b,a])。
676fn rounded_rect_stencil_mesh(rect: Rect, radius: f32) -> (Vec<f32>, Vec<u32>) {
677    if rect.width <= 0.0 || rect.height <= 0.0 {
678        return (Vec::new(), Vec::new());
679    }
680    let (x, y, w, h) = (rect.x, rect.y, rect.width, rect.height);
681    let r = radius.max(0.0).min(w.min(h) * 0.5);
682
683    let mut pts: Vec<(f32, f32)> = Vec::new();
684    if r <= 0.0 {
685        pts.extend_from_slice(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
686    } else {
687        const SEG: u32 = 8;
688        // 顺时针(屏幕 y 向下):右上 → 右下 → 左下 → 左上
689        let arcs = [
690            (x + w - r, y + r, -std::f32::consts::FRAC_PI_2, 0.0),
691            (x + w - r, y + h - r, 0.0, std::f32::consts::FRAC_PI_2),
692            (x + r, y + h - r, std::f32::consts::FRAC_PI_2, std::f32::consts::PI),
693            (x + r, y + r, std::f32::consts::PI, 3.0 * std::f32::consts::FRAC_PI_2),
694        ];
695        for &(cx, cy, a0, a1) in &arcs {
696            for i in 0..=SEG {
697                let a = a0 + (a1 - a0) * (i as f32 / SEG as f32);
698                pts.push((cx + r * a.cos(), cy + r * a.sin()));
699            }
700        }
701        // 最后一角回到起点(首尾重复),去掉
702        if pts.len() > 1 && pts.first() == pts.last() {
703            pts.pop();
704        }
705    }
706    pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5);
707
708    let n = pts.len();
709    if n < 3 {
710        return (Vec::new(), Vec::new());
711    }
712    let mut verts = Vec::with_capacity((n + 1) * 6);
713    for &(px, py) in &pts {
714        verts.extend_from_slice(&[px, py, 1.0, 1.0, 1.0, 1.0]);
715    }
716    verts.extend_from_slice(&[x + w * 0.5, y + h * 0.5, 1.0, 1.0, 1.0, 1.0]);
717    let center = n as u32;
718    let mut indices = Vec::with_capacity(n * 3);
719    for i in 0..n as u32 {
720        indices.extend_from_slice(&[center, i, (i + 1) % n as u32]);
721    }
722    (verts, indices)
723}
724
725/// clip 逻辑坐标 → scissor 物理像素 [x, y, w, h](floor/ceil 取整,clamp 到 texture 尺寸)
726fn clip_to_scissor_px(r: Rect, dpr: f32, tex: (u32, u32)) -> [u32; 4] {
727    let d = dpr.max(0.0);
728    let (tw, th) = (tex.0 as f32, tex.1 as f32);
729    // 近边也必须 clamp 到 target 尺寸,否则完全落在 target 右侧/下方的 clip
730    // 会产出 x/y 越界的 scissor → wgpu validation error。
731    let x0 = (r.x * d).floor().clamp(0.0, tw);
732    let y0 = (r.y * d).floor().clamp(0.0, th);
733    let x1 = ((r.x + r.width) * d).ceil().clamp(0.0, tw).max(x0);
734    let y1 = ((r.y + r.height) * d).ceil().clamp(0.0, th).max(y0);
735    let x = x0 as u32;
736    let y = y0 as u32;
737    let w = (x1 as u32).saturating_sub(x);
738    let h = (y1 as u32).saturating_sub(y);
739    [x, y, w, h]
740}
741
742/// 阶段 B2+B3:一次遍历 paint_list → rect/text instances + scissor 分段
743///
744/// - `PushClip`/`PopClip` 是段边界;`PushClip` 与外层 clip 求交(嵌套 clip)
745/// - instance 与当前 clip 相交才收集(CPU 粗剔除),溢出边缘交给 GPU scissor
746/// - 空段(无 instance)不产出 — 不浪费 draw call
747///
748/// Stage T1:Triangles — 合并所有 PaintCommand::Triangles(vertices,indices)
749/// 进一个 Vec<f32>(vertex flat) + Vec<u32>(index merged + offset by base vertex count)
750/// **不分 clip 分段**(简化:path fill 的三角形通常不需要 clip 分段;
751/// 未来需要时加 tri_range 进 ClipSegment)
752///
753/// **ClipPath stencil** — 最后一个返回值:
754/// 所有 PushClipPath 的 earcut 三角形(供 renderer 在段间写 stencil mask);
755/// 每个 `ClipSegment.stencil_actions` 用下标引用它。
756type CollectedInstances = (
757    Vec<RectInstance>,
758    Vec<TextInstance>,
759    Vec<ImageGroup>,
760    Vec<ClipSegment>,
761    // Stage T1:triangle data(所有 PaintCommand::Triangles 合并)
762    Vec<f32>, // vertex flat data: [x,y,r,g,b,a, x,y,r,g,b,a, ...]
763    Vec<u32>, // merged index data(offset per command)
764    // ClipPath mask triangles(按 PushClipPath 顺序)
765    Vec<StencilDraw>,
766    // 背景模糊参数
767    Vec<BackdropBlurSpec>,
768);
769
770pub(crate) fn collect_instances_segmented(
771    paint_list: &PaintList,
772    dpr: f32,
773    tex_size: (u32, u32),
774) -> CollectedInstances {
775    let mut rects: Vec<RectInstance> = Vec::new();
776    let mut texts: Vec<TextInstance> = Vec::new();
777    let mut image_groups: Vec<ImageGroup> = Vec::new();
778    let mut segments: Vec<ClipSegment> = Vec::new();
779    // Stage T1:triangles
780    let mut tri_vertices: Vec<f32> = Vec::new(); // 扁平化后的顶点
781    let mut tri_indices: Vec<u32> = Vec::new(); // 合并后的 index(加偏移)
782    let mut tri_base_vertex: u32 = 0; // 当前 command 的顶点在全局数组里的 base offset
783                                      // **ClipPath stencil** — 每个 PushClipPath 的 mask 三角形 + 待执行的 +1/-1 操作
784    let mut stencil_draws: Vec<StencilDraw> = Vec::new();
785    let mut pending_stencil: Vec<StencilAction> = Vec::new();
786    let mut backdrop_blurs: Vec<BackdropBlurSpec> = Vec::new();
787    let mut path_draw_stack: Vec<Option<u32>> = Vec::new();
788    let mut clip_depth: u32 = 0;
789    // 混合模式栈:作用于后续矩形族命令,不产生段边界
790    let mut blend_stack: Vec<BlendMode> = Vec::new();
791    let mut cur_blend = BlendMode::Normal;
792    // clip 栈:每层保存"压入前的外层 clip" + 是否为 stencil mask 裁剪
793    let mut stack: Vec<(Option<Rect>, bool)> = Vec::new();
794    let mut cur_clip: Option<Rect> = None;
795    let (mut seg_r, mut seg_t, mut seg_i): (u32, u32, u32) = (0, 0, 0);
796    // 段内绘制顺序(rect/text/image/tri 交错,保留 painter's order)
797    let mut ops: Vec<DrawOp> = Vec::new();
798
799    // 关闭当前段(有绘制操作才记录;重置段起点)
800    macro_rules! close_segment {
801        () => {
802            let r_end = rects.len() as u32;
803            let t_end = texts.len() as u32;
804            let i_end = image_groups.len() as u32;
805            if !ops.is_empty() {
806                segments.push(ClipSegment {
807                    scissor: cur_clip.map(|c| clip_to_scissor_px(c, dpr, tex_size)),
808                    ops: ops.clone(),
809                    rect_range: (seg_r, r_end),
810                    text_range: (seg_t, t_end),
811                    image_range: (seg_i, i_end),
812                    stencil_level: clip_depth,
813                    // 边界上的 mask 操作属于"下一段内容";空段不消费它们,
814                    // 留到下一个有绘制的段(净效果仍然正确)。
815                    stencil_actions: std::mem::take(&mut pending_stencil),
816                });
817                ops.clear();
818            }
819            seg_r = r_end;
820            seg_t = t_end;
821            seg_i = i_end;
822        };
823    }
824
825    fn push_range_op(ops: &mut Vec<DrawOp>, op: DrawOp) {
826        match op {
827            DrawOp::Rect(s, e, mode) => {
828                if let Some(DrawOp::Rect(_, last_end, last_mode)) = ops.last_mut() {
829                    if *last_end == s && *last_mode == mode {
830                        *last_end = e;
831                        return;
832                    }
833                }
834            }
835            DrawOp::Text(s, e) => {
836                if let Some(DrawOp::Text(_, last_end)) = ops.last_mut() {
837                    if *last_end == s {
838                        *last_end = e;
839                        return;
840                    }
841                }
842            }
843            DrawOp::Tri(s, e) => {
844                if let Some(DrawOp::Tri(_, last_end)) = ops.last_mut() {
845                    if *last_end == s {
846                        *last_end = e;
847                        return;
848                    }
849                }
850            }
851            DrawOp::Image(_) => {}
852            DrawOp::Mask(_) => {}
853            DrawOp::BackdropBlur(_) => {}
854        }
855        ops.push(op);
856    }
857
858    // ClipPath / ClipRRect 共用:压入一层 stencil mask + bbox scissor
859    macro_rules! push_mask_clip {
860        ($flat:expr, $idxs:expr, $bbox:expr) => {{
861            clip_depth += 1;
862            let flat_verts: Vec<f32> = $flat;
863            let idxs: &[u32] = $idxs;
864            let draw_index = if !flat_verts.is_empty() && !idxs.is_empty() {
865                let idx = stencil_draws.len() as u32;
866                stencil_draws.push(StencilDraw { vertices: flat_verts, indices: idxs.to_vec() });
867                pending_stencil.push(StencilAction { draw: idx, level: clip_depth, increment: true });
868                Some(idx)
869            } else {
870                None
871            };
872            path_draw_stack.push(draw_index);
873
874            let bbox: Rect = $bbox;
875            stack.push((cur_clip, true));
876            cur_clip = Some(match cur_clip {
877                Some(outer) => intersect_rect(outer, bbox),
878                None => bbox,
879            });
880        }};
881    }
882
883    // 弹出 mask clip:深度的 -1 操作 + 恢复外层 scissor
884    macro_rules! pop_mask_clip {
885        () => {{
886            if let Some(Some(draw)) = path_draw_stack.pop() {
887                // 弹出时 -1,恢复外层的覆盖计数(兄弟 clip 不会互相污染)
888                pending_stencil.push(StencilAction { draw, level: clip_depth, increment: false });
889            }
890            clip_depth = clip_depth.saturating_sub(1);
891        }};
892    }
893
894    for cmd in &paint_list.commands {
895        match cmd {
896            PaintCommand::PushBlendMode(mode) => {
897                blend_stack.push(cur_blend);
898                cur_blend = *mode;
899            }
900            PaintCommand::PopBlendMode => {
901                cur_blend = blend_stack.pop().unwrap_or(BlendMode::Normal);
902            }
903            PaintCommand::PushClip(r) => {
904                close_segment!();
905                stack.push((cur_clip, false));
906                cur_clip = Some(match cur_clip {
907                    Some(outer) => intersect_rect(outer, *r),
908                    None => *r,
909                });
910            }
911            PaintCommand::PushClipRRect { rect, radius } => {
912                close_segment!();
913                let (flat_verts, idxs) = rounded_rect_stencil_mesh(*rect, *radius);
914                push_mask_clip!(flat_verts, &idxs, *rect);
915            }
916            PaintCommand::PopClip => {
917                close_segment!();
918                let (prev, is_mask) = stack.pop().unwrap_or((None, false));
919                if is_mask {
920                    pop_mask_clip!();
921                }
922                cur_clip = prev;
923            }
924            // PushClipPath — 路径裁剪(scissor 用 bbox 粗裁,GPU stencil 精确 mask)
925            PaintCommand::PushClipPath { vertices, indices } => {
926                close_segment!();
927                let mut flat_verts: Vec<f32> = Vec::with_capacity(vertices.len() * 6);
928                for v in vertices {
929                    flat_verts.push(v.x);
930                    flat_verts.push(v.y);
931                    flat_verts.push(v.color.r);
932                    flat_verts.push(v.color.g);
933                    flat_verts.push(v.color.b);
934                    flat_verts.push(v.color.a);
935                }
936                push_mask_clip!(flat_verts, indices, path_bounding_box(vertices));
937            }
938            PaintCommand::PopClipPath => {
939                close_segment!();
940                let (prev, is_mask) = stack.pop().unwrap_or((None, false));
941                if is_mask {
942                    pop_mask_clip!();
943                }
944                cur_clip = prev;
945            }
946            PaintCommand::Rect { rect, color, radius } => {
947                if rect_intersects_clip(rect, cur_clip) {
948                    let start = rects.len() as u32;
949                    rects.push(RectInstance {
950                        rect: [rect.x, rect.y, rect.width, rect.height],
951                        from: [color.r, color.g, color.b, color.a],
952                        to: [color.r, color.g, color.b, color.a],
953                        grad: [0.0; 4],
954                        params: [*radius, 0.0, 0.0, 0.0],
955                    });
956                    push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
957                }
958            }
959            // **T0-2:BoxShadow** — 走同一条 Rect pipeline,shader 根据 blur_radius 做 SDF blur
960            PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
961                if rect_intersects_clip(rect, cur_clip) {
962                    let start = rects.len() as u32;
963                    rects.push(RectInstance {
964                        rect: [rect.x, rect.y, rect.width, rect.height],
965                        from: [color.r, color.g, color.b, color.a],
966                        to: [color.r, color.g, color.b, color.a],
967                        grad: [0.0; 4],
968                        params: [*radius, 0.0, *blur_radius, 0.0],
969                    });
970                    push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
971                }
972            }
973            // **P2-1.4:InsetShadow** — 同一 rect pipeline,shader kind=3 做内侧 SDF 衰减
974            PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
975                if rect_intersects_clip(rect, cur_clip) {
976                    let idx = rects.len() as u32;
977                    rects.push(RectInstance {
978                        rect: [rect.x, rect.y, rect.width, rect.height],
979                        from: [color.r, color.g, color.b, color.a],
980                        to: [color.r, color.g, color.b, color.a],
981                        grad: [0.0; 4],
982                        params: [*radius, 3.0, *blur_radius, 0.0],
983                    });
984                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
985                }
986            }
987            PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
988                if rect_intersects_clip(rect, cur_clip) {
989                    let idx = rects.len() as u32;
990                    rects.push(RectInstance {
991                        rect: [rect.x, rect.y, rect.width, rect.height],
992                        from: [from.r, from.g, from.b, from.a],
993                        to: [to.r, to.g, to.b, to.a],
994                        grad: [start.x, start.y, end.x, end.y],
995                        params: [*corner_radius, 1.0, 0.0, 0.0],
996                    });
997                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
998                }
999            }
1000            PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
1001                if rect_intersects_clip(rect, cur_clip) {
1002                    let idx = rects.len() as u32;
1003                    rects.push(RectInstance {
1004                        rect: [rect.x, rect.y, rect.width, rect.height],
1005                        from: [from.r, from.g, from.b, from.a],
1006                        to: [to.r, to.g, to.b, to.a],
1007                        grad: [center.x, center.y, *radial_radius, 0.0],
1008                        params: [*corner_radius, 2.0, 0.0, 0.0],
1009                    });
1010                    push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
1011                }
1012            }
1013            // **P2-1.4b:背景模糊** — 在命令处切 pass,模糊此前已绘制内容
1014            PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
1015                if rect_intersects_clip(rect, cur_clip) {
1016                    let idx = backdrop_blurs.len() as u32;
1017                    backdrop_blurs.push(BackdropBlurSpec {
1018                        rect: *rect,
1019                        radius: *radius,
1020                        blur_radius: *blur_radius,
1021                        tint: [tint.r, tint.g, tint.b, tint.a],
1022                    });
1023                    ops.push(DrawOp::BackdropBlur(idx));
1024                }
1025            }
1026            // **P2-1.3:纹理 mask** — destination-in,只保留纹理 alpha 覆盖的区域
1027            PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
1028                if *alpha > 0.0 && rect_intersects_clip(rect, cur_clip) {
1029                    let gi = image_groups.len() as u32;
1030                    image_groups.push(ImageGroup {
1031                        texture_id: *texture_id,
1032                        instances: vec![TextInstance {
1033                            rect: [rect.x, rect.y, rect.width, rect.height],
1034                            // mode 2.0 = Alpha:alpha 取纹理 A 通道 × color.a
1035                            color: [1.0, 1.0, 1.0, alpha.clamp(0.0, 1.0)],
1036                            uv: *uv,
1037                            mode: 2.0,
1038                            _pad: [0.0; 3],
1039                        }],
1040                    });
1041                    ops.push(DrawOp::Mask(gi));
1042                }
1043            }
1044            PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
1045                if rect_intersects_clip(rect, cur_clip) {
1046                    // **像素对齐**:text glyph atlas 按物理分辨率栅格化(每个 glyph 一个 texel=一个物理像素),
1047                    // rect 在逻辑坐标上做 round(x*dpr)/dpr → 确保 UV 采样 1:1 对齐 atlas texel → 文字锐
1048                    let snap = |v: f32| (v * dpr).round() / dpr;
1049                    let inst = TextInstance {
1050                        rect: [
1051                            snap(rect.x),
1052                            snap(rect.y),
1053                            snap(rect.x + rect.width) - snap(rect.x),
1054                            snap(rect.y + rect.height) - snap(rect.y),
1055                        ],
1056                        color: [color.r, color.g, color.b, color.a],
1057                        uv: *uv,
1058                        mode: match mode {
1059                            TextureMode::Mask => 0.0,
1060                            TextureMode::Color => 1.0,
1061                        },
1062                        _pad: [0.0; 3],
1063                    };
1064                    if *texture_id == 0 {
1065                        let start = texts.len() as u32;
1066                        texts.push(inst);
1067                        push_range_op(&mut ops, DrawOp::Text(start, start + 1));
1068                    } else {
1069                        // 阶段 6(图片):texture_id != 0 = ImageWidget 的全图 quad。
1070                        // 只有「紧邻的上一笔也是同纹理图片」才合并成组 —— 中间插入
1071                        // rect/text 后必须新开一组,否则绘制顺序无法恢复。
1072                        let reuse_group = ops
1073                            .last()
1074                            .and_then(|op| match op {
1075                                DrawOp::Image(gi) => Some(*gi),
1076                                _ => None,
1077                            })
1078                            .filter(|&gi| image_groups[gi as usize].texture_id == *texture_id);
1079                        if let Some(gi) = reuse_group {
1080                            image_groups[gi as usize].instances.push(inst);
1081                        } else {
1082                            let gi = image_groups.len() as u32;
1083                            image_groups.push(ImageGroup { texture_id: *texture_id, instances: vec![inst] });
1084                            ops.push(DrawOp::Image(gi));
1085                        }
1086                    }
1087                }
1088            }
1089            // Stage T1:Triangles — 合并所有 path fill 的 earcut 输出
1090            // 每个 command 的 indices 加 base offset(避免不同 PathBuilder 的 triangles 互相引用)
1091            PaintCommand::Triangles { vertices, indices } => {
1092                let idx_start = tri_indices.len() as u32;
1093                // vertices 扁平化为 [x, y, r, g, b, a]
1094                for v in vertices {
1095                    tri_vertices.push(v.x);
1096                    tri_vertices.push(v.y);
1097                    tri_vertices.push(v.color.r);
1098                    tri_vertices.push(v.color.g);
1099                    tri_vertices.push(v.color.b);
1100                    tri_vertices.push(v.color.a);
1101                }
1102                // indices 加 base(让每个 command 的顶点全局唯一)
1103                for &idx in indices {
1104                    tri_indices.push(tri_base_vertex + idx);
1105                }
1106                tri_base_vertex += vertices.len() as u32;
1107                if !vertices.is_empty() && !indices.is_empty() {
1108                    push_range_op(&mut ops, DrawOp::Tri(idx_start, tri_indices.len() as u32));
1109                }
1110            }
1111            // Stage T2:PaintCommand::Text — core 层 Widget 要画文字的高层命令
1112            // 让 paint_text_line 展开成 TexturedRect → 逐个收集
1113            PaintCommand::Text { text, range, font_size, color, position, max_width } => {
1114                let mut temp_list = PaintList::new();
1115                crate::text::paint_text_span(text, *range, *font_size, *color, *position, &mut temp_list, *max_width);
1116                // 展开后的 TexturedRect 逐个收集
1117                let snap = |v: f32| (v * dpr).round() / dpr;
1118                let start = texts.len() as u32;
1119                for cmd in temp_list.commands {
1120                    if let PaintCommand::TexturedRect { rect, color, uv, texture_id: 0, .. } = cmd {
1121                        if rect_intersects_clip(&rect, cur_clip) {
1122                            texts.push(TextInstance {
1123                                rect: [
1124                                    snap(rect.x),
1125                                    snap(rect.y),
1126                                    snap(rect.x + rect.width) - snap(rect.x),
1127                                    snap(rect.y + rect.height) - snap(rect.y),
1128                                ],
1129                                color: [color.r, color.g, color.b, color.a],
1130                                uv,
1131                                // glyph atlas 永远走 mask 采样
1132                                mode: 0.0,
1133                                _pad: [0.0; 3],
1134                            });
1135                        }
1136                    }
1137                }
1138                if texts.len() as u32 > start {
1139                    push_range_op(&mut ops, DrawOp::Text(start, texts.len() as u32));
1140                }
1141            }
1142        }
1143    }
1144    // 尾段
1145    close_segment!();
1146    let _ = (seg_r, seg_t, seg_i); // 尾段关闭后不再读 — 显式消费消除 unused_assignments
1147
1148    // P2-1.5:合并相邻且 scissor/stencil 状态相同的段。
1149    // 常见于 PopClip 后立刻 PushClip 同一矩形(虚拟列表/滚动容器),
1150    // 合并后减少 set_scissor / pipeline 状态切换;跨 mask 操作的段不合并。
1151    let mut merged: Vec<ClipSegment> = Vec::with_capacity(segments.len());
1152    for seg in segments.drain(..) {
1153        let can_merge = merged.last().is_some_and(|prev: &ClipSegment| {
1154            prev.scissor == seg.scissor && prev.stencil_level == seg.stencil_level && seg.stencil_actions.is_empty()
1155        });
1156        if can_merge {
1157            let prev = merged.last_mut().expect("checked non-empty");
1158            for op in &seg.ops {
1159                push_range_op(&mut prev.ops, *op);
1160            }
1161            prev.rect_range.1 = seg.rect_range.1;
1162            prev.text_range.1 = seg.text_range.1;
1163            prev.image_range.1 = seg.image_range.1;
1164        } else {
1165            merged.push(seg);
1166        }
1167    }
1168
1169    (rects, texts, image_groups, merged, tri_vertices, tri_indices, stencil_draws, backdrop_blurs)
1170}
1171
1172/// 阶段 B1:helper — 构造 rect batch bind group(0 rect → None)
1173///
1174/// 阶段 B1.5:**per-layer buffer pool** — header(16B 固定)永驻,instances(grow-only)
1175/// 容量够就复用,只 `queue.write_buffer` 覆盖。稳态 0 alloc/帧/layer。
1176///
1177/// **关键教训**:**不能所有 layer 共享一个 pool buffer** — wgpu 的
1178// `queue.write_buffer` 是 staged + 下次 submit 执行;同一 submit 内多个 layer
1179// 依次 write_buffer 同一 buffer → 后写覆盖先写 → 所有 layer 的 draw 都用
1180// 最后一个 layer 的数据 → UI 元素放大/错乱。
1181// =================================================================
1182// 子模块
1183// =================================================================
1184mod batches;
1185mod composition;
1186mod render;
1187mod setup;
1188#[cfg(test)]
1189mod tests;
1190
1191#[cfg(test)]
1192mod present_stats_tests {
1193    use super::*;
1194
1195    fn ms(v: u64) -> Duration {
1196        Duration::from_millis(v)
1197    }
1198
1199    /// 第一帧不许编出一个间隔:这条与 `mgui_video::timing` 那一格是同一条家规的两个入口,
1200    /// 而它坏了的形式很难查 —— 起始那一次会话启动成本会被读成"节奏里有一个慢帧",
1201    /// 而那恰恰是本轮唯一还活着的 >60ms 事件(起始成批),不能被假样本冒充。
1202    #[test]
1203    fn the_first_present_invents_no_gap() {
1204        let mut s = PresentStats::default();
1205        s.record(1_000, 2_000, None, "Fifo", 2);
1206        assert_eq!(s.presents, 1, "present 本身要记上:屏幕上确实出新内容了");
1207        assert_eq!(s.gaps, 0, "没有前驱就不许有间隔");
1208        assert_eq!((s.last_gap_ns, s.gap_sum_ns, s.gap_max_ns), (0, 0, 0));
1209        assert_eq!(s.mean_gap_ns(), 0, "均值给 0 只允许配着 gaps == 0 读");
1210
1211        s.record(1_000, 2_000, Some(ms(33)), "Fifo", 2);
1212        assert_eq!(s.gaps, 1, "第二个 present 才产生第一个间隔");
1213        assert_eq!(s.last_gap_ns, 33_000_000);
1214    }
1215
1216    /// 间隔的三件事(个数 / 最大 / 均值)必须各自独立:只报均值会把"每 8 帧一顿"读成完美。
1217    #[test]
1218    fn gap_stats_tally_count_max_and_mean_separately() {
1219        let mut s = PresentStats::default();
1220        s.record(0, 0, None, "Fifo", 2);
1221        for gap in [ms(16), ms(33), ms(99)] {
1222            s.record(0, 0, Some(gap), "Fifo", 2);
1223        }
1224        assert_eq!(s.presents, 4);
1225        assert_eq!(s.gaps, 3);
1226        assert_eq!(s.gap_max_ns, 99_000_000, "最坏那一顿必须单独看得见,不能被均值抹平");
1227        assert_eq!(s.mean_gap_ns(), (16 + 33 + 99) * 1_000_000 / 3);
1228    }
1229
1230    /// "等 vsync"与"提交"是两问:前者是显示配额(FIFO 下正常就该有),后者是我们自己的成本。
1231    /// 合成一个字段就会得到"present 很慢"这种无法归因的读数。
1232    #[test]
1233    fn waiting_for_the_display_and_submitting_are_two_different_numbers() {
1234        let mut s = PresentStats::default();
1235        s.record(4_000_000, 300_000, None, "Fifo", 2);
1236        s.record(3_000_000, 200_000, Some(ms(33)), "Fifo", 2);
1237        assert_eq!(s.wait_ns, 7_000_000);
1238        assert_eq!(s.submit_ns, 500_000);
1239        assert_ne!(s.wait_ns, s.submit_ns, "两问合一之后,任何一条归因都无从下手");
1240    }
1241
1242    /// 空串 = 这一路**没接线**,不是"这台机器一次都没 present"。这条区分是给读表的工具用的:
1243    /// 多窗口宿主的 slot 与软件回退都会给全零,而那两种"零"的含义不同。
1244    #[test]
1245    fn an_unwired_path_says_so_instead_of_looking_idle() {
1246        let unwired = PresentStats::default();
1247        assert_eq!(unwired.present_mode, "", "没接线的形式必须是可识别的,而不是恰好等于一个合法的零");
1248        assert_eq!(unwired.presents, 0);
1249        let mut wired = PresentStats::default();
1250        wired.record(1, 1, None, "Mailbox", 1);
1251        assert_eq!((wired.present_mode, wired.max_frame_latency), ("Mailbox", 1));
1252        assert_ne!(PresentStats::default().present_mode, wired.present_mode);
1253    }
1254}