Skip to main content

atmos/os_lib/web_engine/
draw_helpers.rs

1use crate::os_lib::css::parse_color;
2pub(crate) use super::css_filters::*;
3pub(crate) use super::bilinear::sample_bilinear_rgba;
4
5/// 計算量: **O(W + H)** — 枠線 4 辺の長さに比例(太さは定数倍)。
6/// 面積ではないので軽い。実測 0〜1 tick。
7pub(super) fn draw_individual_borders(
8    screen: &crate::kernel::draw::Screen,
9    mut x0: i32,
10    mut y0: i32,
11    mut x1: i32,
12    mut y1: i32,
13    el: &super::RenderElement,
14    is_hovered: bool,
15    is_focused: bool,
16    is_active: bool,
17) {
18    // Apply client insets if present (top, right, bottom, left)
19    if let Some((top, right, bottom, left)) = el.client_insets {
20        x0 += left;
21        y0 += top;
22        x1 -= right;
23        y1 -= bottom;
24        // Ensure coordinates remain valid
25        if x0 > x1 || y0 > y1 {
26            return;
27        }
28    }
29    if x0 >= x1 || y0 >= y1 {
30        return;
31    }
32
33    // 【2026-11-18 発見・修正】`opacity: 0` の要素は枠線も描かない。
34    // 背景と文字は `opacity` を掛けて描いていたが、枠線だけ掛けておらず、YouTube のミニガイドの
35    // `yt-interaction` の `.stroke`(`border:1px solid; opacity:0`)が各項目の上に黒い横線として出ていた。
36    // 【2026-11-18】`0 < opacity < 1` の枠線も、背景と同じく不透明度を掛けて背景と混ぜる(下の `scale_alpha`)。
37    if el.opacity == 0 {
38        return;
39    }
40
41    // 【2026-08-05 発見・修正】`border-color: transparent`(アルファ 0)は
42    // **何も描かない**。
43    //
44    // `draw_pixel` はアルファ 0x00 を互換上「不透明」として扱う妥協があるため
45    // (下位のほぼ全ての呼び出しがアルファを設定せず 0 のまま渡すので、
46    //  仕様どおり透明にすると画面が消える)、透明なボーダーが
47    // **不透明な黒**として描かれていた。
48    //
49    // 実測: `#apps` の一覧にある 20×20 の `<i>` 要素や、
50    // セクション見出しの周りに黒い枠(☐ / 角丸の輪郭)が出ていた。
51    // 実サイトには存在しない。
52    //
53    // 幅はレイアウトに残す(CSS では透明ボーダーも場所を占める)。
54    // 描画だけを止める。
55    let all_transparent = [
56        el.border_top_color,
57        el.border_right_color,
58        el.border_bottom_color,
59        el.border_left_color,
60        el.border_color,
61    ]
62    .iter()
63    .flatten()
64    .all(|c| (c >> 24) & 0xFF == 0);
65    let has_any_color = [
66        el.border_top_color,
67        el.border_right_color,
68        el.border_bottom_color,
69        el.border_left_color,
70        el.border_color,
71    ]
72    .iter()
73    .any(|c| c.is_some());
74    if has_any_color && all_transparent {
75        return;
76    }
77
78    // 【2026-11-18】上辺・下辺は左辺・右辺の太さの内側までにして、四隅を 2 度塗りしない。
79    // 以前は 4 辺が四隅で重なり、半透明(opacity < 1)の枠線の四隅だけ濃く(2 回混ぜて)見えた。
80    // 四隅は左辺・右辺が受け持つ(色が辺ごとに違うときの勝ち負けは従来どおり左右が上)。
81    let side_l = if el.border_left_style.is_none() { 0 } else { el.border_left_width.max(0) };
82    let side_r = if el.border_right_style.is_none() { 0 } else { el.border_right_width.max(0) };
83    let h_x0 = (x0 + side_l).min(x1 - 1);
84    let h_x1 = (x1 - side_r).max(h_x0 + 1);
85
86    // Top
87    if el.border_top_width > 0 && !el.border_top_style.is_none() {
88        let color = if is_active {
89            el.active_border_color
90                .or(el.border_top_color)
91                .or(el.border_color)
92                .unwrap_or(el.color)
93        } else if is_hovered {
94            el.hover_border_color
95                .or(el.border_top_color)
96                .or(el.border_color)
97                .unwrap_or(el.color)
98        } else if is_focused {
99            el.focus_border_color
100                .or(el.border_top_color)
101                .or(el.border_color)
102                .unwrap_or(el.color)
103        } else {
104            el.border_top_color.or(el.border_color).unwrap_or(el.color)
105        };
106        let t_w = el.border_top_width;
107        if el.border_top_style == super::BorderStyle::Dashed {
108            let dash = 6;
109            let gap = 4;
110            let mut x = x0;
111            while x < x1 {
112                let end = (x + dash).min(x1);
113                screen.boxfill(
114                    x as u32,
115                    y0 as u32,
116                    (end - 1).max(x) as u32,
117                    (y0 + t_w - 1).max(y0) as u32,
118                    crate::kernel::draw::Color(super::alpha_blend::scale_alpha(color, el.opacity)),
119                );
120                x += dash + gap;
121            }
122        } else {
123            screen.boxfill(
124                h_x0 as u32,
125                y0 as u32,
126                (h_x1 - 1).max(h_x0) as u32,
127                (y0 + t_w - 1).max(y0) as u32,
128                crate::kernel::draw::Color(super::alpha_blend::scale_alpha(color, el.opacity)),
129            );
130        }
131    }
132
133    // Bottom
134    if el.border_bottom_width > 0 && !el.border_bottom_style.is_none() {
135        let color = if is_active {
136            el.active_border_color
137                .or(el.border_bottom_color)
138                .or(el.border_color)
139                .unwrap_or(el.color)
140        } else if is_hovered {
141            el.hover_border_color
142                .or(el.border_bottom_color)
143                .or(el.border_color)
144                .unwrap_or(el.color)
145        } else if is_focused {
146            el.focus_border_color
147                .or(el.border_bottom_color)
148                .or(el.border_color)
149                .unwrap_or(el.color)
150        } else {
151            el.border_bottom_color
152                .or(el.border_color)
153                .unwrap_or(el.color)
154        };
155        let b_w = el.border_bottom_width;
156        if el.border_bottom_style == super::BorderStyle::Dashed {
157            let dash = 6;
158            let gap = 4;
159            let mut x = x0;
160            while x < x1 {
161                let end = (x + dash).min(x1);
162                screen.boxfill(
163                    x as u32,
164                    (y1 - b_w) as u32,
165                    (end - 1).max(x) as u32,
166                    (y1 - 1).max(y1 - b_w) as u32,
167                    crate::kernel::draw::Color(super::alpha_blend::scale_alpha(color, el.opacity)),
168                );
169                x += dash + gap;
170            }
171        } else {
172            screen.boxfill(
173                h_x0 as u32,
174                (y1 - b_w) as u32,
175                (h_x1 - 1).max(h_x0) as u32,
176                (y1 - 1).max(y1 - b_w) as u32,
177                crate::kernel::draw::Color(super::alpha_blend::scale_alpha(color, el.opacity)),
178            );
179        }
180    }
181
182    // Left
183    if el.border_left_width > 0 && !el.border_left_style.is_none() {
184        let color = if is_active {
185            el.active_border_color
186                .or(el.border_left_color)
187                .or(el.border_color)
188                .unwrap_or(el.color)
189        } else if is_hovered {
190            el.hover_border_color
191                .or(el.border_left_color)
192                .or(el.border_color)
193                .unwrap_or(el.color)
194        } else if is_focused {
195            el.focus_border_color
196                .or(el.border_left_color)
197                .or(el.border_color)
198                .unwrap_or(el.color)
199        } else {
200            el.border_left_color.or(el.border_color).unwrap_or(el.color)
201        };
202        let l_w = el.border_left_width;
203        if el.border_left_style == super::BorderStyle::Dashed {
204            let dash = 6;
205            let gap = 4;
206            let mut y = y0;
207            while y < y1 {
208                let end = (y + dash).min(y1);
209                screen.boxfill(
210                    x0 as u32,
211                    y as u32,
212                    (x0 + l_w - 1).max(x0) as u32,
213                    (end - 1).max(y) as u32,
214                    crate::kernel::draw::Color(super::alpha_blend::scale_alpha(color, el.opacity)),
215                );
216                y += dash + gap;
217            }
218        } else {
219            screen.boxfill(
220                x0 as u32,
221                y0 as u32,
222                (x0 + l_w - 1).max(x0) as u32,
223                (y1 - 1).max(y0) as u32,
224                crate::kernel::draw::Color(super::alpha_blend::scale_alpha(color, el.opacity)),
225            );
226        }
227    }
228
229    // Right
230    if el.border_right_width > 0 && !el.border_right_style.is_none() {
231        let color = if is_active {
232            el.active_border_color
233                .or(el.border_right_color)
234                .or(el.border_color)
235                .unwrap_or(el.color)
236        } else if is_hovered {
237            el.hover_border_color
238                .or(el.border_right_color)
239                .or(el.border_color)
240                .unwrap_or(el.color)
241        } else if is_focused {
242            el.focus_border_color
243                .or(el.border_right_color)
244                .or(el.border_color)
245                .unwrap_or(el.color)
246        } else {
247            el.border_right_color
248                .or(el.border_color)
249                .unwrap_or(el.color)
250        };
251        let r_w = el.border_right_width;
252        if el.border_right_style == super::BorderStyle::Dashed {
253            let dash = 6;
254            let gap = 4;
255            let mut y = y0;
256            while y < y1 {
257                let end = (y + dash).min(y1);
258                screen.boxfill(
259                    (x1 - r_w) as u32,
260                    y as u32,
261                    (x1 - 1).max(x1 - r_w) as u32,
262                    (end - 1).max(y) as u32,
263                    crate::kernel::draw::Color(super::alpha_blend::scale_alpha(color, el.opacity)),
264                );
265                y += dash + gap;
266            }
267        } else {
268            screen.boxfill(
269                (x1 - r_w) as u32,
270                y0 as u32,
271                (x1 - 1).max(x1 - r_w) as u32,
272                (y1 - 1).max(y0) as u32,
273                crate::kernel::draw::Color(super::alpha_blend::scale_alpha(color, el.opacity)),
274            );
275        }
276    }
277}
278
279pub fn draw_border(
280    screen: &crate::kernel::draw::Screen,
281    x0: i32,
282    y0: i32,
283    x1: i32,
284    y1: i32,
285    color_val: u32,
286) {
287    if x0 >= x1 || y0 >= y1 {
288        return;
289    }
290    let color = crate::kernel::draw::Color(color_val);
291    let ux0 = x0 as u32;
292    let uy0 = y0 as u32;
293    let ux1 = (x1 - 1) as u32;
294    let uy1 = (y1 - 1) as u32;
295
296    // 上辺
297    screen.boxfill(ux0, uy0, ux1, uy0, color);
298    if y1 - y0 > 1 {
299        // 下辺
300        screen.boxfill(ux0, uy1, ux1, uy1, color);
301    }
302    if y1 - y0 > 2 {
303        // 左辺(四隅重複を除外)
304        screen.boxfill(ux0, uy0 + 1, ux0, uy1 - 1, color);
305        if x1 - x0 > 1 {
306            // 右辺(四隅重複を除外)
307            screen.boxfill(ux1, uy0 + 1, ux1, uy1 - 1, color);
308        }
309    }
310}
311
312pub(super) fn draw_border_with_style(
313    screen: &crate::kernel::draw::Screen,
314    x0: i32,
315    y0: i32,
316    x1: i32,
317    y1: i32,
318    color_val: u32,
319    style: super::BorderStyle,
320) {
321    if style.is_none() {
322        return;
323    }
324    if style == super::BorderStyle::Dashed {
325        draw_dashed_border(screen, x0, y0, x1, y1, color_val);
326        return;
327    }
328    draw_border(screen, x0, y0, x1, y1, color_val);
329}
330
331fn draw_dashed_border(
332    screen: &crate::kernel::draw::Screen,
333    x0: i32,
334    y0: i32,
335    x1: i32,
336    y1: i32,
337    color_val: u32,
338) {
339    if x0 >= x1 || y0 >= y1 {
340        return;
341    }
342    let color = crate::kernel::draw::Color(color_val);
343    let dash = 6;
344    let gap = 4;
345    let mut x = x0;
346    while x < x1 {
347        let end = (x + dash).min(x1);
348        screen.boxfill(
349            x as u32,
350            y0 as u32,
351            (end - 1).max(x) as u32,
352            y0 as u32,
353            color,
354        );
355        if y1 - y0 > 1 {
356            screen.boxfill(
357                x as u32,
358                (y1 - 1) as u32,
359                (end - 1).max(x) as u32,
360                (y1 - 1) as u32,
361                color,
362            );
363        }
364        x += dash + gap;
365    }
366    let mut y = y0;
367    while y < y1 {
368        let end = (y + dash).min(y1);
369        screen.boxfill(
370            x0 as u32,
371            y as u32,
372            x0 as u32,
373            (end - 1).max(y) as u32,
374            color,
375        );
376        if x1 - x0 > 1 {
377            screen.boxfill(
378                (x1 - 1) as u32,
379                y as u32,
380                (x1 - 1) as u32,
381                (end - 1).max(y) as u32,
382                color,
383            );
384        }
385        y += dash + gap;
386    }
387}
388
389pub(super) fn extract_border_color(
390    styled: &crate::os_lib::css::StyledNode<'_>,
391    default_color: u32,
392) -> Option<u32> {
393    for key in [
394        "border-color",
395        "border-top-color",
396        "border-right-color",
397        "border-bottom-color",
398        "border-left-color",
399    ] {
400        if let Some(v) = styled.value(key) {
401            if let Some(c) = parse_color(&v) {
402                return Some(c);
403            }
404        }
405    }
406
407    if let Some(v) = styled.value("border") {
408        for token in v.split_whitespace().rev() {
409            if let Some(c) = parse_color(token) {
410                return Some(c);
411            }
412        }
413    }
414
415    Some(default_color)
416}
417
418pub(super) fn extract_border_style(styled: &crate::os_lib::css::StyledNode<'_>) -> super::BorderStyle {
419    if let Some(v) = styled.value("border-style") {
420        let style = v.trim();
421        if !style.is_empty() {
422            return super::BorderStyle::parse(style);
423        }
424    }
425
426    if let Some(v) = styled.value("border") {
427        for token in v.split_whitespace() {
428            let token_l = token.trim().to_lowercase();
429            if matches!(
430                token_l.as_str(),
431                "none" | "solid" | "dashed" | "dotted" | "double"
432            ) {
433                return super::BorderStyle::parse(&token_l);
434            }
435        }
436    }
437
438    super::BorderStyle::Solid
439}
440
441/// CSS `transform: rotate(Ndeg)` 向け — 回転した塗りつぶし矩形を描く。
442/// cx/cy は回転中心(スクリーン座標)、w/h は元の矩形サイズ、angle_deg は時計回り度数。
443pub fn draw_rotated_rect_filled(
444    screen: &crate::kernel::draw::Screen,
445    cx: i32,
446    cy: i32,
447    w: i32,
448    h: i32,
449    angle_deg: f32,
450    color: u32,
451) {
452    if w <= 0 || h <= 0 {
453        return;
454    }
455    let rad = angle_deg * core::f32::consts::PI / 180.0;
456    let cos_a = libm::cosf(rad);
457    let sin_a = libm::sinf(rad);
458    // 回転後バウンディングボックス
459    let hw = w as f32 / 2.0;
460    let hh = h as f32 / 2.0;
461    let bound_w = libm::ceilf(libm::fabsf(hw * cos_a) + libm::fabsf(hh * sin_a)) as i32;
462    let bound_h = libm::ceilf(libm::fabsf(hw * sin_a) + libm::fabsf(hh * cos_a)) as i32;
463    let draw_color = crate::kernel::draw::Color(color | 0xFF000000);
464    for oy in -bound_h..=bound_h {
465        for ox in -bound_w..=bound_w {
466            // 逆回転でソース座標を求める
467            let sx = ox as f32 * cos_a + oy as f32 * sin_a;
468            let sy = -ox as f32 * sin_a + oy as f32 * cos_a;
469            if sx >= -hw && sx <= hw && sy >= -hh && sy <= hh {
470                let px = cx + ox;
471                let py = cy + oy;
472                if px >= 0 && py >= 0 {
473                    screen.draw_pixel(px as u32, py as u32, draw_color);
474                }
475            }
476        }
477    }
478}
479
480/// CSS `transform: skewX(deg) / skewY(deg)` 向け — せん断変形した塗りつぶし矩形を描く。
481pub fn draw_skewed_rect_filled(
482    screen: &crate::kernel::draw::Screen,
483    cx: i32,
484    cy: i32,
485    w: i32,
486    h: i32,
487    skew_x_deg: f32,
488    skew_y_deg: f32,
489    color: u32,
490) {
491    if w <= 0 || h <= 0 {
492        return;
493    }
494    let rad_x = skew_x_deg * core::f32::consts::PI / 180.0;
495    let rad_y = skew_y_deg * core::f32::consts::PI / 180.0;
496    let tan_x = libm::tanf(rad_x);
497    let tan_y = libm::tanf(rad_y);
498
499    let hw = w as f32 / 2.0;
500    let hh = h as f32 / 2.0;
501
502    let det = 1.0 - tan_x * tan_y;
503    if det.abs() < 1e-6 {
504        return;
505    }
506
507    let bound_w = libm::ceilf(hw + hh * libm::fabsf(tan_x)) as i32;
508    let bound_h = libm::ceilf(hh + hw * libm::fabsf(tan_y)) as i32;
509    let draw_color = crate::kernel::draw::Color(color | 0xFF000000);
510
511    for oy in -bound_h..=bound_h {
512        for ox in -bound_w..=bound_w {
513            let sx = (ox as f32 - oy as f32 * tan_x) / det;
514            let sy = (oy as f32 - ox as f32 * tan_y) / det;
515            if sx >= -hw && sx <= hw && sy >= -hh && sy <= hh {
516                let px = cx + ox;
517                let py = cy + oy;
518                if px >= 0 && py >= 0 {
519                    screen.draw_pixel(px as u32, py as u32, draw_color);
520                }
521            }
522        }
523    }
524}
525
526pub use super::clip_path::*;
527
528pub fn draw_gradation(
529    screen: &crate::kernel::draw::Screen,
530    x0: i32,
531    y0: i32,
532    w: i32,
533    h: i32,
534    c1: u32,
535    c2: u32,
536) {
537    if w <= 0 || h <= 0 {
538        return;
539    }
540    let x_end = (x0 + w - 1).max(x0) as u32;
541    let r1 = ((c1 >> 16) & 0xFF) as i32;
542    let g1 = ((c1 >> 8) & 0xFF) as i32;
543    let b1 = (c1 & 0xFF) as i32;
544
545    let r2 = ((c2 >> 16) & 0xFF) as i32;
546    let g2 = ((c2 >> 8) & 0xFF) as i32;
547    let b2 = (c2 & 0xFF) as i32;
548
549    let denom = (h - 1).max(1);
550    for dy in 0..h {
551        let py = (y0 + dy) as u32;
552        let r = ((r1 * (denom - dy) + r2 * dy) / denom) as u32;
553        let g = ((g1 * (denom - dy) + g2 * dy) / denom) as u32;
554        let b = ((b1 * (denom - dy) + b2 * dy) / denom) as u32;
555        let c = 0xFF000000 | (r << 16) | (g << 8) | b;
556        screen.boxfill(
557            x0 as u32,
558            py,
559            x_end,
560            py,
561            crate::kernel::draw::Color(c),
562        );
563    }
564}
565
566/// 計算量: **O(W×H)**(LUT 化後)— W,H は塗る矩形のサイズ。
567///
568/// 内訳:
569/// - LUT 構築: **O(L × S)** — L = `lut_size(射影長)`(軸方向 1px に 1 段)、
570///   S = ストップ数。`sample_gradient_stops` を L 回呼ぶ
571/// - 塗り: 軸平行(0/180deg)なら **行ごとに `boxfill` 1 回** = O(H) 回の呼び出し。
572///   斜めなら 1 ピクセルずつ **O(W×H)**
573///
574/// 【2026-07-31 改善】以前は 1 ピクセルごとに `sample_gradient_stops`
575/// (ストップ配列の線形走査+4 チャンネル浮動小数補間)を呼んでおり
576/// **O(W×H×S)** だった。924×600 で 55 万回。実測で描画 1 フレームの
577/// 37%(112 tick)を占めていた → LUT 化で 62〜70 tick へ。
578/// 詳細は `spec/gradient_raster.md`。
579pub fn draw_linear_gradient(
580    screen: &crate::kernel::draw::Screen,
581    x0: i32,
582    y0: i32,
583    w: i32,
584    h: i32,
585    grad: &super::LinearGradient,
586) {
587    if w <= 0 || h <= 0 || grad.stops.is_empty() {
588        return;
589    }
590
591    let angle_rad = grad.angle_deg * core::f32::consts::PI / 180.0;
592    // 0deg = to top (0, -1), 90deg = to right (1, 0)
593    let dx = libm::sinf(angle_rad);
594    let dy = -libm::cosf(angle_rad);
595
596    // ボックスの4頂点 (相対座標)
597    let corners = [
598        (0.0, 0.0),
599        (w as f32, 0.0),
600        (0.0, h as f32),
601        (w as f32, h as f32),
602    ];
603
604    let mut min_proj = f32::MAX;
605    let mut max_proj = f32::MIN;
606    for &(cx, cy) in &corners {
607        let p = cx * dx + cy * dy;
608        if p < min_proj { min_proj = p; }
609        if p > max_proj { max_proj = p; }
610    }
611    
612    let length = max_proj - min_proj;
613    let x_end = (x0 + w - 1).max(x0) as u32;
614    if length <= 0.0 {
615        let c = grad.stops[0].color;
616        let y_end = (y0 + h - 1).max(y0) as u32;
617        screen.boxfill(x0 as u32, y0 as u32, x_end, y_end, crate::kernel::draw::Color(c));
618        return;
619    }
620
621    // 【2026-07-31 性能修正】仕様は `spec/gradient_raster.md`。
622    //
623    // 従来は 1 ピクセルごとに `sample_gradient_stops`(ストップ配列の線形走査+
624    // 4 チャンネルの浮動小数補間)を呼んでいた。924×600 なら 55 万回。
625    // 実測で描画 1 フレーム 300 tick のうち 112 tick(37%)がここだった。
626    //
627    // `t` から色への写像はピクセル位置に依存しないので、軸方向の長さぶんの
628    // LUT を先に作る。呼び出しは `length` 回で済む(G-1: 軸方向 1 ピクセルに
629    // 1 段を割り当てるので、軸平行なら従来と厳密に一致する)。
630    use super::gradient_lut::{classify_axis, lut_index, lut_size, Axis};
631    let lut_n = lut_size(length);
632    let mut lut: alloc::vec::Vec<u32> = alloc::vec::Vec::with_capacity(lut_n);
633    for i in 0..lut_n {
634        let t = if lut_n <= 1 {
635            0.0
636        } else {
637            i as f32 / (lut_n - 1) as f32
638        };
639        lut.push(sample_gradient_stops(&grad.stops, t));
640    }
641
642    // 軸平行なら 1 行(または行内の各列)が単色になる。
643    // 縦グラデーションは行ごとに `boxfill` 1 回で済む。
644    let axis = classify_axis(dx, dy);
645
646    if axis == Axis::Horizontal {
647        // 水平グラデーション: dy == 0 のため全行で列ごとの色は共通。
648        // 1 行分の色配列を事前計算し、各行へスキャンライン直列書き込みを行う。
649        let mut row_colors = alloc::vec::Vec::with_capacity(w as usize);
650        for x in 0..w {
651            let p_x = (x as f32) * dx;
652            let t = (p_x - min_proj) / length;
653            row_colors.push(lut[lut_index(t, lut_n)]);
654        }
655        for y in 0..h {
656            let py = y0 + y;
657            screen.draw_scanline_colors(x0, py, &row_colors);
658        }
659        return;
660    }
661
662    let mut row_colors = alloc::vec![0u32; w as usize];
663    for y in 0..h {
664        let py = (y0 + y) as u32;
665        let p_y = (y as f32) * dy;
666
667        if axis == Axis::Vertical {
668            // この行は単色。boxfill は不透明なら一括DMA/fill、半透明なら boxfill_alpha(スキャンライン直接合成)
669            // に自動分岐するため、1行の boxfill 呼び出しで高速に描画できる。
670            let t = (p_y - min_proj) / length;
671            let color = lut[lut_index(t, lut_n)];
672            screen.boxfill(
673                x0 as u32,
674                py,
675                x_end,
676                py,
677                crate::kernel::draw::Color(color),
678            );
679            continue;
680        }
681
682        // 斜めグラデーション: 行バッファを埋めてスキャンライン直列転送
683        for x in 0..w {
684            let p_x = (x as f32) * dx;
685            let p = p_x + p_y;
686            let t = (p - min_proj) / length;
687            row_colors[x as usize] = lut[lut_index(t, lut_n)];
688        }
689        screen.draw_scanline_colors(x0, py as i32, &row_colors);
690    }
691}
692
693/// `stops`(`position` 昇順ソート済み前提)から、位置 `t`(0.0-1.0)における補間色を得る。
694/// `draw_linear_gradient` の同ロジックを N ストップの `conic-gradient` でも再利用するために
695/// 独立関数として切り出した。
696/// 計算量: **O(S)** — S はストップ数(線形走査)。
697/// 4 チャンネルの浮動小数補間を伴うため定数倍も小さくない。
698/// **毎ピクセルで呼ばない**こと(呼び出し側で LUT 化する)。
699pub(crate) fn sample_gradient_stops(stops: &[super::GradientStop], t: f32) -> u32 {
700    if stops.is_empty() {
701        return 0;
702    }
703    if t <= stops[0].position {
704        return stops[0].color;
705    }
706    let last = stops.last().unwrap_or(&stops[0]);
707    if t >= last.position {
708        return last.color;
709    }
710    for i in 0..stops.len() - 1 {
711        let s1 = &stops[i];
712        let s2 = &stops[i + 1];
713        if t >= s1.position && t <= s2.position {
714            let range = s2.position - s1.position;
715            let local_t = if range > 0.0 { (t - s1.position) / range } else { 0.0 };
716            let a1 = ((s1.color >> 24) & 0xFF) as f32;
717            let r1 = ((s1.color >> 16) & 0xFF) as f32;
718            let g1 = ((s1.color >> 8) & 0xFF) as f32;
719            let b1 = (s1.color & 0xFF) as f32;
720            let a2 = ((s2.color >> 24) & 0xFF) as f32;
721            let r2 = ((s2.color >> 16) & 0xFF) as f32;
722            let g2 = ((s2.color >> 8) & 0xFF) as f32;
723            let b2 = (s2.color & 0xFF) as f32;
724            let a = ((1.0 - local_t) * a1 + local_t * a2) as u32;
725            let r = ((1.0 - local_t) * r1 + local_t * r2) as u32;
726            let g = ((1.0 - local_t) * g1 + local_t * g2) as u32;
727            let b = ((1.0 - local_t) * b1 + local_t * b2) as u32;
728            return (a << 24) | (r << 16) | (g << 8) | b;
729        }
730    }
731    last.color
732}
733
734/// `conic-gradient(c1, c2, ..., cN)` — N色ストップを角度方向へ(12時方向起点、時計回り)
735/// 補間して描画する。以前は `kernel::draw::Screen::draw_conic_gradient_rect` が2色固定
736/// だったため3色目以降が失われていた。ここでは `draw_linear_gradient` と同じ補間ロジック
737/// (`sample_gradient_stops`)を角度ベースの `t` に適用する。
738pub fn draw_conic_gradient(
739    screen: &crate::kernel::draw::Screen,
740    x0: i32,
741    y0: i32,
742    w: i32,
743    h: i32,
744    stops: &[super::GradientStop],
745) {
746    if w <= 0 || h <= 0 || stops.is_empty() {
747        return;
748    }
749    let cx = w as f32 / 2.0;
750    let cy = h as f32 / 2.0;
751    const PI: f32 = core::f32::consts::PI;
752    for dy in 0..h {
753        for dx in 0..w {
754            let px = dx as f32 - cx;
755            let py = dy as f32 - cy;
756            // atan2(px, -py): 真上(0,-1)方向を角度0とし、時計回りに増加させる
757            // (kernel::draw::draw_conic_gradient_rect と同じ角度基準)。
758            let mut angle = libm::atan2f(px, -py);
759            if angle < 0.0 {
760                angle += 2.0 * PI;
761            }
762            let t = angle / (2.0 * PI);
763            let color = sample_gradient_stops(stops, t);
764            screen.draw_pixel_alpha(
765                (x0 + dx) as u32,
766                (y0 + dy) as u32,
767                crate::kernel::draw::Color(color),
768                255,
769            );
770        }
771    }
772}
773
774pub fn draw_radial_gradient(
775    screen: &crate::kernel::draw::Screen,
776    x0: i32,
777    y0: i32,
778    w: i32,
779    h: i32,
780    grad: &super::RadialGradient,
781) {
782    if w <= 0 || h <= 0 || grad.stops.is_empty() {
783        return;
784    }
785
786    let cx = (w as f32) * grad.pos_x;
787    let cy = (h as f32) * grad.pos_y;
788    
789    // 最大半径 (四隅のうち最も遠い距離)
790    let max_rx = if grad.pos_x > 0.5 { cx } else { (w as f32) - cx };
791    let max_ry = if grad.pos_y > 0.5 { cy } else { (h as f32) - cy };
792    
793    let (r_x, r_y) = match grad.shape {
794        super::RadialShape::Circle => {
795            let r = libm::sqrtf(max_rx * max_rx + max_ry * max_ry);
796            (r, r)
797        },
798        super::RadialShape::Ellipse => {
799            (max_rx, max_ry)
800        }
801    };
802    
803    if r_x <= 0.0 || r_y <= 0.0 {
804        let c = grad.stops[0].color;
805        screen.boxfill(x0 as u32, y0 as u32, (x0 + w) as u32, (y0 + h) as u32, crate::kernel::draw::Color(c));
806        return;
807    }
808
809    for y in 0..h {
810        let py = y0 + y;
811        let dy = (y as f32) - cy;
812        for x in 0..w {
813            let px = x0 + x;
814            let dx = (x as f32) - cx;
815            
816            let t = libm::sqrtf((dx * dx) / (r_x * r_x) + (dy * dy) / (r_y * r_y));
817            let color = sample_gradient_stops(&grad.stops, t);
818            let alpha = ((color >> 24) & 0xFF) as u8;
819            screen.draw_pixel_alpha(px as u32, py as u32, crate::kernel::draw::Color(color), alpha);
820        }
821    }
822}
823
824/// `background-clip` の `"border-box"`/`"padding-box"`/`"content-box"` を
825/// 実際のピクセル差分(border 幅、または border+padding 幅)に変換する。
826/// border-box は無変換(0,0,0,0)。
827fn box_inset(el: &super::RenderElement, mode: &str) -> (i32, i32, i32, i32) {
828    match mode {
829        "content-box" => (
830            el.border_top_width + el.padding_top,
831            el.border_right_width + el.padding_right,
832            el.border_bottom_width + el.padding_bottom,
833            el.border_left_width + el.padding_left,
834        ),
835        "padding-box" => (
836            el.border_top_width,
837            el.border_right_width,
838            el.border_bottom_width,
839            el.border_left_width,
840        ),
841        _ => (0, 0, 0, 0),
842    }
843}
844
845/// `background-clip` に基づき、背景の描画を制限すべき矩形(border-box 座標系)を返す。
846/// `border-box`(既定)なら el の外形そのまま。
847pub(super) fn bg_clip_rect(
848    el: &super::RenderElement,
849    x0_rect: i32,
850    y0_rect: i32,
851    x1_rect: i32,
852    y1_rect: i32,
853) -> (u32, u32, u32, u32) {
854    let (top, right, bottom, left) = box_inset(el, &el.bg_clip);
855    (
856        (x0_rect + left).max(0) as u32,
857        (y0_rect + top).max(0) as u32,
858        (x1_rect - right).max(0) as u32,
859        (y1_rect - bottom).max(0) as u32,
860    )
861}
862
863/// `background-origin` に基づき、`draw_background_image()` へ渡す
864/// `(origin_shift_x, origin_shift_y, origin_w, origin_h)` を計算する。
865/// `origin_shift_*` は基準 box の左上が描画 box(`eff_w`/`eff_h` の左上)から
866/// どれだけ内側にあるか、`origin_w`/`origin_h` は基準 box 自体のサイズ。
867pub(super) fn bg_origin_shift(
868    el: &super::RenderElement,
869    eff_w: i32,
870    eff_h: i32,
871) -> (i32, i32, i32, i32) {
872    let (top, right, bottom, left) = box_inset(el, &el.bg_origin);
873    (
874        left,
875        top,
876        (eff_w - left - right).max(1),
877        (eff_h - top - bottom).max(1),
878    )
879}
880
881/// background-image を要素の box 内に描画する。background-size/repeat/position を反映する。
882/// `bg_size` が `Stretch`(未指定時の既定)なら従来どおり box 全面へ引き伸ばす。
883/// `layer_override` を指定すると、複数レイヤー(`background-image: url(a), url(b)`)の
884/// うちこのレイヤーだけの size/repeat-x/repeat-y/pos-x/pos-y を使う(以前は全レイヤーが
885/// `el` 側の単一の値を共有しており、レイヤーごとの `background-position`/`-size`/`-repeat`
886/// 指定が無視されるバグがあった)。`None` なら従来通り `el` の値をそのまま使う。
887/// 【2026-07-31計測】背景画像描画に費やした tick の累積(フレーム毎にリセット)。
888/// `paint` が 2.7 秒/フレームかかっている内訳を切り分けるため。
889pub(crate) static BG_IMG_TICKS: core::sync::atomic::AtomicUsize =
890    core::sync::atomic::AtomicUsize::new(0);
891
892/// 【2026-07-31計測】グラデーション描画に費やした tick の累積。
893pub(crate) static GRAD_TICKS: core::sync::atomic::AtomicUsize =
894    core::sync::atomic::AtomicUsize::new(0);
895/// 【2026-07-31計測】ボーダー描画に費やした tick の累積。
896pub(crate) static BORDER_TICKS: core::sync::atomic::AtomicUsize =
897    core::sync::atomic::AtomicUsize::new(0);
898/// 【2026-07-31計測】`<img>` の拡縮描画に費やした tick の累積。
899pub(crate) static IMG_TICKS: core::sync::atomic::AtomicUsize =
900    core::sync::atomic::AtomicUsize::new(0);
901/// 【2026-08-01計測】linear 以外の大面積描画
902/// (radial / conic / 2 色グラデーション / rotate / skew)の累積 tick。
903/// `GRAD_TICKS` は `draw_linear_gradient` しか見ていなかった。
904pub(crate) static OTHERFILL_TICKS: core::sync::atomic::AtomicUsize =
905    core::sync::atomic::AtomicUsize::new(0);
906
907/// 早期 return が複数あるため、Drop で確実に積む。
908struct TickTimer(usize, &'static core::sync::atomic::AtomicUsize);
909impl Drop for TickTimer {
910    fn drop(&mut self) {
911        self.1.fetch_add(
912            crate::kernel::timer::get_ticks().wrapping_sub(self.0),
913            core::sync::atomic::Ordering::Relaxed,
914        );
915    }
916}
917
918/// 早期 return が複数あるため、Drop で確実に積む。
919struct BgImgTimer(usize);
920impl Drop for BgImgTimer {
921    fn drop(&mut self) {
922        BG_IMG_TICKS.fetch_add(
923            crate::kernel::timer::get_ticks().wrapping_sub(self.0),
924            core::sync::atomic::Ordering::Relaxed,
925        );
926    }
927}
928
929/// 計算量: **O(Wd×Hd × R)** — Wd,Hd は描画先サイズ、R は
930/// `background-repeat` によるタイル数(`no-repeat` なら 1)。
931///
932/// 1 ピクセルごとに元画像をサンプリングして拡縮するため、
933/// **元画像のサイズには依存せず描画先の面積で決まる**。
934/// 拡縮結果はキャッシュしていないので**毎フレーム再計算**になる。
935///
936/// 実測: sugi-lab.net の 1 フレームで 33〜47 tick(paint の約 14%)。
937pub(super) fn draw_background_image(
938    screen: &crate::kernel::draw::Screen,
939    img: &super::DecodedImage,
940    el: &super::RenderElement,
941    x0_rect: i32,
942    y0_rect: i32,
943    eff_w: i32,
944    eff_h: i32,
945    clip_s: &Option<ClipShape>,
946    // `background-attachment: fixed` 用。垂直スクロール量をそのまま渡すと、
947    // ボックス自体はスクロールで動いても背景パターンのサンプリング座標だけが
948    // 打ち消されてビューポートに固定されて見える(このエンジンには横スクロール
949    // モデル自体が存在しないため水平方向は常に0)。`scroll`(既定)なら常に0。
950    attachment_shift_y: i32,
951    // `background-origin`(既定 padding-box)用。position/size のパーセンテージ計算の
952    // 基準となる box は、実際に描画・タイル敷き詰めを行う box(`eff_w`/`eff_h`。
953    // `background-clip` により外側で screen.push_clip 済み)とは別物にできる。
954    // `origin_shift_x/y` は基準box の左上が描画box の左上からどれだけ内側にあるか、
955    // `origin_w/h` は基準box 自体のサイズ。border-box(既定と同じ扱い)なら
956    // shift=(0,0)、origin_w/h=eff_w/eff_h を渡せばよい。
957    origin_shift_x: i32,
958    origin_shift_y: i32,
959    origin_w: i32,
960    origin_h: i32,
961    layer_override: Option<(
962        super::BgSizeMode,
963        super::BgRepeatMode,
964        super::BgRepeatMode,
965        f32,
966        f32,
967    )>,
968) {
969    use super::{BgSizeMode, BgSizeVal};
970    let _bg_timer = BgImgTimer(crate::kernel::timer::get_ticks());
971    // Apply client insets to background drawing area
972    let (mut x0_rect, mut y0_rect, mut eff_w, mut eff_h) = (x0_rect, y0_rect, eff_w, eff_h);
973    if let Some((top, right, bottom, left)) = el.client_insets {
974        x0_rect += left;
975        y0_rect += top;
976        eff_w -= left + right;
977        eff_h -= top + bottom;
978        if eff_w <= 0 || eff_h <= 0 {
979            return;
980        }
981    }
982    let (el_bg_size, el_bg_repeat_x, el_bg_repeat_y, el_bg_pos_x, el_bg_pos_y) =
983        layer_override.unwrap_or((el.bg_size, el.bg_repeat_x, el.bg_repeat_y, el.bg_pos_x, el.bg_pos_y));
984    // box_w/box_h: 実際にピクセルを描く(タイル敷き詰めの)範囲。background-clip の
985    // クリップ済み座標系ではなく、常に要素の border-box 全体を走査する
986    // (clip 自体は呼び出し側で screen.push_clip により別途適用済み)。
987    let box_w = eff_w.max(1) as u32;
988    let box_h = eff_h.max(1) as u32;
989    // origin_box_w/h: background-size の % 解決と background-position のオフセット計算に
990    // 使う基準 box(background-origin)。border-box なら box_w/h と同じ値になる。
991    let origin_box_w = origin_w.max(1) as u32;
992    let origin_box_h = origin_h.max(1) as u32;
993    if img.width == 0 || img.height == 0 {
994        return;
995    }
996
997    fn resolve_axis(v: BgSizeVal, box_dim: u32, img_dim: u32) -> Option<u32> {
998        match v {
999            BgSizeVal::Auto => None,
1000            BgSizeVal::Px(px) => Some(px.max(1) as u32),
1001            BgSizeVal::Percent(p) => Some(((box_dim as f32) * p).max(1.0) as u32),
1002        }
1003        .or(Some(img_dim))
1004    }
1005
1006    let (draw_w, draw_h): (u32, u32) = match el_bg_size {
1007        BgSizeMode::Stretch => (origin_box_w, origin_box_h),
1008        BgSizeMode::Cover => {
1009            let scale = (origin_box_w as f32 / img.width as f32)
1010                .max(origin_box_h as f32 / img.height as f32);
1011            (
1012                ((img.width as f32) * scale).max(1.0) as u32,
1013                ((img.height as f32) * scale).max(1.0) as u32,
1014            )
1015        }
1016        BgSizeMode::Contain => {
1017            let scale = (origin_box_w as f32 / img.width as f32)
1018                .min(origin_box_h as f32 / img.height as f32);
1019            (
1020                ((img.width as f32) * scale).max(1.0) as u32,
1021                ((img.height as f32) * scale).max(1.0) as u32,
1022            )
1023        }
1024        BgSizeMode::Explicit(wv, hv) => {
1025            // 片方だけ auto の場合はアスペクト比を保って他方から逆算する。
1026            match (wv, hv) {
1027                (BgSizeVal::Auto, BgSizeVal::Auto) => (img.width, img.height),
1028                (BgSizeVal::Auto, _) => {
1029                    let h = resolve_axis(hv, origin_box_h, img.height).unwrap_or(img.height);
1030                    let w = ((img.width as f32) * (h as f32 / img.height as f32)).max(1.0) as u32;
1031                    (w, h)
1032                }
1033                (_, BgSizeVal::Auto) => {
1034                    let w = resolve_axis(wv, origin_box_w, img.width).unwrap_or(img.width);
1035                    let h = ((img.height as f32) * (w as f32 / img.width as f32)).max(1.0) as u32;
1036                    (w, h)
1037                }
1038                _ => (
1039                    resolve_axis(wv, origin_box_w, img.width).unwrap_or(img.width),
1040                    resolve_axis(hv, origin_box_h, img.height).unwrap_or(img.height),
1041                ),
1042            }
1043        }
1044    };
1045
1046    // `background-repeat: round`(タイルをこの軸に整数個ちょうど収まるよう拡縮)/
1047    // `space`(タイル寸法は変えず、タイル間に等間隔の隙間を配分)を1軸ぶん解決する。
1048    // 戻り値: (実効タイル寸法, タイル開始位置の周期(=タイル+隙間), bg-positionを無視するか)。
1049    // round/space はタイルを軸全体に敷き詰める挙動が前提のため、position は無視する簡略実装。
1050    fn tile_layout(mode: super::BgRepeatMode, box_dim: u32, tile_dim: u32) -> (u32, u32, bool) {
1051        use super::BgRepeatMode;
1052        match mode {
1053            BgRepeatMode::Round => {
1054                let n =
1055                    (libm::roundf(box_dim as f32 / tile_dim.max(1) as f32) as u32).max(1);
1056                let eff = (box_dim / n).max(1);
1057                (eff, eff, true)
1058            }
1059            BgRepeatMode::Space => {
1060                let n = box_dim / tile_dim.max(1);
1061                if n <= 1 {
1062                    (tile_dim, tile_dim, false)
1063                } else {
1064                    let gap = box_dim.saturating_sub(n * tile_dim) / (n - 1);
1065                    (tile_dim, tile_dim + gap, true)
1066                }
1067            }
1068            _ => (tile_dim, tile_dim, false),
1069        }
1070    }
1071
1072    let (draw_w_eff, pitch_w, ignore_pos_x) = tile_layout(el_bg_repeat_x, box_w, draw_w);
1073    let (draw_h_eff, pitch_h, ignore_pos_y) = tile_layout(el_bg_repeat_y, box_h, draw_h);
1074    // off_x/off_y は background-origin の基準 box 内でのオフセット。
1075    // 実際に描くのは box_w/box_h(=描画/クリップ側の座標系)なので、
1076    // 基準 box の左上が描画 box の左上からどれだけ内側にあるか(origin_shift_x/y)を
1077    // 加算してから rel_x/rel_y の計算(下)で使う。
1078    let off_x = if ignore_pos_x {
1079        0
1080    } else {
1081        ((origin_box_w as i32 - draw_w as i32) as f32 * el_bg_pos_x) as i32
1082    };
1083    let off_y = if ignore_pos_y {
1084        0
1085    } else {
1086        ((origin_box_h as i32 - draw_h as i32) as f32 * el_bg_pos_y) as i32
1087    };
1088
1089    // 列方向のサンプリング座標を事前計算し、行ループ内での除算・剰余・条件分岐を完全排除する
1090    let col_src: alloc::vec::Vec<Option<u32>> = (0..box_w)
1091        .map(|col| {
1092            let rel_x = (col as i32 - origin_shift_x) - off_x;
1093            let sample_x = match el_bg_repeat_x {
1094                super::BgRepeatMode::NoRepeat => rel_x,
1095                super::BgRepeatMode::Space => {
1096                    let m = rel_x.rem_euclid(pitch_w as i32);
1097                    if m >= draw_w_eff as i32 {
1098                        return None;
1099                    }
1100                    m
1101                }
1102                _ => rel_x.rem_euclid(draw_w_eff as i32),
1103            };
1104            if sample_x < 0 || sample_x >= draw_w_eff as i32 {
1105                None
1106            } else {
1107                Some((sample_x as u32 * img.width) / draw_w_eff.max(1))
1108            }
1109        })
1110        .collect();
1111
1112    let has_blend = !el.background_blend_mode.is_empty() && el.background_blend_mode != "normal";
1113    let blend_dst = if has_blend {
1114        el.bg_color.map(|bg| (
1115            ((bg >> 16) & 0xFF) as u8,
1116            ((bg >> 8) & 0xFF) as u8,
1117            (bg & 0xFF) as u8,
1118        ))
1119    } else {
1120        None
1121    };
1122
1123    let mut row_buf = if clip_s.is_none() {
1124        alloc::vec![0u32; box_w as usize]
1125    } else {
1126        alloc::vec![]
1127    };
1128
1129    for row in 0..box_h {
1130        let rel_y = (row as i32 + attachment_shift_y - origin_shift_y) - off_y;
1131        let sample_y = match el_bg_repeat_y {
1132            super::BgRepeatMode::NoRepeat => rel_y,
1133            super::BgRepeatMode::Space => {
1134                let m = rel_y.rem_euclid(pitch_h as i32);
1135                if m >= draw_h_eff as i32 {
1136                    continue;
1137                }
1138                m
1139            }
1140            _ => rel_y.rem_euclid(draw_h_eff as i32),
1141        };
1142        if sample_y < 0 || sample_y >= draw_h_eff as i32 {
1143            continue;
1144        }
1145        let src_row = (sample_y as u32 * img.height) / draw_h_eff.max(1);
1146        let row_offset = (src_row * img.width) as usize;
1147        let py = (y0_rect as u32).wrapping_add(row);
1148
1149        if clip_s.is_none() {
1150            // clip-path なしの高速パス: 行バッファを生成してスキャンライン直列転送
1151            for col in 0..box_w {
1152                let src_col = match col_src[col as usize] {
1153                    Some(sc) => sc,
1154                    None => {
1155                        row_buf[col as usize] = 0;
1156                        continue;
1157                    }
1158                };
1159                let idx = (row_offset + src_col as usize) * 4;
1160                if idx + 4 <= img.rgba.len() {
1161                    let mut r = img.rgba[idx];
1162                    let mut g = img.rgba[idx + 1];
1163                    let mut b = img.rgba[idx + 2];
1164                    let raw_a = img.rgba[idx + 3];
1165                    if raw_a == 0 {
1166                        row_buf[col as usize] = 0;
1167                        continue;
1168                    }
1169                    let a = ((raw_a as u32 * el.opacity as u32) / 255) as u8;
1170                    if a == 0 {
1171                        row_buf[col as usize] = 0;
1172                        continue;
1173                    }
1174
1175                    if let Some(dst) = blend_dst {
1176                        let (br, bgc, bb) = blend_pixel(&el.background_blend_mode, (r, g, b), dst);
1177                        r = br;
1178                        g = bgc;
1179                        b = bb;
1180                    }
1181                    row_buf[col as usize] = ((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32);
1182                } else {
1183                    row_buf[col as usize] = 0;
1184                }
1185            }
1186            screen.draw_scanline_colors(x0_rect, py as i32, &row_buf);
1187        } else {
1188            // clip-path ありの汎用パス
1189            for col in 0..box_w {
1190                let src_col = match col_src[col as usize] {
1191                    Some(sc) => sc,
1192                    None => continue,
1193                };
1194                if let Some(ref cs) = clip_s {
1195                    if !clip_inside(cs, col as i32, row as i32) {
1196                        continue;
1197                    }
1198                }
1199
1200                let idx = (row_offset + src_col as usize) * 4;
1201                if idx + 4 <= img.rgba.len() {
1202                    let mut r = img.rgba[idx];
1203                    let mut g = img.rgba[idx + 1];
1204                    let mut b = img.rgba[idx + 2];
1205                    let raw_a = img.rgba[idx + 3];
1206                    if raw_a == 0 {
1207                        continue;
1208                    }
1209                    let a = ((raw_a as u32 * el.opacity as u32) / 255) as u8;
1210                    if a == 0 {
1211                        continue;
1212                    }
1213
1214                    if let Some(dst) = blend_dst {
1215                        let (br, bgc, bb) = blend_pixel(&el.background_blend_mode, (r, g, b), dst);
1216                        r = br;
1217                        g = bgc;
1218                        b = bb;
1219                    }
1220                    let color = crate::kernel::draw::Color(
1221                        0xFF000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32),
1222                    );
1223                    screen.draw_pixel_alpha((x0_rect as u32).wrapping_add(col), py, color, a);
1224                }
1225            }
1226        }
1227    }
1228}
1229
1230/// `text-decoration-line`(underline/line-through)の水平線を `style`
1231/// (solid/dotted/dashed/wavy/double、空文字またはその他は solid 扱い)と
1232/// `thickness`(`text-decoration-thickness`、px。最低1pxにクランプ)で描画する。
1233pub(super) fn draw_decoration_line(
1234    screen: &crate::kernel::draw::Screen,
1235    x0: u32,
1236    y: u32,
1237    x1: u32,
1238    style: &str,
1239    color: u32,
1240    thickness: u32,
1241) {
1242    if x1 <= x0 {
1243        return;
1244    }
1245    let t = thickness.max(1);
1246    let color_val = crate::kernel::draw::Color(color);
1247    match style {
1248        "dotted" => {
1249            let mut x = x0;
1250            while x < x1 {
1251                let seg_end = (x + 2).min(x1);
1252                screen.boxfill(x, y, (seg_end - 1).max(x), y + t - 1, color_val);
1253                x += 4;
1254            }
1255        }
1256        "dashed" => {
1257            let mut x = x0;
1258            while x < x1 {
1259                let seg_end = (x + 5).min(x1);
1260                screen.boxfill(x, y, (seg_end - 1).max(x), y + t - 1, color_val);
1261                x += 8;
1262            }
1263        }
1264        "wavy" => {
1265            // 振幅2px・周期6pxの単純な三角波(サイン波の近似)。thickness分だけ縦に太らせる。
1266            let amplitude = 2i32;
1267            let period = 6i32;
1268            for x in x0..x1 {
1269                let phase = (x as i32 - x0 as i32) % period;
1270                let dy = if phase < period / 2 { phase - amplitude / 2 } else { period - phase - amplitude / 2 };
1271                let py = (y as i32 + dy).max(0) as u32;
1272                screen.boxfill(x, py, x, py + t - 1, color_val);
1273            }
1274        }
1275        "double" => {
1276            let x_end = (x1 - 1).max(x0);
1277            screen.boxfill(x0, y, x_end, y + t - 1, color_val);
1278            let y2 = y + t + 2;
1279            screen.boxfill(x0, y2, x_end, y2 + t - 1, color_val);
1280        }
1281        _ => {
1282            let x_end = (x1 - 1).max(x0);
1283            screen.boxfill(x0, y, x_end, y + t - 1, color_val);
1284        }
1285    }
1286}
1287
1288/// outline を描画する。border-box の外側に `offset` だけ離して `width` px の枠線を引く。
1289/// レイアウトに影響しない装飾のため、border とは独立して呼ぶ。
1290pub(super) fn draw_outline(
1291    screen: &crate::kernel::draw::Screen,
1292    x0: i32,
1293    y0: i32,
1294    x1: i32,
1295    y1: i32,
1296    width: i32,
1297    offset: i32,
1298    color: u32,
1299    style: &str,
1300) {
1301    let ox0 = x0 - offset - width;
1302    let oy0 = y0 - offset - width;
1303    let ox1 = x1 + offset + width;
1304    let oy1 = y1 + offset + width;
1305    // dashed/dotted: 破線パターンの矩形を width 回重ねて太さを近似する
1306    // (dotted も既存の dashed 実装を流用する簡略実装、独立した点線パターンは非対応)。
1307    if matches!(style, "dashed" | "dotted") {
1308        for i in 0..width {
1309            draw_dashed_border(screen, ox0 + i, oy0 + i, ox1 - i, oy1 - i, color);
1310        }
1311        return;
1312    }
1313    for i in 0..width {
1314        draw_border(screen, ox0 + i, oy0 + i, ox1 - i, oy1 - i, color);
1315    }
1316}
1317
1318/// `img` の (src_row, src_col) を中心に半径 `radius`(source pixel 単位)のボックスブラーを
1319/// かけた色を返す。画像端はクランプせず範囲外を単純にスキップする(サンプル数で正規化)。
1320pub(crate) fn sample_box_blur(
1321    img: &super::DecodedImage,
1322    src_row: u32,
1323    src_col: u32,
1324    radius: i32,
1325) -> (u8, u8, u8) {
1326    let r = radius.clamp(1, 8);
1327    let (mut sr, mut sg, mut sb, mut n) = (0i64, 0i64, 0i64, 0i64);
1328    for dy in -r..=r {
1329        let ry = src_row as i32 + dy;
1330        if ry < 0 || ry as u32 >= img.height {
1331            continue;
1332        }
1333        for dx in -r..=r {
1334            let rx = src_col as i32 + dx;
1335            if rx < 0 || rx as u32 >= img.width {
1336                continue;
1337            }
1338            let idx = ((ry as u32 * img.width + rx as u32) as usize) * 4;
1339            if idx + 3 < img.rgba.len() {
1340                sr += img.rgba[idx] as i64;
1341                sg += img.rgba[idx + 1] as i64;
1342                sb += img.rgba[idx + 2] as i64;
1343                n += 1;
1344            }
1345        }
1346    }
1347    if n == 0 {
1348        return (0, 0, 0);
1349    }
1350    ((sr / n) as u8, (sg / n) as u8, (sb / n) as u8)
1351}
1352
1353/// 画面上の指定矩形領域をボックスブラーする(インプレースではなく一時バッファを使用)。
1354pub(crate) fn blur_screen_rect(
1355    screen: &crate::kernel::draw::Screen,
1356    x0: i32,
1357    y0: i32,
1358    x1: i32,
1359    y1: i32,
1360    radius: i32,
1361) {
1362    if radius <= 0 || x1 <= x0 || y1 <= y0 {
1363        return;
1364    }
1365    let r = radius.clamp(1, 8);
1366    let w = (x1 - x0) as usize;
1367    let h = (y1 - y0) as usize;
1368
1369    // 一時バッファに画面のピクセルを読み込む
1370    let mut buf = alloc::vec::Vec::with_capacity(w * h);
1371    for y in y0..y1 {
1372        for x in x0..x1 {
1373            buf.push(screen.read_pixel(x as u32, y as u32).0);
1374        }
1375    }
1376
1377    // 【2026-08-01 性能修正】仕様は `spec/backdrop_blur.md`。
1378    //
1379    // 以前はここで素朴な 2 次元ボックスブラー O(W×H×(2r+1)²) を回していた。
1380    // r は最大 8 なので 1 ピクセルあたり最大 289 サンプル。
1381    // sugi-lab.net のナビゲーションバー(924×44)で 1170 万回/フレームとなり、
1382    // **1 要素だけで 179〜478 tick** かかっていた(面積が 12 倍ある
1383    // 924×529 の要素より数倍重い、という形で実測に現れた)。
1384    //
1385    // 累積和による **O(W×H)**(半径に依存しない)実装へ置換。
1386    // 出力は素朴実装と**ビット単位で一致**する(B-1。単体試験で
1387    // 参照実装と総当たり比較して確認済み)。
1388    let blurred = super::blur_box::box_blur_rgb(&buf, w, h, r as usize);
1389
1390    for y in 0..h {
1391        let sy = y0 + y as i32;
1392        if sy < 0 || sy as u32 >= screen.height {
1393            continue;
1394        }
1395        for x in 0..w {
1396            let sx = x0 + x as i32;
1397            if sx < 0 || sx as u32 >= screen.width {
1398                continue;
1399            }
1400            screen.draw_pixel_alpha(
1401                sx as u32,
1402                sy as u32,
1403                crate::kernel::draw::Color(blurred[y * w + x]),
1404                255,
1405            );
1406        }
1407    }
1408}
1409
1410/// 画面の矩形の写し(`capture_screen_rect`)。
1411pub(crate) struct ScreenRect {
1412    x0: i32,
1413    y0: i32,
1414    w: usize,
1415    h: usize,
1416    px: alloc::vec::Vec<u32>,
1417}
1418
1419fn read_screen_rect(screen: &crate::kernel::draw::Screen, x0: i32, y0: i32, w: usize, h: usize) -> alloc::vec::Vec<u32> {
1420    let mut px = alloc::vec::Vec::with_capacity(w * h);
1421    for y in 0..h as i32 {
1422        for x in 0..w as i32 {
1423            px.push(screen.read_pixel((x0 + x) as u32, (y0 + y) as u32).0);
1424        }
1425    }
1426    px
1427}
1428
1429/// 要素を描く前の画面を写す(`filter: blur()` の合成に使う)。画面の外は切り落とす。
1430pub(crate) fn capture_screen_rect(
1431    screen: &crate::kernel::draw::Screen,
1432    x0: i32,
1433    y0: i32,
1434    x1: i32,
1435    y1: i32,
1436) -> Option<ScreenRect> {
1437    let (x0, y0) = (x0.max(0), y0.max(0));
1438    let (x1, y1) = (x1.min(screen.width as i32), y1.min(screen.height as i32));
1439    if x1 <= x0 || y1 <= y0 {
1440        return None;
1441    }
1442    let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize);
1443    Some(ScreenRect { x0, y0, w, h, px: read_screen_rect(screen, x0, y0, w, h) })
1444}
1445
1446/// 要素の描画だけをぼかして `before` の上へ重ねる(`blur_box::composite_blurred`)。
1447pub(crate) fn blur_element_paint(screen: &crate::kernel::draw::Screen, before: &ScreenRect, radius: i32) {
1448    let after = read_screen_rect(screen, before.x0, before.y0, before.w, before.h);
1449    let r = radius.clamp(1, 8) as usize;
1450    let Some(out) = super::blur_box::composite_blurred(&before.px, &after, before.w, before.h, r) else {
1451        return;
1452    };
1453    for y in 0..before.h {
1454        for x in 0..before.w {
1455            screen.draw_pixel_alpha(
1456                (before.x0 + x as i32) as u32,
1457                (before.y0 + y as i32) as u32,
1458                crate::kernel::draw::Color(out[y * before.w + x]),
1459                255,
1460            );
1461        }
1462    }
1463}
1464
1465pub(crate) fn apply_backdrop_filters_to_screen_rect(
1466    screen: &crate::kernel::draw::Screen,
1467    x0: i32,
1468    y0: i32,
1469    x1: i32,
1470    y1: i32,
1471    backdrop_filter: &str,
1472) {
1473    if backdrop_filter.is_empty() || x1 <= x0 || y1 <= y0 {
1474        return;
1475    }
1476    let backdrop_blur_radius = parse_blur_radius(backdrop_filter);
1477    if backdrop_blur_radius > 0 {
1478        blur_screen_rect(screen, x0, y0, x1, y1, backdrop_blur_radius);
1479    }
1480    
1481    // Check if there are color filter functions (brightness, contrast, saturate, etc.)
1482    let tokens = parse_filter_tokens(backdrop_filter);
1483    let has_color_filters = tokens.iter().any(|(name, _)| name != "blur");
1484    if !has_color_filters {
1485        return;
1486    }
1487
1488    for sy in y0..y1 {
1489        if sy < 0 || sy as u32 >= screen.height { continue; }
1490        for sx in x0..x1 {
1491            if sx < 0 || sx as u32 >= screen.width { continue; }
1492            let orig = screen.read_pixel(sx as u32, sy as u32).0;
1493            let (r, g, b) = (((orig >> 16) & 0xFF) as u8, ((orig >> 8) & 0xFF) as u8, (orig & 0xFF) as u8);
1494            let (fr, fg, fb) = apply_css_filters(backdrop_filter, r, g, b);
1495            let new_col = 0xFF000000 | ((fr as u32) << 16) | ((fg as u32) << 8) | (fb as u32);
1496            screen.draw_pixel_alpha(sx as u32, sy as u32, crate::kernel::draw::Color(new_col), 255);
1497        }
1498    }
1499}
1500
1501/// `mix-blend-mode` / `background-blend-mode`: 描画しようとしている色(src)を、
1502/// 既にフレームバッファ上にある色(dst = 背景)と指定モードで合成する。
1503/// 対応: normal(そのまま)/multiply/screen/darken/lighten/difference/overlay/
1504/// hard-light/soft-light/exclusion/color-dodge/color-burn(チャネルごとの独立計算)と、
1505/// hue/saturation/color/luminosity(W3C Compositing 仕様の Lum/Sat/SetLum/SetSat
1506/// アルゴリズムに基づく非可分モード、3チャネルまとめて計算)。
1507pub(crate) fn blend_pixel(mode: &str, src: (u8, u8, u8), dst: (u8, u8, u8)) -> (u8, u8, u8) {
1508    if matches!(mode, "hue" | "saturation" | "color" | "luminosity") {
1509        return blend_non_separable(mode, src, dst);
1510    }
1511    if mode == "soft-light" {
1512        fn soft(s: u8, d: u8) -> u8 {
1513            let (cs, cb) = (s as f32 / 255.0, d as f32 / 255.0);
1514            let dd = if cb <= 0.25 {
1515                ((16.0 * cb - 12.0) * cb + 4.0) * cb
1516            } else {
1517                libm::sqrtf(cb)
1518            };
1519            let b = if cs <= 0.5 {
1520                cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb)
1521            } else {
1522                cb + (2.0 * cs - 1.0) * (dd - cb)
1523            };
1524            (b.clamp(0.0, 1.0) * 255.0) as u8
1525        }
1526        return (soft(src.0, dst.0), soft(src.1, dst.1), soft(src.2, dst.2));
1527    }
1528    fn ch(mode: &str, s: u8, d: u8) -> u8 {
1529        let (sf, df) = (s as i32, d as i32);
1530        match mode {
1531            "multiply" => (sf * df / 255) as u8,
1532            "screen" => (255 - (255 - sf) * (255 - df) / 255) as u8,
1533            "darken" => sf.min(df) as u8,
1534            "lighten" => sf.max(df) as u8,
1535            "difference" => (sf - df).unsigned_abs() as u8,
1536            "overlay" => {
1537                if df <= 127 {
1538                    (2 * sf * df / 255).clamp(0, 255) as u8
1539                } else {
1540                    (255 - 2 * (255 - sf) * (255 - df) / 255).clamp(0, 255) as u8
1541                }
1542            }
1543            "hard-light" => {
1544                if sf <= 127 {
1545                    (2 * sf * df / 255).clamp(0, 255) as u8
1546                } else {
1547                    (255 - 2 * (255 - sf) * (255 - df) / 255).clamp(0, 255) as u8
1548                }
1549            }
1550            "exclusion" => (sf + df - 2 * sf * df / 255).clamp(0, 255) as u8,
1551            "color-dodge" => {
1552                if df == 0 {
1553                    0
1554                } else if sf >= 255 {
1555                    255
1556                } else {
1557                    (255 * df / (255 - sf)).min(255) as u8
1558                }
1559            }
1560            "color-burn" => {
1561                if df >= 255 {
1562                    255
1563                } else if sf == 0 {
1564                    0
1565                } else {
1566                    (255 - (255 * (255 - df) / sf).min(255)) as u8
1567                }
1568            }
1569            _ => s,
1570        }
1571    }
1572    (
1573        ch(mode, src.0, dst.0),
1574        ch(mode, src.1, dst.1),
1575        ch(mode, src.2, dst.2),
1576    )
1577}
1578
1579/// hue/saturation/color/luminosity(非可分ブレンドモード)。W3C Compositing and
1580/// Blending Level 1 の Lum/ClipColor/SetLum/Sat/SetSat アルゴリズムをそのまま実装する。
1581/// `dst` = backdrop(Cb)、`src` = source(Cs)。
1582fn blend_non_separable(mode: &str, src: (u8, u8, u8), dst: (u8, u8, u8)) -> (u8, u8, u8) {
1583    fn to_f(c: (u8, u8, u8)) -> (f32, f32, f32) {
1584        (c.0 as f32 / 255.0, c.1 as f32 / 255.0, c.2 as f32 / 255.0)
1585    }
1586    fn to_u8(c: (f32, f32, f32)) -> (u8, u8, u8) {
1587        (
1588            (c.0.clamp(0.0, 1.0) * 255.0) as u8,
1589            (c.1.clamp(0.0, 1.0) * 255.0) as u8,
1590            (c.2.clamp(0.0, 1.0) * 255.0) as u8,
1591        )
1592    }
1593    fn lum(c: (f32, f32, f32)) -> f32 {
1594        0.3 * c.0 + 0.59 * c.1 + 0.11 * c.2
1595    }
1596    fn clip_color(c: (f32, f32, f32)) -> (f32, f32, f32) {
1597        let l = lum(c);
1598        let n = c.0.min(c.1).min(c.2);
1599        let x = c.0.max(c.1).max(c.2);
1600        let mut c = c;
1601        if n < 0.0 && l != n {
1602            c = (
1603                l + (c.0 - l) * l / (l - n),
1604                l + (c.1 - l) * l / (l - n),
1605                l + (c.2 - l) * l / (l - n),
1606            );
1607        }
1608        if x > 1.0 && x != l {
1609            c = (
1610                l + (c.0 - l) * (1.0 - l) / (x - l),
1611                l + (c.1 - l) * (1.0 - l) / (x - l),
1612                l + (c.2 - l) * (1.0 - l) / (x - l),
1613            );
1614        }
1615        c
1616    }
1617    fn set_lum(c: (f32, f32, f32), l: f32) -> (f32, f32, f32) {
1618        let d = l - lum(c);
1619        clip_color((c.0 + d, c.1 + d, c.2 + d))
1620    }
1621    fn sat(c: (f32, f32, f32)) -> f32 {
1622        c.0.max(c.1).max(c.2) - c.0.min(c.1).min(c.2)
1623    }
1624    fn set_sat(c: (f32, f32, f32), s: f32) -> (f32, f32, f32) {
1625        let mut v = [c.0, c.1, c.2];
1626        let (mut lo, mut mid, mut hi) = (0usize, 1usize, 2usize);
1627        // インデックスを値の昇順(lo<=mid<=hi)に並べ替える。
1628        if v[lo] > v[mid] {
1629            core::mem::swap(&mut lo, &mut mid);
1630        }
1631        if v[mid] > v[hi] {
1632            core::mem::swap(&mut mid, &mut hi);
1633        }
1634        if v[lo] > v[mid] {
1635            core::mem::swap(&mut lo, &mut mid);
1636        }
1637        if v[hi] > v[lo] {
1638            v[mid] = (v[mid] - v[lo]) * s / (v[hi] - v[lo]);
1639            v[hi] = s;
1640        } else {
1641            v[mid] = 0.0;
1642            v[hi] = 0.0;
1643        }
1644        v[lo] = 0.0;
1645        (v[0], v[1], v[2])
1646    }
1647    let (cb, cs) = (to_f(dst), to_f(src));
1648    let result = match mode {
1649        "hue" => set_lum(set_sat(cs, sat(cb)), lum(cb)),
1650        "saturation" => set_lum(set_sat(cb, sat(cs)), lum(cb)),
1651        "color" => set_lum(cs, lum(cb)),
1652        "luminosity" => set_lum(cb, lum(cs)),
1653        _ => cs,
1654    };
1655    to_u8(result)
1656}
1657
1658/// `list-style-image` 用の小さな画像を (x0,y0) を左上として dst_w x dst_h へ最近傍スケーリング
1659/// して描画する。クリップ・object-fit 等は考慮しない簡易実装(マーカーサイズのアイコン用途)。
1660pub(super) fn draw_image_nn_blit(
1661    screen: &crate::kernel::draw::Screen,
1662    img: &super::DecodedImage,
1663    x0: i32,
1664    y0: i32,
1665    dst_w: u32,
1666    dst_h: u32,
1667) {
1668    if img.width == 0 || img.height == 0 || dst_w == 0 || dst_h == 0 {
1669        return;
1670    }
1671    for row in 0..dst_h {
1672        let src_row = (row * img.height) / dst_h;
1673        for col in 0..dst_w {
1674            let src_col = (col * img.width) / dst_w;
1675            let idx = ((src_row * img.width + src_col) as usize) * 4;
1676            if idx + 4 <= img.rgba.len() {
1677                let r = img.rgba[idx];
1678                let g = img.rgba[idx + 1];
1679                let b = img.rgba[idx + 2];
1680                let a = img.rgba[idx + 3];
1681                let px = x0 + col as i32;
1682                let py = y0 + row as i32;
1683                if px >= 0 && py >= 0 {
1684                    let color = crate::kernel::draw::Color(
1685                        0xFF000000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32),
1686                    );
1687                    screen.draw_pixel_alpha(px as u32, py as u32, color, a);
1688                }
1689            }
1690        }
1691    }
1692}
1693
1694/// <img> の object-fit / object-position を反映して画像を描画する。
1695/// background-image と異なりタイリングはしない(範囲外は透過のまま何も描かない)。
1696///
1697/// 計算量: **O(Wd×Hd)** — Wd,Hd は描画先サイズ。
1698/// 1 ピクセルごとに元画像をサンプリングする(`sample_bilinear_rgba` 使用時は
1699/// 1 ピクセルあたり 4 点読み出し+補間で定数倍が 4 倍になる)。
1700pub(super) fn draw_img_object_fit(
1701    screen: &crate::kernel::draw::Screen,
1702    img: &super::DecodedImage,
1703    el: &super::RenderElement,
1704    x0_rect: i32,
1705    y0_rect: i32,
1706    clip_s: &Option<ClipShape>,
1707) {
1708    use super::ObjectFit;
1709    let box_w = el.width.max(1) as u32;
1710    let box_h = el.height.max(1) as u32;
1711    if img.width == 0 || img.height == 0 {
1712        return;
1713    }
1714
1715    let (draw_w, draw_h): (u32, u32) = match el.object_fit {
1716        ObjectFit::Fill => (box_w, box_h),
1717        ObjectFit::Cover => {
1718            let scale = (box_w as f32 / img.width as f32).max(box_h as f32 / img.height as f32);
1719            (
1720                ((img.width as f32) * scale).max(1.0) as u32,
1721                ((img.height as f32) * scale).max(1.0) as u32,
1722            )
1723        }
1724        ObjectFit::Contain => {
1725            let scale = (box_w as f32 / img.width as f32).min(box_h as f32 / img.height as f32);
1726            (
1727                ((img.width as f32) * scale).max(1.0) as u32,
1728                ((img.height as f32) * scale).max(1.0) as u32,
1729            )
1730        }
1731        ObjectFit::None => (img.width, img.height),
1732        ObjectFit::ScaleDown => {
1733            let contain_scale =
1734                (box_w as f32 / img.width as f32).min(box_h as f32 / img.height as f32);
1735            let scale = contain_scale.min(1.0);
1736            (
1737                ((img.width as f32) * scale).max(1.0) as u32,
1738                ((img.height as f32) * scale).max(1.0) as u32,
1739            )
1740        }
1741    };
1742
1743    let off_x = ((box_w as i32 - draw_w as i32) as f32 * el.object_pos_x) as i32;
1744    let off_y = ((box_h as i32 - draw_h as i32) as f32 * el.object_pos_y) as i32;
1745    let blur_radius = parse_blur_radius(&el.filter);
1746
1747    let is_pixelated = el.image_rendering == "pixelated" || el.image_rendering == "crisp-edges";
1748    let use_nearest = is_pixelated || (draw_w == img.width && draw_h == img.height);
1749    let col_src_lut: alloc::vec::Vec<u32> = if use_nearest {
1750        (0..draw_w).map(|c| (c * img.width) / draw_w.max(1)).collect()
1751    } else {
1752        alloc::vec![]
1753    };
1754
1755    let mut row_buf = alloc::vec![0u32; draw_w as usize];
1756
1757    for row in 0..draw_h {
1758        let py = row as i32 + off_y;
1759        if py < 0 || py as u32 >= box_h {
1760            continue;
1761        }
1762        let src_row = (row * img.height) / draw_h.max(1);
1763        for col in 0..draw_w {
1764            let px = col as i32 + off_x;
1765            if px < 0 || px as u32 >= box_w {
1766                row_buf[col as usize] = 0;
1767                continue;
1768            }
1769            if let Some(ref cs) = clip_s {
1770                if !clip_inside(cs, px, py) {
1771                    row_buf[col as usize] = 0;
1772                    continue;
1773                }
1774            }
1775
1776            let (raw_r, raw_g, raw_b, a) = if use_nearest {
1777                let src_col = col_src_lut[col as usize];
1778                let idx = ((src_row * img.width + src_col) as usize) * 4;
1779                if idx + 4 <= img.rgba.len() {
1780                    let (br_r, br_g, br_b) = if blur_radius > 0 {
1781                        sample_box_blur(img, src_row, src_col, blur_radius)
1782                    } else {
1783                        (img.rgba[idx], img.rgba[idx + 1], img.rgba[idx + 2])
1784                    };
1785                    (br_r, br_g, br_b, img.rgba[idx + 3])
1786                } else {
1787                    (0, 0, 0, 0)
1788                }
1789            } else {
1790                let u = ((col as f32) + 0.5) * (img.width as f32) / (draw_w as f32) - 0.5;
1791                let v = ((row as f32) + 0.5) * (img.height as f32) / (draw_h as f32) - 0.5;
1792                sample_bilinear_rgba(img, u, v)
1793            };
1794            if a == 0 {
1795                row_buf[col as usize] = 0;
1796                continue;
1797            }
1798            let (r, g, b) = apply_css_filters(&el.filter, raw_r, raw_g, raw_b);
1799            row_buf[col as usize] = ((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32);
1800        }
1801
1802        screen.draw_scanline_colors(x0_rect + off_x, y0_rect + py, &row_buf);
1803    }
1804}
1805