Skip to main content

mgui_core/
paint.rs

1//! 绘制命令 + Layer 效果 —— 原 mgui-paint crate,已合入 mgui-core
2//!
3//! PaintCommand / PaintList / LayerEffect / effect_flags
4//! 作为 RenderObject → Renderer 之间的中间协议。
5//!
6//! 版本演进:
7//! v1: Rect / TexturedRect / PushClip / PopClip
8//! v2: + Triangles(Path CPU tessellation) + PathBuilder
9//! v3: + ClipRRect / 纹理 alpha mask / BlendMode
10
11use std::collections::hash_map::DefaultHasher;
12use std::hash::{Hash, Hasher};
13use std::rc::Rc;
14
15use crate::geometry::{Color, Point, RRectDef, Rect, Transform2D};
16
17/// 路径三角化后的顶点(wgpu VertexBuffer 零拷贝兼容)
18#[derive(Clone, Copy, Debug, PartialEq)]
19pub struct Vertex {
20    pub x: f32,
21    pub y: f32,
22    pub color: Color,
23}
24
25/// 纹理矩形(文字字形 / 图片)的采样模式
26///
27/// TexturedRect 与 text pipeline 共用一个 shader(text.wgsl),instance 里带
28/// `mode` 标志,fragment 按模式选 alpha 来源:
29/// - `Mask`:alpha 取纹理 **R 通道**(glyph atlas R8 / SVG 单色 tint coverage),
30///   输出 `color.rgb`,alpha = `color.a × tex.r` — 一份 coverage 纹理任意着色
31/// - `Color`:纹理是**直通(straight)RGBA 彩色位图**(SVG 全彩 / PNG 图片),
32///   输出 `tex.rgb × color.rgb`,alpha = `tex.a × color.a`
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum TextureMode {
35    /// 单色 mask:alpha 在纹理 R 通道
36    Mask,
37    /// 彩色 RGBA(straight alpha,非预乘)
38    Color,
39}
40
41/// **P2-1.3** 绘制混合模式(固定功能可实现子集)。
42///
43/// 作用于后续的矩形族命令(`Rect` / `BoxShadow` / 渐变),配对
44/// `PopBlendMode` 恢复。文字/图片/三角形当前固定 SrcOver。
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
46pub enum BlendMode {
47    /// 常规 alpha 混合
48    #[default]
49    Normal,
50    /// 正片叠底:src × dst
51    Multiply,
52    /// 滤色:src + dst − src × dst
53    Screen,
54    /// 线性相加:src + dst
55    Add,
56}
57
58/// 单条绘制指令。
59#[derive(Clone, Debug)]
60pub enum PaintCommand {
61    /// 填充矩形(可带圆角)
62    Rect { rect: Rect, color: Color, radius: f32 },
63    /// 纹理矩形(文字字形 / 图片)
64    ///
65    /// `uv` 是归一化纹理坐标 `(u0, v0, u1, v1)`,左上角原点。
66    /// `texture_id` 在 0..n 范围内,具体含义由 renderer 决定
67    /// (本阶段固定为 0 = glyph atlas)。
68    TexturedRect {
69        rect: Rect,
70        color: Color,
71        uv: [f32; 4],
72        texture_id: u32,
73        /// 纹理采样模式(glyph/SVG tint = Mask;全彩 SVG/PNG = Color)
74        mode: TextureMode,
75    },
76    /// 三角网格(路径 CPU 三角化结果,PathBuilder → earcut → 本命令)
77    ///
78    /// vertices 按 indices 索引渲染 triangles,与 wgpu vertex pipeline 零拷贝兼容。
79    /// renderer 按 `vertex[i]` 的 x/y 作为屏幕坐标(逻辑像素),color 直接来自 vertex。
80    Triangles { vertices: Vec<Vertex>, indices: Vec<u32> },
81    /// **Stage T2**:核心层 Widget 要画文字时用的高层命令
82    ///
83    /// 与 `TexturedRect`(低层 glyph quad)不同 — `Text` 让 renderer 自己调
84    /// parley shaping + swash 栅格化。核心层 Widget 不需要知道 glyph 细节。
85    ///
86    /// renderer 在 collect_instances_segmented 里会 `paint_text_line(...)`
87    /// 把它展开成 N 个 TexturedRect instances(每个 glyph 一个)。
88    Text {
89        /// 文本(`Rc<str>` 共享:同一整串被多条命令引用时零拷贝,
90        /// runtime shaping 缓存也直接以它作 key,命中路径不再克隆全文)
91        text: Rc<str>,
92        /// 可选绘制子区间(字节,相对 `text`;None = 绘制全文)。
93        /// 编辑器逐语法 span 绘制时复用整行 `Rc<str>`,只带区间,
94        /// 避免"每个 span 一次子串 String 分配"。
95        range: Option<(usize, usize)>,
96        font_size: f32,
97        color: Color,
98        /// 绘制起点(逻辑像素,layer 本地坐标)
99        position: Point,
100        /// 可选 soft wrap 宽度(None = 单行)
101        max_width: Option<f32>,
102    },
103    /// **T0-2:BoxShadow** — 带 GPU SDF blur 的圆角矩形阴影
104    ///
105    /// 与 `Rect { radius }` 的区别:额外携带 `blur_radius`(高斯模糊半径)。
106    /// renderer 复用 Rect pipeline,shader 里 smoothstep AA 区间从 1px 扩展到 `1 + blur_radius`,
107    /// 实现单 pass SDF blur(无需额外 render pass 或临时纹理)。
108    ///
109    /// **注意**:rect 应该已经包含 blur padding(即调用方负责外扩 blur_radius)。
110    /// PaintList::box_shadow() helper 已自动处理 rect + offset + spread + blur padding。
111    BoxShadow {
112        rect: Rect,
113        color: Color,
114        radius: f32,
115        /// 高斯模糊半径(逻辑像素);0 = 无 blur(等价普通 Rect)
116        blur_radius: f32,
117    },
118    /// **P2-1.4b:背景模糊** — 对 rect 内**已绘制内容**做模糊(tint 可选)
119    ///
120    /// GPU 在命令处结束当前 pass → resolve snapshot → 重开 pass 采样 13-tap blur;
121    /// 软件光栅化对当前目标像素做同参数卷积。矩形为圆角遮罩,外部不受影响。
122    /// `tint.a` > 0 时把模糊结果向 `tint.rgb` 混合(磨砂玻璃色调)。
123    BackdropBlur { rect: Rect, radius: f32, blur_radius: f32, tint: Color },
124    /// **P2-1.4:内阴影** — 在矩形内侧沿边缘衰减的阴影(inset shadow)
125    ///
126    /// SDF 单 pass:边缘处 coverage=1,向中心按 `exp(-depth² / 2blur²)` 衰减;
127    /// `blur_radius=0` 时为 1px 内侧描边。绘制在已有内容之上(SourceOver)。
128    InsetShadow { rect: Rect, color: Color, radius: f32, blur_radius: f32 },
129    /// 两色线性渐变矩形(可带圆角)。
130    LinearGradient {
131        rect: Rect,
132        /// 渐变起点(layer 本地坐标)
133        start: Point,
134        /// 渐变终点
135        end: Point,
136        from: Color,
137        to: Color,
138        corner_radius: f32,
139    },
140    /// 两色径向渐变矩形(可带圆角)。
141    RadialGradient { rect: Rect, center: Point, radial_radius: f32, from: Color, to: Color, corner_radius: f32 },
142    /// **P2-1.3: 纹理 mask** — 用纹理 alpha 裁掉 layer 中已有内容(destination-in)
143    ///
144    /// 只影响 `rect` 范围内已经绘制的内容:`new_alpha = old_alpha × tex.a × alpha`。
145    /// 纹理需通过 `PaintList::push_texture` 或 renderer 的 register_image 注册;
146    /// `uv` 是归一化坐标(左上原点)。
147    MaskRect { rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32 },
148    /// **P2-1.3** 压入混合模式,作用于后续矩形族命令,直到 `PopBlendMode`
149    PushBlendMode(BlendMode),
150    /// 恢复上一个混合模式
151    PopBlendMode,
152    /// 压入裁剪矩形(layer 本地坐标)
153    ///
154    /// 之后的绘制命令都被裁在该矩形内,直到配对的 `PopClip`。
155    /// 嵌套时与外层 clip 求交(即当前 clip = 所有未弹出 clip 的交集)。
156    /// GPU 侧由 render pass 的 scissor_rect 精确实现。
157    PushClip(Rect),
158    /// **P2-1.3** 压入圆角矩形裁剪(layer 本地坐标),配对 `PopClip`
159    ///
160    /// 与 `PushClip` 共用同一剪裁栈;GPU 用 stencil SDF 三角形精确裁角,
161    /// 软件光栅化用 tiny-skia 圆角路径 mask。`radius <= 0` 等价直角。
162    PushClipRRect { rect: Rect, radius: f32 },
163    /// 弹出最近一次 `PushClip` / `PushClipRRect`(与 push 严格配对)
164    PopClip,
165    /// **路径裁剪** — 压入一个 PathBuilder.fill() 产出的三角形网格作为裁剪区域
166    ///
167    /// - `vertices` + `indices` 与 `Triangles` 完全同结构(PathBuilder.fill() 的 earcut 输出)
168    /// - GPU 用 stencil mask 精确裁剪(支持嵌套,见 `PushClipRRect` 同机制)
169    /// - 嵌套时与外层 clip 求交
170    PushClipPath { vertices: Vec<Vertex>, indices: Vec<u32> },
171    /// 弹出最近一次 `PushClipPath`(也接受 `PushClipRRect`;与 push 严格配对)
172    PopClipPath,
173}
174
175/// 视频帧的观测元数据(0.4 阶段 0)。
176///
177/// 随 [`PendingTexture`] 从 `RenderObject::paint` 一路漂到 `Renderer::register_image`,
178/// 把 produced → taken → painted → submitted 用同一个 `sequence` 串起来。
179/// 静态图片 / SVG / 图标不带这份元数据(`meta == None`),不承担视频语义。
180///
181/// `sequence` **只用于关联**;帧年龄一律由 `taken_at` 与提交时刻在同一把单调钟上
182/// 相减得到(取帧与注册都在 UI 线程,同钟减法合法)。
183#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub struct TextureFrameMeta {
185    pub sequence: u64,
186    pub generation: u64,
187    pub taken_at: std::time::Instant,
188    /// RO 在 state→RO 刷新阶段同步这一帧时写入 `sequence`。`0` = 从未被同步过 ——
189    /// 这正是「PaintList 重新生成了、但携带旧像素」那一格的判据。
190    pub synced_seq: u64,
191    /// paint 时共享格里**最新**一帧的 sequence。与 `sequence` 对比可看出本次声明落后多少帧。
192    pub latest_seq: u64,
193}
194
195/// 一条待注册纹理声明。`meta == None` 时行为与阶段 0 之前完全一致。
196#[derive(Clone, Debug)]
197pub struct PendingTexture {
198    pub texture_id: u32,
199    pub data: Rc<crate::image::ImageData>,
200    pub meta: Option<TextureFrameMeta>,
201}
202
203/// 一帧的绘制指令列表。
204/// 保留式:跨帧复用,只有脏的 RenderObject 会重建自己那部分。
205#[derive(Clone, Debug, Default)]
206pub struct PaintList {
207    pub commands: Vec<PaintCommand>,
208    /// 侧通道:本帧 RenderObject 声明的新增待注册纹理
209    /// renderer render 开始前 drain,调 register_image(幂等)
210    /// 不走 PaintCommand 避免大数据 clone 污染绘制协议
211    pub pending_textures: Vec<PendingTexture>,
212}
213
214// =================================================================
215// Layer 合成时的视觉效果
216// =================================================================
217
218/// layer 合成到父 layer/surface 时的视觉效果
219///
220/// 嵌套 layer 树语义:child layer 的 effect 是相对于 parent layer 的
221/// 局部坐标系(parent 已经做了 transform,child effect 是在 parent 变换
222/// 之后的世界空间继续应用)。
223///
224/// `None` 是常见情况 — 大部分 layer 不需要 effect,shader 走快速路径。
225#[derive(Clone, Copy, Debug, Default, PartialEq)]
226pub enum LayerEffect {
227    /// 无效果(默认值)— shader 走无开销 blit 路径
228    #[default]
229    None,
230    /// 2D 仿射变换(平移+旋转+均匀缩放),绕 layer 中心
231    Transform(Transform2D),
232    /// 整体 alpha 乘(0.0 = 完全透明,1.0 = 不透明)
233    Opacity(f32),
234    /// 圆角裁剪(在 4 个角的圆角 SDF 区域 alpha=0)
235    ClipRRect(RRectDef),
236}
237
238/// effect flag(bit field) — shader 用这个走分支
239///
240/// bit 分配(预留 8 bit):
241/// - bit 0: has_transform
242/// - bit 1: has_opacity
243/// - bit 2: has_clip
244/// - bit 3-7: 预留(Blur/DropShadow/ColorMatrix/Filters...)
245pub mod effect_flags {
246    pub const HAS_TRANSFORM: u32 = 1 << 0;
247    pub const HAS_OPACITY: u32 = 1 << 1;
248    pub const HAS_CLIP: u32 = 1 << 2;
249    /// bit 3 预留(Blur)
250    pub const HAS_BLUR: u32 = 1 << 3;
251    /// bit 4 预留(DropShadow)
252    pub const HAS_DROP_SHADOW: u32 = 1 << 4;
253}
254
255fn hash_f32(hasher: &mut DefaultHasher, value: f32) {
256    value.to_bits().hash(hasher);
257}
258
259fn hash_color(hasher: &mut DefaultHasher, color: Color) {
260    hash_f32(hasher, color.r);
261    hash_f32(hasher, color.g);
262    hash_f32(hasher, color.b);
263    hash_f32(hasher, color.a);
264}
265
266fn hash_rect(hasher: &mut DefaultHasher, rect: Rect) {
267    hash_f32(hasher, rect.x);
268    hash_f32(hasher, rect.y);
269    hash_f32(hasher, rect.width);
270    hash_f32(hasher, rect.height);
271}
272
273fn hash_point(hasher: &mut DefaultHasher, point: Point) {
274    hash_f32(hasher, point.x);
275    hash_f32(hasher, point.y);
276}
277
278fn hash_vertices(hasher: &mut DefaultHasher, vertices: &[Vertex], indices: &[u32]) {
279    vertices.len().hash(hasher);
280    for vertex in vertices {
281        hash_f32(hasher, vertex.x);
282        hash_f32(hasher, vertex.y);
283        hash_color(hasher, vertex.color);
284    }
285    indices.hash(hasher);
286}
287
288impl PaintList {
289    pub fn new() -> Self {
290        Self { commands: Vec::new(), pending_textures: Vec::new() }
291    }
292
293    /// 绘制内容 digest:用于 layer cache 的增量失效判定。
294    ///
295    /// 只覆盖会改变像素结果的数据:命令序列、文本/区间、纹理采样模式与视频帧 sequence。
296    /// `pending_textures` 用 `Rc` 指针身份参与,静态纹理若被新对象替换则保守重画;
297    /// `TextureFrameMeta::taken_at` 是观测时间,故意不入 key(同一帧元数据不应因时钟漂移失效)。
298    pub fn content_digest(&self) -> u64 {
299        let mut hasher = DefaultHasher::new();
300        self.commands.len().hash(&mut hasher);
301        for command in &self.commands {
302            std::mem::discriminant(command).hash(&mut hasher);
303            match command {
304                PaintCommand::Rect { rect, color, radius } => {
305                    hash_rect(&mut hasher, *rect);
306                    hash_color(&mut hasher, *color);
307                    hash_f32(&mut hasher, *radius);
308                }
309                PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
310                    hash_rect(&mut hasher, *rect);
311                    hash_color(&mut hasher, *color);
312                    for value in uv {
313                        hash_f32(&mut hasher, *value);
314                    }
315                    texture_id.hash(&mut hasher);
316                    mode.hash(&mut hasher);
317                }
318                PaintCommand::Triangles { vertices, indices } => hash_vertices(&mut hasher, vertices, indices),
319                PaintCommand::Text { text, range, font_size, color, position, max_width } => {
320                    text.as_bytes().hash(&mut hasher);
321                    range.hash(&mut hasher);
322                    hash_f32(&mut hasher, *font_size);
323                    hash_color(&mut hasher, *color);
324                    hash_point(&mut hasher, *position);
325                    max_width.map(f32::to_bits).hash(&mut hasher);
326                }
327                PaintCommand::BoxShadow { rect, color, radius, blur_radius }
328                | PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
329                    hash_rect(&mut hasher, *rect);
330                    hash_color(&mut hasher, *color);
331                    hash_f32(&mut hasher, *radius);
332                    hash_f32(&mut hasher, *blur_radius);
333                }
334                PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
335                    hash_rect(&mut hasher, *rect);
336                    hash_f32(&mut hasher, *radius);
337                    hash_f32(&mut hasher, *blur_radius);
338                    hash_color(&mut hasher, *tint);
339                }
340                PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
341                    hash_rect(&mut hasher, *rect);
342                    hash_point(&mut hasher, *start);
343                    hash_point(&mut hasher, *end);
344                    hash_color(&mut hasher, *from);
345                    hash_color(&mut hasher, *to);
346                    hash_f32(&mut hasher, *corner_radius);
347                }
348                PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
349                    hash_rect(&mut hasher, *rect);
350                    hash_point(&mut hasher, *center);
351                    hash_f32(&mut hasher, *radial_radius);
352                    hash_color(&mut hasher, *from);
353                    hash_color(&mut hasher, *to);
354                    hash_f32(&mut hasher, *corner_radius);
355                }
356                PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
357                    hash_rect(&mut hasher, *rect);
358                    texture_id.hash(&mut hasher);
359                    for value in uv {
360                        hash_f32(&mut hasher, *value);
361                    }
362                    hash_f32(&mut hasher, *alpha);
363                }
364                PaintCommand::PushBlendMode(mode) => mode.hash(&mut hasher),
365                PaintCommand::PopBlendMode | PaintCommand::PopClip | PaintCommand::PopClipPath => {}
366                PaintCommand::PushClip(rect) => hash_rect(&mut hasher, *rect),
367                PaintCommand::PushClipRRect { rect, radius } => {
368                    hash_rect(&mut hasher, *rect);
369                    hash_f32(&mut hasher, *radius);
370                }
371                PaintCommand::PushClipPath { vertices, indices } => hash_vertices(&mut hasher, vertices, indices),
372            }
373        }
374        self.pending_textures.len().hash(&mut hasher);
375        for pending in &self.pending_textures {
376            pending.texture_id.hash(&mut hasher);
377            (Rc::as_ptr(&pending.data) as usize).hash(&mut hasher);
378            match &pending.meta {
379                None => 0u8.hash(&mut hasher),
380                Some(meta) => {
381                    1u8.hash(&mut hasher);
382                    meta.sequence.hash(&mut hasher);
383                    meta.generation.hash(&mut hasher);
384                    meta.synced_seq.hash(&mut hasher);
385                    meta.latest_seq.hash(&mut hasher);
386                }
387            }
388        }
389        hasher.finish()
390    }
391
392    pub fn clear(&mut self) {
393        self.commands.clear();
394        self.pending_textures.clear();
395    }
396
397    pub fn push(&mut self, cmd: PaintCommand) {
398        self.commands.push(cmd);
399    }
400
401    /// 声明一条待注册纹理(renderer render 开始前 drain)。静态图片 / SVG 走这里。
402    pub fn push_texture(&mut self, texture_id: u32, data: std::rc::Rc<crate::image::ImageData>) {
403        self.pending_textures.push(PendingTexture { texture_id, data, meta: None });
404    }
405
406    /// 声明一条**带视频帧元数据**的待注册纹理。
407    /// 元数据必须一路带到 `Renderer::register_image`,否则帧年龄没有落点。
408    pub fn push_texture_with_meta(
409        &mut self,
410        texture_id: u32,
411        data: std::rc::Rc<crate::image::ImageData>,
412        meta: TextureFrameMeta,
413    ) {
414        self.pending_textures.push(PendingTexture { texture_id, data, meta: Some(meta) });
415    }
416
417    /// 追加另一个 list 的所有 commands(多 layer 合成用)
418    pub fn extend(&mut self, other: &PaintList) {
419        self.commands.extend(other.commands.iter().cloned());
420        // 整条 clone(含可选 meta),纹理声明可能来自子 layer;漏掉 meta 会让多 layer 合成丢帧号
421        self.pending_textures.extend(other.pending_textures.iter().cloned());
422    }
423
424    /// 直角矩形
425    pub fn rect(&mut self, rect: Rect, color: Color) {
426        self.commands.push(PaintCommand::Rect { rect, color, radius: 0.0 });
427    }
428
429    /// 圆角矩形
430    pub fn rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
431        self.commands.push(PaintCommand::Rect { rect, color, radius });
432    }
433
434    /// 高层文字命令(runtime 层展开成 glyph quads)
435    pub fn text(&mut self, text: impl Into<Rc<str>>, font_size: f32, color: Color, position: Point) {
436        self.commands.push(PaintCommand::Text {
437            text: text.into(),
438            range: None,
439            font_size,
440            color,
441            position,
442            max_width: None,
443        });
444    }
445
446    /// 带可选 soft wrap 的高层文字命令
447    pub fn text_wrapped(
448        &mut self,
449        text: impl Into<Rc<str>>,
450        font_size: f32,
451        color: Color,
452        position: Point,
453        max_width: Option<f32>,
454    ) {
455        self.commands.push(PaintCommand::Text {
456            text: text.into(),
457            range: None,
458            font_size,
459            color,
460            position,
461            max_width,
462        });
463    }
464
465    /// 共享整串 + 字节区间的高层文字命令
466    ///
467    /// 编辑器等"一行文本切多个语法 span"的场景使用:整行 `Rc<str>` 被所有
468    /// span 命令共享,只携带区间,shaping 缓存命中时零字符串分配。
469    pub fn text_span(&mut self, text: &Rc<str>, range: (usize, usize), font_size: f32, color: Color, position: Point) {
470        self.commands.push(PaintCommand::Text {
471            text: Rc::clone(text),
472            range: Some(range),
473            font_size,
474            color,
475            position,
476            max_width: None,
477        });
478    }
479
480    /// **T0-2:GPU SDF BoxShadow** — 单 pass shader blur(无需多 render pass)
481    ///
482    /// 旧 N 层半透明近似已被替代。现在发 1 个 `BoxShadow` 命令,
483    /// renderer 复用 Rect pipeline,shader 里 smoothstep 过渡区从 1px 扩展到 blur_radius,
484    /// 实现真正的 Gaussian-like blur。
485    ///
486    /// - `rect`:子元素 bounding box(阴影的"中心形状")
487    /// - `offset`:阴影相对 rect 的偏移(dx, dy)
488    /// - `blur_radius`:模糊半径(逻辑像素);shader smoothstep 区间 = ±blur_radius
489    /// - `spread`:阴影扩张(+外扩/-内缩)
490    /// - `color`:阴影颜色(通常带 alpha,如 Color::rgba(0,0,0,0.25))
491    /// - `corner_radius`:子元素圆角(阴影同形状)
492    pub fn box_shadow(
493        &mut self,
494        rect: Rect,
495        offset: Point,
496        blur_radius: f32,
497        spread: f32,
498        color: Color,
499        corner_radius: f32,
500    ) {
501        // 1. 基础 shape rect(阴影几何中心)
502        let sh_x = rect.x + offset.x - spread;
503        let sh_y = rect.y + offset.y - spread;
504        let sh_w = (rect.width + spread * 2.0).max(0.0);
505        let sh_h = (rect.height + spread * 2.0).max(0.0);
506        // 负 spread 收缩形状,圆角同步收缩(CSS/Flutter 语义)
507        let base_radius = (corner_radius + spread).max(0.0);
508
509        // 2. BoxShadow rect 外扩 4×blur — Gaussian 衰减到 d=4σ 时已 ≈0.03%
510        // (exp(-8)),quad 边界不会留下硬切边。shader 侧约定同样按 4×blur
511        // 还原基础 shape 的半尺寸(见 rect.wgsl 的 SHADOW_PAD_FACTOR)。
512        let b = blur_radius.max(0.0);
513        let pad = b * 4.0;
514        let padded = Rect::new(sh_x - pad, sh_y - pad, sh_w + pad * 2.0, sh_h + pad * 2.0);
515
516        self.commands.push(PaintCommand::BoxShadow {
517            rect: padded,
518            color,
519            radius: base_radius, // **不扩 blur_radius**(shader 内补偿)
520            blur_radius: b,
521        });
522    }
523
524    /// 两色线性渐变(可带圆角)。
525    pub fn linear_gradient(
526        &mut self,
527        rect: Rect,
528        start: Point,
529        end: Point,
530        from: Color,
531        to: Color,
532        corner_radius: f32,
533    ) {
534        self.commands.push(PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius });
535    }
536
537    /// 两色径向渐变(可带圆角)。
538    pub fn radial_gradient(
539        &mut self,
540        rect: Rect,
541        center: Point,
542        radial_radius: f32,
543        from: Color,
544        to: Color,
545        corner_radius: f32,
546    ) {
547        self.commands.push(PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius });
548    }
549
550    /// 纹理 alpha mask(destination-in):裁掉此前已绘制内容的透明度。
551    pub fn mask(&mut self, rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32) {
552        self.commands.push(PaintCommand::MaskRect { rect, texture_id, uv, alpha: alpha.clamp(0.0, 1.0) });
553    }
554
555    /// 内阴影(绘制在 rect 内部边缘)
556    pub fn inset_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur_radius: f32) {
557        self.commands.push(PaintCommand::InsetShadow { rect, color, radius, blur_radius: blur_radius.max(0.0) });
558    }
559
560    /// 背景模糊(对 rect 内已绘制内容做 13-tap blur;tint.a 可加磨砂色调)
561    pub fn backdrop_blur(&mut self, rect: Rect, radius: f32, blur_radius: f32, tint: Color) {
562        self.commands.push(PaintCommand::BackdropBlur {
563            rect,
564            radius: radius.max(0.0),
565            blur_radius: blur_radius.max(0.0),
566            tint,
567        });
568    }
569
570    /// 压入混合模式(作用于后续矩形族命令)
571    pub fn push_blend_mode(&mut self, mode: BlendMode) {
572        self.commands.push(PaintCommand::PushBlendMode(mode));
573    }
574
575    /// 恢复上一个混合模式
576    pub fn pop_blend_mode(&mut self) {
577        self.commands.push(PaintCommand::PopBlendMode);
578    }
579
580    /// 压入裁剪矩形(之后的绘制被裁在该矩形内,直到 `pop_clip`)
581    pub fn push_clip(&mut self, rect: Rect) {
582        self.commands.push(PaintCommand::PushClip(rect));
583    }
584
585    /// 压入圆角矩形裁剪(之后的绘制被裁在该圆角矩形内,直到 `pop_clip`)
586    pub fn push_clip_rrect(&mut self, rect: Rect, radius: f32) {
587        self.commands.push(PaintCommand::PushClipRRect { rect, radius });
588    }
589
590    /// 弹出最近一次 `push_clip`
591    pub fn pop_clip(&mut self) {
592        self.commands.push(PaintCommand::PopClip);
593    }
594
595    pub fn is_empty(&self) -> bool {
596        self.commands.is_empty()
597    }
598    pub fn len(&self) -> usize {
599        self.commands.len()
600    }
601}
602
603// =================================================================
604// PathBuilder — MoveTo/LineTo/QuadTo/CubicTo/Close → earcut → Triangles
605// =================================================================
606//
607// v2 Path 填充方案:CPU 侧 flatten 贝塞尔为折线 + earcut 三角剖分,
608// 结果 = PaintCommand::Triangles,走 wgpu vertex pipeline(与 renderer
609// 现有 Rect pipeline 结构一致,新增极少)。
610//
611// 设计取舍:
612// - fill 不支持 anti-aliasing / 自相交多边形 / 多回路洞(earcut 仅处理
613//   简单非自相交多边形,UI 路径的典型场景)
614// - **曲线段在存储期保留**(PathSeg::Quad/Cubic,fill 导出时才 flatten);
615//   stroke 通道(curve_contours)把曲线直接交给描边器(如 tiny-skia
616//   PathStroker),避免密集折线逼近导致的内 join 毛刺自相交
617// - QuadTo flatten 用递归细分(flatness 小于给定容差时停止)
618
619/// 路径段(曲线感知存储;fill/paths 导出时 flatten 成折线)
620#[derive(Clone, Copy, Debug)]
621pub enum PathSeg {
622    /// 直线段终点
623    Line(f32, f32),
624    /// 二次贝塞尔:控制点 + 终点 + flatten 容差(各坐标空间)
625    Quad { cx: f32, cy: f32, x: f32, y: f32, flat: f32 },
626    /// 三次贝塞尔:两控制点 + 终点 + flatten 容差
627    Cubic { c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32, flat: f32 },
628}
629
630/// 一条回路:起点 + 段序列 + 是否显式 close
631#[derive(Clone, Debug, Default)]
632struct Contour {
633    start: (f32, f32),
634    segs: Vec<PathSeg>,
635    closed: bool,
636}
637
638impl PathSeg {
639    /// 段终点
640    fn end(&self) -> (f32, f32) {
641        match *self {
642            PathSeg::Line(x, y) => (x, y),
643            PathSeg::Quad { x, y, .. } => (x, y),
644            PathSeg::Cubic { x, y, .. } => (x, y),
645        }
646    }
647
648    /// 坐标缩放(sx, sy);flatten 容差按 fscale 同步缩放(均匀缩放下严格正确)
649    fn transform(&mut self, sx: f32, sy: f32, fscale: f32) {
650        match self {
651            PathSeg::Line(x, y) => {
652                *x *= sx;
653                *y *= sy;
654            }
655            PathSeg::Quad { cx, cy, x, y, flat } => {
656                *cx *= sx;
657                *cy *= sy;
658                *x *= sx;
659                *y *= sy;
660                *flat *= fscale;
661            }
662            PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
663                *c1x *= sx;
664                *c1y *= sy;
665                *c2x *= sx;
666                *c2y *= sy;
667                *x *= sx;
668                *y *= sy;
669                *flat *= fscale;
670            }
671        }
672    }
673}
674
675/// 路径构造器(多回路,支持 fill 三角化与 stroke 曲线导出)
676#[derive(Default, Clone, Debug)]
677pub struct PathBuilder {
678    /// 当前点
679    cx: f32,
680    cy: f32,
681    /// 当前回路起点(move_to 设置)
682    start: (f32, f32),
683    /// 当前回路的段(未 close 前积累在此)
684    segs: Vec<PathSeg>,
685    /// 已完成回路(close 或 move_to 冲刷)
686    contours: Vec<Contour>,
687}
688
689impl PathBuilder {
690    pub fn new() -> Self {
691        Self::default()
692    }
693
694    /// 对所有已积累的坐标乘 (sx, sy) —— 用于把 viewBox 坐标缩放到屏幕像素。
695    /// 段内 flatten 容差按 max(|sx|,|sy|) 同步缩放(均匀缩放下严格正确)。
696    pub fn transform(&mut self, sx: f32, sy: f32) {
697        let fscale = sx.abs().max(sy.abs());
698        for c in self.contours.iter_mut() {
699            c.start.0 *= sx;
700            c.start.1 *= sy;
701            for seg in c.segs.iter_mut() {
702                seg.transform(sx, sy, fscale);
703            }
704        }
705        self.start.0 *= sx;
706        self.start.1 *= sy;
707        for seg in self.segs.iter_mut() {
708            seg.transform(sx, sy, fscale);
709        }
710        self.cx *= sx;
711        self.cy *= sy;
712    }
713
714    /// 把回路 flatten 成折线(导出用;首点为回路起点,不含重复尾点)
715    fn flatten_contour(start: (f32, f32), segs: &[PathSeg], out: &mut Vec<(f32, f32)>) {
716        out.push(start);
717        let (mut x0, mut y0) = start;
718        for seg in segs {
719            match *seg {
720                PathSeg::Line(x, y) => out.push((x, y)),
721                PathSeg::Quad { cx, cy, x, y, flat } => flatten_quad_bezier(x0, y0, cx, cy, x, y, flat, out),
722                PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
723                    flatten_cubic_bezier(x0, y0, c1x, c1y, c2x, c2y, x, y, flat, out)
724                }
725            }
726            x0 = seg.end().0;
727            y0 = seg.end().1;
728        }
729    }
730
731    pub fn move_to(&mut self, x: f32, y: f32) {
732        // 先把之前未闭合的回路冲掉(如果有)
733        if !self.segs.is_empty() {
734            let segs = std::mem::take(&mut self.segs);
735            self.contours.push(Contour { start: self.start, segs, closed: false });
736        }
737        self.start = (x, y);
738        self.cx = x;
739        self.cy = y;
740    }
741
742    pub fn line_to(&mut self, x: f32, y: f32) {
743        self.segs.push(PathSeg::Line(x, y));
744        self.cx = x;
745        self.cy = y;
746    }
747
748    /// 二次贝塞尔(控制点 cx,cy,终点 ex,ey),flat = 当前坐标空间容差(0.5 / scale)。
749    /// 存储期保留曲线,fill/paths 导出时才按 flat flatten。
750    pub fn quad_to(&mut self, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32) {
751        self.segs.push(PathSeg::Quad { cx, cy, x: ex, y: ey, flat });
752        self.cx = ex;
753        self.cy = ey;
754    }
755
756    /// 三次贝塞尔(控制点 c1/c2,终点 ex,ey),flat 语义同 quad_to
757    #[allow(clippy::too_many_arguments)]
758    pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, ex: f32, ey: f32, flat: f32) {
759        self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: ex, y: ey, flat });
760        self.cx = ex;
761        self.cy = ey;
762    }
763
764    /// 圆弧(圆心 cx,cy + 半径 r + 起/终角度(弧度) + 分段数上限)
765    /// 以三次贝塞尔段逼近存储(kappa 圆逼近),fill 导出时 flatten。
766    ///
767    /// - `start_angle`/`end_angle` 标准数学极坐标:0 = +X 轴,逆时针增大
768    /// - `num_segments` 只是段数上限;实际段数 = ceil(|sweep| / 90°)
769    /// - 自动处理跨过 ±TAU 的情况(end < start 时逆时针走大弧)
770    pub fn arc_to(&mut self, cx: f32, cy: f32, r: f32, start_angle: f32, end_angle: f32, num_segments: u32) {
771        if r <= 0.0 {
772            return;
773        }
774        let sweep = end_angle - start_angle;
775        // 避免完全闭合(会产生自相交或多 contour 问题) — earcut 单 contour 要求简单多边形
776        let sweep = if sweep.abs() >= std::f32::consts::TAU { sweep * 0.999 } else { sweep };
777
778        // 段数:每段 ≤90°(kappa 精确逼近,径向误差 ~2.7e-4·r,远低于 0.5px 光栅化
779        // 精度)。**不要细分更多**:stroker 在每段边界发 inner join,段越多毛刺越多
780        // (32 段/90° 实测产生叶片伪影;usvg 归一化就是 90° 1 段)。cubic stroke 的
781        // 平行曲线由描边器自行细分,无需输入侧预细分。fill(earcut) 侧 flat 已足够。
782        let segs = (((sweep.abs() / std::f32::consts::FRAC_PI_2).ceil()) as u32).clamp(1, num_segments.max(1));
783        let step = sweep / segs as f32;
784        let flat = (r * step).abs() * 0.05;
785
786        // 兼容性:旧 arc_to 总是先落弧起点 —— 调用方惯用法有两种:
787        // ① move_to(弧起点) 后续接(当前点 == 弧起点,无需补线)
788        // ② move_to(圆心) 画饼形(需要一条 圆心→弧起点 的径向边)
789        // 当前点偏离弧起点时补 Line,两种惯用法都得到与旧版相同的折线。
790        let (sx, sy) = (cx + r * start_angle.cos(), cy + r * start_angle.sin());
791        let dcx = sx - self.cx;
792        let dcy = sy - self.cy;
793        if dcx * dcx + dcy * dcy > 1e-12 {
794            self.segs.push(PathSeg::Line(sx, sy));
795            self.cx = sx;
796            self.cy = sy;
797        }
798
799        let k = (4.0 / 3.0) * (step / 4.0).tan() * r; // 控制点切向偏移长度
800        let mut a0 = start_angle;
801        for _ in 0..segs {
802            let a1 = a0 + step;
803            let (x0, y0) = (cx + r * a0.cos(), cy + r * a0.sin());
804            let (x1, y1) = (cx + r * a1.cos(), cy + r * a1.sin());
805            // 切向(角度递增方向)= (-sin a, cos a)
806            let c1x = x0 - k * a0.sin();
807            let c1y = y0 + k * a0.cos();
808            let c2x = x1 + k * a1.sin();
809            let c2y = y1 - k * a1.cos();
810            self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: x1, y: y1, flat });
811            self.cx = x1;
812            self.cy = y1;
813            a0 = a1;
814        }
815    }
816
817    pub fn close(&mut self) {
818        if !self.segs.is_empty() {
819            let segs = std::mem::take(&mut self.segs);
820            // closed = 显式 close(earcut/fill 按闭合回路处理)
821            self.contours.push(Contour { start: self.start, segs, closed: true });
822        }
823    }
824
825    /// 导出所有已闭合回路(去掉首尾重复点;曲线段 flatten 成折线)。
826    /// 需要曲线时请用 curve_contours。
827    pub fn paths(&self) -> Vec<Vec<(f32, f32)>> {
828        let mut out = Vec::with_capacity(self.contours.len());
829        for c in &self.contours {
830            let mut pts = Vec::new();
831            Self::flatten_contour(c.start, &c.segs, &mut pts);
832            if pts.first() == pts.last() && pts.len() > 1 {
833                pts.pop();
834            }
835            if pts.len() >= 2 {
836                out.push(pts);
837            }
838        }
839        // 如果还有未闭合回路(没 close),也导出来(首尾不重复)
840        if !self.segs.is_empty() {
841            let mut pts = Vec::new();
842            Self::flatten_contour(self.start, &self.segs, &mut pts);
843            if pts.first() == pts.last() && pts.len() > 1 {
844                pts.pop();
845            }
846            if pts.len() >= 2 {
847                out.push(pts);
848            }
849        }
850        out
851    }
852
853    /// 曲线保留导出:每个回路 (起点, 段序列, 是否显式 close)。
854    ///
855    /// 与 paths() 的区别:Quad/Cubic **不 flatten**,把曲线原样交给曲线感知
856    /// 消费者(如 tiny-skia PathStroker 的 quad/cubic stroke 路径)——密集折线
857    /// 逼近会让 stroker 在每个折点发 inner join 毛刺,锐角/密段时互相交叉。
858    pub fn curve_contours(&self) -> Vec<((f32, f32), Vec<PathSeg>, bool)> {
859        let mut out = Vec::with_capacity(self.contours.len() + 1);
860        for c in &self.contours {
861            out.push((c.start, c.segs.clone(), c.closed));
862        }
863        if !self.segs.is_empty() {
864            out.push((self.start, self.segs.clone(), false));
865        }
866        out
867    }
868
869    /// 导出所有回路及其闭合状态:`(回路折线, 是否显式 close)`。
870    ///
871    /// 闭合判定:显式 close 的回路 closed=true;move_to 冲刷的未闭合回路
872    /// closed=false。stroke 需要区分开/闭路径(开放路径不补 closing 边)。
873    pub fn paths_with_closed(&self) -> Vec<(Vec<(f32, f32)>, bool)> {
874        let mut out = Vec::with_capacity(self.contours.len() + 1);
875        for c in &self.contours {
876            let mut pts = Vec::new();
877            Self::flatten_contour(c.start, &c.segs, &mut pts);
878            if pts.first() == pts.last() && pts.len() > 1 {
879                pts.pop();
880            }
881            if pts.len() >= 2 {
882                out.push((pts, c.closed));
883            }
884        }
885        if !self.segs.is_empty() {
886            let mut pts = Vec::new();
887            Self::flatten_contour(self.start, &self.segs, &mut pts);
888            if pts.first() == pts.last() && pts.len() > 1 {
889                pts.pop();
890            }
891            if pts.len() >= 2 {
892                out.push((pts, false));
893            }
894        }
895        out
896    }
897
898    /// 把已闭合回路三角化为 PaintCommand::Triangles 并写进 list。
899    /// 支持多回路(外轮廓顺时针 + 内洞逆时针的 winding rule)。
900    pub fn fill(self, color: Color, list: &mut PaintList) {
901        if self.contours.is_empty() && self.segs.is_empty() {
902            return;
903        }
904        // 处理每条回路:曲线段 flatten;去掉首尾重复点
905        let mut clean_contours: Vec<Vec<(f32, f32)>> = Vec::with_capacity(self.contours.len());
906        for c in self.contours.iter() {
907            let mut pts = Vec::new();
908            Self::flatten_contour(c.start, &c.segs, &mut pts);
909            if pts.first() == pts.last() && pts.len() > 1 {
910                pts.pop();
911            }
912            if pts.len() >= 3 {
913                clean_contours.push(pts);
914            }
915        }
916        if clean_contours.is_empty() {
917            return;
918        }
919
920        // earcut 需要所有顶点 flatten 成一个大数组,外加每条回路的起始索引
921        let mut flat: Vec<(f32, f32)> = Vec::new();
922        let mut hole_offsets: Vec<usize> = Vec::new();
923        let mut first = true;
924        for contour in clean_contours.iter() {
925            if !first {
926                hole_offsets.push(flat.len());
927            }
928            first = false;
929            for &p in contour {
930                flat.push(p);
931            }
932        }
933        // 关键:顶点必须取自 earcut 实际索引的那份点集 —— 多回路(含洞)时
934        // earcut 会把洞桥接进外轮廓生成新的顶点数组,索引指向它而非 flat,
935        // 若此处仍用 flat 建 vertices,索引会越界(GPU 静默读垃圾,CPU 光栅化 panic)。
936        let (tri_points, indices) = earcut(&flat, if hole_offsets.is_empty() { None } else { Some(&hole_offsets) });
937        if indices.len() < 3 {
938            return;
939        }
940        let vertices: Vec<Vertex> = tri_points.iter().map(|&(x, y)| Vertex { x, y, color }).collect();
941        list.push(PaintCommand::Triangles { vertices, indices });
942    }
943}
944
945// =================================================================
946// 数学工具:quad bezier flatten + earcut
947// =================================================================
948
949#[allow(dead_code)]
950const MAX_FLATTEN_DEPTH: u32 = 10;
951
952#[allow(clippy::too_many_arguments)]
953fn flatten_quad_bezier(x0: f32, y0: f32, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32, out: &mut Vec<(f32, f32)>) {
954    // 控制点到首尾连线的距离,判断是否可以停止细分
955    let dx = ex - x0;
956    let dy = ey - y0;
957    let len_sq = dx * dx + dy * dy;
958    if len_sq < 1e-6 {
959        out.push((ex, ey));
960        return;
961    }
962    // 叉积:点到直线距离 * |ab| = |ab × ac|
963    let cross = dx * (cy - y0) - dy * (cx - x0);
964    let dist = (cross / len_sq.sqrt().max(1e-6)).abs();
965    if dist < flat {
966        out.push((ex, ey));
967        return;
968    }
969    // 二分
970    let mx0 = (x0 + cx) / 2.0;
971    let my0 = (y0 + cy) / 2.0;
972    let mx1 = (cx + ex) / 2.0;
973    let my1 = (cy + ey) / 2.0;
974    let mx = (mx0 + mx1) / 2.0;
975    let my = (my0 + my1) / 2.0;
976    flatten_quad_bezier(x0, y0, mx0, my0, mx, my, flat, out);
977    flatten_quad_bezier(mx, my, mx1, my1, ex, ey, flat, out);
978}
979
980/// 三次贝塞尔 flatten(递归细分,flatness 容差)
981#[allow(dead_code, clippy::too_many_arguments)]
982fn flatten_cubic_bezier(
983    x0: f32,
984    y0: f32,
985    x1: f32,
986    y1: f32,
987    x2: f32,
988    y2: f32,
989    x3: f32,
990    y3: f32,
991    flat: f32,
992    out: &mut Vec<(f32, f32)>,
993) {
994    // 两控制点到首尾连线的最大距离作为 flatness
995    let dx = x3 - x0;
996    let dy = y3 - y0;
997    let len = (dx * dx + dy * dy).sqrt().max(1e-6);
998    let d1 = (dx * (y1 - y0) - dy * (x1 - x0)).abs() / len;
999    let d2 = (dx * (y2 - y0) - dy * (x2 - x0)).abs() / len;
1000    if d1.max(d2) < flat {
1001        out.push((x3, y3));
1002        return;
1003    }
1004    let (mx01x, mx01y) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
1005    let (mx12x, mx12y) = ((x1 + x2) / 2.0, (y1 + y2) / 2.0);
1006    let (mx23x, mx23y) = ((x2 + x3) / 2.0, (y2 + y3) / 2.0);
1007    let (mxx, mxy) = ((mx01x + mx12x) / 2.0, (mx01y + mx12y) / 2.0);
1008    let (myy, myz) = ((mx12x + mx23x) / 2.0, (mx12y + mx23y) / 2.0);
1009    let (midx, midy) = ((mxx + myy) / 2.0, (mxy + myz) / 2.0);
1010    flatten_cubic_bezier(x0, y0, mx01x, mx01y, mxx, mxy, midx, midy, flat, out);
1011    flatten_cubic_bezier(midx, midy, myy, myz, mx23x, mx23y, x3, y3, flat, out);
1012}
1013
1014/// earcut 三角剖分(简单多边形 O(n²) 剪耳法)
1015///
1016/// 返回 `(实际参与索引的点集, indices)`。单回路时返回原始 `points`;
1017/// 多回路(含洞)时返回桥接洞后合并出的新点集 —— 调用方必须用返回的点集
1018/// 构造顶点,否则 indices 会越界。
1019fn earcut(points: &[(f32, f32)], hole_offsets: Option<&[usize]>) -> (Vec<(f32, f32)>, Vec<u32>) {
1020    let n = points.len();
1021    if n < 3 {
1022        return (Vec::new(), Vec::new());
1023    }
1024    // 简单多边形(单 contour,无洞)
1025    if hole_offsets.is_none() {
1026        return (points.to_vec(), earcut_single(points));
1027    }
1028    // 多回路:把洞合并进外轮廓(按桥接边的方向拼接)
1029    // 简化实现:第一个 contour 为外轮廓,其余按顺序桥接
1030    let hole_offsets = hole_offsets.unwrap();
1031    let mut merged: Vec<(f32, f32)> = Vec::with_capacity(n + hole_offsets.len());
1032    // 外轮廓
1033    let first_end = hole_offsets.first().copied().unwrap_or(n);
1034    merged.extend_from_slice(&points[0..first_end]);
1035    // 每个洞:找最近点桥接
1036    let mut contour_start = first_end;
1037    for &end_idx in hole_offsets.iter().skip(1) {
1038        let hole = &points[contour_start..end_idx];
1039        bridge_hole(&mut merged, hole);
1040        contour_start = end_idx;
1041    }
1042    if contour_start < n {
1043        let last = &points[contour_start..n];
1044        bridge_hole(&mut merged, last);
1045    }
1046    let indices = earcut_single(&merged);
1047    (merged, indices)
1048}
1049
1050/// 把洞桥接进外轮廓:找到外轮廓上离洞最近的点,在两者之间插入两条边
1051fn bridge_hole(outer: &mut Vec<(f32, f32)>, hole: &[(f32, f32)]) {
1052    if hole.is_empty() {
1053        return;
1054    }
1055    // 洞的 winding 必须与外轮廓相反;否则 earcut 会把洞当成实体重复填充
1056    let mut hole = hole.to_vec();
1057    let outer_ccw = area2(outer) > 0.0;
1058    let hole_ccw = area2(&hole) > 0.0;
1059    if hole_ccw == outer_ccw {
1060        hole.reverse();
1061    }
1062    // 找 outer 上离 hole 最近的点
1063    let hole_pt = hole[0];
1064    let mut best_i = 0usize;
1065    let mut best_d = f32::INFINITY;
1066    for (i, &p) in outer.iter().enumerate() {
1067        let d = (p.0 - hole_pt.0).powi(2) + (p.1 - hole_pt.1).powi(2);
1068        if d < best_d {
1069            best_d = d;
1070            best_i = i;
1071        }
1072    }
1073    let insert_pos = best_i + 1;
1074    let skip_last = if hole.first() == hole.last() { hole.len() - 1 } else { hole.len() };
1075    let bridge = outer[best_i];
1076    // 桥接必须「出去 → 绕洞一整圈 → 回到洞起点 → 原路返回」:
1077    // 只绕到洞的最后一个点就回去会漏掉洞的闭合边,填充区域会少掉
1078    // 外轮廓点与洞首尾之间的那块三角(甜甜圈面积对不上)。
1079    outer.insert(insert_pos, bridge);
1080    outer.splice(insert_pos + 1..insert_pos + 1, hole[..skip_last].iter().copied());
1081    let close_pos = insert_pos + 1 + skip_last;
1082    if let Some(&first) = hole.first() {
1083        outer.insert(close_pos, first);
1084        outer.insert(close_pos + 1, bridge);
1085    }
1086}
1087
1088/// 单 contour earcut
1089fn earcut_single(points: &[(f32, f32)]) -> Vec<u32> {
1090    let n = points.len();
1091    // 去掉闭合时的重复首尾点
1092    let points = if points.first() == points.last() { &points[..n - 1] } else { points };
1093    let n = points.len();
1094    if n < 3 {
1095        return Vec::new();
1096    }
1097
1098    let mut result = Vec::with_capacity((n - 2) * 3);
1099    // 活动节点链表:start = 0,按 ear 剪
1100    let mut active: Vec<usize> = (0..n).collect();
1101    // 轮廓 winding:凸角判定必须与整体方向一致(顺/逆时针都支持)
1102    let ccw = area2(points) > 0.0;
1103
1104    // 迭代剪耳:每次找一个 ear triangle,把中间点从链表移除
1105    let mut safety = n * n; // 防无限循环
1106    while active.len() >= 3 && safety > 0 {
1107        safety -= 1;
1108        if active.len() == 3 {
1109            // 收尾三角形直接输出(弱简单多边形的桥接点常留下共线的最后三个点,
1110            // 用 is_ear 判会因面积≈0 失败并误触发整多边形 fan 兜底,把前面
1111            // 已经剪好的耳全部丢掉)。
1112            let (a, b, c) = (active[0], active[1], active[2]);
1113            let (ax, ay) = points[a];
1114            let (bx, by) = points[b];
1115            let (cx, cy) = points[c];
1116            let cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
1117            if cross.abs() > 1e-6 {
1118                result.push(a as u32);
1119                result.push(b as u32);
1120                result.push(c as u32);
1121            }
1122            break;
1123        }
1124        let m = active.len();
1125        let mut found = None;
1126        for j in 0..m {
1127            let prev = active[(j + m - 1) % m];
1128            let curr = active[j];
1129            let next = active[(j + 1) % m];
1130            if is_ear(points, prev, curr, next, ccw) {
1131                found = Some(j);
1132                break;
1133            }
1134        }
1135        match found {
1136            Some(j) => {
1137                let prev = active[(j + m - 1) % m];
1138                let curr = active[j];
1139                let next = active[(j + 1) % m];
1140                result.push(prev as u32);
1141                result.push(curr as u32);
1142                result.push(next as u32);
1143                active.remove(j);
1144            }
1145            None => {
1146                // 没 ear 了(自相交),直接用 fan 分解凸化近似
1147                return fan_triangulation(points);
1148            }
1149        }
1150    }
1151    if result.is_empty() {
1152        fan_triangulation(points)
1153    } else {
1154        result
1155    }
1156}
1157
1158fn area2(points: &[(f32, f32)]) -> f32 {
1159    let mut a = 0.0f32;
1160    for w in points.windows(2) {
1161        a += w[0].0 * w[1].1 - w[1].0 * w[0].1;
1162    }
1163    if points.len() >= 2 {
1164        a += points.last().unwrap().0 * points[0].1 - points[0].0 * points.last().unwrap().1;
1165    }
1166    a
1167}
1168
1169fn is_ear(points: &[(f32, f32)], a: usize, b: usize, c: usize, ccw: bool) -> bool {
1170    let (ax, ay) = points[a];
1171    let (bx, by) = points[b];
1172    let (cx, cy) = points[c];
1173    // 凸角判定:三角形方向必须与轮廓 winding 一致。凹(反射)顶点
1174    // 切出来的三角形会覆盖到多边形外,造成重叠/错色。
1175    let abc_cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
1176    if (abc_cross > 0.0) != ccw {
1177        return false;
1178    }
1179    // 检查没有其他点在三角形内部(严格内部:边界/共线点不阻塞剪耳)
1180    for (i, &(px, py)) in points.iter().enumerate() {
1181        if i == a || i == b || i == c {
1182            continue;
1183        }
1184        if point_in_triangle(px, py, ax, ay, bx, by, cx, cy) {
1185            return false;
1186        }
1187    }
1188    true
1189}
1190
1191#[allow(clippy::too_many_arguments)]
1192fn point_in_triangle(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32, cx: f32, cy: f32) -> bool {
1193    let v0x = cx - ax;
1194    let v0y = cy - ay;
1195    let v1x = bx - ax;
1196    let v1y = by - ay;
1197    let v2x = px - ax;
1198    let v2y = py - ay;
1199
1200    let dot00 = v0x * v0x + v0y * v0y;
1201    let dot01 = v0x * v1x + v0y * v1y;
1202    let dot02 = v0x * v2x + v0y * v2y;
1203    let dot11 = v1x * v1x + v1y * v1y;
1204    let dot12 = v1x * v2x + v1y * v2y;
1205
1206    let inv_denom = 1.0 / (dot00 * dot11 - dot01 * dot01).max(1e-9);
1207    let u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
1208    let v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
1209    // 严格内部:边界上的共线点不应阻止剪耳(否则直角/网格类轮廓频繁
1210    // 找不到 ear → 退化到错误的 fan 兜底)。
1211    const EPS: f32 = 1e-6;
1212    u > EPS && v > EPS && (u + v) < 1.0 - EPS
1213}
1214
1215/// 简单扇形三角化(凸多边形,或 earcut 失败时的兜底)
1216fn fan_triangulation(points: &[(f32, f32)]) -> Vec<u32> {
1217    let mut result = Vec::new();
1218    if points.len() < 3 {
1219        return result;
1220    }
1221    let base = points[0];
1222    // 尝试从 base 扇形切
1223    for i in 2..points.len() {
1224        // 检查三角形 base,0,i 是否包含其他点
1225        let mut ok = true;
1226        for j in 1..points.len() {
1227            if j == i || j == 0 {
1228                continue;
1229            }
1230            if point_in_triangle(
1231                points[j].0,
1232                points[j].1,
1233                base.0,
1234                base.1,
1235                points[1].0,
1236                points[1].1,
1237                points[i].0,
1238                points[i].1,
1239            ) {
1240                ok = false;
1241                break;
1242            }
1243        }
1244        if ok {
1245            result.push(0u32);
1246            result.push(1u32);
1247            result.push(i as u32);
1248        }
1249    }
1250    // 如果 fan 结果太少(凹多边形),用一个中间点做退化分割
1251    if result.len() < 3 && points.len() >= 3 {
1252        let n = points.len() as u32;
1253        for i in 1..n - 1 {
1254            result.push(0);
1255            result.push(i);
1256            result.push(i + 1);
1257        }
1258    }
1259    result
1260}
1261
1262#[cfg(test)]
1263mod tests {
1264    use super::*;
1265    use crate::Color;
1266
1267    #[test]
1268    fn content_digest_is_stable_and_sensitive_to_pixel_inputs() {
1269        let mut a = PaintList::new();
1270        a.rect(Rect::new(1.0, 2.0, 30.0, 40.0), Color::rgb(0.1, 0.2, 0.3));
1271        a.text("你好", 14.0, Color::WHITE, Point::new(3.0, 4.0));
1272        let b = a.clone();
1273        assert_eq!(a.content_digest(), b.content_digest());
1274
1275        let mut changed = a.clone();
1276        if let PaintCommand::Rect { color, .. } = &mut changed.commands[0] {
1277            color.r = 0.9;
1278        }
1279        assert_ne!(a.content_digest(), changed.content_digest(), "颜色变化必须改变 key");
1280
1281        let mut changed = a.clone();
1282        changed.text("你坏", 14.0, Color::WHITE, Point::new(3.0, 4.0));
1283        assert_ne!(a.content_digest(), changed.content_digest(), "文本变化必须改变 key");
1284    }
1285
1286    #[test]
1287    fn path_builder_triangulates_square() {
1288        let mut pb = PathBuilder::new();
1289        pb.move_to(0.0, 0.0);
1290        pb.line_to(100.0, 0.0);
1291        pb.line_to(100.0, 100.0);
1292        pb.line_to(0.0, 100.0);
1293        pb.close();
1294        let mut list = PaintList::new();
1295        pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1296        assert_eq!(list.commands.len(), 1);
1297        if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1298            // 正方形 earcut:4 vertices + 6 indices = 2 triangles(顺序取决于 winding)
1299            assert_eq!(vertices.len(), 4);
1300            assert_eq!(indices.len(), 6);
1301        } else {
1302            panic!("expected Triangles");
1303        }
1304    }
1305
1306    #[test]
1307    fn path_builder_quadbezier_flattens() {
1308        let mut pb = PathBuilder::new();
1309        pb.move_to(0.0, 50.0);
1310        pb.quad_to(50.0, 0.0, 100.0, 50.0, 0.5);
1311        pb.quad_to(50.0, 100.0, 0.0, 50.0, 0.5);
1312        pb.close();
1313        let mut list = PaintList::new();
1314        pb.fill(Color::rgb(0.0, 1.0, 0.0), &mut list);
1315        assert_eq!(list.commands.len(), 1);
1316        if let PaintCommand::Triangles { indices, .. } = &list.commands[0] {
1317            assert!(indices.len() >= 6, "bezier triangulation should produce >= 6 indices, got {}", indices.len());
1318        }
1319    }
1320
1321    #[test]
1322    fn path_builder_arc_to_produces_points() {
1323        let mut pb = PathBuilder::new();
1324        // 1/4 圆弧(从 +X 到 +Y,90 度)
1325        pb.move_to(100.0, 100.0);
1326        pb.arc_to(100.0, 100.0, 50.0, 0.0, std::f32::consts::FRAC_PI_2, 16);
1327        pb.close();
1328        let mut list = PaintList::new();
1329        pb.fill(Color::WHITE, &mut list);
1330
1331        if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1332            assert!(vertices.len() >= 4, "arc + close → 至少 4 vertices");
1333            assert!(indices.len() >= 6, "earcut → 至少 1 triangle(3 indices)");
1334            // 检查点都在半径 50 附近
1335            for v in vertices {
1336                let dx = v.x - 100.0;
1337                let dy = v.y - 100.0;
1338                let d = (dx * dx + dy * dy).sqrt();
1339                assert!((d - 50.0).abs() < 1.0 || d < 1.0, "vertex ({}, {}) should be at r≈50 or center", v.x, v.y);
1340            }
1341        }
1342    }
1343
1344    #[test]
1345    fn path_builder_annulus_sector_triangulates() {
1346        // Circular Progress 的 annulus sector:外弧 + 径向 + 内弧 + close
1347        let cx = 100.0;
1348        let cy = 100.0;
1349        let outer_r = 80.0;
1350        let inner_r = 60.0;
1351        let start_a = -std::f32::consts::FRAC_PI_2;
1352        let end_a = start_a + std::f32::consts::TAU * 0.75; // 270 度
1353        let segs = 32u32;
1354
1355        let mut pb = PathBuilder::new();
1356        pb.move_to(cx + outer_r * start_a.cos(), cy + outer_r * start_a.sin());
1357        pb.arc_to(cx, cy, outer_r, start_a, end_a, segs);
1358        pb.line_to(cx + inner_r * end_a.cos(), cy + inner_r * end_a.sin());
1359        pb.arc_to(cx, cy, inner_r, end_a, start_a, segs);
1360        pb.close();
1361
1362        let mut list = PaintList::new();
1363        pb.fill(Color::rgb(0.2, 0.6, 1.0), &mut list);
1364
1365        if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1366            // 外弧 33 + 径向连线 → 内弧 33 反向 → close → ~68 vertices(earcut 会用其中的)
1367            assert!(vertices.len() >= 20, "annulus sector should have many vertices, got {}", vertices.len());
1368            assert!(indices.len() >= 6, "should produce triangles");
1369
1370            // 点要么在外半径附近,要么在内半径附近(径向连线除外)
1371            for v in vertices {
1372                let dx = v.x - cx;
1373                let dy = v.y - cy;
1374                let d = (dx * dx + dy * dy).sqrt();
1375                let on_outer = (d - outer_r).abs() < 1.0;
1376                let on_inner = (d - inner_r).abs() < 1.0;
1377                let on_radial = v.y == cy; // 径向连线端点在 y=cy 上(start_a = -PI/2)
1378                assert!(
1379                    on_outer || on_inner || on_radial,
1380                    "vertex ({}, {}) d={} not on inner/outer/radial",
1381                    v.x,
1382                    v.y,
1383                    d
1384                );
1385            }
1386        }
1387    }
1388
1389    #[test]
1390    fn box_shadow_pads_four_sigma_and_shrinks_radius_on_negative_spread() {
1391        let mut list = PaintList::new();
1392        list.box_shadow(Rect::new(10.0, 20.0, 100.0, 50.0), Point::new(2.0, 3.0), 5.0, 1.0, Color::BLACK, 8.0);
1393        match &list.commands[0] {
1394            PaintCommand::BoxShadow { rect, radius, blur_radius, .. } => {
1395                // shape=(11,22,102,52),pad=4×5=20 → 外扩后 (-9,2,142,92)
1396                assert_eq!(*rect, Rect::new(-9.0, 2.0, 142.0, 92.0));
1397                assert_eq!(*radius, 9.0, "正 spread 圆角增大");
1398                assert_eq!(*blur_radius, 5.0);
1399            }
1400            other => panic!("expected BoxShadow, got {other:?}"),
1401        }
1402
1403        let mut list = PaintList::new();
1404        list.box_shadow(Rect::new(0.0, 0.0, 100.0, 50.0), Point::ZERO, 0.0, -4.0, Color::BLACK, 10.0);
1405        match &list.commands[0] {
1406            PaintCommand::BoxShadow { rect, radius, .. } => {
1407                assert_eq!(*rect, Rect::new(4.0, 4.0, 92.0, 42.0));
1408                assert_eq!(*radius, 6.0, "负 spread 圆角应收缩");
1409            }
1410            other => panic!("expected BoxShadow, got {other:?}"),
1411        }
1412    }
1413
1414    #[test]
1415    fn path_builder_empty_nop() {
1416        let pb = PathBuilder::new();
1417        let mut list = PaintList::new();
1418        pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1419        assert!(list.is_empty());
1420    }
1421
1422    #[test]
1423    fn earcut_simple_triangle() {
1424        let pts = vec![(0.0, 0.0), (10.0, 0.0), (5.0, 10.0), (0.0, 0.0)];
1425        let (points, indices) = earcut(&pts, None);
1426        // 有效三角形 = 3 indices,方向取决于 winding(不影响渲染)
1427        assert_eq!(indices.len(), 3);
1428        let unique: std::collections::HashSet<&u32> = indices.iter().collect();
1429        assert_eq!(unique.len(), 3); // 三个不同顶点
1430                                     // 索引必须落在返回点集范围内(防越界回归)
1431        assert!(indices.iter().all(|&i| (i as usize) < points.len()));
1432    }
1433
1434    fn tri_area_sum(points: &[(f32, f32)], indices: &[u32]) -> f32 {
1435        let mut area = 0.0;
1436        for t in indices.as_chunks::<3>().0 {
1437            let (ax, ay) = points[t[0] as usize];
1438            let (bx, by) = points[t[1] as usize];
1439            let (cx, cy) = points[t[2] as usize];
1440            area += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() * 0.5;
1441        }
1442        area
1443    }
1444
1445    /// 凹多边形:三角化总面积必须等于多边形面积(无重叠/无越界覆盖)
1446    #[test]
1447    fn earcut_concave_polygon_area_matches() {
1448        // L 形(逆时针)
1449        let pts = vec![(0.0, 0.0), (60.0, 0.0), (60.0, 20.0), (20.0, 20.0), (20.0, 60.0), (0.0, 60.0)];
1450        let (points, indices) = earcut(&pts, None);
1451        assert_eq!(indices.len(), 12, "6 顶点凹多边形 → 4 个三角形");
1452        assert!(indices.iter().all(|&i| (i as usize) < points.len()));
1453        let expected = area2(&pts).abs() * 0.5;
1454        let got = tri_area_sum(&points, &indices);
1455        assert!((got - expected).abs() < 0.5, "凹多边形面积: expected={expected}, got={got}");
1456    }
1457
1458    /// 带洞填充:总面积 = 外轮廓 - 洞(桥接拓扑正确性回归)
1459    #[test]
1460    fn earcut_donut_hole_area_subtracted() {
1461        let outer = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
1462        let hole = vec![(25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0)];
1463        let mut pts = outer.clone();
1464        pts.extend_from_slice(&hole);
1465        let (points, indices) = earcut(&pts, Some(&[outer.len()]));
1466        assert!(!indices.is_empty());
1467        assert!(indices.iter().all(|&i| (i as usize) < points.len()), "索引不得越界");
1468        let got = tri_area_sum(&points, &indices);
1469        let expected = 100.0 * 100.0 - 50.0 * 50.0;
1470        assert!((got - expected).abs() < 1.0, "带洞面积: expected={expected}, got={got}");
1471    }
1472
1473    /// 回归:含洞(多回路)的 fill 索引不得越界。
1474    /// 修复前 earcut 索引指向桥接后的 merged 点集,而 fill 用 flat 建 vertices,
1475    /// 最后一根索引恰好 == flat.len() → CPU 光栅化 panic。
1476    #[test]
1477    fn fill_multi_contour_indices_in_range() {
1478        let mut pb = PathBuilder::new();
1479        // 外轮廓(正方形)
1480        pb.move_to(0.0, 0.0);
1481        pb.line_to(100.0, 0.0);
1482        pb.line_to(100.0, 100.0);
1483        pb.line_to(0.0, 100.0);
1484        pb.close();
1485        // 洞(内部小三角)
1486        pb.move_to(40.0, 40.0);
1487        pb.line_to(60.0, 40.0);
1488        pb.line_to(50.0, 60.0);
1489        pb.close();
1490        let mut list = PaintList::new();
1491        pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1492        assert_eq!(list.commands.len(), 1);
1493        if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1494            assert!(
1495                indices.iter().all(|&i| (i as usize) < vertices.len()),
1496                "索引 {} 越界(vertices.len={})",
1497                indices.iter().max().unwrap(),
1498                vertices.len()
1499            );
1500        } else {
1501            panic!("expected Triangles");
1502        }
1503    }
1504}