velox-engine 0.1.0

Velox core UI engine: arena, pod state, 1D fixed-point layout solver, damage tracker, SDF scanline rasterizer, and cross-platform GPU/software backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
//! TrueType 矢量字体按需解析、轮廓光栅化与 `GlyphAtlas` 内存缓存(仅在 `feature = "std"` 下启用)。
//!
//! 设计原则:
//! - **零启动全量解码**:使用 `ttf_parser::Face` 直接零拷贝读取字体偏移表,按需解析实际渲染字符的字形轮廓;
//! - **主字体与 CJK 回退分离**:默认仅加载轻量级主 UI 字体(如 `segoeui.ttf` / `DejaVuSans.ttf`),仅在遇到缺失的非 ASCII 字符时才按需惰性加载 CJK 大字库(如 `msyh.ttc`);
//! - **布局测宽零位图分配**:`measure_ttf_char_advance` 直接读取 `hmtx` 步进宽度并缓存,不再为测宽触发字形光栅化。

use core::cell::RefCell;
#[cfg(not(target_arch = "wasm32"))]
use std::boxed::Box;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock, RwLock};
use std::vec;
use std::vec::Vec;

use ttf_parser::{Face, GlyphId, OutlineBuilder};

/// 缓存的单字形 256 级抗锯齿位图与度量信息。
#[derive(Clone)]
pub struct CachedGlyph {
    pub width: usize,
    pub height: usize,
    pub xmin: i32,
    pub ymin: i32,
    #[allow(dead_code)]
    pub advance_width: i16,
    pub bitmap: Vec<u8>,
}

struct LoadedFont {
    bytes: &'static [u8],
    face: Face<'static>,
}

#[cfg(not(target_arch = "wasm32"))]
const PRIMARY_FONT_CANDIDATES: &[&str] = &[
    "/system.ttf",
    "/system/fonts/RobotoStatic-Regular.ttf",
    "/system/fonts/Roboto-Regular.ttf",
    "C:\\Windows\\Fonts\\segoeui.ttf",
    "C:\\Windows\\Fonts\\arial.ttf",
    "/System/Library/Fonts/Supplemental/Arial.ttf",
    "/System/Library/Fonts/Helvetica.ttc",
    "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    "/usr/share/fonts/TTF/DejaVuSans.ttf",
    "/usr/share/fonts/noto/NotoSans-Regular.ttf",
    "/usr/share/fonts/liberation/LiberationSans-Regular.ttf",
];

#[cfg(not(target_arch = "wasm32"))]
const FALLBACK_CJK_CANDIDATES: &[&str] = &[
    "C:\\Windows\\Fonts\\msyh.ttc",
    "C:\\Windows\\Fonts\\msyhbd.ttc",
    "C:\\Windows\\Fonts\\simhei.ttf",
    "/System/Library/Fonts/PingFang.ttc",
    "/system/fonts/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
];

#[cfg(not(target_arch = "wasm32"))]
static PRIMARY_BYTES: OnceLock<Option<Box<[u8]>>> = OnceLock::new();
#[cfg(not(target_arch = "wasm32"))]
static PRIMARY_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();

#[cfg(not(target_arch = "wasm32"))]
static FALLBACK_CJK_BYTES: OnceLock<Option<Box<[u8]>>> = OnceLock::new();
#[cfg(not(target_arch = "wasm32"))]
static FALLBACK_CJK_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();

#[cfg(target_arch = "wasm32")]
static WASM_SUBSET_TTF_BYTES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/wasm_subset.ttf"));
#[cfg(target_arch = "wasm32")]
static WASM_FONT: OnceLock<Option<LoadedFont>> = OnceLock::new();

static GLYPH_CACHE: OnceLock<RwLock<HashMap<(char, u16), Arc<CachedGlyph>>>> = OnceLock::new();

const TLS_SLOT_COUNT: usize = 256;
const MAX_GLYPH_CACHE_ENTRIES: usize = 4096;

std::thread_local! {
    /// 线程本地直接映射字形位图缓存(键为 `(char, font_size_q4)`,支持 0.25px 亚像素精度字号)。
    static TLS_GLYPHS: RefCell<[Option<(char, u16, Arc<CachedGlyph>)>; TLS_SLOT_COUNT]> =
        RefCell::new([const { None }; TLS_SLOT_COUNT]);

    /// 线程本地高精度浮点步进宽度缓存:文本布局测宽、折行与字形排布共享同一真源,零位图光栅化开销。
    static TLS_ADVANCES: RefCell<[Option<(char, u8, f32)>; TLS_SLOT_COUNT]> =
        RefCell::new([const { None }; TLS_SLOT_COUNT]);

    /// 线程本地 TrueType `kern` 高精度浮点字偶距微调缓存(`(prev, curr, font_size, kern_px_f32)`)。
    static TLS_KERNING: RefCell<[Option<(char, char, u8, f32)>; TLS_SLOT_COUNT]> =
        RefCell::new([const { None }; TLS_SLOT_COUNT]);
}

#[cfg(not(target_arch = "wasm32"))]
fn read_first_valid_font(candidates: &[&str]) -> Option<Box<[u8]>> {
    for path in candidates {
        if let Ok(bytes) = std::fs::read(path) {
            if Face::parse(bytes.as_slice(), 0).is_ok() {
                return Some(bytes.into_boxed_slice());
            }
        }
    }
    None
}

#[cfg(not(target_arch = "wasm32"))]
fn primary_font() -> Option<&'static LoadedFont> {
    PRIMARY_FONT
        .get_or_init(|| {
            let bytes = PRIMARY_BYTES
                .get_or_init(|| {
                    read_first_valid_font(PRIMARY_FONT_CANDIDATES)
                        .or_else(|| read_first_valid_font(FALLBACK_CJK_CANDIDATES))
                })
                .as_deref()?;
            let face = Face::parse(bytes, 0).ok()?;
            Some(LoadedFont { bytes, face })
        })
        .as_ref()
}

#[cfg(not(target_arch = "wasm32"))]
fn fallback_cjk_font() -> Option<&'static LoadedFont> {
    FALLBACK_CJK_FONT
        .get_or_init(|| {
            let bytes = FALLBACK_CJK_BYTES
                .get_or_init(|| read_first_valid_font(FALLBACK_CJK_CANDIDATES))
                .as_deref()?;
            let face = Face::parse(bytes, 0).ok()?;
            Some(LoadedFont { bytes, face })
        })
        .as_ref()
}

#[cfg(target_arch = "wasm32")]
fn primary_font() -> Option<&'static LoadedFont> {
    WASM_FONT
        .get_or_init(|| {
            if WASM_SUBSET_TTF_BYTES.is_empty() {
                return None;
            }
            let face = Face::parse(WASM_SUBSET_TTF_BYTES, 0).ok()?;
            Some(LoadedFont {
                bytes: WASM_SUBSET_TTF_BYTES,
                face,
            })
        })
        .as_ref()
}

#[inline]
fn select_font_and_glyph(ch: char) -> Option<(&'static LoadedFont, GlyphId)> {
    let primary = primary_font()?;
    if let Some(gid) = primary.face.glyph_index(ch) {
        if gid.0 != 0 {
            return Some((primary, gid));
        }
    }
    #[cfg(not(target_arch = "wasm32"))]
    if !ch.is_ascii() && !ch.is_control() {
        if let Some(cjk) = fallback_cjk_font() {
            if let Some(gid) = cjk.face.glyph_index(ch) {
                if gid.0 != 0 {
                    return Some((cjk, gid));
                }
            }
        }
    }
    let fallback_gid = primary.face.glyph_index(ch).unwrap_or(GlyphId(0));
    Some((primary, fallback_gid))
}

/// 在后台线程中并行预热系统主 TrueType 字体(可选同时预热 CJK 字体),
/// 使其磁盘读取与桌面 GPU 管线初始化并发重叠,缩短冷启动首屏耗时。
#[cfg(all(feature = "winit", not(target_arch = "wasm32")))]
pub(crate) fn spawn_font_preload(preload_cjk: bool) {
    if PRIMARY_FONT.get().is_some() && (!preload_cjk || FALLBACK_CJK_FONT.get().is_some()) {
        return;
    }
    let _ = std::thread::Builder::new()
        .name(std::string::String::from("velox-font-preload"))
        .stack_size(128 * 1024)
        .spawn(move || {
            let _ = primary_font();
            if preload_cjk {
                let _ = fallback_cjk_font();
            }
        });
}

/// 判断宿主是否存在可用的系统 TrueType 矢量字体(绝不触发 CJK 回退字库加载)。
#[inline]
pub fn has_system_font() -> bool {
    primary_font().is_some()
}

/// 获取自动加载的系统主 TrueType 字体原始字节流。
#[allow(dead_code)]
pub fn get_system_font_bytes() -> Option<&'static [u8]> {
    primary_font().map(|f| f.bytes)
}

/// 解析指定字符应当使用的系统字体原始字节切片与字形 ID(支持惰性 CJK 回退)。
#[allow(dead_code)]
#[inline]
pub fn resolve_char_font_and_glyph(ch: char) -> Option<(&'static [u8], u16)> {
    let (font, gid) = select_font_and_glyph(ch)?;
    Some((font.bytes, gid.0))
}

/// 获取指定精确浮点字号(`fs`)在单行行盒内的光学垂直居中基线偏移(像素),
/// 基于字体真实 `capital_height`(大写字母高度,缺省回退 `0.70 * upem`)居中,避免 `hhea.ascender` 过大导致按钮文字偏下。
pub fn get_font_ascent_f32(fs: f32) -> i32 {
    let fs = fs.max(8.0);
    let fs_i = fs.round() as i32;
    if let Some(font) = primary_font() {
        let upem = font.face.units_per_em().max(1) as f32;
        let scale = fs / upem;
        let cap_h = font
            .face
            .capital_height()
            .filter(|&h| h > 0)
            .map(|h| (h as f32) * scale)
            .unwrap_or(fs * 0.70);
        // 光学居中:让大写字母墨水区间 `[base_y - cap_h, base_y]` 精确居中于 `[0, fs]` 行盒中
        let centered = ((fs + cap_h) * 0.5 + 0.5) as i32;
        return centered.clamp(1, (fs_i - 2).max(1));
    }
    (fs_i * 4) / 5
}

/// 获取指定整数字号(`font_size`)在单行行盒内的光学垂直居中基线偏移(像素)。
#[allow(dead_code)]
#[inline]
pub fn get_font_ascent(font_size: u8) -> i32 {
    get_font_ascent_f32((font_size.max(8)) as f32)
}

/// 在浮点 Font Units 空间内精确累加整行 TrueType 水平步进宽度与 `kern` 字偶距(不做向上取整),
/// 供光标定位、选区测量与鼠标命中测试使用,与 `WgpuRenderer` / 软件渲染字形排布共享同一浮点真源。
pub fn measure_ttf_line_width_f32(line: &str, font_size: u8) -> Option<f32> {
    if primary_font().is_none() {
        return None;
    }
    if line.is_empty() {
        return Some(0.0);
    }
    let mut total_px = 0.0f32;
    let mut prev: Option<char> = None;

    for ch in line.chars() {
        if let Some(p) = prev {
            total_px += measure_ttf_kerning_f32(p, ch, font_size);
        }
        let adv = measure_ttf_char_advance_f32(ch, font_size)?;
        total_px = (total_px + adv).max(0.0);
        prev = Some(ch);
    }
    Some(total_px)
}

/// 在浮点 Font Units 空间内精确累加整行 TrueType 水平步进宽度与 `kern` 字偶距(最后单次向上取整),
/// 与 `measure_ttf_char_advance_f32` / `measure_ttf_kerning_f32` 复用同一 TLS 浮点缓存真源,
/// 彻底消除布局测宽、自动折行与渲染字形推进之间的累加误差。
pub fn measure_ttf_line_width_exact(line: &str, font_size: u8) -> Option<i16> {
    let total_px = measure_ttf_line_width_f32(line, font_size)?;
    if total_px <= 0.0 {
        return Some(0);
    }
    Some((total_px.ceil() as i32).clamp(1, i16::MAX as i32) as i16)
}

#[inline]
fn compute_scaled_advance_f32(face: &Face<'_>, gid: GlyphId, font_size: u8) -> f32 {
    let fs = font_size.max(8) as f32;
    let upem = face.units_per_em().max(1) as f32;
    let raw_adv = face.glyph_hor_advance(gid).unwrap_or(0) as f32;
    ((raw_adv * fs) / upem).max(1.0)
}

/// 零位图光栅化、零锁查询指定字符在目标字号下的高精度浮点步进宽度(`hmtx` TLS 缓存直出)。
#[inline]
pub fn measure_ttf_char_advance_f32(ch: char, font_size: u8) -> Option<f32> {
    let slot_idx = (((ch as usize).wrapping_mul(2654435761)) ^ (font_size as usize))
        & (TLS_SLOT_COUNT - 1);
    if let Some(adv) = TLS_ADVANCES.with(|tls| {
        let borrow = tls.borrow();
        match borrow[slot_idx] {
            Some((c, fs, a)) if c == ch && fs == font_size => Some(a),
            _ => None,
        }
    }) {
        return Some(adv);
    }

    let (font, gid) = select_font_and_glyph(ch)?;
    let adv = compute_scaled_advance_f32(&font.face, gid, font_size);
    TLS_ADVANCES.with(|tls| {
        tls.borrow_mut()[slot_idx] = Some((ch, font_size, adv));
    });
    Some(adv)
}

/// 零位图光栅化、零原子引用计数开销地查询指定字符在目标字号下的整数步进宽度(`hmtx` 缓存直出)。
#[inline]
pub fn measure_ttf_char_advance(ch: char, font_size: u8) -> Option<i16> {
    measure_ttf_char_advance_f32(ch, font_size).map(|a| (a + 0.5) as i16)
}

/// 零拷贝查询 TrueType `kern` 表中相邻字符 `(prev, curr)` 在目标字号下的高精度浮点水平字距微调像素(带 TLS 直接映射缓存)。
#[inline]
pub fn measure_ttf_kerning_f32(prev: char, curr: char, font_size: u8) -> f32 {
    if prev.is_control() || curr.is_control() {
        return 0.0;
    }
    let slot_idx = (((prev as usize).wrapping_mul(2654435761))
        ^ ((curr as usize).wrapping_mul(2246822519))
        ^ ((font_size as usize) << 3))
        & (TLS_SLOT_COUNT - 1);

    if let Some(k) = TLS_KERNING.with(|tls| {
        let borrow = tls.borrow();
        match borrow[slot_idx] {
            Some((p, c, fs, val)) if p == prev && c == curr && fs == font_size => Some(val),
            _ => None,
        }
    }) {
        return k;
    }

    let kern_px = (|| -> Option<f32> {
        let (f1, g1) = select_font_and_glyph(prev)?;
        let (f2, g2) = select_font_and_glyph(curr)?;
        if !core::ptr::eq(f1, f2) {
            return Some(0.0);
        }
        let kern_table = f1.face.tables().kern?;
        let mut raw_kern: i32 = 0;
        for subtable in kern_table.subtables {
            if subtable.horizontal && !subtable.variable {
                if let Some(v) = subtable.glyphs_kerning(g1, g2) {
                    raw_kern += v as i32;
                }
            }
        }
        if raw_kern == 0 {
            return Some(0.0);
        }
        let fs = font_size.max(8) as f32;
        let upem = f1.face.units_per_em().max(1) as f32;
        Some(((raw_kern as f32) * fs / upem).clamp(-32.0, 32.0))
    })()
    .unwrap_or(0.0);

    TLS_KERNING.with(|tls| {
        tls.borrow_mut()[slot_idx] = Some((prev, curr, font_size, kern_px));
    });
    kern_px
}

/// 零拷贝查询 TrueType `kern` 表中相邻字符 `(prev, curr)` 在目标字号下的整数水平字距微调像素(带 TLS 直接映射缓存)。
///
/// 对 `"AV"`、`"To"`、`"Wa"` 等典型字偶距返回负像素收紧量;非同字体或无 `kern` 表时快速返回 `0`。
#[inline]
pub fn measure_ttf_kerning(prev: char, curr: char, font_size: u8) -> i16 {
    measure_ttf_kerning_f32(prev, curr, font_size).round() as i16
}

#[derive(Copy, Clone)]
struct EdgeSegment {
    x0: f32,
    y0: f32,
    x1: f32,
    y1: f32,
}

struct ScaledOutlineCollector {
    scale: f32,
    subpath_start: Option<(f32, f32)>,
    current: (f32, f32),
    edges: Vec<EdgeSegment>,
    min_x: f32,
    min_y: f32,
    max_x: f32,
    max_y: f32,
}

impl ScaledOutlineCollector {
    fn new(scale: f32) -> Self {
        Self {
            scale,
            subpath_start: None,
            current: (0.0, 0.0),
            edges: Vec::with_capacity(32),
            min_x: f32::INFINITY,
            min_y: f32::INFINITY,
            max_x: f32::NEG_INFINITY,
            max_y: f32::NEG_INFINITY,
        }
    }

    #[inline]
    fn to_screen(&self, x: f32, y: f32) -> (f32, f32) {
        (x * self.scale, -y * self.scale)
    }

    #[inline]
    fn push_edge(&mut self, x0: f32, y0: f32, x1: f32, y1: f32) {
        self.min_x = self.min_x.min(x0).min(x1);
        self.max_x = self.max_x.max(x0).max(x1);
        self.min_y = self.min_y.min(y0).min(y1);
        self.max_y = self.max_y.max(y0).max(y1);
        if (y1 - y0).abs() > 1e-6 {
            self.edges.push(EdgeSegment { x0, y0, x1, y1 });
        }
    }

    fn finish_subpath(&mut self) {
        if let Some((sx, sy)) = self.subpath_start.take() {
            let (cx, cy) = self.current;
            if (cx - sx).abs() > 1e-5 || (cy - sy).abs() > 1e-5 {
                self.push_edge(cx, cy, sx, sy);
            }
            self.current = (sx, sy);
        }
    }
}

impl OutlineBuilder for ScaledOutlineCollector {
    fn move_to(&mut self, x: f32, y: f32) {
        self.finish_subpath();
        let pt = self.to_screen(x, y);
        self.subpath_start = Some(pt);
        self.current = pt;
    }

    fn line_to(&mut self, x: f32, y: f32) {
        let (x0, y0) = self.current;
        let (x1, y1) = self.to_screen(x, y);
        if (x1 - x0).abs() > 1e-6 || (y1 - y0).abs() > 1e-6 {
            self.push_edge(x0, y0, x1, y1);
        }
        self.current = (x1, y1);
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        let (sx0, sy0) = self.current;
        let (cx, cy) = self.to_screen(x1, y1);
        let (sx1, sy1) = self.to_screen(x, y);

        let err = (cx - 0.5 * (sx0 + sx1)).abs() + (cy - 0.5 * (sy0 + sy1)).abs();
        let steps = if err <= 0.1 {
            1usize
        } else {
            ((err * 2.5).sqrt().ceil() as usize).clamp(2, 32)
        };

        let mut px = sx0;
        let mut py = sy0;
        let inv = 1.0 / (steps as f32);
        for i in 1..=steps {
            let t = (i as f32) * inv;
            let u = 1.0 - t;
            let nx = if i == steps {
                sx1
            } else {
                u * u * sx0 + 2.0 * u * t * cx + t * t * sx1
            };
            let ny = if i == steps {
                sy1
            } else {
                u * u * sy0 + 2.0 * u * t * cy + t * t * sy1
            };
            self.push_edge(px, py, nx, ny);
            px = nx;
            py = ny;
        }
        self.current = (sx1, sy1);
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        let (sx0, sy0) = self.current;
        let (cx1, cy1) = self.to_screen(x1, y1);
        let (cx2, cy2) = self.to_screen(x2, y2);
        let (sx1, sy1) = self.to_screen(x, y);

        let lx1 = sx0 + (sx1 - sx0) * (1.0 / 3.0);
        let ly1 = sy0 + (sy1 - sy0) * (1.0 / 3.0);
        let lx2 = sx0 + (sx1 - sx0) * (2.0 / 3.0);
        let ly2 = sy0 + (sy1 - sy0) * (2.0 / 3.0);
        let err1 = (cx1 - lx1).abs() + (cy1 - ly1).abs();
        let err2 = (cx2 - lx2).abs() + (cy2 - ly2).abs();
        let err = err1.max(err2);
        let steps = if err <= 0.1 {
            1usize
        } else {
            ((err * 3.0).sqrt().ceil() as usize).clamp(2, 48)
        };

        let mut px = sx0;
        let mut py = sy0;
        let inv = 1.0 / (steps as f32);
        for i in 1..=steps {
            let t = (i as f32) * inv;
            let u = 1.0 - t;
            let u2 = u * u;
            let t2 = t * t;
            let nx = if i == steps {
                sx1
            } else {
                u2 * u * sx0 + 3.0 * u2 * t * cx1 + 3.0 * u * t2 * cx2 + t2 * t * sx1
            };
            let ny = if i == steps {
                sy1
            } else {
                u2 * u * sy0 + 3.0 * u2 * t * cy1 + 3.0 * u * t2 * cy2 + t2 * t * sy1
            };
            self.push_edge(px, py, nx, ny);
            px = nx;
            py = ny;
        }
        self.current = (sx1, sy1);
    }

    fn close(&mut self) {
        self.finish_subpath();
    }
}

/// 使用非零缠绕解析梯形有向面积积分光栅化单个字符轮廓为 `A8` 抗锯齿位图(支持 0.25px 亚像素精度字号)。
fn rasterize_glyph_outline(font: &LoadedFont, gid: GlyphId, fs: f32) -> CachedGlyph {
    let fs = fs.max(8.0);
    let upem = font.face.units_per_em().max(1) as f32;
    let raw_adv = font.face.glyph_hor_advance(gid).unwrap_or(0) as f32;
    let adv = (((raw_adv * fs) / upem).max(1.0) + 0.5) as i16;
    let scale = fs / upem;

    let mut collector = ScaledOutlineCollector::new(scale);
    let outlined = font.face.outline_glyph(gid, &mut collector).is_some();
    collector.finish_subpath();

    if !outlined || collector.edges.is_empty() || !collector.min_x.is_finite() {
        return CachedGlyph {
            width: 0,
            height: 0,
            xmin: 0,
            ymin: 0,
            advance_width: adv,
            bitmap: Vec::new(),
        };
    }

    let px_min_x = collector.min_x.floor() as i32;
    let px_max_x = collector.max_x.ceil() as i32;
    let px_min_y = collector.min_y.floor() as i32;
    let px_max_y = collector.max_y.ceil() as i32;

    let w = (px_max_x - px_min_x).clamp(0, 512) as usize;
    let h = (px_max_y - px_min_y).clamp(0, 512) as usize;
    if w == 0 || h == 0 {
        return CachedGlyph {
            width: 0,
            height: 0,
            xmin: 0,
            ymin: 0,
            advance_width: adv,
            bitmap: Vec::new(),
        };
    }

    let ox = px_min_x as f32;
    let oy = px_min_y as f32;
    let wf = w as f32;
    let area_stride = w + 1;
    let mut area = vec![0.0f32; area_stride * h];

    for seg in &collector.edges {
        let sx0 = seg.x0 - ox;
        let sy0 = seg.y0 - oy;
        let sx1 = seg.x1 - ox;
        let sy1 = seg.y1 - oy;

        let (dir, ax0, ay0, ax1, ay1) = if sy1 > sy0 {
            (1.0f32, sx0, sy0, sx1, sy1)
        } else {
            (-1.0f32, sx1, sy1, sx0, sy0)
        };
        let dy_total = ay1 - ay0;
        if dy_total <= 1e-6 {
            continue;
        }

        let r_start = (ay0.floor() as isize).max(0) as usize;
        let r_end = ((ay1.ceil() as isize).min(h as isize)).max(0) as usize;
        let inv_dy = 1.0 / dy_total;

        for row in r_start..r_end {
            let rf0 = row as f32;
            let rf1 = (row + 1) as f32;
            let ry0 = ay0.max(rf0);
            let ry1 = ay1.min(rf1);
            let dh = ry1 - ry0;
            if dh <= 1e-6 {
                continue;
            }

            let t0 = (ry0 - ay0) * inv_dy;
            let t1 = (ry1 - ay0) * inv_dy;
            let rx0 = (ax0 + (ax1 - ax0) * t0).clamp(0.0, wf);
            let rx1 = (ax0 + (ax1 - ax0) * t1).clamp(0.0, wf);
            let row_dh = dir * dh;
            let row_off = row * area_stride;

            let x_min = rx0.min(rx1);
            let x_max = rx0.max(rx1);
            if x_min >= wf {
                continue;
            }

            let dx_abs = x_max - x_min;
            if dx_abs <= 1e-6 {
                let x_mid = 0.5 * (rx0 + rx1);
                if x_mid < wf {
                    let col = (x_mid.floor() as usize).min(w - 1);
                    let frac = (x_mid - (col as f32)).clamp(0.0, 1.0);
                    area[row_off + col] += row_dh * (1.0 - frac);
                    area[row_off + col + 1] += row_dh * frac;
                }
            } else {
                let c_first = (x_min.floor() as usize).min(w - 1);
                let c_last = ((x_max.ceil() as usize).saturating_sub(1)).min(w - 1);
                let inv_dx = 1.0 / dx_abs;
                for col in c_first..=c_last {
                    let cf0 = col as f32;
                    let cf1 = (col + 1) as f32;
                    let cx0 = x_min.max(cf0);
                    let cx1 = x_max.min(cf1);
                    if cx1 <= cx0 {
                        continue;
                    }
                    let sub_dh = row_dh * ((cx1 - cx0) * inv_dx);
                    let mid_frac = (0.5 * (cx0 + cx1) - cf0).clamp(0.0, 1.0);
                    area[row_off + col] += sub_dh * (1.0 - mid_frac);
                    area[row_off + col + 1] += sub_dh * mid_frac;
                }
            }
        }
    }

    let mut bitmap = vec![0u8; w * h];
    for row in 0..h {
        let row_off = row * area_stride;
        let dst_off = row * w;
        let mut acc = 0.0f32;
        for col in 0..w {
            acc += area[row_off + col];
            let cov = acc.abs().min(1.0);
            bitmap[dst_off + col] = (cov * 255.0 + 0.5) as u8;
        }
    }

    CachedGlyph {
        width: w,
        height: h,
        xmin: px_min_x,
        // 对齐 draw_ttf_glyph: gy = base_y - height - ymin == base_y + px_min_y
        ymin: -px_max_y,
        advance_width: adv,
        bitmap,
    }
}

/// 从 `GlyphAtlas` 缓存中获取指定字符与 0.25px 量化字号(`font_size_q4 = round(fs * 4)`)的抗锯齿光栅化字形
/// (线程本地缓存 -> 全局读写锁 -> 按需轮廓光栅化),在 125% / 150% / 175% 等分数 DPI 下达到 0.00px 字体尺寸误差。
pub fn get_cached_glyph_q4(ch: char, font_size_q4: u16) -> Option<Arc<CachedGlyph>> {
    let q4 = font_size_q4.clamp(32, 1020);
    let slot_idx =
        (((ch as usize).wrapping_mul(2654435761)) ^ (q4 as usize)) & (TLS_SLOT_COUNT - 1);
    if let Some(hit) = TLS_GLYPHS.with(|tls| {
        let borrow = tls.borrow();
        match &borrow[slot_idx] {
            Some((c, fs, g)) if *c == ch && *fs == q4 => Some(Arc::clone(g)),
            _ => None,
        }
    }) {
        return Some(hit);
    }

    let (font, gid) = select_font_and_glyph(ch)?;
    let cache = GLYPH_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
    if let Ok(read_guard) = cache.read() {
        if let Some(g) = read_guard.get(&(ch, q4)) {
            let cloned = Arc::clone(g);
            TLS_GLYPHS.with(|tls| {
                tls.borrow_mut()[slot_idx] = Some((ch, q4, Arc::clone(&cloned)));
            });
            return Some(cloned);
        }
    }
    if let Ok(mut write_guard) = cache.write() {
        if let Some(g) = write_guard.get(&(ch, q4)) {
            let cloned = Arc::clone(g);
            TLS_GLYPHS.with(|tls| {
                tls.borrow_mut()[slot_idx] = Some((ch, q4, Arc::clone(&cloned)));
            });
            return Some(cloned);
        }
        if write_guard.len() >= MAX_GLYPH_CACHE_ENTRIES {
            write_guard.clear();
        }
        let entry = Arc::new(rasterize_glyph_outline(font, gid, (q4 as f32) * 0.25));
        write_guard.insert((ch, q4), Arc::clone(&entry));
        TLS_GLYPHS.with(|tls| {
            tls.borrow_mut()[slot_idx] = Some((ch, q4, Arc::clone(&entry)));
        });
        return Some(entry);
    }
    None
}

/// 从 `GlyphAtlas` 缓存中获取指定字符与整数字号的抗锯齿光栅化字形(线程本地缓存 -> 全局读写锁 -> 按需轮廓光栅化)。
#[allow(dead_code)]
#[inline]
pub fn get_cached_glyph(ch: char, font_size: u8) -> Option<Arc<CachedGlyph>> {
    get_cached_glyph_q4(ch, (font_size.max(8) as u16) << 2)
}