Skip to main content

velox_engine/motion/
draw_op.rs

1//! 扁平绘制指令原语(`DrawOp`、`DrawPayload` 与帧间差异指纹 `DrawOpSnapshot`)。
2
3use crate::arena::StrRef;
4use crate::element::SpriteSource;
5use crate::paint::{ExternalTextureSpec, LayerSpec, StyledQuad};
6use crate::solver::Region;
7use crate::style::Color;
8
9/// 将有符号 4-bit 亚像素偏移 `(dx_q4, dy_q4)`(范围 `-8..=7`,单位 `1/16 px`)紧凑打包为 1 字节。
10#[inline(always)]
11pub const fn pack_subpx_q4(dx_q4: i8, dy_q4: i8) -> u8 {
12    let dx = if dx_q4 < -8 {
13        -8
14    } else if dx_q4 > 7 {
15        7
16    } else {
17        dx_q4
18    };
19    let dy = if dy_q4 < -8 {
20        -8
21    } else if dy_q4 > 7 {
22        7
23    } else {
24        dy_q4
25    };
26    (((dx as u8) & 0x0F) << 4) | ((dy as u8) & 0x0F)
27}
28
29/// 将 [`pack_subpx_q4`] 打包的 1 字节解码为有符号 `(dx_q4, dy_q4)`(范围 `-8..=7`,单位 `1/16 px`)。
30#[inline(always)]
31pub const fn unpack_subpx_q4(packed: u8) -> (i8, i8) {
32    let dx = (packed as i8) >> 4;
33    let dy = ((packed << 4) as i8) >> 4;
34    (dx, dy)
35}
36
37/// 扁平化一维渲染指令。
38#[derive(Copy, Clone, PartialEq, Eq)]
39pub struct DrawOp<'a> {
40    /// 关联的元素 ID(用于 $O(1)$ 匹配上一帧指令触发过渡动画)。
41    pub id: Option<u32>,
42    /// 屏幕绝对坐标矩形。
43    pub bounds: Region,
44    /// 父级裁剪区(用于滚动视图与圆角容器裁剪)。
45    pub clip: Region,
46    /// 父级裁剪圆角半径(逻辑像素;`0` 表示轴对齐直角裁剪,非零时启用抗锯齿圆角 SDF 裁切)。
47    pub clip_radius: u8,
48    /// 亚像素动画平移残差(利用结构体原有对齐空洞,0 字节膨胀;高 4 位 `dx_q4`、低 4 位 `dy_q4`,单位 `1/16 px`)。
49    pub subpx_q4: u8,
50    /// 绘制负载数据。
51    pub payload: DrawPayload<'a>,
52}
53
54/// 闭合绘制负载枚举(3 种零开销高频基元 `Quad`/`TextRun`/`Sprite` + 3 种零体积膨胀冷路径高级原语)。
55#[derive(Copy, Clone)]
56pub enum DrawPayload<'a> {
57    /// 圆角矩形、定点数线性渐变与边框(由 SDF 扫描线算法一次性合成,`border_width` 最高位 `0x80` 标识水平渐变)。
58    Quad {
59        bg: Color,
60        bg_grad: Color,
61        border_color: Color,
62        rounded: u8,
63        border_width: u8,
64    },
65    /// 文本切片(`text_flags` 包含水平对齐、`ellipsis` 省略号与 `nowrap` 标志位)。
66    TextRun {
67        text: StrRef<'a>,
68        color: Color,
69        font_size: u8,
70        text_flags: u8,
71    },
72    /// A4/A8 抗锯齿 Alpha 图标掩码、RGB565 贴图或过程化矢量精灵。
73    Sprite(SpriteSource<'a>),
74    /// 高级矩形图元:多色标渐变(Linear/Radial/Conic + OKLab)、四角独立圆角、2D 仿射变换与单图元混合模式(8B Arena 引用,不膨胀 `DrawOp`)。
75    StyledQuad(&'a StyledQuad<'a>),
76    /// 推入隔离合成图层:支持组级不透明度、27 种混合模式、高斯模糊、色彩矩阵、任意形状投影、实时毛玻璃与 SVG Path 裁剪(8B Arena 引用)。
77    PushLayer(&'a LayerSpec<'a>),
78    /// 弹出当前隔离合成图层并执行滤镜后处理与合成回父画布(0B)。
79    PopLayer,
80    /// 外部零拷贝 GPU 纹理(如海图/视频/3D 视口共享的 `wgpu::TextureView`,8B Arena 引用,零膨胀 `DrawOp`)。
81    ExternalTexture(&'a ExternalTextureSpec),
82    /// 行内多字族/字重/BiDi/彩色 Emoji 富文本段落(8B Arena 引用,零膨胀 `DrawOp`)。
83    RichText(&'a crate::text_rich::RichTextSpec<'a>),
84    /// 支持 `ObjectFit` / `NineSlice` / LRU 纹理缓存的通用解码图像(8B Arena 引用)。
85    DecodedImage(&'a crate::image_pipeline::DecodedImageSpec),
86    /// 原生抗锯齿 2D 矢量画布(8B Arena 引用)。
87    Vector(&'a crate::vector_canvas::VectorDrawSpec<'a>),
88    /// 高密度 2D 交互式场景画布(8B Arena 引用,零膨胀 `DrawOp`)。
89    SceneCanvas(&'a crate::canvas_scene::SceneCanvasSpec<'a>),
90}
91
92impl<'a> PartialEq for DrawPayload<'a> {
93    fn eq(&self, other: &Self) -> bool {
94        match (*self, *other) {
95            (
96                Self::Quad {
97                    bg: b1,
98                    bg_grad: bg1,
99                    border_color: bc1,
100                    rounded: r1,
101                    border_width: bw1,
102                },
103                Self::Quad {
104                    bg: b2,
105                    bg_grad: bg2,
106                    border_color: bc2,
107                    rounded: r2,
108                    border_width: bw2,
109                },
110            ) => b1 == b2 && bg1 == bg2 && bc1 == bc2 && r1 == r2 && bw1 == bw2,
111            (
112                Self::TextRun {
113                    text: t1,
114                    color: c1,
115                    font_size: f1,
116                    text_flags: tf1,
117                },
118                Self::TextRun {
119                    text: t2,
120                    color: c2,
121                    font_size: f2,
122                    text_flags: tf2,
123                },
124            ) => t1 == t2 && c1 == c2 && f1 == f2 && tf1 == tf2,
125            (
126                Self::Sprite(SpriteSource::Bitmap {
127                    bytes: b1,
128                    format: f1,
129                    tint: t1,
130                }),
131                Self::Sprite(SpriteSource::Bitmap {
132                    bytes: b2,
133                    format: f2,
134                    tint: t2,
135                }),
136            ) => {
137                core::ptr::eq(b1.as_ptr(), b2.as_ptr())
138                    && b1.len() == b2.len()
139                    && f1 == f2
140                    && t1 == t2
141            }
142            (
143                Self::Sprite(SpriteSource::Shader { state_hash: h1, .. }),
144                Self::Sprite(SpriteSource::Shader { state_hash: h2, .. }),
145            ) => h1 == h2,
146            (
147                Self::Sprite(s1 @ SpriteSource::Svg { .. }),
148                Self::Sprite(s2 @ SpriteSource::Svg { .. }),
149            ) => s1 == s2,
150            (Self::Sprite(s1 @ SpriteSource::Arc { .. }), Self::Sprite(s2 @ SpriteSource::Arc { .. })) => {
151                s1 == s2
152            }
153            (Self::StyledQuad(a), Self::StyledQuad(b)) => a == b,
154            (Self::PushLayer(a), Self::PushLayer(b)) => a == b,
155            (Self::PopLayer, Self::PopLayer) => true,
156            (Self::ExternalTexture(a), Self::ExternalTexture(b)) => a == b,
157            (Self::RichText(a), Self::RichText(b)) => a == b,
158            (Self::DecodedImage(a), Self::DecodedImage(b)) => a == b,
159            (Self::Vector(a), Self::Vector(b)) => a == b,
160            (Self::SceneCanvas(a), Self::SceneCanvas(b)) => a == b,
161            _ => false,
162        }
163    }
164}
165
166impl<'a> Eq for DrawPayload<'a> {}
167
168/// 独立于帧生命周期的 `DrawOp` 微快照(12 字节紧凑表示,预求交裁剪框并内联哈希,用于原地流式比对)。
169#[repr(C)]
170#[derive(Copy, Clone, PartialEq, Eq, Debug)]
171pub struct DrawOpSnapshot {
172    /// 预先与父级 `clip` 求交后的有效屏幕矩形(8 字节)。
173    pub effective_bounds: Region,
174    /// 包含 ID、裁剪区与绘制负载的 32 位 FNV-1a 哈希(4 字节)。
175    pub payload_hash: u32,
176}
177
178impl<'a> DrawOp<'a> {
179    /// 生成与 `'a` 生命周期无关的 12 字节紧凑绘制快照。
180    pub fn to_snapshot(&self) -> DrawOpSnapshot {
181        let mut h: u32 = 0x811c_9dc5;
182        let mix = |h: &mut u32, byte: u8| {
183            *h ^= byte as u32;
184            *h = h.wrapping_mul(0x0100_0193);
185        };
186        let mix_i16 = |h: &mut u32, val: i16| {
187            for b in val.to_le_bytes() {
188                mix(h, b);
189            }
190        };
191        let mix_u32 = |h: &mut u32, val: u32| {
192            for b in val.to_le_bytes() {
193                mix(h, b);
194            }
195        };
196        if let Some(id) = self.id {
197            mix(&mut h, 0xFF);
198            mix_u32(&mut h, id);
199        }
200        // 将原始 bounds 与 clip 混入哈希,保证任何几何或裁剪变化均能被检出
201        mix_i16(&mut h, self.bounds.x);
202        mix_i16(&mut h, self.bounds.y);
203        mix_i16(&mut h, self.bounds.w);
204        mix_i16(&mut h, self.bounds.h);
205        mix_i16(&mut h, self.clip.x);
206        mix_i16(&mut h, self.clip.y);
207        mix_i16(&mut h, self.clip.w);
208        mix_i16(&mut h, self.clip.h);
209        mix(&mut h, self.clip_radius);
210        mix(&mut h, self.subpx_q4);
211
212        match self.payload {
213            DrawPayload::Quad {
214                bg,
215                bg_grad,
216                border_color,
217                rounded,
218                border_width,
219            } => {
220                mix(&mut h, 1);
221                mix_u32(&mut h, bg.0);
222                mix_u32(&mut h, bg_grad.0);
223                mix_u32(&mut h, border_color.0);
224                mix(&mut h, rounded);
225                mix(&mut h, border_width);
226            }
227            DrawPayload::TextRun {
228                text,
229                color,
230                font_size,
231                text_flags,
232            } => {
233                mix(&mut h, 2);
234                mix_u32(&mut h, color.0);
235                mix(&mut h, font_size);
236                mix(&mut h, text_flags);
237                for &b in text.as_str().as_bytes() {
238                    mix(&mut h, b);
239                }
240            }
241            DrawPayload::Sprite(SpriteSource::Bitmap {
242                bytes,
243                format,
244                tint,
245            }) => {
246                mix(&mut h, 3);
247                mix(&mut h, format as u8);
248                mix_u32(&mut h, tint.0);
249                mix_u32(&mut h, bytes.as_ptr() as usize as u32);
250                mix_u32(&mut h, bytes.len() as u32);
251            }
252            DrawPayload::Sprite(SpriteSource::Shader { state_hash, .. }) => {
253                mix(&mut h, 4);
254                mix_u32(&mut h, state_hash);
255            }
256            DrawPayload::Sprite(SpriteSource::Svg {
257                source,
258                is_path_only,
259                tint,
260                stroke_width_x10,
261            }) => {
262                mix(&mut h, 6);
263                mix(&mut h, if is_path_only { 1 } else { 0 });
264                mix(&mut h, stroke_width_x10);
265                mix_u32(&mut h, tint.0);
266                for &b in source.as_str().as_bytes() {
267                    mix(&mut h, b);
268                }
269            }
270            DrawPayload::Sprite(SpriteSource::Arc {
271                thickness,
272                start_deg10,
273                sweep_deg10,
274                fill_sweep_deg10,
275                track_color,
276                fill_color,
277            }) => {
278                mix(&mut h, 5);
279                mix(&mut h, thickness);
280                mix_i16(&mut h, start_deg10 as i16);
281                mix_i16(&mut h, sweep_deg10 as i16);
282                mix_i16(&mut h, fill_sweep_deg10 as i16);
283                mix_u32(&mut h, track_color.0);
284                mix_u32(&mut h, fill_color.0);
285            }
286            DrawPayload::StyledQuad(sq) => {
287                mix(&mut h, 7);
288                sq.mix_hash(&mut h);
289            }
290            DrawPayload::PushLayer(layer) => {
291                mix(&mut h, 8);
292                layer.mix_hash(&mut h);
293            }
294            DrawPayload::PopLayer => {
295                mix(&mut h, 9);
296            }
297            DrawPayload::ExternalTexture(ext) => {
298                mix(&mut h, 10);
299                ext.mix_hash(&mut h);
300            }
301            DrawPayload::RichText(rt) => {
302                mix(&mut h, 11);
303                rt.mix_hash(&mut h);
304            }
305            DrawPayload::DecodedImage(img) => {
306                mix(&mut h, 12);
307                img.mix_hash(&mut h);
308            }
309            DrawPayload::Vector(vec_spec) => {
310                mix(&mut h, 13);
311                vec_spec.mix_hash(&mut h);
312            }
313            DrawPayload::SceneCanvas(spec) => {
314                mix(&mut h, 14);
315                mix_u32(&mut h, spec.content_hash());
316            }
317        }
318        let eff_bounds = self.effective_damage_bounds();
319        DrawOpSnapshot {
320            effective_bounds: eff_bounds,
321            payload_hash: h,
322        }
323    }
324
325    /// 计算本条绘制指令实际可能触及的逻辑像素包围盒(供 `DamageTracker` 与 `DrawOpSnapshot` 共用)。
326    ///
327    /// 对单行 / `nowrap` `TextRun` 同步覆盖与 `compute_scaled_text_box` 同源的横向/纵向外扩范围(受 `self.clip` 裁剪),
328    /// 确保溢出布局框的长文本在变更或删除时均生成完整脏区,杜绝持久渲染目标局部重绘残影。
329    #[inline]
330    pub fn effective_damage_bounds(&self) -> Region {
331        match self.payload {
332            DrawPayload::PushLayer(layer) => layer.expanded_bounds().intersect(self.clip),
333            DrawPayload::StyledQuad(sq) => {
334                if let Some(t) = sq.transform {
335                    let cx = self.bounds.x as f32 + self.bounds.w as f32 * 0.5;
336                    let cy = self.bounds.y as f32 + self.bounds.h as f32 * 0.5;
337                    t.centered_at(cx, cy)
338                        .transform_region(self.bounds)
339                        .intersect(self.clip)
340                } else {
341                    self.bounds.intersect(self.clip)
342                }
343            }
344            DrawPayload::TextRun {
345                text,
346                color,
347                font_size,
348                text_flags,
349            } => {
350                if text.is_empty() || color.a() == 0 {
351                    return Region::EMPTY;
352                }
353                let logical_fs = font_size.max(8);
354                let char_h = logical_fs as i16;
355                let line_step = (char_h.saturating_mul(5) / 4).max(char_h);
356                let is_ellipsis = (text_flags & 0x04) != 0;
357                let is_nowrap = (text_flags & 0x08) != 0;
358                let mut b = self.bounds;
359
360                let measure_w = |s: &str| -> i16 {
361                    {
362                        crate::display::measure_line_width_f32(s, logical_fs).ceil() as i16
363                    }
364                };
365
366                // 统一覆盖单行/nowrap 与多行折行(含圆角父容器中溢出布局框的多行文本),零堆分配
367                let (line_count, max_line_w) = if is_nowrap || is_ellipsis || self.bounds.w <= 0 {
368                    (1i16, measure_w(text.as_str()))
369                } else {
370                    let mut count = 0i16;
371                    let mut max_w = 0i16;
372                    let mut rem = text.as_str();
373                    while !rem.is_empty() && count < 32 {
374                        let (line_slice, next_rem) =
375                            crate::display::next_wrapped_line(rem, logical_fs, self.bounds.w);
376                        max_w = max_w.max(measure_w(line_slice));
377                        count += 1;
378                        if next_rem.len() == rem.len() {
379                            break;
380                        }
381                        rem = next_rem;
382                    }
383                    (count.max(1), max_w)
384                };
385
386                if !is_ellipsis {
387                    // 横向:覆盖单行 HiDPI 扩展或长词超出布局框的真实绘制宽度(+~3% 或至少 4px 余量)
388                    let extra_w = (max_line_w / 32).max(4);
389                    let target_w = max_line_w.saturating_add(extra_w);
390                    if target_w > b.w {
391                        let diff_w = target_w - b.w;
392                        match text_flags & 0x03 {
393                            1 => b.x = b.x.saturating_sub(diff_w / 2),
394                            2 => b.x = b.x.saturating_sub(diff_w),
395                            _ => {}
396                        }
397                        b.w = target_w;
398                        if b.right() > self.clip.right() {
399                            let over = b.right().saturating_sub(self.clip.right());
400                            b.x = b.x.saturating_sub(over).max(self.clip.x);
401                        }
402                    }
403                    // 纵向:覆盖单行字高扩宽与多行总块高 `char_h + line_step * (lines - 1)` + ascent/descent 余量
404                    let block_h = char_h
405                        .saturating_add(line_step.saturating_mul(line_count.saturating_sub(1)))
406                        .saturating_add((char_h / 2).max(4));
407                    if block_h > b.h {
408                        if line_count <= 1 {
409                            let diff_h = block_h - b.h;
410                            b.y = b.y.saturating_sub(diff_h / 2);
411                        } else {
412                            // 多行文本从 top_y = bounds.y 开始向下延伸,同时顶部预留 ascent 微量溢出余量
413                            let top_pad = (char_h / 4).max(2);
414                            b.y = b.y.saturating_sub(top_pad);
415                        }
416                        b.h = block_h.saturating_add((char_h / 4).max(2));
417                    }
418                } else if max_line_w <= self.bounds.w {
419                    b.w = b.w.max(max_line_w.saturating_add(4));
420                }
421
422                let mut res = b.union(self.bounds);
423                if self.subpx_q4 != 0 {
424                    res = Region::new(
425                        res.x.saturating_sub(1),
426                        res.y.saturating_sub(1),
427                        res.w.saturating_add(2),
428                        res.h.saturating_add(2),
429                    );
430                }
431                res.intersect(self.clip)
432            }
433            _ => {
434                let mut res = self.bounds;
435                if self.subpx_q4 != 0 {
436                    res = Region::new(
437                        res.x.saturating_sub(1),
438                        res.y.saturating_sub(1),
439                        res.w.saturating_add(2),
440                        res.h.saturating_add(2),
441                    );
442                }
443                res.intersect(self.clip)
444            }
445        }
446    }
447}
448