Skip to main content

mgui_runtime/renderer/
mod.rs

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