Skip to main content

mgui_runtime/renderer/
setup.rs

1//! Renderer 构建与 GPU 资源创建(new / pipeline / atlas / layer cache)。
2//! 从 renderer.rs 拆出;struct 定义在父模块,后代模块可访问其私有字段。
3
4use super::composition::LayerComposition;
5use super::*;
6use mgui_core::paint::BlendMode;
7
8const STENCIL_FMT: wgpu::TextureFormat = wgpu::TextureFormat::Stencil8;
9
10/// 所有 layer resolve texture 的总字节预算(256 MiB,与图片纹理预算一致)。
11pub const LAYER_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
12
13/// 单层目标纹理尺寸。
14pub(crate) type LayerTextureSize = (LayerId, (u32, u32));
15/// `(每层尺寸, 实际缩放系数)`。
16pub(crate) type LayerTextureTargets = (Vec<LayerTextureSize>, f32);
17
18/// 单个 layer 的目标纹理尺寸(logical → 物理,再钳制设备上限)。
19fn layer_tex_size(logical: Option<Size>, dpr: f32, screen: (f32, f32), max_dim: u32) -> (u32, u32) {
20    let (w, h) = match logical {
21        Some(s) => (s.width, s.height),
22        None => screen,
23    };
24    // NaN/负数 → 0,无穷大 → u32::MAX;两者都由 max/min 收敛到合法范围。
25    let w = (w * dpr).ceil() as u32;
26    let h = (h * dpr).ceil() as u32;
27    (w.max(1).min(max_dim), h.max(1).min(max_dim))
28}
29
30fn layer_tex_total_bytes(sizes: &[LayerTextureSize]) -> u64 {
31    sizes.iter().map(|&(_, (w, h))| w as u64 * h as u64 * 4).sum()
32}
33
34/// 计算本帧所有 layer 的目标纹理尺寸(P1-4 资源预算)。
35///
36/// - 每层按 `logical_size * dpr`(None → 视口)向上取整,并钳制到
37///   `max_dim`(防异常 content_size 触发纹理创建失败);
38/// - 若总字节超过 `budget`,统一按面积比例降采样到预算内。图层绘制仍按
39///   逻辑尺寸归一化、blit 时再拉伸回逻辑尺寸,因此几何/命中不变,只降低
40///   极端场景下的分辨率。
41///
42/// 返回 `(每层尺寸, 实际缩放系数)`;正常情况缩放系数为 1.0。
43pub(crate) fn layer_texture_targets(
44    layer_paints: &[LayerPaint],
45    dpr: f32,
46    screen_size: (f32, f32),
47    max_dim: u32,
48    budget: u64,
49) -> LayerTextureTargets {
50    let dpr = if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 };
51    let max_dim = max_dim.max(1);
52    let compute = |scale: f32| -> Vec<LayerTextureSize> {
53        layer_paints
54            .iter()
55            .map(|lp| (lp.layer_id, layer_tex_size(lp.logical_size, dpr * scale, screen_size, max_dim)))
56            .collect()
57    };
58
59    let mut scale = 1.0f32;
60    let mut sizes = compute(scale);
61    let mut total = layer_tex_total_bytes(&sizes);
62    if total > budget {
63        // ceil()/1px 下限会让首次缩放后略超预算;迭代收紧几次直到收敛。
64        for _ in 0..8 {
65            if total <= budget {
66                break;
67            }
68            let factor = ((budget as f64) / (total as f64)).sqrt().clamp(0.05, 0.99);
69            let next = (scale as f64 * factor) as f32;
70            if next >= scale || next <= 0.01 {
71                break;
72            }
73            scale = next;
74            sizes = compute(scale);
75            total = layer_tex_total_bytes(&sizes);
76        }
77        // 量化到 1/8 步长:overlay 开合导致层数小幅变化时不至于让
78        // 所有 layer texture 反复重建。向下取整只会更省(仍然 ≤ 预算)。
79        let quantized = (scale * 8.0).floor() / 8.0;
80        if quantized > 0.0 && quantized < scale {
81            scale = quantized;
82            sizes = compute(scale);
83        }
84    }
85    (sizes, scale)
86}
87
88/// 固定功能可实现的混合模式子集(矩形族)。
89fn blend_state_for(mode: BlendMode) -> wgpu::BlendState {
90    use wgpu::{BlendComponent, BlendFactor, BlendOperation, BlendState};
91    let comp = |src_factor, dst_factor| BlendComponent { src_factor, dst_factor, operation: BlendOperation::Add };
92    match mode {
93        BlendMode::Normal => BlendState::ALPHA_BLENDING,
94        BlendMode::Multiply => BlendState {
95            color: comp(BlendFactor::Dst, BlendFactor::Zero),
96            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
97        },
98        BlendMode::Screen => BlendState {
99            color: comp(BlendFactor::One, BlendFactor::OneMinusSrc),
100            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
101        },
102        BlendMode::Add => BlendState {
103            color: comp(BlendFactor::One, BlendFactor::One),
104            alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
105        },
106    }
107}
108
109/// ClipPath/ClipRRect 内容测试:stencil == reference,不写 stencil。
110fn stencil_equal_state() -> wgpu::DepthStencilState {
111    let face = wgpu::StencilFaceState {
112        compare: wgpu::CompareFunction::Equal,
113        fail_op: wgpu::StencilOperation::Keep,
114        depth_fail_op: wgpu::StencilOperation::Keep,
115        pass_op: wgpu::StencilOperation::Keep,
116    };
117    wgpu::DepthStencilState {
118        format: STENCIL_FMT,
119        depth_write_enabled: None,
120        depth_compare: None,
121        stencil: wgpu::StencilState { front: face, back: face, read_mask: 0xFF, write_mask: 0 },
122        bias: wgpu::DepthBiasState::default(),
123    }
124}
125
126impl Renderer {
127    /// 克隆可跨窗口复用的 pipeline / layout / sampler 句柄。
128    pub fn shared_resources(&self) -> RendererShared {
129        // 多窗口共享缓存:预算 eviction 暂交给 host(避免误淘汰其他窗口在用的纹理)。
130        self.image_cache.borrow_mut().evict_enabled = false;
131        RendererShared {
132            atlas_cache: Rc::clone(&self.atlas_cache),
133            image_cache: Rc::clone(&self.image_cache),
134            rect_pipelines: self.rect_pipelines.clone(),
135            rect_bgl: self.rect_bgl.clone(),
136            text_pipeline: self.text_pipeline.clone(),
137            text_bgl: self.text_bgl.clone(),
138            text_pipeline_mask: self.text_pipeline_mask.clone(),
139            text_pipeline_mask_stencil_test: self.text_pipeline_mask_stencil_test.clone(),
140            tri_pipeline: self.tri_pipeline.clone(),
141            tri_bgl: self.tri_bgl.clone(),
142            tri_pipeline_stencil_inc: self.tri_pipeline_stencil_inc.clone(),
143            tri_pipeline_stencil_dec: self.tri_pipeline_stencil_dec.clone(),
144            rect_pipelines_stencil_test: self.rect_pipelines_stencil_test.clone(),
145            text_pipeline_stencil_test: self.text_pipeline_stencil_test.clone(),
146            tri_pipeline_stencil_test: self.tri_pipeline_stencil_test.clone(),
147            blit_pipeline: self.blit_pipeline.clone(),
148            blit_bgl: self.blit_bgl.clone(),
149            blit_sampler: self.blit_sampler.clone(),
150            backdrop_pipeline: self.backdrop_pipeline.clone(),
151            backdrop_bgl: self.backdrop_bgl.clone(),
152            format: self.format,
153        }
154    }
155
156    /// 复用另一个窗口的 pipeline/layout/sampler,只初始化本窗口缓存。
157    pub fn new_with_shared(device: &wgpu::Device, shared: &RendererShared) -> Self {
158        Self {
159            rect_pipelines: shared.rect_pipelines.clone(),
160            rect_bgl: shared.rect_bgl.clone(),
161            text_pipeline: shared.text_pipeline.clone(),
162            text_bgl: shared.text_bgl.clone(),
163            text_pipeline_mask: shared.text_pipeline_mask.clone(),
164            text_pipeline_mask_stencil_test: shared.text_pipeline_mask_stencil_test.clone(),
165            tri_pipeline: shared.tri_pipeline.clone(),
166            tri_bgl: shared.tri_bgl.clone(),
167            tri_pipeline_stencil_inc: shared.tri_pipeline_stencil_inc.clone(),
168            tri_pipeline_stencil_dec: shared.tri_pipeline_stencil_dec.clone(),
169            rect_pipelines_stencil_test: shared.rect_pipelines_stencil_test.clone(),
170            text_pipeline_stencil_test: shared.text_pipeline_stencil_test.clone(),
171            tri_pipeline_stencil_test: shared.tri_pipeline_stencil_test.clone(),
172            atlas_cache: Rc::clone(&shared.atlas_cache),
173            layer_cache: HashMap::new(),
174            active_layer_ids: std::collections::HashSet::new(),
175            frame_layer_sizes: HashMap::new(),
176            composition_scratch: mgui_core::CompositionScratch::default(),
177            blit_pipeline: shared.blit_pipeline.clone(),
178            blit_bgl: shared.blit_bgl.clone(),
179            blit_sampler: shared.blit_sampler.clone(),
180            backdrop_pipeline: shared.backdrop_pipeline.clone(),
181            backdrop_bgl: shared.backdrop_bgl.clone(),
182            format: shared.format,
183            gpu_profiler: crate::gpu_profiler::GpuProfiler::new(device),
184            batch_pools: HashMap::new(),
185            image_cache: Rc::clone(&shared.image_cache),
186            msaa_scratch: HashMap::new(),
187            stencil_scratch: HashMap::new(),
188            snapshot_scratch: HashMap::new(),
189            last_stats: RenderStats::default(),
190        }
191    }
192
193    pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
194        // ============ **Pass1:4x MSAA** ============
195        // 矢量图边缘毛边根因:所有 Pass1 pipeline 之前 count=1(零 MSAA),
196        // 三角形硬边缘只有 0/1 覆盖度 → 锯齿。4x MSAA 让 GPU 算亚像素 coverage,
197        // 边缘有 partial coverage → 抗锯齿。
198        // 注意:blit_pipeline(Pass2)必须保持 count=1,因为它画到 surface(单采样)。
199        let pass1_msaa = wgpu::MultisampleState { count: 4, mask: !0, alpha_to_coverage_enabled: false };
200        // text_pipeline MSAA 也 count=4(wgpu 要求 pipeline.sample_count == render pass attachment.sample_count)
201        // text glyph rect 已 snap 到物理像素(snap 函数在 collect_instances_segmented),
202        // glyph 边缘正好在像素边界 → 4 个子样全 0 或全 1 → coverage 不生效 → glyph 自带 alpha AA 正常
203        let text_msaa = pass1_msaa;
204
205        // ============ 纯色矩形 pipeline ============
206        let rect_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
207            label: Some("rect-shader"),
208            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/rect.wgsl").into()),
209        });
210
211        let rect_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
212            label: Some("rect-bgl"),
213            entries: &[
214                wgpu::BindGroupLayoutEntry {
215                    // binding 0:batch header(screen_size + count)uniform
216                    binding: 0,
217                    visibility: wgpu::ShaderStages::VERTEX,
218                    ty: wgpu::BindingType::Buffer {
219                        ty: wgpu::BufferBindingType::Uniform,
220                        has_dynamic_offset: false,
221                        min_binding_size: None,
222                    },
223                    count: None,
224                },
225                wgpu::BindGroupLayoutEntry {
226                    // 阶段 B1:binding 1:rect instance 数组 storage buffer
227                    binding: 1,
228                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
229                    ty: wgpu::BindingType::Buffer {
230                        ty: wgpu::BufferBindingType::Storage { read_only: true },
231                        has_dynamic_offset: false,
232                        min_binding_size: None,
233                    },
234                    count: None,
235                },
236            ],
237        });
238
239        let rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
240            label: Some("rect-pipeline-layout"),
241            bind_group_layouts: &[Some(&rect_bgl)],
242            immediate_size: 0,
243        });
244
245        // 矩形族 pipeline:Normal / Multiply / Screen / Add 各一个
246        // (stencil 版本在下方用同一个 closure 创建)
247        const RECT_BLEND_MODES: [BlendMode; 4] =
248            [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Add];
249        let make_rect_pipeline =
250            |label: &'static str, blend: wgpu::BlendState, depth_stencil: Option<wgpu::DepthStencilState>| {
251                device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
252                    label: Some(label),
253                    layout: Some(&rect_pipeline_layout),
254                    vertex: wgpu::VertexState {
255                        module: &rect_shader,
256                        entry_point: Some("vs_main"),
257                        compilation_options: Default::default(),
258                        buffers: &[],
259                    },
260                    primitive: wgpu::PrimitiveState {
261                        topology: wgpu::PrimitiveTopology::TriangleList,
262                        ..Default::default()
263                    },
264                    depth_stencil,
265                    multisample: pass1_msaa,
266                    fragment: Some(wgpu::FragmentState {
267                        module: &rect_shader,
268                        entry_point: Some("fs_main"),
269                        compilation_options: Default::default(),
270                        targets: &[Some(wgpu::ColorTargetState {
271                            format,
272                            blend: Some(blend),
273                            write_mask: wgpu::ColorWrites::ALL,
274                        })],
275                    }),
276                    multiview_mask: None,
277                    cache: None,
278                })
279            };
280        let rect_pipelines: [wgpu::RenderPipeline; 4] =
281            std::array::from_fn(|i| make_rect_pipeline("rect-pipeline", blend_state_for(RECT_BLEND_MODES[i]), None));
282
283        // ============ 文字 pipeline(纹理) ============
284        let text_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
285            label: Some("text-shader"),
286            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/text.wgsl").into()),
287        });
288
289        let text_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
290            label: Some("text-bgl"),
291            entries: &[
292                wgpu::BindGroupLayoutEntry {
293                    // 阶段 B2:binding 0 = batch header uniform
294                    binding: 0,
295                    visibility: wgpu::ShaderStages::VERTEX,
296                    ty: wgpu::BindingType::Buffer {
297                        ty: wgpu::BufferBindingType::Uniform,
298                        has_dynamic_offset: false,
299                        min_binding_size: None,
300                    },
301                    count: None,
302                },
303                wgpu::BindGroupLayoutEntry {
304                    // 阶段 B2:binding 1 = text instance storage buffer
305                    binding: 1,
306                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
307                    ty: wgpu::BindingType::Buffer {
308                        ty: wgpu::BufferBindingType::Storage { read_only: true },
309                        has_dynamic_offset: false,
310                        min_binding_size: None,
311                    },
312                    count: None,
313                },
314                wgpu::BindGroupLayoutEntry {
315                    // binding 2 = atlas texture(同 layer 所有 text 共享)
316                    binding: 2,
317                    visibility: wgpu::ShaderStages::FRAGMENT,
318                    ty: wgpu::BindingType::Texture {
319                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
320                        view_dimension: wgpu::TextureViewDimension::D2,
321                        multisampled: false,
322                    },
323                    count: None,
324                },
325                wgpu::BindGroupLayoutEntry {
326                    // 阶段 B2:binding 3 = atlas sampler(共享)
327                    binding: 3,
328                    visibility: wgpu::ShaderStages::FRAGMENT,
329                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
330                    count: None,
331                },
332            ],
333        });
334
335        let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
336            label: Some("text-pipeline-layout"),
337            bind_group_layouts: &[Some(&text_bgl)],
338            immediate_size: 0,
339        });
340
341        // **P2-1.3 纹理 mask** — 只缩放目的地 alpha,保留 RGB。
342        // layer texture 走 blit 的 straight-alpha 约定:若 RGB 也乘 src.a,
343        // blit 再乘一次 alpha 会双重变暗(BUG:50% mask 变成 25%)。
344        let mask_blend = wgpu::BlendState {
345            color: wgpu::BlendComponent {
346                src_factor: wgpu::BlendFactor::Zero,
347                dst_factor: wgpu::BlendFactor::One,
348                operation: wgpu::BlendOperation::Add,
349            },
350            alpha: wgpu::BlendComponent {
351                src_factor: wgpu::BlendFactor::Zero,
352                dst_factor: wgpu::BlendFactor::SrcAlpha,
353                operation: wgpu::BlendOperation::Add,
354            },
355        };
356
357        let text_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
358            label: Some("text-pipeline"),
359            layout: Some(&text_pipeline_layout),
360            vertex: wgpu::VertexState {
361                module: &text_shader,
362                entry_point: Some("vs_main"),
363                compilation_options: Default::default(),
364                buffers: &[],
365            },
366            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
367            depth_stencil: None,
368            // text glyph atlas 自带 alpha AA,MSAA 会额外糊一层
369            multisample: text_msaa,
370            fragment: Some(wgpu::FragmentState {
371                module: &text_shader,
372                entry_point: Some("fs_main"),
373                compilation_options: Default::default(),
374                targets: &[Some(wgpu::ColorTargetState {
375                    format,
376                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
377                    write_mask: wgpu::ColorWrites::ALL,
378                })],
379            }),
380            multiview_mask: None,
381            cache: None,
382        });
383
384        // 纹理 mask:同一 text shader,alpha 模式 + destination-in
385        let text_pipeline_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
386            label: Some("text-pipeline-mask"),
387            layout: Some(&text_pipeline_layout),
388            vertex: wgpu::VertexState {
389                module: &text_shader,
390                entry_point: Some("vs_main"),
391                compilation_options: Default::default(),
392                buffers: &[],
393            },
394            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
395            depth_stencil: None,
396            multisample: text_msaa,
397            fragment: Some(wgpu::FragmentState {
398                module: &text_shader,
399                entry_point: Some("fs_main"),
400                compilation_options: Default::default(),
401                targets: &[Some(wgpu::ColorTargetState {
402                    format,
403                    blend: Some(mask_blend),
404                    write_mask: wgpu::ColorWrites::ALL,
405                })],
406            }),
407            multiview_mask: None,
408            cache: None,
409        });
410
411        // ============ Stage T1:triangle pipeline ============
412        let tri_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
413            label: Some("tri-shader"),
414            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/tri.wgsl").into()),
415        });
416
417        let tri_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
418            label: Some("tri-bgl"),
419            entries: &[wgpu::BindGroupLayoutEntry {
420                binding: 0,
421                visibility: wgpu::ShaderStages::VERTEX,
422                ty: wgpu::BindingType::Buffer {
423                    ty: wgpu::BufferBindingType::Uniform,
424                    has_dynamic_offset: false,
425                    min_binding_size: None,
426                },
427                count: None,
428            }],
429        });
430
431        let tri_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
432            label: Some("tri-pipeline-layout"),
433            bind_group_layouts: &[Some(&tri_bgl)],
434            immediate_size: 0,
435        });
436
437        let tri_vb_layouts = [Some(wgpu::VertexBufferLayout {
438            array_stride: 24,
439            step_mode: wgpu::VertexStepMode::Vertex,
440            attributes: &[
441                wgpu::VertexAttribute { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float32x2 },
442                wgpu::VertexAttribute { offset: 8, shader_location: 1, format: wgpu::VertexFormat::Float32x4 },
443            ],
444        })];
445
446        let tri_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
447            label: Some("tri-pipeline"),
448            layout: Some(&tri_pipeline_layout),
449            vertex: wgpu::VertexState {
450                module: &tri_shader,
451                entry_point: Some("vs_main"),
452                compilation_options: Default::default(),
453                buffers: &tri_vb_layouts,
454            },
455            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
456            depth_stencil: None,
457            multisample: pass1_msaa,
458            fragment: Some(wgpu::FragmentState {
459                module: &tri_shader,
460                entry_point: Some("fs_main"),
461                compilation_options: Default::default(),
462                targets: &[Some(wgpu::ColorTargetState {
463                    format,
464                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
465                    write_mask: wgpu::ColorWrites::ALL,
466                })],
467            }),
468            multiview_mask: None,
469            cache: None,
470        });
471
472        // ============ **ClipPath GPU stencil** — pipeline variants ============
473        // 嵌套 mask:推入时 IncrementWrap、弹出时 DecrementWrap(双面同 op,
474        // 与三角形绕序无关);内容段用 Equal(depth) 测试 → 所有 clip 的交集。
475        let keep_op = wgpu::StencilOperation::Keep;
476
477        // ---- tri_pipeline_stencil_inc/dec:只写 stencil,color=NONE ----
478        let stencil_write_pipeline = |label: &'static str, op: wgpu::StencilOperation| {
479            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
480                label: Some(label),
481                layout: Some(&tri_pipeline_layout),
482                vertex: wgpu::VertexState {
483                    module: &tri_shader,
484                    entry_point: Some("vs_main"),
485                    compilation_options: Default::default(),
486                    buffers: &tri_vb_layouts,
487                },
488                primitive: wgpu::PrimitiveState {
489                    topology: wgpu::PrimitiveTopology::TriangleList,
490                    ..Default::default()
491                },
492                depth_stencil: Some(wgpu::DepthStencilState {
493                    format: STENCIL_FMT,
494                    depth_write_enabled: None,
495                    depth_compare: None,
496                    stencil: wgpu::StencilState {
497                        front: wgpu::StencilFaceState {
498                            compare: wgpu::CompareFunction::Always,
499                            fail_op: keep_op,
500                            depth_fail_op: keep_op,
501                            pass_op: op,
502                        },
503                        back: wgpu::StencilFaceState {
504                            compare: wgpu::CompareFunction::Always,
505                            fail_op: keep_op,
506                            depth_fail_op: keep_op,
507                            pass_op: op,
508                        },
509                        read_mask: 0xFF,
510                        write_mask: 0xFF,
511                    },
512                    bias: wgpu::DepthBiasState::default(),
513                }),
514                multisample: pass1_msaa,
515                fragment: Some(wgpu::FragmentState {
516                    module: &tri_shader,
517                    entry_point: Some("fs_main"),
518                    compilation_options: Default::default(),
519                    targets: &[Some(wgpu::ColorTargetState {
520                        format,
521                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
522                        write_mask: wgpu::ColorWrites::empty(), // 关键:只写 stencil,不写 color
523                    })],
524                }),
525                multiview_mask: None,
526                cache: None,
527            })
528        };
529        let tri_pipeline_stencil_inc =
530            stencil_write_pipeline("tri-pipeline-stencil-inc", wgpu::StencilOperation::IncrementWrap);
531        let tri_pipeline_stencil_dec =
532            stencil_write_pipeline("tri-pipeline-stencil-dec", wgpu::StencilOperation::DecrementWrap);
533
534        // ---- rect_pipelines_stencil_test:stencil Equal(depth) × 4 种混合模式 ----
535        let rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4] = std::array::from_fn(|i| {
536            make_rect_pipeline(
537                "rect-pipeline-stencil-test",
538                blend_state_for(RECT_BLEND_MODES[i]),
539                Some(stencil_equal_state()),
540            )
541        });
542
543        // ---- text_pipeline_stencil_test ----
544        let text_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
545            label: Some("text-pipeline-stencil-test"),
546            layout: Some(&text_pipeline_layout),
547            vertex: wgpu::VertexState {
548                module: &text_shader,
549                entry_point: Some("vs_main"),
550                compilation_options: Default::default(),
551                buffers: &[],
552            },
553            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
554            depth_stencil: Some(wgpu::DepthStencilState {
555                format: STENCIL_FMT,
556                depth_write_enabled: None,
557                depth_compare: None,
558                stencil: wgpu::StencilState {
559                    front: wgpu::StencilFaceState {
560                        compare: wgpu::CompareFunction::Equal,
561                        fail_op: keep_op,
562                        depth_fail_op: keep_op,
563                        pass_op: keep_op,
564                    },
565                    back: wgpu::StencilFaceState {
566                        compare: wgpu::CompareFunction::Equal,
567                        fail_op: keep_op,
568                        depth_fail_op: keep_op,
569                        pass_op: keep_op,
570                    },
571                    read_mask: 0xFF,
572                    write_mask: 0,
573                },
574                bias: wgpu::DepthBiasState::default(),
575            }),
576            multisample: text_msaa,
577            fragment: Some(wgpu::FragmentState {
578                module: &text_shader,
579                entry_point: Some("fs_main"),
580                compilation_options: Default::default(),
581                targets: &[Some(wgpu::ColorTargetState {
582                    format,
583                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
584                    write_mask: wgpu::ColorWrites::ALL,
585                })],
586            }),
587            multiview_mask: None,
588            cache: None,
589        });
590
591        // ---- text_pipeline_mask_stencil_test:mask 在 ClipPath/ClipRRect 内也精确裁剪 ----
592        let text_pipeline_mask_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
593            label: Some("text-pipeline-mask-stencil-test"),
594            layout: Some(&text_pipeline_layout),
595            vertex: wgpu::VertexState {
596                module: &text_shader,
597                entry_point: Some("vs_main"),
598                compilation_options: Default::default(),
599                buffers: &[],
600            },
601            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
602            depth_stencil: Some(wgpu::DepthStencilState {
603                format: STENCIL_FMT,
604                depth_write_enabled: None,
605                depth_compare: None,
606                stencil: wgpu::StencilState {
607                    front: wgpu::StencilFaceState {
608                        compare: wgpu::CompareFunction::Equal,
609                        fail_op: keep_op,
610                        depth_fail_op: keep_op,
611                        pass_op: keep_op,
612                    },
613                    back: wgpu::StencilFaceState {
614                        compare: wgpu::CompareFunction::Equal,
615                        fail_op: keep_op,
616                        depth_fail_op: keep_op,
617                        pass_op: keep_op,
618                    },
619                    read_mask: 0xFF,
620                    write_mask: 0,
621                },
622                bias: wgpu::DepthBiasState::default(),
623            }),
624            multisample: text_msaa,
625            fragment: Some(wgpu::FragmentState {
626                module: &text_shader,
627                entry_point: Some("fs_main"),
628                compilation_options: Default::default(),
629                targets: &[Some(wgpu::ColorTargetState {
630                    format,
631                    blend: Some(mask_blend),
632                    write_mask: wgpu::ColorWrites::ALL,
633                })],
634            }),
635            multiview_mask: None,
636            cache: None,
637        });
638
639        // ---- tri_pipeline_stencil_test ----
640        let tri_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
641            label: Some("tri-pipeline-stencil-test"),
642            layout: Some(&tri_pipeline_layout),
643            vertex: wgpu::VertexState {
644                module: &tri_shader,
645                entry_point: Some("vs_main"),
646                compilation_options: Default::default(),
647                buffers: &tri_vb_layouts,
648            },
649            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
650            depth_stencil: Some(wgpu::DepthStencilState {
651                format: STENCIL_FMT,
652                depth_write_enabled: None,
653                depth_compare: None,
654                stencil: wgpu::StencilState {
655                    front: wgpu::StencilFaceState {
656                        compare: wgpu::CompareFunction::Equal,
657                        fail_op: keep_op,
658                        depth_fail_op: keep_op,
659                        pass_op: keep_op,
660                    },
661                    back: wgpu::StencilFaceState {
662                        compare: wgpu::CompareFunction::Equal,
663                        fail_op: keep_op,
664                        depth_fail_op: keep_op,
665                        pass_op: keep_op,
666                    },
667                    read_mask: 0xFF,
668                    write_mask: 0,
669                },
670                bias: wgpu::DepthBiasState::default(),
671            }),
672            multisample: pass1_msaa,
673            fragment: Some(wgpu::FragmentState {
674                module: &tri_shader,
675                entry_point: Some("fs_main"),
676                compilation_options: Default::default(),
677                targets: &[Some(wgpu::ColorTargetState {
678                    format,
679                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
680                    write_mask: wgpu::ColorWrites::ALL,
681                })],
682            }),
683            multiview_mask: None,
684            cache: None,
685        });
686
687        // ============ 阶段 4-B:blit pipeline(全屏 sample layer texture) ============
688        let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
689            label: Some("blit-shader"),
690            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/blit.wgsl").into()),
691        });
692        let blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
693            label: Some("blit-bgl"),
694            entries: &[
695                wgpu::BindGroupLayoutEntry {
696                    binding: 0,
697                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
698                    ty: wgpu::BindingType::Buffer {
699                        ty: wgpu::BufferBindingType::Uniform,
700                        has_dynamic_offset: false,
701                        min_binding_size: None,
702                    },
703                    count: None,
704                },
705                wgpu::BindGroupLayoutEntry {
706                    binding: 1,
707                    visibility: wgpu::ShaderStages::FRAGMENT,
708                    ty: wgpu::BindingType::Texture {
709                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
710                        view_dimension: wgpu::TextureViewDimension::D2,
711                        multisampled: false,
712                    },
713                    count: None,
714                },
715                wgpu::BindGroupLayoutEntry {
716                    binding: 2,
717                    visibility: wgpu::ShaderStages::FRAGMENT,
718                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
719                    count: None,
720                },
721            ],
722        });
723        let blit_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
724            label: Some("blit-pipeline-layout"),
725            bind_group_layouts: &[Some(&blit_bgl)],
726            immediate_size: 0,
727        });
728        let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
729            label: Some("blit-pipeline"),
730            layout: Some(&blit_pipeline_layout),
731            vertex: wgpu::VertexState {
732                module: &blit_shader,
733                entry_point: Some("vs_main"),
734                compilation_options: Default::default(),
735                buffers: &[],
736            },
737            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
738            depth_stencil: None,
739            // blit 画到 surface(单采样),必须 count=1
740            multisample: wgpu::MultisampleState::default(),
741            fragment: Some(wgpu::FragmentState {
742                module: &blit_shader,
743                entry_point: Some("fs_main"),
744                compilation_options: Default::default(),
745                targets: &[Some(wgpu::ColorTargetState {
746                    format,
747                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
748                    write_mask: wgpu::ColorWrites::ALL,
749                })],
750            }),
751            multiview_mask: None,
752            cache: None,
753        });
754        // ============ P2-1.4b:背景模糊 pipeline ============
755        let backdrop_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
756            label: Some("backdrop-shader"),
757            source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/backdrop.wgsl").into()),
758        });
759        let backdrop_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
760            label: Some("backdrop-bgl"),
761            entries: &[
762                wgpu::BindGroupLayoutEntry {
763                    binding: 0,
764                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
765                    ty: wgpu::BindingType::Buffer {
766                        ty: wgpu::BufferBindingType::Uniform,
767                        has_dynamic_offset: false,
768                        min_binding_size: None,
769                    },
770                    count: None,
771                },
772                wgpu::BindGroupLayoutEntry {
773                    binding: 1,
774                    visibility: wgpu::ShaderStages::FRAGMENT,
775                    ty: wgpu::BindingType::Texture {
776                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
777                        view_dimension: wgpu::TextureViewDimension::D2,
778                        multisampled: false,
779                    },
780                    count: None,
781                },
782                wgpu::BindGroupLayoutEntry {
783                    binding: 2,
784                    visibility: wgpu::ShaderStages::FRAGMENT,
785                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
786                    count: None,
787                },
788            ],
789        });
790        let backdrop_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
791            label: Some("backdrop-pipeline-layout"),
792            bind_group_layouts: &[Some(&backdrop_bgl)],
793            immediate_size: 0,
794        });
795        let backdrop_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
796            label: Some("backdrop-pipeline"),
797            layout: Some(&backdrop_pipeline_layout),
798            vertex: wgpu::VertexState {
799                module: &backdrop_shader,
800                entry_point: Some("vs_main"),
801                compilation_options: Default::default(),
802                buffers: &[],
803            },
804            primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
805            // 背景模糊层始终带 stencil attachment,保证 clip 生效
806            depth_stencil: Some(stencil_equal_state()),
807            multisample: pass1_msaa,
808            fragment: Some(wgpu::FragmentState {
809                module: &backdrop_shader,
810                entry_point: Some("fs_main"),
811                compilation_options: Default::default(),
812                targets: &[Some(wgpu::ColorTargetState {
813                    format,
814                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
815                    write_mask: wgpu::ColorWrites::ALL,
816                })],
817            }),
818            multiview_mask: None,
819            cache: None,
820        });
821
822        let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
823            address_mode_u: wgpu::AddressMode::ClampToEdge,
824            address_mode_v: wgpu::AddressMode::ClampToEdge,
825            address_mode_w: wgpu::AddressMode::ClampToEdge,
826            mag_filter: wgpu::FilterMode::Linear,
827            min_filter: wgpu::FilterMode::Linear,
828            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
829            ..Default::default()
830        });
831
832        Self {
833            rect_pipelines,
834            rect_bgl,
835            text_pipeline,
836            text_bgl,
837            text_pipeline_mask,
838            text_pipeline_mask_stencil_test,
839            tri_pipeline,
840            tri_bgl,
841            tri_pipeline_stencil_inc,
842            tri_pipeline_stencil_dec,
843            rect_pipelines_stencil_test,
844            text_pipeline_stencil_test,
845            tri_pipeline_stencil_test,
846            atlas_cache: Rc::new(RefCell::new(None)),
847            layer_cache: HashMap::new(),
848            blit_pipeline,
849            blit_bgl,
850            blit_sampler,
851            backdrop_pipeline,
852            backdrop_bgl,
853            // 阶段 2-E 修复:记录 surface 格式 — layer texture 必须用同一格式,
854            // 否则 rect/text pipeline(render target = surface 格式)画进
855            // layer texture 时 wgpu validation error
856            format,
857            // P2:frame 级复用容器
858            active_layer_ids: std::collections::HashSet::new(),
859            frame_layer_sizes: HashMap::new(),
860            composition_scratch: mgui_core::CompositionScratch::default(),
861            // 阶段 B4:GPU timestamp profiler(可选,无 TIMESTAMP_QUERY 时 None)
862            gpu_profiler: crate::gpu_profiler::GpuProfiler::new(device),
863            // 阶段 B1.5:per-layer buffer pool
864            batch_pools: HashMap::new(),
865            image_cache: Rc::new(RefCell::new(ImageTextureCache { evict_enabled: true, ..Default::default() })),
866            msaa_scratch: HashMap::new(),
867            stencil_scratch: HashMap::new(),
868            snapshot_scratch: HashMap::new(),
869            last_stats: RenderStats::default(),
870        }
871    }
872
873    /// 确保 GPU atlas 资源是最新的
874    ///
875    /// - size 变化 → 重建 texture/view/sampler
876    /// - dirty    → `write_texture` 上传新像素
877    /// - 其他     → 复用 cache
878    pub(crate) fn ensure_atlas(
879        &mut self,
880        device: &wgpu::Device,
881        queue: &wgpu::Queue,
882    ) -> (wgpu::TextureView, wgpu::Sampler) {
883        let snap = crate::text::atlas_snapshot();
884        let mut atlas_cache = self.atlas_cache.borrow_mut();
885
886        let need_recreate = match atlas_cache.as_ref() {
887            None => true,
888            Some(c) => c.cached_size != (snap.width, snap.height),
889        };
890
891        if need_recreate {
892            log::info!("atlas: rebuild texture (size {}x{}, dirty={})", snap.width, snap.height, snap.dirty);
893            // 第一次或尺寸变化 → 重建(texture 初值为 0,只需上传 dirty 行)
894            let (dy0, dy1) = snap.dirty_y;
895            let rows = dy1.saturating_sub(dy0);
896            let pixels = snap.pixels.as_deref().filter(|p| !p.is_empty()).unwrap_or(&[]);
897            let texture = device.create_texture(&wgpu::TextureDescriptor {
898                label: Some("glyph-atlas"),
899                size: wgpu::Extent3d { width: snap.width, height: snap.height, depth_or_array_layers: 1 },
900                mip_level_count: 1,
901                sample_count: 1,
902                dimension: wgpu::TextureDimension::D2,
903                format: wgpu::TextureFormat::R8Unorm,
904                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
905                view_formats: &[],
906            });
907            if rows > 0 && !pixels.is_empty() {
908                queue.write_texture(
909                    wgpu::TexelCopyTextureInfo {
910                        texture: &texture,
911                        mip_level: 0,
912                        origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
913                        aspect: wgpu::TextureAspect::All,
914                    },
915                    pixels,
916                    wgpu::TexelCopyBufferLayout {
917                        offset: 0,
918                        bytes_per_row: Some(snap.width),
919                        rows_per_image: Some(rows),
920                    },
921                    wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
922                );
923            }
924            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
925            let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
926                address_mode_u: wgpu::AddressMode::ClampToEdge,
927                address_mode_v: wgpu::AddressMode::ClampToEdge,
928                address_mode_w: wgpu::AddressMode::ClampToEdge,
929                mag_filter: wgpu::FilterMode::Linear,
930                min_filter: wgpu::FilterMode::Linear,
931                mipmap_filter: wgpu::MipmapFilterMode::Nearest,
932                ..Default::default()
933            });
934            *atlas_cache = Some(AtlasGpu { texture, view, sampler, cached_size: (snap.width, snap.height) });
935        } else if snap.dirty {
936            let (dy0, dy1) = snap.dirty_y;
937            let rows = dy1.saturating_sub(dy0);
938            log::info!("atlas: upload {} KB (rows {}..{})", (snap.width * rows) as usize / 1024, dy0, dy1);
939            // 尺寸未变但有新 glyph → 只上传本次写入的行区间(整行宽度满足对齐)
940            if rows > 0 {
941                if let (Some(cache), Some(pixels)) = (atlas_cache.as_ref(), snap.pixels.as_deref()) {
942                    queue.write_texture(
943                        wgpu::TexelCopyTextureInfo {
944                            texture: &cache.texture,
945                            mip_level: 0,
946                            origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
947                            aspect: wgpu::TextureAspect::All,
948                        },
949                        pixels,
950                        wgpu::TexelCopyBufferLayout {
951                            offset: 0,
952                            bytes_per_row: Some(snap.width),
953                            rows_per_image: Some(rows),
954                        },
955                        wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
956                    );
957                }
958            }
959        }
960
961        // 同步 CPU 端 dirty 状态(避免下次又走上传分支)
962        if snap.dirty {
963            crate::text::atlas_clear_dirty();
964        }
965
966        let atlas = atlas_cache.as_ref().expect("atlas cache populated");
967        (atlas.view.clone(), atlas.sampler.clone())
968    }
969
970    /// 渲染一帧(阶段 4-B + 4-D:layer GPU cache + 嵌套层隔离 + DPR + offset/size blit)。
971    ///
972    /// 流程:
973    /// 1. **Pass 1**(为每个 dirty layer 独立一个 render pass):
974    ///    把 layer 的 `paint_list` 画到 layer 自己的 GPU texture(按 `logical_size` 物理像素大小)
975    /// 2. **Pass 2**(一次 render pass 到 surface):
976    ///    按 z_order 升序 blit 每个 layer 的 texture 到 surface 的 (offset.x, offset.y) 位置
977    ///    (逻辑坐标),alpha 混合叠加
978    ///
979    /// 干净 layer 在 Pass 1 被跳过(其 GPU cache 保持上次的画);在 Pass 2 被 blit
980    /// 到 surface(blit 操作很便宜,几乎免费)。**真正的局部重画完成**。
981    ///
982    /// 阶段 4-D(候选 2):layer offset/size
983    /// - 每个 layer texture 大小 = logical_size * dpr(None 时 fallback 全屏)
984    /// - blit 时按 layer.offset 把 texture 画到 surface 的 logical 位置
985    /// - 高分屏(2.0/3.0 dpr)下小 layer 用小 texture,大幅节省 fillrate
986    ///
987    /// 阶段 4-D(候选 3):DPR 支持
988    /// - `screen_size`:logical 尺寸(pixel),用于 rect/text 顶点坐标(归一化)
989    /// - `physical_size`:物理像素尺寸,用于 layer texture 大小 + surface viewport
990    ///   比例=physical/logical,典型 1.0/1.5/2.0/3.0
991    ///
992    /// 阶段 4-B + 4-D:确保所有 layer 都有 GPU cache(按需创建/重建)
993    ///
994    /// 阶段 4-D 新行为:
995    /// - 每个 layer texture 大小 = `logical_size * dpr`(None 时 fallback 全屏)
996    /// - size 变化(重新 layout 后)时重建 texture
997    /// - 同一 layer 多次 paint 复用同一 texture(只要 size 没变)
998    ///
999    /// P1-4:总字节预算。所有活跃 layer 的目标尺寸先按 `dpr` 计算,若总和超过
1000    /// [`LAYER_TEXTURE_BUDGET_BYTES`],统一按面积比例降采样(几何不变,只降低
1001    /// 分辨率);极端多 layer/4K/高 DPI 下不会无限占用显存。
1002    pub(crate) fn ensure_all_layer_caches(
1003        &mut self,
1004        device: &wgpu::Device,
1005        layer_paints: &[LayerPaint],
1006        dpr: f32,
1007        screen_size: (f32, f32),
1008    ) {
1009        let max_dim = device.limits().max_texture_dimension_2d.max(1);
1010        let (targets, scale) =
1011            layer_texture_targets(layer_paints, dpr, screen_size, max_dim, LAYER_TEXTURE_BUDGET_BYTES);
1012        if scale < 0.999 {
1013            log::debug!(
1014                target: "mgui_profile",
1015                "layer texture budget exceeded: rendering {} layers at {:.0}% resolution",
1016                targets.len(),
1017                scale * 100.0
1018            );
1019        }
1020
1021        for (layer_id, tex_size) in targets {
1022            // P2-1.5:每层只保留持久的 resolve texture;MSAA/stencil/snapshot
1023            // 改为跨 layer 复用的 scratch(见 msaa_scratch_view / stencil_scratch_view)。
1024            let need_create = match self.layer_cache.get(&layer_id) {
1025                None => true,
1026                Some(c) => c.cached_size != tex_size,
1027            };
1028            if need_create {
1029                let resolve_tex = device.create_texture(&wgpu::TextureDescriptor {
1030                    label: Some("layer-resolve"),
1031                    size: wgpu::Extent3d { width: tex_size.0, height: tex_size.1, depth_or_array_layers: 1 },
1032                    mip_level_count: 1,
1033                    sample_count: 1,
1034                    dimension: wgpu::TextureDimension::D2,
1035                    format: self.format,
1036                    // resolve texture 既可做 resolve_target(RENDER_ATTACHMENT)又可被 blit 采样
1037                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT
1038                        | wgpu::TextureUsages::TEXTURE_BINDING
1039                        | wgpu::TextureUsages::COPY_SRC,
1040                    view_formats: &[],
1041                });
1042                let resolve_view = resolve_tex.create_view(&wgpu::TextureViewDescriptor::default());
1043                self.layer_cache.insert(
1044                    layer_id,
1045                    LayerGpuCache { resolve_texture: resolve_tex, resolve_view, cached_size: tex_size },
1046                );
1047            }
1048        }
1049    }
1050
1051    /// P2-1.5:按尺寸复用 MSAA scratch(sample_count=4)。
1052    pub(super) fn msaa_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
1053        if let Some(v) = self.msaa_scratch.get(&size) {
1054            return v.clone();
1055        }
1056        let tex = device.create_texture(&wgpu::TextureDescriptor {
1057            label: Some("scratch-msaa"),
1058            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1059            mip_level_count: 1,
1060            sample_count: 4,
1061            dimension: wgpu::TextureDimension::D2,
1062            format: self.format,
1063            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1064            view_formats: &[],
1065        });
1066        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1067        self.msaa_scratch.insert(size, view.clone());
1068        view
1069    }
1070
1071    /// P2-1.5:按尺寸复用 stencil scratch(MSAA sample_count=4)。
1072    pub(super) fn stencil_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
1073        if let Some(v) = self.stencil_scratch.get(&size) {
1074            return v.clone();
1075        }
1076        let tex = device.create_texture(&wgpu::TextureDescriptor {
1077            label: Some("scratch-stencil"),
1078            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1079            mip_level_count: 1,
1080            sample_count: 4,
1081            dimension: wgpu::TextureDimension::D2,
1082            format: wgpu::TextureFormat::Stencil8,
1083            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1084            view_formats: &[],
1085        });
1086        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1087        self.stencil_scratch.insert(size, view.clone());
1088        view
1089    }
1090
1091    /// P2-1.5:按尺寸复用背景模糊 snapshot(单采样)。
1092    pub(super) fn snapshot_scratch(
1093        &mut self,
1094        device: &wgpu::Device,
1095        size: (u32, u32),
1096    ) -> (wgpu::Texture, wgpu::TextureView) {
1097        if let Some((tex, view)) = self.snapshot_scratch.get(&size) {
1098            return (tex.clone(), view.clone());
1099        }
1100        let tex = device.create_texture(&wgpu::TextureDescriptor {
1101            label: Some("scratch-snapshot"),
1102            size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1103            mip_level_count: 1,
1104            sample_count: 1,
1105            dimension: wgpu::TextureDimension::D2,
1106            format: self.format,
1107            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1108            view_formats: &[],
1109        });
1110        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1111        self.snapshot_scratch.insert(size, (tex.clone(), view.clone()));
1112        (tex, view)
1113    }
1114
1115    // ================================================================
1116    // 阶段 5 入口已上移到 render() 里调用 build_blit_uniform
1117    // ================================================================
1118}
1119
1120// 重新打开 impl Renderer 包含后续 build_paint_bind_groups
1121// (build_blit_uniform 是 free function,定义在下面 impl 之外)
1122
1123/// 阶段 5:从 LayerPaint 的 effect 字段生成 BlitUniform(单层,无父级继承)。
1124/// 渲染主路径使用 `build_blit_uniform_composed`;此函数仅供单测。
1125#[cfg(test)]
1126pub(crate) fn build_blit_uniform(lp: &LayerPaint, layer_logical_size: &Size, screen_size: (f32, f32)) -> BlitUniform {
1127    let comp = LayerComposition::single(lp, *layer_logical_size);
1128    build_blit_uniform_composed(lp, &comp, layer_logical_size, screen_size)
1129}
1130
1131/// 用已解析的合成参数构造 blit uniform。
1132///
1133/// 兼容字段(rotation/scale/clip_radius/quad_*)保留给测试与调试;
1134/// shader 实际使用 `affine` / `affine_translate` / `clip_rect*`。
1135pub(crate) fn build_blit_uniform_composed(
1136    lp: &LayerPaint,
1137    comp: &LayerComposition,
1138    layer_logical_size: &Size,
1139    screen_size: (f32, f32),
1140) -> BlitUniform {
1141    let mut flags: u32 = 0;
1142    let mut rotation = 0.0_f32;
1143    let mut scale_x = 1.0_f32;
1144    let mut scale_y = 1.0_f32;
1145    let mut translate_x = 0.0_f32;
1146    let mut translate_y = 0.0_f32;
1147    let mut clip_radius = 0.0_f32;
1148
1149    match lp.effect {
1150        LayerEffect::None => {}
1151        LayerEffect::Transform(t) => {
1152            if !t.is_identity() {
1153                flags |= effect_flags::HAS_TRANSFORM;
1154            }
1155            rotation = t.rotation;
1156            scale_x = t.scale_x;
1157            scale_y = t.scale_y;
1158            translate_x = t.translate.x;
1159            translate_y = t.translate.y;
1160        }
1161        LayerEffect::Opacity(_) => {}
1162        LayerEffect::ClipRRect(RRectDef { radius }) => {
1163            clip_radius = radius;
1164        }
1165    }
1166    if comp.opacity < 1.0 {
1167        flags |= effect_flags::HAS_OPACITY;
1168    }
1169    if !comp.clips.is_empty() {
1170        flags |= effect_flags::HAS_CLIP;
1171    }
1172
1173    let w = layer_logical_size.width;
1174    let h = layer_logical_size.height;
1175    let mut clip_rect0 = [0.0; 4];
1176    let mut clip_rect1 = [0.0; 4];
1177    let mut clip_params = [0.0; 4];
1178    if let Some(c) = comp.clips.first() {
1179        clip_rect0 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
1180        clip_params[0] = c.radius;
1181    }
1182    if let Some(c) = comp.clips.get(1) {
1183        clip_rect1 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
1184        clip_params[1] = c.radius;
1185    }
1186    clip_params[2] = comp.clips.len().min(2) as f32;
1187
1188    BlitUniform {
1189        offset: [lp.offset.x, lp.offset.y],
1190        size: [w, h],
1191        screen: [screen_size.0, screen_size.1],
1192        effect_flags: flags,
1193        opacity: comp.opacity,
1194        rotation,
1195        scale_x,
1196        translate_x,
1197        translate_y,
1198        clip_radius,
1199        scale_y,
1200        quad_offset: [lp.offset.x, lp.offset.y],
1201        quad_size: [w, h],
1202        // phys_screen 由调用点按 dpr 填(build_blit_uniform 不感知设备)
1203        phys_screen: [0.0, 0.0],
1204        affine: [comp.affine.a, comp.affine.b, comp.affine.c, comp.affine.d],
1205        affine_translate: [comp.affine.tx, comp.affine.ty],
1206        _affine_pad: [0.0; 2],
1207        clip_rect0,
1208        clip_rect1,
1209        clip_params,
1210    }
1211}