Skip to main content

velox_engine/renderers/wgpu/
pipeline.rs

1//! `WgpuRenderer` 核心 2D SDF 渲染管线(单 RenderPass / 单 Draw Call 合批编码、分数 DPI Pixel Snapping 与提交)。
2
3use ::wgpu;
4use std::collections::HashMap;
5use std::string::String;
6use std::sync::Arc;
7use std::vec::Vec;
8
9use crate::display::{measure_char_advance, measure_char_kerning, Rgba8888};
10use crate::element::SpriteSource;
11use crate::motion::{DrawOp, DrawPayload};
12use crate::renderers::software::{
13    align_offset_x, compute_scaled_text_box, compute_unoccluded_clip, rasterize_sprite_source,
14    split_text_lines,
15};
16use crate::solver::Region;
17use crate::style::Color;
18
19use super::atlas::{GlyphAtlas, SpriteAtlas, SpriteCacheKey, GLYPH_ATLAS_INIT_SIZE};
20use super::{
21    color_to_f32, make_arc_primitive, make_quad_primitive, make_shadow_primitive, pod_as_bytes,
22    snap_bounds, snap_clip, GpuPrimitive, ViewportUniform, KIND_GLYPH, KIND_SPRITE,
23};
24
25const SDF_WGSL: &str = include_str!("shader.wgsl");
26const INITIAL_INSTANCE_CAPACITY: usize = 512;
27const MAX_TEXT_LAYOUT_CACHE_ENTRIES: usize = 512;
28
29#[derive(Copy, Clone, PartialEq, Eq, Hash)]
30struct TextLayoutKey {
31    text_hash: u64,
32    text_len: u32,
33    logical_font_size: u8,
34    font_size_q4: u16,
35    max_width: i16,
36    text_flags: u8,
37    use_ttf: bool,
38}
39
40#[derive(Copy, Clone)]
41struct ShapedGlyphPos {
42    ch: char,
43    rel_x: i16,
44    rel_y: i16,
45}
46
47struct CachedTextLayout {
48    text: String,
49    total_h: i16,
50    glyphs: Vec<ShapedGlyphPos>,
51}
52
53#[inline]
54fn hash_layout_text(text: &str) -> u64 {
55    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
56    for &b in text.as_bytes() {
57        h ^= b as u64;
58        h = h.wrapping_mul(0x0100_0000_01b3);
59    }
60    h
61}
62
63/// 自研轻量级 `wgpu` 2D SDF 渲染管线核心(绑定任意目标 `TextureView` 即可渲染)。
64pub struct WgpuRenderer {
65    pipeline: wgpu::RenderPipeline,
66    bind_group_layout: wgpu::BindGroupLayout,
67    bind_group: wgpu::BindGroup,
68    viewport_buf: wgpu::Buffer,
69    instance_buf: wgpu::Buffer,
70    instance_capacity: usize,
71    sampler: wgpu::Sampler,
72    glyph_atlas: GlyphAtlas,
73    sprite_atlas: SpriteAtlas,
74    primitives: Vec<GpuPrimitive>,
75    sprite_scratch: Vec<Rgba8888>,
76    #[cfg(not(target_endian = "little"))]
77    sprite_bytes_scratch: Vec<u8>,
78    text_layout_cache: HashMap<TextLayoutKey, Arc<CachedTextLayout>>,
79    text_layout_hits: u64,
80    target_is_srgb: bool,
81}
82
83impl WgpuRenderer {
84    /// 基于已有 `wgpu::Device` 与目标表面像素格式创建 2D SDF 渲染管线。
85    pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
86        let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
87        let t0 = std::time::Instant::now();
88        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
89            label: Some("velox_wgpu_2d_shader"),
90            source: wgpu::ShaderSource::Wgsl(SDF_WGSL.into()),
91        });
92        let t_shader = t0.elapsed();
93
94        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
95            label: Some("velox_wgpu_bgl"),
96            entries: &[
97                wgpu::BindGroupLayoutEntry {
98                    binding: 0,
99                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
100                    ty: wgpu::BindingType::Buffer {
101                        ty: wgpu::BufferBindingType::Uniform,
102                        has_dynamic_offset: false,
103                        min_binding_size: None,
104                    },
105                    count: None,
106                },
107                wgpu::BindGroupLayoutEntry {
108                    binding: 1,
109                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
110                    ty: wgpu::BindingType::Buffer {
111                        ty: wgpu::BufferBindingType::Storage { read_only: true },
112                        has_dynamic_offset: false,
113                        min_binding_size: None,
114                    },
115                    count: None,
116                },
117                wgpu::BindGroupLayoutEntry {
118                    binding: 2,
119                    visibility: wgpu::ShaderStages::FRAGMENT,
120                    ty: wgpu::BindingType::Texture {
121                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
122                        view_dimension: wgpu::TextureViewDimension::D2,
123                        multisampled: false,
124                    },
125                    count: None,
126                },
127                wgpu::BindGroupLayoutEntry {
128                    binding: 3,
129                    visibility: wgpu::ShaderStages::FRAGMENT,
130                    ty: wgpu::BindingType::Texture {
131                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
132                        view_dimension: wgpu::TextureViewDimension::D2,
133                        multisampled: false,
134                    },
135                    count: None,
136                },
137                wgpu::BindGroupLayoutEntry {
138                    binding: 4,
139                    visibility: wgpu::ShaderStages::FRAGMENT,
140                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
141                    count: None,
142                },
143            ],
144        });
145
146        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
147            label: Some("velox_wgpu_pipeline_layout"),
148            bind_group_layouts: &[Some(&bind_group_layout)],
149            immediate_size: 0,
150        });
151
152        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
153            label: Some("velox_wgpu_2d_pipeline"),
154            layout: Some(&pipeline_layout),
155            vertex: wgpu::VertexState {
156                module: &shader,
157                entry_point: Some("vs_main"),
158                compilation_options: wgpu::PipelineCompilationOptions::default(),
159                buffers: &[],
160            },
161            primitive: wgpu::PrimitiveState {
162                topology: wgpu::PrimitiveTopology::TriangleList,
163                strip_index_format: None,
164                front_face: wgpu::FrontFace::Ccw,
165                cull_mode: None,
166                unclipped_depth: false,
167                polygon_mode: wgpu::PolygonMode::Fill,
168                conservative: false,
169            },
170            depth_stencil: None,
171            multisample: wgpu::MultisampleState::default(),
172            fragment: Some(wgpu::FragmentState {
173                module: &shader,
174                entry_point: Some("fs_main"),
175                compilation_options: wgpu::PipelineCompilationOptions::default(),
176                targets: &[Some(wgpu::ColorTargetState {
177                    format: target_format,
178                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
179                    write_mask: wgpu::ColorWrites::ALL,
180                })],
181            }),
182            multiview_mask: None,
183            cache: None,
184        });
185        let t_pso = t0.elapsed();
186        if trace {
187            std::println!(
188                "[VELOX_STARTUP_TRACE]   pipeline detail: create_shader_module={:.1}ms, create_render_pipeline=+{:.1}ms",
189                t_shader.as_secs_f64() * 1000.0,
190                (t_pso - t_shader).as_secs_f64() * 1000.0,
191            );
192        }
193
194        let viewport_buf = device.create_buffer(&wgpu::BufferDescriptor {
195            label: Some("velox_wgpu_viewport"),
196            size: core::mem::size_of::<ViewportUniform>() as u64,
197            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
198            mapped_at_creation: false,
199        });
200
201        let instance_buf = Self::create_instance_buffer(device, INITIAL_INSTANCE_CAPACITY);
202        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
203            label: Some("velox_atlas_sampler"),
204            address_mode_u: wgpu::AddressMode::ClampToEdge,
205            address_mode_v: wgpu::AddressMode::ClampToEdge,
206            address_mode_w: wgpu::AddressMode::ClampToEdge,
207            mag_filter: wgpu::FilterMode::Nearest,
208            min_filter: wgpu::FilterMode::Nearest,
209            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
210            ..Default::default()
211        });
212
213        let glyph_atlas = GlyphAtlas::new(device, GLYPH_ATLAS_INIT_SIZE);
214        let sprite_atlas = SpriteAtlas::new(device, 1);
215        let bind_group = Self::create_bind_group(
216            device,
217            &bind_group_layout,
218            &viewport_buf,
219            &instance_buf,
220            &glyph_atlas.view,
221            &sprite_atlas.view,
222            &sampler,
223        );
224
225        Self {
226            pipeline,
227            bind_group_layout,
228            bind_group,
229            viewport_buf,
230            instance_buf,
231            instance_capacity: INITIAL_INSTANCE_CAPACITY,
232            sampler,
233            glyph_atlas,
234            sprite_atlas,
235            primitives: Vec::with_capacity(INITIAL_INSTANCE_CAPACITY),
236            sprite_scratch: Vec::new(),
237            #[cfg(not(target_endian = "little"))]
238            sprite_bytes_scratch: Vec::new(),
239            text_layout_cache: HashMap::with_capacity(64),
240            text_layout_hits: 0,
241            target_is_srgb: target_format.is_srgb(),
242        }
243    }
244
245    fn create_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
246        device.create_buffer(&wgpu::BufferDescriptor {
247            label: Some("velox_wgpu_instances"),
248            size: (capacity.max(1) * core::mem::size_of::<GpuPrimitive>()) as u64,
249            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
250            mapped_at_creation: false,
251        })
252    }
253
254    fn create_bind_group(
255        device: &wgpu::Device,
256        layout: &wgpu::BindGroupLayout,
257        viewport_buf: &wgpu::Buffer,
258        instance_buf: &wgpu::Buffer,
259        glyph_view: &wgpu::TextureView,
260        sprite_view: &wgpu::TextureView,
261        sampler: &wgpu::Sampler,
262    ) -> wgpu::BindGroup {
263        device.create_bind_group(&wgpu::BindGroupDescriptor {
264            label: Some("velox_wgpu_bg"),
265            layout,
266            entries: &[
267                wgpu::BindGroupEntry {
268                    binding: 0,
269                    resource: viewport_buf.as_entire_binding(),
270                },
271                wgpu::BindGroupEntry {
272                    binding: 1,
273                    resource: instance_buf.as_entire_binding(),
274                },
275                wgpu::BindGroupEntry {
276                    binding: 2,
277                    resource: wgpu::BindingResource::TextureView(glyph_view),
278                },
279                wgpu::BindGroupEntry {
280                    binding: 3,
281                    resource: wgpu::BindingResource::TextureView(sprite_view),
282                },
283                wgpu::BindGroupEntry {
284                    binding: 4,
285                    resource: wgpu::BindingResource::Sampler(sampler),
286                },
287            ],
288        })
289    }
290
291    /// 返回最近一帧合批提交的 [`GpuPrimitive`] 实例数量。
292    #[inline]
293    pub fn last_primitive_count(&self) -> usize {
294        self.primitives.len()
295    }
296
297    /// 返回当前字形图集与精灵图集的物理像素边长 `(glyph_size, sprite_size)`。
298    #[inline]
299    pub const fn atlas_sizes(&self) -> (u32, u32) {
300        (self.glyph_atlas.width, self.sprite_atlas.width)
301    }
302
303    /// 返回静态精灵跨帧驻留缓存累计命中次数。
304    #[inline]
305    pub const fn sprite_cache_hits(&self) -> u64 {
306        self.sprite_atlas.cache_hits
307    }
308
309    /// 返回跨帧文本行排版缓存(`TextLayoutCache`)累计命中次数。
310    #[inline]
311    pub const fn text_layout_cache_hits(&self) -> u64 {
312        self.text_layout_hits
313    }
314
315    /// 返回跨帧文本行排版缓存当前驻留条目数。
316    #[inline]
317    pub fn text_layout_cache_len(&self) -> usize {
318        self.text_layout_cache.len()
319    }
320
321    fn rebuild_bind_group(&mut self, device: &wgpu::Device) {
322        self.bind_group = Self::create_bind_group(
323            device,
324            &self.bind_group_layout,
325            &self.viewport_buf,
326            &self.instance_buf,
327            &self.glyph_atlas.view,
328            &self.sprite_atlas.view,
329            &self.sampler,
330        );
331    }
332
333    #[inline]
334    fn sprite_cache_hash(sprite: SpriteSource<'_>, rel_x: i16, rel_y: i16, sb_w: i16, sb_h: i16) -> u64 {
335        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
336        let mix = |h: &mut u64, v: u64| {
337            *h ^= v;
338            *h = h.wrapping_mul(0x0100_0000_01b3);
339        };
340        mix(&mut h, ((rel_x as u16 as u64) << 16) | (rel_y as u16 as u64));
341        mix(&mut h, ((sb_w as u16 as u64) << 16) | (sb_h as u16 as u64));
342        match sprite {
343            SpriteSource::Bitmap {
344                bytes,
345                format,
346                tint,
347            } => {
348                mix(&mut h, 1);
349                mix(&mut h, bytes.as_ptr() as usize as u64);
350                mix(&mut h, bytes.len() as u64);
351                mix(&mut h, format as u64);
352                mix(&mut h, tint.0 as u64);
353            }
354            SpriteSource::Shader { state_hash, .. } => {
355                mix(&mut h, 2);
356                mix(&mut h, state_hash as u64);
357            }
358            SpriteSource::Svg {
359                source,
360                is_path_only,
361                tint,
362                stroke_width_x10,
363            } => {
364                mix(&mut h, 3);
365                mix(&mut h, if is_path_only { 1 } else { 0 });
366                mix(&mut h, stroke_width_x10 as u64);
367                mix(&mut h, tint.0 as u64);
368                let s = source.as_str().as_bytes();
369                mix(&mut h, s.len() as u64);
370                for &b in s {
371                    mix(&mut h, b as u64);
372                }
373            }
374            SpriteSource::Arc { .. } => {}
375        }
376        h
377    }
378
379    /// 将 `DrawOp` 编码为 `self.primitives` 并按需上传字形与精灵图集;
380    /// 若某个图集需要扩容则返回 `Err((need_glyph_grow, sprite_need))` 以便调用方扩容并重试一次。
381    fn try_encode_ops(
382        &mut self,
383        queue: &wgpu::Queue,
384        ops: &[DrawOp<'_>],
385        viewport: Region,
386        scale_factor: f32,
387    ) -> Result<(), (bool, Option<(u32, u32)>)> {
388        self.primitives.clear();
389        if viewport.is_empty() {
390            return Ok(());
391        }
392
393        let sf = scale_factor.clamp(0.5, 4.0);
394        let use_ttf = crate::display::ttf_atlas::has_system_font();
395
396        for (idx, op) in ops.iter().enumerate() {
397            let raw_clip = viewport.intersect(op.clip).intersect(op.bounds);
398            if raw_clip.is_empty() {
399                continue;
400            }
401            let eff_clip = compute_unoccluded_clip(raw_clip, &ops[(idx + 1)..]);
402            if eff_clip.is_empty() {
403                continue;
404            }
405
406            let sb_f = snap_bounds(op.bounds, sf);
407            // 当父容器启用了圆角裁切时保留原始圆角裁剪盒(避免前向遮挡收缩破坏四角圆角中心)
408            let clip_region = if op.clip_radius > 0 { op.clip } else { eff_clip };
409            let mut sc_f = snap_clip(clip_region, sf);
410            // 对未被遮挡的 1px 细线(光标、分割线、缩进参考线),避免 op.clip 预交集后的奇数坐标截断稳定物理线宽
411            if (op.bounds.w == 1 && eff_clip.w == 1) || (op.bounds.h == 1 && eff_clip.h == 1) {
412                let vp_clip_f = snap_clip(viewport, sf);
413                if op.bounds.w == 1 && eff_clip.w == 1 {
414                    sc_f[2] = sc_f[2].max(sb_f[0] + sb_f[2]).min(vp_clip_f[2]);
415                }
416                if op.bounds.h == 1 && eff_clip.h == 1 {
417                    sc_f[3] = sc_f[3].max(sb_f[1] + sb_f[3]).min(vp_clip_f[3]);
418                }
419            }
420            let clip_radius_px = (op.clip_radius as f32) * sf;
421
422            match op.payload {
423                DrawPayload::Quad {
424                    bg,
425                    bg_grad,
426                    border_color,
427                    rounded,
428                    border_width,
429                } => {
430                    let raw_bw = border_width & 0x7F;
431                    let bw = if raw_bw == 0 {
432                        0.0
433                    } else {
434                        ((raw_bw as f32) * sf).round().max(1.0)
435                    };
436                    let horiz = (border_width & 0x80) != 0;
437                    let r = (rounded as f32) * sf;
438                    let is_shadow = border_color.a() == 0 && raw_bw > 0;
439                    if is_shadow {
440                        if bg.a() > 0 {
441                            self.primitives.push(make_shadow_primitive(
442                                sb_f,
443                                sc_f,
444                                clip_radius_px,
445                                r,
446                                (raw_bw as f32) * sf,
447                                bg,
448                            ));
449                        }
450                    } else if bg.a() > 0 || bg_grad.a() > 0 || (bw > 0.0 && border_color.a() > 0) {
451                        self.primitives.push(make_quad_primitive(
452                            sb_f,
453                            sc_f,
454                            clip_radius_px,
455                            r,
456                            bw,
457                            horiz,
458                            bg,
459                            bg_grad,
460                            border_color,
461                        ));
462                    }
463                }
464                DrawPayload::TextRun {
465                    text,
466                    color,
467                    font_size,
468                    text_flags,
469                } => {
470                    if text.is_empty() || color.a() == 0 {
471                        continue;
472                    }
473                    let sb = Region::new(
474                        sb_f[0] as i16,
475                        sb_f[1] as i16,
476                        sb_f[2] as i16,
477                        sb_f[3] as i16,
478                    );
479                    let sc = Region::new(
480                        sc_f[0] as i16,
481                        sc_f[1] as i16,
482                        (sc_f[2] - sc_f[0]).max(0.0) as i16,
483                        (sc_f[3] - sc_f[1]).max(0.0) as i16,
484                    );
485                    // 与软件光栅器共享同一套 0.25px 亚像素字号与单行扩框真源,确保首屏切 GPU 0.00px 零漂移
486                    let (adj_bounds, adj_sc, adj_flags, logical_fs, fs_q4) =
487                        compute_scaled_text_box(
488                            op.bounds,
489                            op.clip,
490                            viewport,
491                            sb,
492                            sc,
493                            text.as_str(),
494                            font_size,
495                            text_flags,
496                            sf,
497                        );
498                    let adj_sc_f = [
499                        adj_sc.x as f32,
500                        adj_sc.y as f32,
501                        adj_sc.right() as f32,
502                        adj_sc.bottom() as f32,
503                    ];
504                    if !self.encode_text_run(
505                        queue,
506                        adj_bounds,
507                        adj_sc,
508                        adj_sc_f,
509                        clip_radius_px,
510                        text.as_str(),
511                        color,
512                        logical_fs,
513                        fs_q4,
514                        adj_flags,
515                        use_ttf,
516                    ) {
517                        return Err((true, None));
518                    }
519                }
520                DrawPayload::Sprite(SpriteSource::Arc {
521                    thickness,
522                    start_deg10,
523                    sweep_deg10,
524                    fill_sweep_deg10,
525                    track_color,
526                    fill_color,
527                }) => {
528                    // 原生 GPU 解析圆弧 SDF:零 CPU 光栅化、零纹理上传
529                    self.primitives.push(make_arc_primitive(
530                        sb_f,
531                        sc_f,
532                        clip_radius_px,
533                        ((thickness.max(1) as f32) * sf).max(1.5),
534                        start_deg10,
535                        sweep_deg10,
536                        fill_sweep_deg10,
537                        track_color,
538                        fill_color,
539                    ));
540                }
541                DrawPayload::Sprite(sprite) => {
542                    let sb = Region::new(
543                        sb_f[0] as i16,
544                        sb_f[1] as i16,
545                        sb_f[2] as i16,
546                        sb_f[3] as i16,
547                    );
548                    let sc = Region::new(
549                        sc_f[0] as i16,
550                        sc_f[1] as i16,
551                        (sc_f[2] - sc_f[0]).max(0.0) as i16,
552                        (sc_f[3] - sc_f[1]).max(0.0) as i16,
553                    );
554                    let eff = sc.intersect(sb);
555                    if eff.is_empty() {
556                        continue;
557                    }
558                    let w = eff.w.max(1) as usize;
559                    let h = eff.h.max(1) as usize;
560                    let cache_key = SpriteCacheKey {
561                        w: w as u32,
562                        h: h as u32,
563                        hash: Self::sprite_cache_hash(
564                            sprite,
565                            eff.x.saturating_sub(sb.x),
566                            eff.y.saturating_sub(sb.y),
567                            sb.w,
568                            sb.h,
569                        ),
570                    };
571
572                    let uv = if let Some(cached_uv) = self.sprite_atlas.lookup(cache_key) {
573                        cached_uv
574                    } else {
575                        let len = w * h;
576                        if self.sprite_scratch.len() < len {
577                            self.sprite_scratch.resize(len, Rgba8888(0));
578                        }
579                        let slice = &mut self.sprite_scratch[..len];
580                        slice.fill(Rgba8888(0));
581                        rasterize_sprite_source(sb, eff, sprite, eff.x, eff.y, w, slice);
582
583                        #[cfg(target_endian = "little")]
584                        let rgba_bytes: &[u8] = pod_as_bytes(slice);
585                        #[cfg(not(target_endian = "little"))]
586                        let rgba_bytes: &[u8] = {
587                            self.sprite_bytes_scratch.clear();
588                            self.sprite_bytes_scratch.reserve(len * 4);
589                            for px in slice.iter() {
590                                self.sprite_bytes_scratch
591                                    .extend_from_slice(&px.to_rgba_bytes());
592                            }
593                            &self.sprite_bytes_scratch
594                        };
595
596                        let Some(uv) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
597                        else {
598                            return Err((false, Some((w as u32, h as u32))));
599                        };
600                        uv
601                    };
602
603                    self.primitives.push(GpuPrimitive {
604                        bounds: [eff.x as f32, eff.y as f32, w as f32, h as f32],
605                        clip: sc_f,
606                        uv,
607                        color0: [1.0; 4],
608                        color1: [0.0; 4],
609                        border_color: [0.0; 4],
610                        params: [0.0, 0.0, KIND_SPRITE, 0.0],
611                        extra: [clip_radius_px, 0.0, 0.0, 0.0],
612                    });
613                }
614            }
615        }
616        Ok(())
617    }
618
619    fn get_or_build_text_layout(
620        &mut self,
621        text: &str,
622        logical_font_size: u8,
623        font_size_q4: u16,
624        max_width: i16,
625        text_flags: u8,
626        use_ttf: bool,
627    ) -> Arc<CachedTextLayout> {
628        let logical_fs = logical_font_size.max(8);
629        let q4 = font_size_q4.clamp(32, 1020);
630        let key = TextLayoutKey {
631            text_hash: hash_layout_text(text),
632            text_len: text.len() as u32,
633            logical_font_size: logical_fs,
634            font_size_q4: q4,
635            max_width,
636            text_flags,
637            use_ttf,
638        };
639        if let Some(hit) = self.text_layout_cache.get(&key) {
640            if hit.text.as_str() == text {
641                self.text_layout_hits = self.text_layout_hits.wrapping_add(1);
642                return Arc::clone(hit);
643            }
644        }
645
646        let render_fs = (q4 as f32) * 0.25;
647        let fs_u8 = ((q4 + 2) >> 2).clamp(8, 255) as u8;
648        let scale_ratio = render_fs / (logical_fs as f32);
649        let is_ellipsis = (text_flags & 0x04) != 0;
650        let is_nowrap = (text_flags & 0x08) != 0;
651        let lines = if use_ttf {
652            let logical_max_w = ((max_width as f32) / scale_ratio)
653                .round()
654                .clamp(1.0, i16::MAX as f32) as i16;
655            split_text_lines(text, logical_fs, logical_max_w, is_nowrap || is_ellipsis)
656        } else {
657            split_text_lines(text, fs_u8, max_width, is_nowrap || is_ellipsis)
658        };
659        let line_count = lines.len();
660        let char_h = if use_ttf {
661            (render_fs.round() as i16).max(8)
662        } else {
663            (fs_u8 as i16).max(8)
664        };
665        let line_step = if use_ttf {
666            ((render_fs * 1.25).round() as i16).max(char_h)
667        } else {
668            ((fs_u8 as i16) * 5 / 4).max(char_h)
669        };
670        let ascent = if use_ttf {
671            crate::display::ttf_atlas::get_font_ascent_f32(render_fs) as i16
672        } else {
673            char_h
674        };
675        let dot_w = measure_char_advance('.', fs_u8);
676        let dot_adv_f = if use_ttf {
677            crate::display::ttf_atlas::measure_ttf_char_advance_f32('.', logical_fs)
678                .map(|a| a * scale_ratio)
679                .unwrap_or(dot_w as f32)
680        } else {
681            dot_w as f32
682        };
683        let total_h = if line_count == 0 {
684            0
685        } else {
686            char_h.saturating_add(line_step.saturating_mul((line_count as i16) - 1))
687        };
688
689        let mut glyphs = Vec::with_capacity(text.len().min(128));
690        for (line_idx, &(b_start, b_end, raw_line_w_orig)) in lines.as_slice().iter().enumerate() {
691            let line_str = &text[b_start..b_end];
692            let raw_line_w = if use_ttf {
693                (crate::display::measure_line_width_f32(line_str, logical_fs) * scale_ratio).ceil()
694                    as i16
695            } else {
696                raw_line_w_orig
697            };
698            let need_ellipsis = is_ellipsis && raw_line_w > max_width && max_width > dot_w * 3;
699            let eff_w = if need_ellipsis {
700                max_width
701            } else {
702                raw_line_w.min(max_width)
703            };
704            let start_rel_x = align_offset_x(max_width, eff_w, text_flags);
705            let rel_y = if use_ttf {
706                ascent.saturating_add((line_idx as i16).saturating_mul(line_step))
707            } else {
708                (line_idx as i16).saturating_mul(line_step)
709            };
710
711            if use_ttf {
712                let mut pen_x = start_rel_x as f32;
713                let max_x_before_dots_f = (max_width as f32) - dot_adv_f * 3.0;
714                let mut prev_ch: Option<char> = None;
715                for ch in line_str.chars() {
716                    if let Some(p) = prev_ch {
717                        pen_x += crate::display::ttf_atlas::measure_ttf_kerning_f32(
718                            p, ch, logical_fs,
719                        ) * scale_ratio;
720                    }
721                    let adv_f =
722                        crate::display::ttf_atlas::measure_ttf_char_advance_f32(ch, logical_fs)
723                            .map(|a| a * scale_ratio)
724                            .unwrap_or_else(|| {
725                                (measure_char_advance(ch, logical_fs) as f32) * scale_ratio
726                            });
727                    if need_ellipsis && pen_x + adv_f > max_x_before_dots_f + 0.01 {
728                        for _ in 0..3 {
729                            glyphs.push(ShapedGlyphPos {
730                                ch: '.',
731                                rel_x: pen_x.round() as i16,
732                                rel_y,
733                            });
734                            pen_x += dot_adv_f;
735                        }
736                        break;
737                    }
738                    if ch != ' ' {
739                        glyphs.push(ShapedGlyphPos {
740                            ch,
741                            rel_x: pen_x.round() as i16,
742                            rel_y,
743                        });
744                    }
745                    pen_x += adv_f;
746                    prev_ch = Some(ch);
747                }
748            } else {
749                let mut rel_x = start_rel_x;
750                let max_x_before_dots = max_width.saturating_sub(dot_w * 3);
751                let mut prev_ch: Option<char> = None;
752                for ch in line_str.chars() {
753                    if let Some(p) = prev_ch {
754                        rel_x = rel_x.saturating_add(measure_char_kerning(p, ch, fs_u8));
755                    }
756                    let adv = measure_char_advance(ch, fs_u8);
757                    if need_ellipsis && rel_x.saturating_add(adv) > max_x_before_dots {
758                        for _ in 0..3 {
759                            glyphs.push(ShapedGlyphPos {
760                                ch: '.',
761                                rel_x,
762                                rel_y,
763                            });
764                            rel_x = rel_x.saturating_add(dot_w);
765                        }
766                        break;
767                    }
768                    if ch != ' ' {
769                        glyphs.push(ShapedGlyphPos { ch, rel_x, rel_y });
770                    }
771                    rel_x = rel_x.saturating_add(adv);
772                    prev_ch = Some(ch);
773                }
774            }
775        }
776
777        let built = Arc::new(CachedTextLayout {
778            text: String::from(text),
779            total_h,
780            glyphs,
781        });
782        if self.text_layout_cache.len() >= MAX_TEXT_LAYOUT_CACHE_ENTRIES {
783            self.text_layout_cache.clear();
784        }
785        self.text_layout_cache.insert(key, Arc::clone(&built));
786        built
787    }
788
789    #[allow(clippy::too_many_arguments)]
790    fn encode_text_run(
791        &mut self,
792        queue: &wgpu::Queue,
793        bounds: Region,
794        clip: Region,
795        clip_f32: [f32; 4],
796        clip_radius_px: f32,
797        text: &str,
798        color: Color,
799        logical_font_size: u8,
800        font_size_q4: u16,
801        text_flags: u8,
802        use_ttf: bool,
803    ) -> bool {
804        let layout = self.get_or_build_text_layout(
805            text,
806            logical_font_size,
807            font_size_q4,
808            bounds.w,
809            text_flags,
810            use_ttf,
811        );
812        if layout.glyphs.is_empty() {
813            return true;
814        }
815        let top_y = bounds
816            .y
817            .saturating_add(bounds.h.saturating_sub(layout.total_h).max(0) >> 1);
818        let col_f32 = color_to_f32(color);
819
820        for g in &layout.glyphs {
821            let Some(entry) = self
822                .glyph_atlas
823                .get_or_insert(queue, g.ch, font_size_q4, use_ttf)
824            else {
825                return false;
826            };
827            if entry.width > 0 && entry.height > 0 {
828                let gx = bounds
829                    .x
830                    .saturating_add(g.rel_x)
831                    .saturating_add(entry.xmin);
832                let gy = if use_ttf {
833                    top_y
834                        .saturating_add(g.rel_y)
835                        .saturating_sub(entry.height)
836                        .saturating_sub(entry.ymin)
837                } else {
838                    top_y.saturating_add(g.rel_y)
839                };
840                let greg = Region::new(gx, gy, entry.width, entry.height);
841                if !clip.intersect(greg).is_empty() {
842                    self.primitives.push(GpuPrimitive {
843                        bounds: [
844                            gx as f32,
845                            gy as f32,
846                            entry.width as f32,
847                            entry.height as f32,
848                        ],
849                        clip: clip_f32,
850                        uv: entry.uv,
851                        color0: col_f32,
852                        color1: [0.0; 4],
853                        border_color: [0.0; 4],
854                        params: [0.0, 0.0, KIND_GLYPH, 0.0],
855                        extra: [clip_radius_px, 0.0, 0.0, 0.0],
856                    });
857                }
858            }
859        }
860        true
861    }
862
863    /// 将当前帧 `ops` 直接渲染至目标 `target_view`(单 RenderPass,单 Draw Call,支持分数 DPI 缩放因子 `scale_factor`)。
864    #[allow(clippy::too_many_arguments)]
865    pub fn render_to_view(
866        &mut self,
867        device: &wgpu::Device,
868        queue: &wgpu::Queue,
869        ops: &[DrawOp<'_>],
870        viewport: Region,
871        scale_factor: f32,
872        target_view: &wgpu::TextureView,
873        phys_width: u32,
874        phys_height: u32,
875        clear_color: wgpu::Color,
876    ) {
877        let mut bind_group_dirty = false;
878        for _attempt in 0..4 {
879            match self.try_encode_ops(queue, ops, viewport, scale_factor) {
880                Ok(()) => break,
881                Err((glyph_full, sprite_need)) => {
882                    if glyph_full && self.glyph_atlas.reset_or_grow(device) {
883                        bind_group_dirty = true;
884                    }
885                    if let Some((sw, sh)) = sprite_need {
886                        let (recreated, can_retry) =
887                            self.sprite_atlas.reset_or_grow(device, sw, sh);
888                        if recreated {
889                            bind_group_dirty = true;
890                        }
891                        if !can_retry {
892                            break;
893                        }
894                    }
895                }
896            }
897        }
898
899        if self.primitives.len() > self.instance_capacity {
900            self.instance_capacity = self.primitives.len().next_power_of_two();
901            self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
902            bind_group_dirty = true;
903        }
904        if bind_group_dirty {
905            self.rebuild_bind_group(device);
906        }
907
908        let uniform = ViewportUniform {
909            size: [phys_width.max(1) as f32, phys_height.max(1) as f32],
910            is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
911            _pad: 0.0,
912        };
913        queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[uniform]));
914
915        if !self.primitives.is_empty() {
916            queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
917        }
918
919        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
920            label: Some("velox_wgpu_render_encoder"),
921        });
922        {
923            let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
924                label: Some("velox_wgpu_render_pass"),
925                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
926                    view: target_view,
927                    depth_slice: None,
928                    resolve_target: None,
929                    ops: wgpu::Operations {
930                        load: wgpu::LoadOp::Clear(clear_color),
931                        store: wgpu::StoreOp::Store,
932                    },
933                })],
934                depth_stencil_attachment: None,
935                occlusion_query_set: None,
936                timestamp_writes: None,
937                multiview_mask: None,
938            });
939            if !self.primitives.is_empty() {
940                rpass.set_pipeline(&self.pipeline);
941                rpass.set_bind_group(0, &self.bind_group, &[]);
942                rpass.draw(0..6, 0..(self.primitives.len() as u32));
943            }
944        }
945        queue.submit([encoder.finish()]);
946    }
947}