Skip to main content

velox_engine/
paint.rs

1//! 现代 2D 矢量与合成原语(`#![no_std]` 零全局堆分配兼容):
2//!
3//! 对标 Skia / Vello 的核心渲染语义,为 GPU (`wgpu`) 与软件 (`software`) 双后端提供统一真源:
4//! - [`CornerRadii`]:四角独立圆角 `[tl, tr, br, bl]`;
5//! - [`Paint`] / [`ColorStop`] / [`ExtendMode`] / [`GradientSpace`]:多色标任意角度线性渐变、双圆焦点径向渐变、锥形扫描渐变,支持 `sRGB` / `LinearRgb` / `Oklab` 色彩空间与 `Pad` / `Repeat` / `Reflect` 延展模式;
6//! - [`BlendMode`]:完整 27 种 Porter-Duff 合成模式与 W3C Compositing Level 1 可分离 / HSL 不可分离混合模式;
7//! - [`ColorMatrix`] / [`DropShadow`] / [`LayerFilter`] / [`BackdropFilter`]:色彩矩阵、子树高斯模糊、任意形状投影与实时毛玻璃背景模糊;
8//! - [`StyledQuad`] / [`LayerSpec`] / [`PaintEffects`]:分配于 `ScratchArena` 的零堆冷路径渲染载荷,不增加常规节点一字节内存。
9
10use crate::arena::StrRef;
11use crate::solver::Region;
12use crate::style::Color;
13use crate::svg::math::{
14    abs_f32, atan2_f32, cbrt_f32, floor_f32, linear_to_srgb_f32, sin_cos_f32, sqrt_f32,
15    srgb_to_linear_f32, PI, TAU,
16};
17pub use crate::svg::Transform2D;
18
19/// 规范化 `f32` 位模式(消除 `-0.0` 与 `NaN` 差异以保证快照哈希确定性)。
20#[inline(always)]
21pub(crate) fn canonical_f32_bits(v: f32) -> u32 {
22    if v == 0.0 {
23        0
24    } else if v.is_nan() {
25        0x7FC0_0000
26    } else {
27        v.to_bits()
28    }
29}
30
31#[inline(always)]
32pub(crate) fn mix_u8(h: &mut u32, b: u8) {
33    *h ^= b as u32;
34    *h = h.wrapping_mul(0x0100_0193);
35}
36
37#[inline(always)]
38pub(crate) fn mix_u32(h: &mut u32, v: u32) {
39    for b in v.to_le_bytes() {
40        mix_u8(h, b);
41    }
42}
43
44#[inline(always)]
45pub(crate) fn mix_f32(h: &mut u32, v: f32) {
46    mix_u32(h, canonical_f32_bits(v));
47}
48
49#[inline(always)]
50pub(crate) fn mix_transform(h: &mut u32, t: Transform2D) {
51    mix_f32(h, t.a);
52    mix_f32(h, t.b);
53    mix_f32(h, t.c);
54    mix_f32(h, t.d);
55    mix_f32(h, t.e);
56    mix_f32(h, t.f);
57}
58
59// ============================================================================
60// 1. 四角独立圆角 `CornerRadii`
61// ============================================================================
62
63/// 矩形四角独立圆角半径(逻辑像素,顺序:`[top-left, top-right, bottom-right, bottom-left]`)。
64#[repr(C)]
65#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash)]
66pub struct CornerRadii {
67    pub tl: u8,
68    pub tr: u8,
69    pub br: u8,
70    pub bl: u8,
71}
72
73impl CornerRadii {
74    /// 直角(四角全为 `0`)。
75    pub const ZERO: Self = Self::all(0);
76
77    /// 四角使用统一圆角半径 `r`。
78    #[inline(always)]
79    pub const fn all(r: u8) -> Self {
80        Self {
81            tl: r,
82            tr: r,
83            br: r,
84            bl: r,
85        }
86    }
87
88    /// 分别指定左上、右上、右下、左下四角圆角半径。
89    #[inline(always)]
90    pub const fn new(tl: u8, tr: u8, br: u8, bl: u8) -> Self {
91        Self { tl, tr, br, bl }
92    }
93
94    /// 仅顶部两角圆角(底部直角,常用于选项卡、抽屉顶栏、弹窗头)。
95    #[inline(always)]
96    pub const fn top(r: u8) -> Self {
97        Self::new(r, r, 0, 0)
98    }
99
100    /// 仅底部两角圆角(顶部直角)。
101    #[inline(always)]
102    pub const fn bottom(r: u8) -> Self {
103        Self::new(0, 0, r, r)
104    }
105
106    /// 仅左侧两角圆角(右侧直角,常用于分段按钮左端)。
107    #[inline(always)]
108    pub const fn left(r: u8) -> Self {
109        Self::new(r, 0, 0, r)
110    }
111
112    /// 仅右侧两角圆角(左侧直角)。
113    #[inline(always)]
114    pub const fn right(r: u8) -> Self {
115        Self::new(0, r, r, 0)
116    }
117
118    /// 四角是否全部相等。
119    #[inline(always)]
120    pub const fn is_uniform(self) -> bool {
121        self.tl == self.tr && self.tr == self.br && self.br == self.bl
122    }
123
124    /// 四角是否全为 `0`。
125    #[inline(always)]
126    pub const fn is_zero(self) -> bool {
127        self.tl == 0 && self.tr == 0 && self.br == 0 && self.bl == 0
128    }
129
130    /// 返回四角中的最大圆角半径。
131    #[inline(always)]
132    pub const fn max_radius(self) -> u8 {
133        let a = if self.tl > self.tr { self.tl } else { self.tr };
134        let b = if self.br > self.bl { self.br } else { self.bl };
135        if a > b { a } else { b }
136    }
137
138    /// 转为 `[tl, tr, br, bl]` 数组。
139    #[inline(always)]
140    pub const fn as_array(self) -> [u8; 4] {
141        [self.tl, self.tr, self.br, self.bl]
142    }
143}
144
145// ============================================================================
146// 2. 完整多色标渐变系统(Linear / Radial / Conic + ExtendMode + OKLab)
147// ============================================================================
148
149/// 渐变单个色标(归一化位置 `offset` 通常位于 `0.0..=1.0`)。
150#[derive(Copy, Clone, Debug)]
151pub struct ColorStop {
152    pub offset: f32,
153    pub color: Color,
154}
155
156impl ColorStop {
157    /// 构造一个渐变色标。
158    #[inline(always)]
159    pub const fn new(offset: f32, color: Color) -> Self {
160        Self { offset, color }
161    }
162}
163
164impl PartialEq for ColorStop {
165    #[inline]
166    fn eq(&self, other: &Self) -> bool {
167        canonical_f32_bits(self.offset) == canonical_f32_bits(other.offset)
168            && self.color == other.color
169    }
170}
171
172impl Eq for ColorStop {}
173
174/// 渐变越界延展模式(对应 W3C / Skia TileMode / Vello Extend)。
175#[repr(u8)]
176#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash)]
177pub enum ExtendMode {
178    /// 钳位至首尾色标(默认)。
179    #[default]
180    Pad = 0,
181    /// 周期重复(`fract(t)`)。
182    Repeat = 1,
183    /// 镜像往复反射(乒乓锯齿波)。
184    Reflect = 2,
185}
186
187/// 渐变色标插值色彩空间。
188#[repr(u8)]
189#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash)]
190pub enum GradientSpace {
191    /// 经典 sRGB 预乘 Alpha 插值(兼容传统 CSS / Canvas)。
192    #[default]
193    Srgb = 0,
194    /// 物理线性光强(Linear sRGB)插值(光晕与暗色过渡更自然)。
195    LinearRgb = 1,
196    /// 感知均匀 OKLab 色彩空间插值(消除红-绿 / 蓝-黄渐变中段发灰)。
197    Oklab = 2,
198}
199
200/// 通用填充画刷原语(零堆分配,渐变色标借用自 `ScratchArena` 或 `'static` 切片)。
201#[derive(Copy, Clone, Debug)]
202pub enum Paint<'a> {
203    /// 纯色填充。
204    Solid(Color),
205    /// 任意角度/任意起止点多色标线性渐变(`start`/`end` 为归一化局部坐标 `[0.0..=1.0]`)。
206    LinearGradient {
207        start: [f32; 2],
208        end: [f32; 2],
209        stops: &'a [ColorStop],
210        extend: ExtendMode,
211        space: GradientSpace,
212    },
213    /// 支持双圆焦点偏移的多色标径向渐变(所有坐标与半径均为归一化局部坐标,相对元素宽高的最小边或各自轴)。
214    RadialGradient {
215        center: [f32; 2],
216        radius: f32,
217        focal: [f32; 2],
218        focal_radius: f32,
219        stops: &'a [ColorStop],
220        extend: ExtendMode,
221        space: GradientSpace,
222    },
223    /// 多色标锥形/扫描渐变(`start_angle_deg` 以 12 点钟为 `0°` 顺时针增加,`sweep_deg` 默认 `360°`)。
224    ConicGradient {
225        center: [f32; 2],
226        start_angle_deg: f32,
227        sweep_deg: f32,
228        stops: &'a [ColorStop],
229        extend: ExtendMode,
230        space: GradientSpace,
231    },
232}
233
234impl<'a> PartialEq for Paint<'a> {
235    fn eq(&self, other: &Self) -> bool {
236        match (*self, *other) {
237            (Self::Solid(a), Self::Solid(b)) => a == b,
238            (
239                Self::LinearGradient {
240                    start: s1,
241                    end: e1,
242                    stops: st1,
243                    extend: ex1,
244                    space: sp1,
245                },
246                Self::LinearGradient {
247                    start: s2,
248                    end: e2,
249                    stops: st2,
250                    extend: ex2,
251                    space: sp2,
252                },
253            ) => {
254                canonical_f32_bits(s1[0]) == canonical_f32_bits(s2[0])
255                    && canonical_f32_bits(s1[1]) == canonical_f32_bits(s2[1])
256                    && canonical_f32_bits(e1[0]) == canonical_f32_bits(e2[0])
257                    && canonical_f32_bits(e1[1]) == canonical_f32_bits(e2[1])
258                    && ex1 == ex2
259                    && sp1 == sp2
260                    && st1 == st2
261            }
262            (
263                Self::RadialGradient {
264                    center: c1,
265                    radius: r1,
266                    focal: f1,
267                    focal_radius: fr1,
268                    stops: st1,
269                    extend: ex1,
270                    space: sp1,
271                },
272                Self::RadialGradient {
273                    center: c2,
274                    radius: r2,
275                    focal: f2,
276                    focal_radius: fr2,
277                    stops: st2,
278                    extend: ex2,
279                    space: sp2,
280                },
281            ) => {
282                canonical_f32_bits(c1[0]) == canonical_f32_bits(c2[0])
283                    && canonical_f32_bits(c1[1]) == canonical_f32_bits(c2[1])
284                    && canonical_f32_bits(r1) == canonical_f32_bits(r2)
285                    && canonical_f32_bits(f1[0]) == canonical_f32_bits(f2[0])
286                    && canonical_f32_bits(f1[1]) == canonical_f32_bits(f2[1])
287                    && canonical_f32_bits(fr1) == canonical_f32_bits(fr2)
288                    && ex1 == ex2
289                    && sp1 == sp2
290                    && st1 == st2
291            }
292            (
293                Self::ConicGradient {
294                    center: c1,
295                    start_angle_deg: a1,
296                    sweep_deg: sw1,
297                    stops: st1,
298                    extend: ex1,
299                    space: sp1,
300                },
301                Self::ConicGradient {
302                    center: c2,
303                    start_angle_deg: a2,
304                    sweep_deg: sw2,
305                    stops: st2,
306                    extend: ex2,
307                    space: sp2,
308                },
309            ) => {
310                canonical_f32_bits(c1[0]) == canonical_f32_bits(c2[0])
311                    && canonical_f32_bits(c1[1]) == canonical_f32_bits(c2[1])
312                    && canonical_f32_bits(a1) == canonical_f32_bits(a2)
313                    && canonical_f32_bits(sw1) == canonical_f32_bits(sw2)
314                    && ex1 == ex2
315                    && sp1 == sp2
316                    && st1 == st2
317            }
318            _ => false,
319        }
320    }
321}
322
323impl<'a> Eq for Paint<'a> {}
324
325impl<'a> Paint<'a> {
326    /// 按 CSS 角度规范构造多色标线性渐变(`0°` 向上、`90°` 向右、`180°` 向下,`135°` 左上至右下)。
327    #[inline]
328    pub fn linear_angle(angle_deg: f32, stops: &'a [ColorStop]) -> Self {
329        let rad = angle_deg * (PI / 180.0);
330        let (sin_a, cos_a) = sin_cos_f32(rad);
331        // CSS 0deg = 向上 (0, -1), 90deg = 向右 (1, 0)
332        let dx = sin_a;
333        let dy = -cos_a;
334        let half_len = 0.5 * (abs_f32(dx) + abs_f32(dy));
335        let hx = dx * half_len;
336        let hy = dy * half_len;
337        Self::LinearGradient {
338            start: [0.5 - hx, 0.5 - hy],
339            end: [0.5 + hx, 0.5 + hy],
340            stops,
341            extend: ExtendMode::Pad,
342            space: GradientSpace::Srgb,
343        }
344    }
345
346    /// 构造居中径向渐变(默认中心 `[0.5, 0.5]`、半径 `0.5`)。
347    #[inline]
348    pub const fn radial(stops: &'a [ColorStop]) -> Self {
349        Self::RadialGradient {
350            center: [0.5, 0.5],
351            radius: 0.5,
352            focal: [0.5, 0.5],
353            focal_radius: 0.0,
354            stops,
355            extend: ExtendMode::Pad,
356            space: GradientSpace::Srgb,
357        }
358    }
359
360    /// 构造带焦点的双圆径向渐变。
361    #[inline]
362    pub const fn radial_focal(
363        center: [f32; 2],
364        radius: f32,
365        focal: [f32; 2],
366        focal_radius: f32,
367        stops: &'a [ColorStop],
368    ) -> Self {
369        Self::RadialGradient {
370            center,
371            radius,
372            focal,
373            focal_radius,
374            stops,
375            extend: ExtendMode::Pad,
376            space: GradientSpace::Srgb,
377        }
378    }
379
380    /// 构造居中锥形/扫描渐变(`start_angle_deg` 以 12 点钟为 `0°` 顺时针)。
381    #[inline]
382    pub const fn conic(start_angle_deg: f32, stops: &'a [ColorStop]) -> Self {
383        Self::ConicGradient {
384            center: [0.5, 0.5],
385            start_angle_deg,
386            sweep_deg: 360.0,
387            stops,
388            extend: ExtendMode::Pad,
389            space: GradientSpace::Srgb,
390        }
391    }
392
393    /// 设置渐变的延展模式(`Pad` / `Repeat` / `Reflect`)。
394    #[inline]
395    pub const fn with_extend(mut self, mode: ExtendMode) -> Self {
396        match &mut self {
397            Self::LinearGradient { extend, .. }
398            | Self::RadialGradient { extend, .. }
399            | Self::ConicGradient { extend, .. } => *extend = mode,
400            Self::Solid(_) => {}
401        }
402        self
403    }
404
405    /// 设置渐变的色彩插值空间(`Srgb` / `LinearRgb` / `Oklab`)。
406    #[inline]
407    pub const fn with_space(mut self, color_space: GradientSpace) -> Self {
408        match &mut self {
409            Self::LinearGradient { space, .. }
410            | Self::RadialGradient { space, .. }
411            | Self::ConicGradient { space, .. } => *space = color_space,
412            Self::Solid(_) => {}
413        }
414        self
415    }
416
417    /// 判断该画刷是否全范围完全透明(可安全跳过填充绘制)。
418    #[inline]
419    pub fn is_fully_transparent(&self) -> bool {
420        match *self {
421            Self::Solid(c) => c.a() == 0,
422            Self::LinearGradient { stops, .. }
423            | Self::RadialGradient { stops, .. }
424            | Self::ConicGradient { stops, .. } => {
425                stops.is_empty() || stops.iter().all(|s| s.color.a() == 0)
426            }
427        }
428    }
429
430    /// 判断该画刷是否在所有采样点都 100% 不透明。
431    #[inline]
432    pub fn is_fully_opaque(&self) -> bool {
433        match *self {
434            Self::Solid(c) => c.a() == 255,
435            Self::LinearGradient { stops, .. }
436            | Self::RadialGradient { stops, .. }
437            | Self::ConicGradient { stops, .. } => {
438                !stops.is_empty() && stops.iter().all(|s| s.color.a() == 255)
439            }
440        }
441    }
442
443    /// 将当前画刷全部字段混入 FNV-1a 哈希(供 `DrawOpSnapshot` 与 GPU Ramp 缓存使用)。
444    pub fn mix_hash(&self, h: &mut u32) {
445        match *self {
446            Self::Solid(c) => {
447                mix_u8(h, 1);
448                mix_u32(h, c.0);
449            }
450            Self::LinearGradient {
451                start,
452                end,
453                stops,
454                extend,
455                space,
456            } => {
457                mix_u8(h, 2);
458                mix_f32(h, start[0]);
459                mix_f32(h, start[1]);
460                mix_f32(h, end[0]);
461                mix_f32(h, end[1]);
462                mix_u8(h, extend as u8);
463                mix_u8(h, space as u8);
464                mix_stops_hash(h, stops);
465            }
466            Self::RadialGradient {
467                center,
468                radius,
469                focal,
470                focal_radius,
471                stops,
472                extend,
473                space,
474            } => {
475                mix_u8(h, 3);
476                mix_f32(h, center[0]);
477                mix_f32(h, center[1]);
478                mix_f32(h, radius);
479                mix_f32(h, focal[0]);
480                mix_f32(h, focal[1]);
481                mix_f32(h, focal_radius);
482                mix_u8(h, extend as u8);
483                mix_u8(h, space as u8);
484                mix_stops_hash(h, stops);
485            }
486            Self::ConicGradient {
487                center,
488                start_angle_deg,
489                sweep_deg,
490                stops,
491                extend,
492                space,
493            } => {
494                mix_u8(h, 4);
495                mix_f32(h, center[0]);
496                mix_f32(h, center[1]);
497                mix_f32(h, start_angle_deg);
498                mix_f32(h, sweep_deg);
499                mix_u8(h, extend as u8);
500                mix_u8(h, space as u8);
501                mix_stops_hash(h, stops);
502            }
503        }
504    }
505
506    /// 评估归一化局部坐标 `(u, v) ∈ [0, 1]²` 处的渐变位置参数 `t`(`None` 表示退化或双圆锥外无效区)。
507    #[inline]
508    pub fn eval_gradient_t(&self, u: f32, v: f32) -> Option<f32> {
509        match *self {
510            Self::Solid(_) => Some(0.0),
511            Self::LinearGradient {
512                start, end, extend, ..
513            } => {
514                let dx = end[0] - start[0];
515                let dy = end[1] - start[1];
516                let denom = dx * dx + dy * dy;
517                if denom < 1e-8 {
518                    return Some(0.0);
519                }
520                let t = ((u - start[0]) * dx + (v - start[1]) * dy) / denom;
521                Some(apply_extend(t, extend))
522            }
523            Self::RadialGradient {
524                center,
525                radius,
526                focal,
527                focal_radius,
528                extend,
529                ..
530            } => {
531                let r1 = radius.max(1e-5);
532                let r0 = focal_radius.max(0.0);
533                let cdx = center[0] - focal[0];
534                let cdy = center[1] - focal[1];
535                if abs_f32(cdx) < 1e-6 && abs_f32(cdy) < 1e-6 && r0 < 1e-6 {
536                    let dx = u - center[0];
537                    let dy = v - center[1];
538                    let t = sqrt_f32(dx * dx + dy * dy) / r1;
539                    return Some(apply_extend(t, extend));
540                }
541                // 双圆焦点径向渐变:求解 |p - (f + t*(c - f))|² = (r0 + t*(r1 - r0))²
542                let px = u - focal[0];
543                let py = v - focal[1];
544                let dr = r1 - r0;
545                let a = cdx * cdx + cdy * cdy - dr * dr;
546                let b = -2.0 * (px * cdx + py * cdy + r0 * dr);
547                let c_term = px * px + py * py - r0 * r0;
548                let t = if abs_f32(a) < 1e-6 {
549                    if abs_f32(b) < 1e-6 {
550                        return None;
551                    }
552                    -c_term / b
553                } else {
554                    let disc = b * b - 4.0 * a * c_term;
555                    if disc < 0.0 {
556                        return None;
557                    }
558                    let sd = sqrt_f32(disc);
559                    let t_hi = (-b + sd) / (2.0 * a);
560                    let t_lo = (-b - sd) / (2.0 * a);
561                    if r0 + t_hi * dr >= 0.0 {
562                        t_hi
563                    } else if r0 + t_lo * dr >= 0.0 {
564                        t_lo
565                    } else {
566                        return None;
567                    }
568                };
569                Some(apply_extend(t, extend))
570            }
571            Self::ConicGradient {
572                center,
573                start_angle_deg,
574                sweep_deg,
575                extend,
576                ..
577            } => {
578                let dx = u - center[0];
579                let dy = v - center[1];
580                // 12 点钟方向为 0 rad,顺时针增加到 TAU
581                let mut angle = atan2_f32(dx, -dy);
582                if angle < 0.0 {
583                    angle += TAU;
584                }
585                let start_rad_raw = start_angle_deg * (PI / 180.0);
586                let start_rad = start_rad_raw - floor_f32(start_rad_raw / TAU) * TAU;
587                let mut rel = angle - start_rad;
588                if rel < 0.0 {
589                    rel += TAU;
590                }
591                let sweep_rad = (abs_f32(sweep_deg).max(1e-3) * (PI / 180.0)).min(TAU);
592                let t = rel / sweep_rad;
593                Some(apply_extend(t, extend))
594            }
595        }
596    }
597}
598
599#[inline]
600fn mix_stops_hash(h: &mut u32, stops: &[ColorStop]) {
601    mix_u32(h, stops.len() as u32);
602    for s in stops {
603        mix_f32(h, s.offset);
604        mix_u32(h, s.color.0);
605    }
606}
607
608/// 计算 64 位渐变色标与色彩空间指纹(供 GPU `GradientRampAtlas` 缓存复用)。
609pub fn gradient_ramp_hash(stops: &[ColorStop], space: GradientSpace, opacity: u8) -> u64 {
610    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
611    let mix = |h: &mut u64, v: u64| {
612        *h ^= v;
613        *h = h.wrapping_mul(0x0100_0000_01b3);
614    };
615    mix(&mut h, space as u64);
616    mix(&mut h, opacity as u64);
617    mix(&mut h, stops.len() as u64);
618    for s in stops {
619        mix(&mut h, canonical_f32_bits(s.offset) as u64);
620        mix(&mut h, s.color.0 as u64);
621    }
622    h
623}
624
625/// 按 [`ExtendMode`] 将任意实数 `t` 归约到 `[0.0, 1.0]`。
626#[inline(always)]
627pub fn apply_extend(t: f32, mode: ExtendMode) -> f32 {
628    match mode {
629        ExtendMode::Pad => t.clamp(0.0, 1.0),
630        ExtendMode::Repeat => {
631            let f = t - floor_f32(t);
632            f.clamp(0.0, 1.0)
633        }
634        ExtendMode::Reflect => {
635            let half = t * 0.5;
636            let f = (half - floor_f32(half)) * 2.0;
637            let r = if f <= 1.0 { f } else { 2.0 - f };
638            r.clamp(0.0, 1.0)
639        }
640    }
641}
642
643/// Linear sRGB 转感知均匀 OKLab(Björn Ottosson 官方标准系数)。
644#[inline]
645pub fn linear_srgb_to_oklab(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
646    let l = 0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b;
647    let m = 0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b;
648    let s = 0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b;
649    let l_ = cbrt_f32(l);
650    let m_ = cbrt_f32(m);
651    let s_ = cbrt_f32(s);
652    (
653        0.210_454_26 * l_ + 0.793_617_8 * m_ - 0.004_072_047 * s_,
654        1.977_998_5 * l_ - 2.428_592_2 * m_ + 0.450_593_7 * s_,
655        0.025_904_037 * l_ + 0.782_771_77 * m_ - 0.808_675_77 * s_,
656    )
657}
658
659/// OKLab 转 Linear sRGB(带 `[0.0, 1.0]` 色域安全钳位)。
660#[inline]
661pub fn oklab_to_linear_srgb(l: f32, a: f32, b: f32) -> (f32, f32, f32) {
662    let l_ = l + 0.396_337_78 * a + 0.215_803_76 * b;
663    let m_ = l - 0.105_561_346 * a - 0.063_854_17 * b;
664    let s_ = l - 0.089_484_18 * a - 1.291_485_5 * b;
665    let l3 = l_ * l_ * l_;
666    let m3 = m_ * m_ * m_;
667    let s3 = s_ * s_ * s_;
668    let r = 4.076_741_7 * l3 - 3.307_711_6 * m3 + 0.230_969_94 * s3;
669    let g = -1.268_438 * l3 + 2.609_757_4 * m3 - 0.341_319_38 * s3;
670    let bl = -0.004_196_086_3 * l3 - 0.703_418_6 * m3 + 1.707_614_7 * s3;
671    (r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), bl.clamp(0.0, 1.0))
672}
673
674/// 在指定 [`GradientSpace`] 下于两个颜色之间执行预乘 Alpha 友好插值,返回 sRGB 直通 `Color`。
675#[inline]
676pub fn interpolate_colors(c0: Color, c1: Color, t: f32, space: GradientSpace) -> Color {
677    let t = t.clamp(0.0, 1.0);
678    let inv = 1.0 - t;
679    let a0 = (c0.a() as f32) * (1.0 / 255.0);
680    let a1 = (c1.a() as f32) * (1.0 / 255.0);
681    let a = a0 * inv + a1 * t;
682    if a <= 1e-5 {
683        return Color::TRANSPARENT;
684    }
685    let (r0, g0, b0) = (
686        (c0.r() as f32) * (1.0 / 255.0),
687        (c0.g() as f32) * (1.0 / 255.0),
688        (c0.b() as f32) * (1.0 / 255.0),
689    );
690    let (r1, g1, b1) = (
691        (c1.r() as f32) * (1.0 / 255.0),
692        (c1.g() as f32) * (1.0 / 255.0),
693        (c1.b() as f32) * (1.0 / 255.0),
694    );
695
696    let (r, g, b) = match space {
697        GradientSpace::Srgb => {
698            // 预乘 Alpha 插值,避免透明色过渡出现发黑脏边
699            let pr = (r0 * a0) * inv + (r1 * a1) * t;
700            let pg = (g0 * a0) * inv + (g1 * a1) * t;
701            let pb = (b0 * a0) * inv + (b1 * a1) * t;
702            (pr / a, pg / a, pb / a)
703        }
704        GradientSpace::LinearRgb => {
705            let lr0 = srgb_to_linear_f32(r0);
706            let lg0 = srgb_to_linear_f32(g0);
707            let lb0 = srgb_to_linear_f32(b0);
708            let lr1 = srgb_to_linear_f32(r1);
709            let lg1 = srgb_to_linear_f32(g1);
710            let lb1 = srgb_to_linear_f32(b1);
711            let pr = (lr0 * a0) * inv + (lr1 * a1) * t;
712            let pg = (lg0 * a0) * inv + (lg1 * a1) * t;
713            let pb = (lb0 * a0) * inv + (lb1 * a1) * t;
714            (
715                linear_to_srgb_f32(pr / a),
716                linear_to_srgb_f32(pg / a),
717                linear_to_srgb_f32(pb / a),
718            )
719        }
720        GradientSpace::Oklab => {
721            let (l0, oa0, ob0) = linear_srgb_to_oklab(
722                srgb_to_linear_f32(r0),
723                srgb_to_linear_f32(g0),
724                srgb_to_linear_f32(b0),
725            );
726            let (l1, oa1, ob1) = linear_srgb_to_oklab(
727                srgb_to_linear_f32(r1),
728                srgb_to_linear_f32(g1),
729                srgb_to_linear_f32(b1),
730            );
731            // 预乘 Alpha 权重以在透明端保持色相稳定
732            let w0 = inv * a0;
733            let w1 = t * a1;
734            let wsum = w0 + w1;
735            let (l, oa, ob) = if wsum > 1e-6 {
736                (
737                    (l0 * w0 + l1 * w1) / wsum,
738                    (oa0 * w0 + oa1 * w1) / wsum,
739                    (ob0 * w0 + ob1 * w1) / wsum,
740                )
741            } else {
742                (l0 * inv + l1 * t, oa0 * inv + oa1 * t, ob0 * inv + ob1 * t)
743            };
744            let (lr, lg, lb) = oklab_to_linear_srgb(l, oa, ob);
745            (
746                linear_to_srgb_f32(lr),
747                linear_to_srgb_f32(lg),
748                linear_to_srgb_f32(lb),
749            )
750        }
751    };
752
753    Color::rgba(
754        (r.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
755        (g.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
756        (b.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
757        (a.clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
758    )
759}
760
761/// 在色标切片 `stops` 中按 `t ∈ [0.0, 1.0]` 采样插值颜色(支持任意顺序或重复 offset,零堆分配)。
762pub fn sample_gradient_stops(
763    stops: &[ColorStop],
764    t: f32,
765    space: GradientSpace,
766    opacity: u8,
767) -> Color {
768    if stops.is_empty() || opacity == 0 {
769        return Color::TRANSPARENT;
770    }
771    if stops.len() == 1 {
772        return stops[0].color.scale_alpha(opacity);
773    }
774    let t = t.clamp(0.0, 1.0);
775    // 支持升序常见路径,同时对非单调输入稳健回退
776    let first = stops[0];
777    let last = stops[stops.len() - 1];
778    if t <= first.offset {
779        return first.color.scale_alpha(opacity);
780    }
781    if t >= last.offset {
782        return last.color.scale_alpha(opacity);
783    }
784    for i in 0..(stops.len() - 1) {
785        let s0 = stops[i];
786        let s1 = stops[i + 1];
787        if t <= s1.offset {
788            let span = s1.offset - s0.offset;
789            let local_t = if span <= 1e-6 {
790                1.0
791            } else {
792                ((t - s0.offset) / span).clamp(0.0, 1.0)
793            };
794            return interpolate_colors(s0.color, s1.color, local_t, space).scale_alpha(opacity);
795        }
796    }
797    last.color.scale_alpha(opacity)
798}
799
800/// 烘焙 1D 渐变查找表(GPU `GradientRampAtlas` 与软件光栅器共享真源,输出 sRGB 直通 RGBA8 字节)。
801pub fn bake_gradient_lut<const N: usize>(
802    stops: &[ColorStop],
803    space: GradientSpace,
804    opacity: u8,
805    out: &mut [[u8; 4]; N],
806) {
807    let denom = (N.saturating_sub(1)).max(1) as f32;
808    for (i, slot) in out.iter_mut().enumerate() {
809        let t = (i as f32) / denom;
810        let c = sample_gradient_stops(stops, t, space, opacity);
811        *slot = [c.r(), c.g(), c.b(), c.a()];
812    }
813}
814
815// ============================================================================
816// 3. 完整 27 种 Porter-Duff 与 W3C 混合模式 `BlendMode`
817// ============================================================================
818
819/// 完整 27 种 Porter-Duff 合成模式与 W3C Compositing & Blending Level 1 混合模式。
820#[repr(u8)]
821#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash)]
822pub enum BlendMode {
823    // --- Porter-Duff 合成模式 (0..=11) ---
824    /// 标准源覆盖目标(默认)。
825    #[default]
826    SrcOver = 0,
827    /// 清空目标像素。
828    Clear = 1,
829    /// 仅保留源像素(替换)。
830    Src = 2,
831    /// 仅保留目标像素。
832    Dst = 3,
833    /// 源裁剪至目标 Alpha 内(遮罩保留源)。
834    SrcIn = 4,
835    /// 目标裁剪至源 Alpha 内(使用源作为 Alpha Mask 裁切下层)。
836    DstIn = 5,
837    /// 源仅绘制在目标透明区。
838    SrcOut = 6,
839    /// 目标仅保留在源透明区(镂空/擦除)。
840    DstOut = 7,
841    /// 源绘制在目标已有像素上并保留目标轮廓。
842    SrcAtop = 8,
843    /// 目标绘制在源轮廓内。
844    DstAtop = 9,
845    /// 源与目标异或镂空。
846    Xor = 10,
847    /// 线性光强相加(Additive / Lighter)。
848    Plus = 11,
849
850    // --- W3C 可分离混合模式 (12..=22) ---
851    /// 正片叠底。
852    Multiply = 12,
853    /// 滤色。
854    Screen = 13,
855    /// 叠加。
856    Overlay = 14,
857    /// 变暗。
858    Darken = 15,
859    /// 变亮。
860    Lighten = 16,
861    /// 颜色减淡。
862    ColorDodge = 17,
863    /// 颜色加深。
864    ColorBurn = 18,
865    /// 强光。
866    HardLight = 19,
867    /// 柔光。
868    SoftLight = 20,
869    /// 差值。
870    Difference = 21,
871    /// 排除。
872    Exclusion = 22,
873
874    // --- W3C 不可分离 HSL 混合模式 (23..=26) ---
875    /// 色相。
876    Hue = 23,
877    /// 饱和度。
878    Saturation = 24,
879    /// 颜色(保留目标明度,替换源色相与饱和度)。
880    Color = 25,
881    /// 明度(保留目标色相与饱和度,替换源明度)。
882    Luminosity = 26,
883}
884
885impl BlendMode {
886    /// 是否为默认 `SrcOver`。
887    #[inline(always)]
888    pub const fn is_normal(self) -> bool {
889        matches!(self, Self::SrcOver)
890    }
891
892    /// 是否需要读取目标画布像素以执行可编程合成(即非默认 `SrcOver`)。
893    #[inline(always)]
894    pub const fn requires_backdrop_read(self) -> bool {
895        !matches!(self, Self::SrcOver)
896    }
897}
898
899#[inline(always)]
900fn lum(c: [f32; 3]) -> f32 {
901    0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
902}
903
904#[inline]
905fn clip_color(mut c: [f32; 3]) -> [f32; 3] {
906    let l = lum(c);
907    let n = c[0].min(c[1]).min(c[2]);
908    let x = c[0].max(c[1]).max(c[2]);
909    if n < 0.0 && (l - n) > 1e-6 {
910        let f = l / (l - n);
911        c[0] = l + (c[0] - l) * f;
912        c[1] = l + (c[1] - l) * f;
913        c[2] = l + (c[2] - l) * f;
914    }
915    if x > 1.0 && (x - l) > 1e-6 {
916        let f = (1.0 - l) / (x - l);
917        c[0] = l + (c[0] - l) * f;
918        c[1] = l + (c[1] - l) * f;
919        c[2] = l + (c[2] - l) * f;
920    }
921    [c[0].clamp(0.0, 1.0), c[1].clamp(0.0, 1.0), c[2].clamp(0.0, 1.0)]
922}
923
924#[inline]
925fn set_lum(c: [f32; 3], l: f32) -> [f32; 3] {
926    let d = l - lum(c);
927    clip_color([c[0] + d, c[1] + d, c[2] + d])
928}
929
930#[inline(always)]
931fn sat(c: [f32; 3]) -> f32 {
932    c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
933}
934
935#[inline]
936fn set_sat(c: [f32; 3], s: f32) -> [f32; 3] {
937    let mut idx = [0usize, 1, 2];
938    if c[idx[0]] > c[idx[1]] {
939        idx.swap(0, 1);
940    }
941    if c[idx[1]] > c[idx[2]] {
942        idx.swap(1, 2);
943    }
944    if c[idx[0]] > c[idx[1]] {
945        idx.swap(0, 1);
946    }
947    let mut out = [0.0f32; 3];
948    let min_v = c[idx[0]];
949    let mid_v = c[idx[1]];
950    let max_v = c[idx[2]];
951    if max_v > min_v {
952        out[idx[1]] = ((mid_v - min_v) * s) / (max_v - min_v);
953        out[idx[2]] = s;
954    }
955    out
956}
957
958#[inline]
959fn blend_channel_separable(cb: f32, cs: f32, mode: BlendMode) -> f32 {
960    match mode {
961        BlendMode::Multiply => cb * cs,
962        BlendMode::Screen => cb + cs - cb * cs,
963        BlendMode::Overlay => {
964            if cb <= 0.5 {
965                2.0 * cb * cs
966            } else {
967                1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
968            }
969        }
970        BlendMode::Darken => cb.min(cs),
971        BlendMode::Lighten => cb.max(cs),
972        BlendMode::ColorDodge => {
973            if cb <= 0.0 {
974                0.0
975            } else if cs >= 1.0 {
976                1.0
977            } else {
978                (cb / (1.0 - cs)).min(1.0)
979            }
980        }
981        BlendMode::ColorBurn => {
982            if cb >= 1.0 {
983                1.0
984            } else if cs <= 0.0 {
985                0.0
986            } else {
987                1.0 - ((1.0 - cb) / cs).min(1.0)
988            }
989        }
990        BlendMode::HardLight => {
991            if cs <= 0.5 {
992                2.0 * cb * cs
993            } else {
994                1.0 - 2.0 * (1.0 - cb) * (1.0 - cs)
995            }
996        }
997        BlendMode::SoftLight => {
998            if cs <= 0.5 {
999                cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)
1000            } else {
1001                let d = if cb <= 0.25 {
1002                    ((16.0 * cb - 12.0) * cb + 4.0) * cb
1003                } else {
1004                    sqrt_f32(cb)
1005                };
1006                cb + (2.0 * cs - 1.0) * (d - cb)
1007            }
1008        }
1009        BlendMode::Difference => abs_f32(cb - cs),
1010        BlendMode::Exclusion => cb + cs - 2.0 * cb * cs,
1011        _ => cs,
1012    }
1013}
1014
1015/// 对预乘 Alpha 的源像素 `src_pm` 与目标像素 `dst_pm` 执行完整 W3C / Porter-Duff 合成,返回预乘 Alpha 结果。
1016#[inline]
1017pub fn blend_premul_f32(src_pm: [f32; 4], dst_pm: [f32; 4], mode: BlendMode) -> [f32; 4] {
1018    let sa = src_pm[3].clamp(0.0, 1.0);
1019    let da = dst_pm[3].clamp(0.0, 1.0);
1020    let inv_sa = 1.0 - sa;
1021    let inv_da = 1.0 - da;
1022
1023    match mode {
1024        BlendMode::SrcOver => [
1025            src_pm[0] + dst_pm[0] * inv_sa,
1026            src_pm[1] + dst_pm[1] * inv_sa,
1027            src_pm[2] + dst_pm[2] * inv_sa,
1028            sa + da * inv_sa,
1029        ],
1030        BlendMode::Clear => [0.0; 4],
1031        BlendMode::Src => src_pm,
1032        BlendMode::Dst => dst_pm,
1033        BlendMode::SrcIn => [
1034            src_pm[0] * da,
1035            src_pm[1] * da,
1036            src_pm[2] * da,
1037            sa * da,
1038        ],
1039        BlendMode::DstIn => [
1040            dst_pm[0] * sa,
1041            dst_pm[1] * sa,
1042            dst_pm[2] * sa,
1043            da * sa,
1044        ],
1045        BlendMode::SrcOut => [
1046            src_pm[0] * inv_da,
1047            src_pm[1] * inv_da,
1048            src_pm[2] * inv_da,
1049            sa * inv_da,
1050        ],
1051        BlendMode::DstOut => [
1052            dst_pm[0] * inv_sa,
1053            dst_pm[1] * inv_sa,
1054            dst_pm[2] * inv_sa,
1055            da * inv_sa,
1056        ],
1057        BlendMode::SrcAtop => [
1058            src_pm[0] * da + dst_pm[0] * inv_sa,
1059            src_pm[1] * da + dst_pm[1] * inv_sa,
1060            src_pm[2] * da + dst_pm[2] * inv_sa,
1061            da,
1062        ],
1063        BlendMode::DstAtop => [
1064            dst_pm[0] * sa + src_pm[0] * inv_da,
1065            dst_pm[1] * sa + src_pm[1] * inv_da,
1066            dst_pm[2] * sa + src_pm[2] * inv_da,
1067            sa,
1068        ],
1069        BlendMode::Xor => [
1070            src_pm[0] * inv_da + dst_pm[0] * inv_sa,
1071            src_pm[1] * inv_da + dst_pm[1] * inv_sa,
1072            src_pm[2] * inv_da + dst_pm[2] * inv_sa,
1073            sa * inv_da + da * inv_sa,
1074        ],
1075        BlendMode::Plus => [
1076            (src_pm[0] + dst_pm[0]).min(1.0),
1077            (src_pm[1] + dst_pm[1]).min(1.0),
1078            (src_pm[2] + dst_pm[2]).min(1.0),
1079            (sa + da).min(1.0),
1080        ],
1081        _ => {
1082            // W3C Compositing Level 1:
1083            // co = αs*(1-αb)*Cs + αb*(1-αs)*Cb + αs*αb*B(Cb, Cs)
1084            let cs = if sa > 1e-6 {
1085                [
1086                    (src_pm[0] / sa).clamp(0.0, 1.0),
1087                    (src_pm[1] / sa).clamp(0.0, 1.0),
1088                    (src_pm[2] / sa).clamp(0.0, 1.0),
1089                ]
1090            } else {
1091                [0.0; 3]
1092            };
1093            let cb = if da > 1e-6 {
1094                [
1095                    (dst_pm[0] / da).clamp(0.0, 1.0),
1096                    (dst_pm[1] / da).clamp(0.0, 1.0),
1097                    (dst_pm[2] / da).clamp(0.0, 1.0),
1098                ]
1099            } else {
1100                [0.0; 3]
1101            };
1102            let blended = match mode {
1103                BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)),
1104                BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)),
1105                BlendMode::Color => set_lum(cs, lum(cb)),
1106                BlendMode::Luminosity => set_lum(cb, lum(cs)),
1107                _ => [
1108                    blend_channel_separable(cb[0], cs[0], mode),
1109                    blend_channel_separable(cb[1], cs[1], mode),
1110                    blend_channel_separable(cb[2], cs[2], mode),
1111                ],
1112            };
1113            let sada = sa * da;
1114            let ao = (sa + da * inv_sa).clamp(0.0, 1.0);
1115            [
1116                (src_pm[0] * inv_da + dst_pm[0] * inv_sa + sada * blended[0]).clamp(0.0, 1.0),
1117                (src_pm[1] * inv_da + dst_pm[1] * inv_sa + sada * blended[1]).clamp(0.0, 1.0),
1118                (src_pm[2] * inv_da + dst_pm[2] * inv_sa + sada * blended[2]).clamp(0.0, 1.0),
1119                ao,
1120            ]
1121        }
1122    }
1123}
1124
1125/// 将直通 sRGB `Color` 转为归一化预乘 `[f32; 4]`。
1126#[inline(always)]
1127pub fn color_to_premul_f32(c: Color) -> [f32; 4] {
1128    const INV: f32 = 1.0 / 255.0;
1129    let a = (c.a() as f32) * INV;
1130    [
1131        (c.r() as f32) * INV * a,
1132        (c.g() as f32) * INV * a,
1133        (c.b() as f32) * INV * a,
1134        a,
1135    ]
1136}
1137
1138/// 将归一化预乘 `[f32; 4]` 还原为直通 sRGB `Color`。
1139#[inline(always)]
1140pub fn premul_f32_to_color(pm: [f32; 4]) -> Color {
1141    let a = pm[3].clamp(0.0, 1.0);
1142    if a <= 1e-5 {
1143        return Color::TRANSPARENT;
1144    }
1145    let inv_a = 1.0 / a;
1146    Color::rgba(
1147        ((pm[0] * inv_a).clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
1148        ((pm[1] * inv_a).clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
1149        ((pm[2] * inv_a).clamp(0.0, 1.0) * 255.0 + 0.5) as u8,
1150        (a * 255.0 + 0.5) as u8,
1151    )
1152}
1153
1154/// 以指定 [`BlendMode`] 合成两个直通 sRGB `Color`。
1155#[inline]
1156pub fn blend_colors(src: Color, dst: Color, mode: BlendMode) -> Color {
1157    premul_f32_to_color(blend_premul_f32(
1158        color_to_premul_f32(src),
1159        color_to_premul_f32(dst),
1160        mode,
1161    ))
1162}
1163
1164// ============================================================================
1165// 4. 滤镜原语(ColorMatrix / DropShadow / LayerFilter / BackdropFilter)
1166// ============================================================================
1167
1168/// 标准 4×5 RGBA 色彩变换矩阵(行主序,第 5 列为归一化偏移 `[-1.0..=1.0]`,对齐 Skia `SkColorMatrix` / SVG `<feColorMatrix>`)。
1169#[repr(C)]
1170#[derive(Copy, Clone, Debug)]
1171pub struct ColorMatrix(pub [f32; 20]);
1172
1173impl PartialEq for ColorMatrix {
1174    fn eq(&self, other: &Self) -> bool {
1175        for i in 0..20 {
1176            if canonical_f32_bits(self.0[i]) != canonical_f32_bits(other.0[i]) {
1177                return false;
1178            }
1179        }
1180        true
1181    }
1182}
1183
1184impl Eq for ColorMatrix {}
1185
1186impl Default for ColorMatrix {
1187    #[inline(always)]
1188    fn default() -> Self {
1189        Self::IDENTITY
1190    }
1191}
1192
1193impl ColorMatrix {
1194    /// 单位矩阵(无色彩变化)。
1195    pub const IDENTITY: Self = Self([
1196        1.0, 0.0, 0.0, 0.0, 0.0, // R
1197        0.0, 1.0, 0.0, 0.0, 0.0, // G
1198        0.0, 0.0, 1.0, 0.0, 0.0, // B
1199        0.0, 0.0, 0.0, 1.0, 0.0, // A
1200    ]);
1201
1202    /// 灰度滤镜(`amount ∈ [0.0, 1.0]`,`1.0` 为完全灰度)。
1203    #[inline]
1204    pub fn grayscale(amount: f32) -> Self {
1205        let t = amount.clamp(0.0, 1.0);
1206        let inv = 1.0 - t;
1207        let (lr, lg, lb) = (0.2126 * t, 0.7152 * t, 0.0722 * t);
1208        Self([
1209            lr + inv, lg, lb, 0.0, 0.0,
1210            lr, lg + inv, lb, 0.0, 0.0,
1211            lr, lg, lb + inv, 0.0, 0.0,
1212            0.0, 0.0, 0.0, 1.0, 0.0,
1213        ])
1214    }
1215
1216    /// 怀旧棕褐滤镜(`amount ∈ [0.0, 1.0]`)。
1217    #[inline]
1218    pub fn sepia(amount: f32) -> Self {
1219        let t = amount.clamp(0.0, 1.0);
1220        let inv = 1.0 - t;
1221        Self([
1222            inv + 0.393 * t, 0.769 * t, 0.189 * t, 0.0, 0.0,
1223            0.349 * t, inv + 0.686 * t, 0.168 * t, 0.0, 0.0,
1224            0.272 * t, 0.534 * t, inv + 0.131 * t, 0.0, 0.0,
1225            0.0, 0.0, 0.0, 1.0, 0.0,
1226        ])
1227    }
1228
1229    /// 饱和度调整(`amount = 0.0` 为灰度,`1.0` 保持不变,`> 1.0` 增强鲜艳度,毛玻璃常配 `1.4~1.8`)。
1230    #[inline]
1231    pub fn saturate(amount: f32) -> Self {
1232        let s = amount.max(0.0);
1233        let inv = 1.0 - s;
1234        let (lr, lg, lb) = (0.2126 * inv, 0.7152 * inv, 0.0722 * inv);
1235        Self([
1236            lr + s, lg, lb, 0.0, 0.0,
1237            lr, lg + s, lb, 0.0, 0.0,
1238            lr, lg, lb + s, 0.0, 0.0,
1239            0.0, 0.0, 0.0, 1.0, 0.0,
1240        ])
1241    }
1242
1243    /// 亮度调整(`1.0` 保持不变,`> 1.0` 提亮,`< 1.0` 压暗)。
1244    #[inline]
1245    pub fn brightness(amount: f32) -> Self {
1246        let b = amount.max(0.0);
1247        Self([
1248            b, 0.0, 0.0, 0.0, 0.0,
1249            0.0, b, 0.0, 0.0, 0.0,
1250            0.0, 0.0, b, 0.0, 0.0,
1251            0.0, 0.0, 0.0, 1.0, 0.0,
1252        ])
1253    }
1254
1255    /// 对比度调整(`1.0` 保持不变,`> 1.0` 提高对比度)。
1256    #[inline]
1257    pub fn contrast(amount: f32) -> Self {
1258        let c = amount.max(0.0);
1259        let bias = 0.5 * (1.0 - c);
1260        Self([
1261            c, 0.0, 0.0, 0.0, bias,
1262            0.0, c, 0.0, 0.0, bias,
1263            0.0, 0.0, c, 0.0, bias,
1264            0.0, 0.0, 0.0, 1.0, 0.0,
1265        ])
1266    }
1267
1268    /// 色相旋转(角度制 `deg`)。
1269    #[inline]
1270    pub fn hue_rotate(deg: f32) -> Self {
1271        let (s, c) = sin_cos_f32(deg * (PI / 180.0));
1272        Self([
1273            0.213 + c * 0.787 - s * 0.213, 0.715 - c * 0.715 - s * 0.715, 0.072 - c * 0.072 + s * 0.928, 0.0, 0.0,
1274            0.213 - c * 0.213 + s * 0.143, 0.715 + c * 0.285 + s * 0.140, 0.072 - c * 0.072 - s * 0.283, 0.0, 0.0,
1275            0.213 - c * 0.213 - s * 0.787, 0.715 - c * 0.715 + s * 0.715, 0.072 + c * 0.928 + s * 0.072, 0.0, 0.0,
1276            0.0, 0.0, 0.0, 1.0, 0.0,
1277        ])
1278    }
1279
1280    /// 反色滤镜(`amount ∈ [0.0, 1.0]`,`1.0` 为完全反相)。
1281    #[inline]
1282    pub fn invert(amount: f32) -> Self {
1283        let t = amount.clamp(0.0, 1.0);
1284        let scale = 1.0 - 2.0 * t;
1285        Self([
1286            scale, 0.0, 0.0, 0.0, t,
1287            0.0, scale, 0.0, 0.0, t,
1288            0.0, 0.0, scale, 0.0, t,
1289            0.0, 0.0, 0.0, 1.0, 0.0,
1290        ])
1291    }
1292
1293    /// 复合两个色彩矩阵:先应用 `self`,再应用 `next`(等价于 `next * self`)。
1294    #[inline]
1295    pub fn then(self, next: Self) -> Self {
1296        let a = &next.0;
1297        let b = &self.0;
1298        let mut out = [0.0f32; 20];
1299        for row in 0..4 {
1300            let r = row * 5;
1301            for col in 0..4 {
1302                out[r + col] = a[r] * b[col]
1303                    + a[r + 1] * b[5 + col]
1304                    + a[r + 2] * b[10 + col]
1305                    + a[r + 3] * b[15 + col];
1306            }
1307            out[r + 4] = a[r] * b[4]
1308                + a[r + 1] * b[9]
1309                + a[r + 2] * b[14]
1310                + a[r + 3] * b[19]
1311                + a[r + 4];
1312        }
1313        Self(out)
1314    }
1315
1316    /// 对直通 RGBA `[0.0, 1.0]` 应用色彩矩阵。
1317    #[inline]
1318    pub fn apply_straight(&self, rgba: [f32; 4]) -> [f32; 4] {
1319        let m = &self.0;
1320        let r = m[0] * rgba[0] + m[1] * rgba[1] + m[2] * rgba[2] + m[3] * rgba[3] + m[4];
1321        let g = m[5] * rgba[0] + m[6] * rgba[1] + m[7] * rgba[2] + m[8] * rgba[3] + m[9];
1322        let b = m[10] * rgba[0] + m[11] * rgba[1] + m[12] * rgba[2] + m[13] * rgba[3] + m[14];
1323        let a = m[15] * rgba[0] + m[16] * rgba[1] + m[17] * rgba[2] + m[18] * rgba[3] + m[19];
1324        [
1325            r.clamp(0.0, 1.0),
1326            g.clamp(0.0, 1.0),
1327            b.clamp(0.0, 1.0),
1328            a.clamp(0.0, 1.0),
1329        ]
1330    }
1331
1332    /// 对预乘 RGBA `[0.0, 1.0]` 应用色彩矩阵(解预乘 -> 变换 -> 再预乘)。
1333    #[inline]
1334    pub fn apply_premul(&self, pm: [f32; 4]) -> [f32; 4] {
1335        let a = pm[3].clamp(0.0, 1.0);
1336        let straight = if a > 1e-5 {
1337            [
1338                (pm[0] / a).clamp(0.0, 1.0),
1339                (pm[1] / a).clamp(0.0, 1.0),
1340                (pm[2] / a).clamp(0.0, 1.0),
1341                a,
1342            ]
1343        } else {
1344            [0.0; 4]
1345        };
1346        let out = self.apply_straight(straight);
1347        [out[0] * out[3], out[1] * out[3], out[2] * out[3], out[3]]
1348    }
1349
1350    /// 混入 FNV-1a 哈希。
1351    pub fn mix_hash(&self, h: &mut u32) {
1352        for &v in &self.0 {
1353            mix_f32(h, v);
1354        }
1355    }
1356}
1357
1358/// 任意子树/形状投影滤镜(CSS `filter: drop-shadow(...)`)。
1359#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
1360pub struct DropShadow {
1361    pub blur: u8,
1362    pub offset_x: i8,
1363    pub offset_y: i8,
1364    pub color: Color,
1365}
1366
1367impl DropShadow {
1368    #[inline(always)]
1369    pub const fn new(blur: u8, offset_x: i8, offset_y: i8, color: Color) -> Self {
1370        Self {
1371            blur,
1372            offset_x,
1373            offset_y,
1374            color,
1375        }
1376    }
1377
1378    #[inline(always)]
1379    pub const fn is_active(self) -> bool {
1380        self.color.a() > 0 && (self.blur > 0 || self.offset_x != 0 || self.offset_y != 0)
1381    }
1382}
1383
1384/// 作用在离屏图层内容上的后处理滤镜(`filter`)。
1385#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
1386pub struct LayerFilter {
1387    /// 高斯/Kawase 模糊半径(逻辑像素,`0` 表示关闭)。
1388    pub blur_radius: u8,
1389    /// 可选 4×5 色彩矩阵(灰度、饱和度、亮度、对比度、色相旋转等)。
1390    pub color_matrix: Option<ColorMatrix>,
1391    /// 可选任意形状投影(基于子树 Alpha 轮廓)。
1392    pub drop_shadow: Option<DropShadow>,
1393}
1394
1395impl LayerFilter {
1396    pub const NONE: Self = Self {
1397        blur_radius: 0,
1398        color_matrix: None,
1399        drop_shadow: None,
1400    };
1401
1402    #[inline(always)]
1403    pub const fn is_empty(&self) -> bool {
1404        self.blur_radius == 0 && self.color_matrix.is_none() && self.drop_shadow.is_none()
1405    }
1406
1407    /// 计算该滤镜导致绘制向外溢出的安全边界膨胀量 `(left, top, right, bottom)`(逻辑像素)。
1408    #[inline]
1409    pub const fn outset(&self) -> (i16, i16, i16, i16) {
1410        let mut l = (self.blur_radius as i16).saturating_mul(2);
1411        let mut t = l;
1412        let mut r = l;
1413        let mut b = l;
1414        if let Some(ds) = self.drop_shadow {
1415            if ds.color.a() > 0 {
1416                let db = (ds.blur as i16).saturating_mul(2);
1417                let sl = db.saturating_sub(ds.offset_x as i16);
1418                let sr = db.saturating_add(ds.offset_x as i16);
1419                let st = db.saturating_sub(ds.offset_y as i16);
1420                let sb = db.saturating_add(ds.offset_y as i16);
1421                if sl > l { l = sl; }
1422                if sr > r { r = sr; }
1423                if st > t { t = st; }
1424                if sb > b { b = sb; }
1425            }
1426        }
1427        (l, t, r, b)
1428    }
1429
1430    pub fn mix_hash(&self, h: &mut u32) {
1431        mix_u8(h, self.blur_radius);
1432        if let Some(cm) = &self.color_matrix {
1433            mix_u8(h, 1);
1434            cm.mix_hash(h);
1435        } else {
1436            mix_u8(h, 0);
1437        }
1438        if let Some(ds) = self.drop_shadow {
1439            mix_u8(h, 1);
1440            mix_u8(h, ds.blur);
1441            mix_u8(h, ds.offset_x as u8);
1442            mix_u8(h, ds.offset_y as u8);
1443            mix_u32(h, ds.color.0);
1444        } else {
1445            mix_u8(h, 0);
1446        }
1447    }
1448}
1449
1450/// 作用在元素下方已有背景上的实时背景滤镜(CSS `backdrop-filter`,用于毛玻璃 / Acrylic / Mica)。
1451#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
1452pub struct BackdropFilter {
1453    /// 背景模糊半径(逻辑像素,`0` 表示不模糊)。
1454    pub blur_radius: u8,
1455    /// 可选背景色彩矩阵(如毛玻璃 `saturate(1.6)` + `brightness(1.08)`)。
1456    pub color_matrix: Option<ColorMatrix>,
1457    /// 可选叠层磨砂着色(`#no_std` 嵌入式低内存档位亦自动降级为此着色)。
1458    pub tint: Color,
1459    /// 可选 Acrylic 细微噪点颗粒强度(`0..=255`,推荐 `8..=20`)。
1460    pub noise_amount: u8,
1461}
1462
1463impl BackdropFilter {
1464    pub const NONE: Self = Self {
1465        blur_radius: 0,
1466        color_matrix: None,
1467        tint: Color::TRANSPARENT,
1468        noise_amount: 0,
1469    };
1470
1471    /// 快捷创建毛玻璃背景模糊。
1472    #[inline(always)]
1473    pub const fn blur(radius: u8) -> Self {
1474        Self {
1475            blur_radius: radius,
1476            color_matrix: None,
1477            tint: Color::TRANSPARENT,
1478            noise_amount: 0,
1479        }
1480    }
1481
1482    /// 快捷创建现代 Acrylic / Vibrancy 毛玻璃(模糊 + 提饱和 + 细微颗粒 + 着色)。
1483    #[inline]
1484    pub fn acrylic(blur_radius: u8, tint: Color) -> Self {
1485        Self {
1486            blur_radius,
1487            color_matrix: Some(ColorMatrix::saturate(1.45)),
1488            tint,
1489            noise_amount: 12,
1490        }
1491    }
1492
1493    #[inline(always)]
1494    pub const fn is_empty(&self) -> bool {
1495        self.blur_radius == 0
1496            && self.color_matrix.is_none()
1497            && self.tint.a() == 0
1498            && self.noise_amount == 0
1499    }
1500
1501    pub fn mix_hash(&self, h: &mut u32) {
1502        mix_u8(h, self.blur_radius);
1503        mix_u32(h, self.tint.0);
1504        mix_u8(h, self.noise_amount);
1505        if let Some(cm) = &self.color_matrix {
1506            mix_u8(h, 1);
1507            cm.mix_hash(h);
1508        } else {
1509            mix_u8(h, 0);
1510        }
1511    }
1512}
1513
1514// ============================================================================
1515// 5. 冷路径节点特效包与高级 DrawOp 载荷(分配在 ScratchArena,常规节点 0 字节开销)
1516// ============================================================================
1517
1518/// 外部零拷贝 GPU 纹理槽位 ID(如海图渲染引擎、视频帧或 3D 视口注册至 `WgpuRenderer` 的共享纹理标识)。
1519#[repr(transparent)]
1520#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Hash)]
1521pub struct ExternalTextureId(pub u32);
1522
1523/// 外部零拷贝纹理绘制描述(分配于 `ScratchArena`,通过 8B 引用挂入 `DrawPayload::ExternalTexture`,零膨胀 `DrawOp`)。
1524#[derive(Copy, Clone, Debug)]
1525pub struct ExternalTextureSpec {
1526    /// 外部纹理注册表中的句柄 ID。
1527    pub id: ExternalTextureId,
1528    /// 归一化采样 UV 矩形 `[u0, v0, u1, v1]`(默认 `[0.0, 0.0, 1.0, 1.0]`)。
1529    pub uv_rect: [f32; 4],
1530    /// 四角独立圆角裁切(逻辑像素,复用 GPU SDF 抗锯齿圆角裁切)。
1531    pub radii: CornerRadii,
1532    /// 整体不透明度(`0..=255`)。
1533    pub opacity: u8,
1534    /// 外部纹理是否已为预乘 Alpha(`false` 时采样后自动执行预乘)。
1535    pub premultiplied: bool,
1536    /// 与下方画布的合成混合模式(默认 `BlendMode::SrcOver`,支持全部 27 种混合)。
1537    pub blend_mode: BlendMode,
1538    /// 外部画面内容版本号(同一纹理被外部引擎重绘时递增此值以精确触发 `DamageTracker` 局部刷新)。
1539    pub content_revision: u64,
1540    /// 软件光栅器或无 GPU 环境下显示的占位回退颜色。
1541    pub fallback_bg: Color,
1542}
1543
1544impl ExternalTextureSpec {
1545    /// 按外部纹理 ID 构造默认全幅(`[0,0,1,1]`)绘制描述。
1546    #[inline(always)]
1547    pub const fn new(id: ExternalTextureId) -> Self {
1548        Self {
1549            id,
1550            uv_rect: [0.0, 0.0, 1.0, 1.0],
1551            radii: CornerRadii::ZERO,
1552            opacity: 255,
1553            premultiplied: true,
1554            blend_mode: BlendMode::SrcOver,
1555            content_revision: 0,
1556            fallback_bg: Color::rgb(12, 18, 28),
1557        }
1558    }
1559
1560    #[inline(always)]
1561    pub const fn with_uv(mut self, uv_rect: [f32; 4]) -> Self {
1562        self.uv_rect = uv_rect;
1563        self
1564    }
1565
1566    #[inline(always)]
1567    pub const fn with_radii(mut self, radii: CornerRadii) -> Self {
1568        self.radii = radii;
1569        self
1570    }
1571
1572    #[inline(always)]
1573    pub const fn with_opacity(mut self, opacity: u8) -> Self {
1574        self.opacity = opacity;
1575        self
1576    }
1577
1578    #[inline(always)]
1579    pub const fn with_premultiplied(mut self, premultiplied: bool) -> Self {
1580        self.premultiplied = premultiplied;
1581        self
1582    }
1583
1584    #[inline(always)]
1585    pub const fn with_blend_mode(mut self, blend_mode: BlendMode) -> Self {
1586        self.blend_mode = blend_mode;
1587        self
1588    }
1589
1590    #[inline(always)]
1591    pub const fn with_revision(mut self, rev: u64) -> Self {
1592        self.content_revision = rev;
1593        self
1594    }
1595
1596    #[inline(always)]
1597    pub const fn with_fallback_bg(mut self, color: Color) -> Self {
1598        self.fallback_bg = color;
1599        self
1600    }
1601
1602    pub fn mix_hash(&self, h: &mut u32) {
1603        mix_u32(h, self.id.0);
1604        for v in self.uv_rect {
1605            mix_u32(h, canonical_f32_bits(v));
1606        }
1607        mix_u8(h, self.radii.tl);
1608        mix_u8(h, self.radii.tr);
1609        mix_u8(h, self.radii.br);
1610        mix_u8(h, self.radii.bl);
1611        mix_u8(h, self.opacity);
1612        mix_u8(h, if self.premultiplied { 1 } else { 0 });
1613        mix_u8(h, self.blend_mode as u8);
1614        mix_u32(h, self.content_revision as u32);
1615        mix_u32(h, (self.content_revision >> 32) as u32);
1616        mix_u32(h, self.fallback_bg.0);
1617    }
1618}
1619
1620impl PartialEq for ExternalTextureSpec {
1621    fn eq(&self, other: &Self) -> bool {
1622        self.id == other.id
1623            && canonical_f32_bits(self.uv_rect[0]) == canonical_f32_bits(other.uv_rect[0])
1624            && canonical_f32_bits(self.uv_rect[1]) == canonical_f32_bits(other.uv_rect[1])
1625            && canonical_f32_bits(self.uv_rect[2]) == canonical_f32_bits(other.uv_rect[2])
1626            && canonical_f32_bits(self.uv_rect[3]) == canonical_f32_bits(other.uv_rect[3])
1627            && self.radii == other.radii
1628            && self.opacity == other.opacity
1629            && self.premultiplied == other.premultiplied
1630            && self.blend_mode == other.blend_mode
1631            && self.content_revision == other.content_revision
1632            && self.fallback_bg == other.fallback_bg
1633    }
1634}
1635
1636impl Eq for ExternalTextureSpec {}
1637
1638/// 按需分配于 `ScratchArena` 的 `Div` 高级渲染特效包(多色标渐变、独立圆角、混合模式、滤镜、2D 变换、路径裁剪与外部零拷贝纹理)。
1639#[derive(Copy, Clone, Debug, Default)]
1640pub struct PaintEffects<'a> {
1641    pub bg_paint: Option<Paint<'a>>,
1642    pub corner_radii: Option<CornerRadii>,
1643    pub blend_mode: BlendMode,
1644    pub isolate: bool,
1645    pub filter: LayerFilter,
1646    pub backdrop_filter: BackdropFilter,
1647    pub transform: Option<Transform2D>,
1648    pub clip_path: Option<StrRef<'a>>,
1649    pub external_texture: Option<&'a ExternalTextureSpec>,
1650}
1651
1652impl<'a> PaintEffects<'a> {
1653    pub const EMPTY: Self = Self {
1654        bg_paint: None,
1655        corner_radii: None,
1656        blend_mode: BlendMode::SrcOver,
1657        isolate: false,
1658        filter: LayerFilter::NONE,
1659        backdrop_filter: BackdropFilter::NONE,
1660        transform: None,
1661        clip_path: None,
1662        external_texture: None,
1663    };
1664
1665    /// 判断是否未配置任何高级视觉特效。
1666    #[inline]
1667    pub fn is_empty(&self) -> bool {
1668        self.bg_paint.is_none()
1669            && self.corner_radii.is_none()
1670            && self.blend_mode.is_normal()
1671            && !self.isolate
1672            && self.filter.is_empty()
1673            && self.backdrop_filter.is_empty()
1674            && self.transform.is_none()
1675            && self.clip_path.is_none()
1676            && self.external_texture.is_none()
1677    }
1678
1679    /// 判断是否需要创建独立离屏合成图层(`PushLayer` / `PopLayer`)。
1680    #[inline]
1681    pub fn needs_layer(&self, has_children: bool, opacity: u8) -> bool {
1682        !self.filter.is_empty()
1683            || !self.backdrop_filter.is_empty()
1684            || self.clip_path.is_some()
1685            || (!self.blend_mode.is_normal() && has_children)
1686            || (self.isolate && opacity < 255)
1687            || (self.transform.is_some() && has_children)
1688    }
1689}
1690
1691/// 高级矩形绘制载荷(分配于 `ScratchArena`,通过 8B 引用挂入 `DrawPayload::StyledQuad`)。
1692#[derive(Copy, Clone, Debug)]
1693pub struct StyledQuad<'a> {
1694    pub paint: Paint<'a>,
1695    pub border_color: Color,
1696    pub border_width: u8,
1697    pub radii: CornerRadii,
1698    pub opacity: u8,
1699    pub blend_mode: BlendMode,
1700    pub transform: Option<Transform2D>,
1701}
1702
1703impl<'a> PartialEq for StyledQuad<'a> {
1704    fn eq(&self, other: &Self) -> bool {
1705        self.paint == other.paint
1706            && self.border_color == other.border_color
1707            && self.border_width == other.border_width
1708            && self.radii == other.radii
1709            && self.opacity == other.opacity
1710            && self.blend_mode == other.blend_mode
1711            && match (self.transform, other.transform) {
1712                (None, None) => true,
1713                (Some(a), Some(b)) => {
1714                    canonical_f32_bits(a.a) == canonical_f32_bits(b.a)
1715                        && canonical_f32_bits(a.b) == canonical_f32_bits(b.b)
1716                        && canonical_f32_bits(a.c) == canonical_f32_bits(b.c)
1717                        && canonical_f32_bits(a.d) == canonical_f32_bits(b.d)
1718                        && canonical_f32_bits(a.e) == canonical_f32_bits(b.e)
1719                        && canonical_f32_bits(a.f) == canonical_f32_bits(b.f)
1720                }
1721                _ => false,
1722            }
1723    }
1724}
1725
1726impl<'a> Eq for StyledQuad<'a> {}
1727
1728impl<'a> StyledQuad<'a> {
1729    pub fn mix_hash(&self, h: &mut u32) {
1730        self.paint.mix_hash(h);
1731        mix_u32(h, self.border_color.0);
1732        mix_u8(h, self.border_width);
1733        mix_u8(h, self.radii.tl);
1734        mix_u8(h, self.radii.tr);
1735        mix_u8(h, self.radii.br);
1736        mix_u8(h, self.radii.bl);
1737        mix_u8(h, self.opacity);
1738        mix_u8(h, self.blend_mode as u8);
1739        if let Some(t) = self.transform {
1740            mix_u8(h, 1);
1741            mix_transform(h, t);
1742        } else {
1743            mix_u8(h, 0);
1744        }
1745    }
1746}
1747
1748/// 隔离合成图层规格(分配于 `ScratchArena`,通过 8B 引用挂入 `DrawPayload::PushLayer`)。
1749#[derive(Copy, Clone, Debug)]
1750pub struct LayerSpec<'a> {
1751    /// 图层逻辑范围(用于离屏纹理尺寸估算与圆角/路径掩码坐标系)。
1752    pub bounds: Region,
1753    /// 图层四角独立圆角裁切(全 0 表示矩形裁切)。
1754    pub clip_radii: CornerRadii,
1755    /// 可选任意 SVG Path 裁剪/遮罩路径字符串(在图层局部 `[0..w, 0..h]` 坐标系内评估)。
1756    pub clip_path: Option<StrRef<'a>>,
1757    /// 组级隔离不透明度(`0..=255`)。
1758    pub opacity: u8,
1759    /// 图层合成混合模式(27 种 Porter-Duff / W3C 混合)。
1760    pub blend_mode: BlendMode,
1761    /// 图层后处理滤镜(模糊、色彩矩阵、任意形状投影)。
1762    pub filter: LayerFilter,
1763    /// 图层下方背景滤镜(实时毛玻璃、饱和度增强、颗粒感)。
1764    pub backdrop_filter: BackdropFilter,
1765    /// 可选图层 2D 仿射变换(作用于整个子树,以图层中心为原点)。
1766    pub transform: Option<Transform2D>,
1767}
1768
1769impl<'a> PartialEq for LayerSpec<'a> {
1770    fn eq(&self, other: &Self) -> bool {
1771        self.bounds == other.bounds
1772            && self.clip_radii == other.clip_radii
1773            && self.clip_path == other.clip_path
1774            && self.opacity == other.opacity
1775            && self.blend_mode == other.blend_mode
1776            && self.filter == other.filter
1777            && self.backdrop_filter == other.backdrop_filter
1778            && match (self.transform, other.transform) {
1779                (None, None) => true,
1780                (Some(a), Some(b)) => {
1781                    canonical_f32_bits(a.a) == canonical_f32_bits(b.a)
1782                        && canonical_f32_bits(a.b) == canonical_f32_bits(b.b)
1783                        && canonical_f32_bits(a.c) == canonical_f32_bits(b.c)
1784                        && canonical_f32_bits(a.d) == canonical_f32_bits(b.d)
1785                        && canonical_f32_bits(a.e) == canonical_f32_bits(b.e)
1786                        && canonical_f32_bits(a.f) == canonical_f32_bits(b.f)
1787                }
1788                _ => false,
1789            }
1790    }
1791}
1792
1793impl<'a> Eq for LayerSpec<'a> {}
1794
1795impl<'a> LayerSpec<'a> {
1796    /// 计算包含模糊核、阴影与仿射变换膨胀后的有效脏区矩形(防止局部重绘出现模糊接缝)。
1797    pub fn expanded_bounds(&self) -> Region {
1798        let mut reg = if let Some(t) = self.transform {
1799            let cx = self.bounds.x as f32 + self.bounds.w as f32 * 0.5;
1800            let cy = self.bounds.y as f32 + self.bounds.h as f32 * 0.5;
1801            t.centered_at(cx, cy).transform_region(self.bounds)
1802        } else {
1803            self.bounds
1804        };
1805        let (fl, ft, fr, fb) = self.filter.outset();
1806        let bd_pad = (self.backdrop_filter.blur_radius as i16).saturating_mul(2);
1807        let l = fl.max(bd_pad);
1808        let t = ft.max(bd_pad);
1809        let r = fr.max(bd_pad);
1810        let b = fb.max(bd_pad);
1811        if l > 0 || t > 0 || r > 0 || b > 0 {
1812            reg = Region::new(
1813                reg.x.saturating_sub(l),
1814                reg.y.saturating_sub(t),
1815                reg.w.saturating_add(l).saturating_add(r),
1816                reg.h.saturating_add(t).saturating_add(b),
1817            );
1818        }
1819        reg
1820    }
1821
1822    pub fn mix_hash(&self, h: &mut u32) {
1823        mix_u32(h, ((self.bounds.x as u16 as u32) << 16) | (self.bounds.y as u16 as u32));
1824        mix_u32(h, ((self.bounds.w as u16 as u32) << 16) | (self.bounds.h as u16 as u32));
1825        mix_u8(h, self.clip_radii.tl);
1826        mix_u8(h, self.clip_radii.tr);
1827        mix_u8(h, self.clip_radii.br);
1828        mix_u8(h, self.clip_radii.bl);
1829        mix_u8(h, self.opacity);
1830        mix_u8(h, self.blend_mode as u8);
1831        self.filter.mix_hash(h);
1832        self.backdrop_filter.mix_hash(h);
1833        if let Some(cp) = self.clip_path {
1834            mix_u8(h, 1);
1835            for &b in cp.as_str().as_bytes() {
1836                mix_u8(h, b);
1837            }
1838        } else {
1839            mix_u8(h, 0);
1840        }
1841        if let Some(t) = self.transform {
1842            mix_u8(h, 1);
1843            mix_transform(h, t);
1844        } else {
1845            mix_u8(h, 0);
1846        }
1847    }
1848}