Skip to main content

euv_core/render/hardware/
impl.rs

1use super::*;
2
3/// Packing, conversion, and compile-time ABI stride verification helpers for `GpuPrimitiveInstance`.
4impl GpuPrimitiveInstance {
5    /// Packs normalized `[r, g, b, a]` floating-point channels into little-endian RGBA8 `u32`.
6    ///
7    /// # Arguments
8    ///
9    /// - `[f32; 4]` - Normalized RGBA channels in `[0.0..=1.0]`.
10    ///
11    /// # Returns
12    ///
13    /// - `u32` - Packed RGBA8 color word (`R` in low byte, `A` in high byte).
14    #[must_use]
15    pub fn pack_rgba8_f32(rgba: [f32; 4]) -> u32 {
16        let red_val: u32 = (rgba[0].clamp(0.0, 1.0) * 255.0).round() as u32;
17        let green_val: u32 = (rgba[1].clamp(0.0, 1.0) * 255.0).round() as u32;
18        let blue_val: u32 = (rgba[2].clamp(0.0, 1.0) * 255.0).round() as u32;
19        let alpha_val: u32 = (rgba[3].clamp(0.0, 1.0) * 255.0).round() as u32;
20        red_val | (green_val << 8) | (blue_val << 16) | (alpha_val << 24)
21    }
22
23    /// Packs a `Color` into little-endian RGBA8 `u32`.
24    ///
25    /// # Arguments
26    ///
27    /// - `Color` - Source sRGB color with alpha.
28    ///
29    /// # Returns
30    ///
31    /// - `u32` - Packed RGBA8 color word.
32    #[must_use]
33    pub fn pack_color_rgba8(color: Color) -> u32 {
34        (color.get_red() as u32)
35            | ((color.get_green() as u32) << 8)
36            | ((color.get_blue() as u32) << 16)
37            | ((color.get_alpha() as u32) << 24)
38    }
39
40    /// Packs a non-negative physical pixel radius into Q12.4 unsigned fixed-point (`1/16` px).
41    ///
42    /// # Arguments
43    ///
44    /// - `f32` - Physical pixel measurement (`>= 0.0`).
45    ///
46    /// # Returns
47    ///
48    /// - `u16` - Q12.4 quantized fixed-point value.
49    #[must_use]
50    pub fn pack_u16_q4(value: f32) -> u16 {
51        (value.clamp(0.0, 4095.9375) * 16.0).round() as u16
52    }
53
54    /// Returns the geometric corner-radius ceiling (half the shortest side) for a quad so oversized
55    /// full-pill radii (e.g. `999.0` logical px at high DPR) encode losslessly within Q12.4 range.
56    ///
57    /// # Arguments
58    ///
59    /// - `[f32; 4]` - Physical quad rectangle `[x, y, w, h]` (shadow quads include blur padding).
60    /// - `u32` - Primitive kind discriminant (`2` = shadow).
61    /// - `f32` - Shadow blur padding stored in the angle slot for shadow quads.
62    ///
63    /// # Returns
64    ///
65    /// - `f32` - Maximum meaningful corner radius in physical pixels.
66    #[must_use]
67    pub fn corner_radius_cap(rect: [f32; 4], kind: u32, shadow_pad: f32) -> f32 {
68        let shortest: f32 = rect[2].min(rect[3]);
69        let inner: f32 = if kind == GpuPrimitiveKind::Shadow as u32 {
70            shortest - shadow_pad * 2.0
71        } else {
72            shortest
73        };
74        (inner * 0.5).max(0.0)
75    }
76
77    /// Converts a finite `f32` into IEEE-754 binary16 (`f16`) raw bit representation.
78    ///
79    /// # Arguments
80    ///
81    /// - `f32` - Single-precision floating-point value.
82    ///
83    /// # Returns
84    ///
85    /// - `u16` - IEEE-754 binary16 encoded bits.
86    #[must_use]
87    pub fn f32_to_f16_bits(value: f32) -> u16 {
88        let bits: u32 = value.to_bits();
89        let sign: u32 = (bits >> 16) & 0x8000;
90        let exp: i32 = ((bits >> 23) & 0xFF) as i32 - 127 + 15;
91        let frac: u32 = bits & 0x007F_FFFF;
92        if exp <= 0 {
93            if exp < -10 {
94                return sign as u16;
95            }
96            let mant: u32 = (frac | 0x0080_0000) >> (1 - exp);
97            return (sign | ((mant + 0x1000) >> 13)) as u16;
98        }
99        if exp >= 31 {
100            return (sign | 0x7C00) as u16;
101        }
102        let rounded: u32 = frac + 0x1000;
103        if (rounded & 0x0080_0000) != 0 {
104            (sign | (((exp + 1) as u32) << 10)) as u16
105        } else {
106            (sign | ((exp as u32) << 10) | (rounded >> 13)) as u16
107        }
108    }
109
110    /// Packs two `f32` values into an IEEE-754 `f16x2` `u32` matching GPU `unpack2x16float` / `half2`.
111    ///
112    /// # Arguments
113    ///
114    /// - `f32` - Low-lane parameter (`stroke_or_blur`).
115    /// - `f32` - High-lane parameter (`angle_or_pad`).
116    ///
117    /// # Returns
118    ///
119    /// - `u32` - Packed `f16x2` parameter word.
120    #[must_use]
121    pub fn pack_f16x2(lo: f32, hi: f32) -> u32 {
122        (Self::f32_to_f16_bits(lo) as u32) | ((Self::f32_to_f16_bits(hi) as u32) << 16)
123    }
124
125    /// Encodes `PrimKind`, `clip_mask_or_sub`, `tex_slot`, and `layer_id` into `kind_flags`.
126    ///
127    /// # Arguments
128    ///
129    /// - `PrimKind` - Unified 8-variant primitive discriminant (`bits[0..4]`).
130    /// - `u16` - Clip-mask identifier or `VectorSubKind` (`bits[4..16]`).
131    /// - `u8` - Bound texture slot index (`bits[16..24]`).
132    /// - `u8` - Owning retained layer identifier (`bits[24..32]`).
133    ///
134    /// # Returns
135    ///
136    /// - `u32` - Packed `kind_flags` bitfield.
137    #[must_use]
138    pub const fn pack_kind_flags(
139        kind: PrimKind,
140        clip_mask_or_sub: u16,
141        tex_slot: u8,
142        layer_id: u8,
143    ) -> u32 {
144        ((kind as u32) & 0xF)
145            | (((clip_mask_or_sub as u32) & 0xFFF) << 4)
146            | ((tex_slot as u32) << 16)
147            | ((layer_id as u32) << 24)
148    }
149
150    /// Decodes the `PrimKind` variant stored in `kind_flags` bits `[0..4]`.
151    ///
152    /// # Returns
153    ///
154    /// - `PrimKind` - Decoded primitive variant.
155    #[must_use]
156    pub fn prim_kind(&self) -> PrimKind {
157        match self.get_kind_flags() & 0xF {
158            1 => PrimKind::LinearGradientRect,
159            2 => PrimKind::Shadow,
160            3 => PrimKind::GlyphAlpha8,
161            4 => PrimKind::GlyphColorRgba8,
162            5 => PrimKind::ImageTexture,
163            6 => PrimKind::VectorShape,
164            7 => PrimKind::ExternalGpuSurface,
165            8 => PrimKind::BackdropBlur,
166            _ => PrimKind::RoundedRect,
167        }
168    }
169
170    /// Returns the `clip_mask_id` / `VectorSubKind` stored in `kind_flags` bits `[4..16]`.
171    ///
172    /// # Returns
173    ///
174    /// - `u16` - Encoded clip-mask ID or vector sub-kind.
175    #[must_use]
176    pub fn clip_or_sub_kind(&self) -> u16 {
177        ((self.get_kind_flags() >> 4) & 0xFFF) as u16
178    }
179
180    /// Encodes a physical rounded-clip corner radius (`0.0..=500.0 px`) into 6 bits matching all 4 uber-shaders.
181    ///
182    /// # Arguments
183    ///
184    /// - `f32` - Physical rounded-clip radius in pixels.
185    ///
186    /// # Returns
187    ///
188    /// - `u16` - Quantized 6-bit value in `0..=63`.
189    #[must_use]
190    pub fn encode_clip_radius_6bit(radius_px: f32) -> u16 {
191        let clamped: f32 = radius_px.clamp(0.0, 500.0);
192        if clamped <= 15.5 {
193            (clamped * 2.0).round().clamp(0.0, 31.0) as u16
194        } else if clamped <= 76.0 {
195            32_u16 + (((clamped - 16.0) / 4.0).round().clamp(0.0, 15.0) as u16)
196        } else {
197            48_u16 + (((clamped - 80.0) / 28.0).round().clamp(0.0, 15.0) as u16)
198        }
199    }
200
201    /// Decodes a 6-bit rounded-clip radius code back to physical pixels matching all 4 uber-shaders.
202    ///
203    /// # Arguments
204    ///
205    /// - `u16` - Quantized 6-bit radius code in `0..=63`.
206    ///
207    /// # Returns
208    ///
209    /// - `f32` - Decoded physical rounded-clip radius in pixels.
210    #[must_use]
211    pub fn decode_clip_radius_6bit(encoded: u16) -> f32 {
212        let masked: u16 = encoded & 0x3F;
213        if masked <= 31 {
214            (masked as f32) * 0.5
215        } else if masked <= 47 {
216            16.0 + ((masked - 32) as f32) * 4.0
217        } else {
218            80.0 + ((masked - 48) as f32) * 28.0
219        }
220    }
221
222    /// Encodes a 10-bit per-corner rounded-clip descriptor (`bits[0..4]` = active `TL/TR/BR/BL` corner mask, `bits[4..10]` = extended 6-bit physical radius up to `500px`) across nested rectangular and rounded clips.
223    ///
224    /// # Arguments
225    ///
226    /// - `Rect` - Parent active physical scissor rectangle.
227    /// - `u16` - Parent encoded 10-bit rounded-clip descriptor.
228    /// - `Rect` - Intersected child physical scissor rectangle.
229    /// - `Rect` - Newly pushed physical clip rectangle.
230    /// - `Option<CornerRadius>` - Newly pushed physical corner radii (`None` for rectangular `PushClip`).
231    ///
232    /// # Returns
233    ///
234    /// - `u16` - Encoded 10-bit rounded-clip descriptor (`0` when no rounded corner touches `next_scissor`).
235    #[must_use]
236    pub fn encode_rounded_clip_bits(
237        parent_scissor: Rect,
238        parent_bits: u16,
239        next_scissor: Rect,
240        pushed_rect: Rect,
241        pushed_radius_phys: Option<CornerRadius>,
242    ) -> u16 {
243        if next_scissor.get_width() <= 0.0 || next_scissor.get_height() <= 0.0 {
244            return 0;
245        }
246        let parent_mask: u16 = parent_bits & 0xF;
247        let parent_q_rad: u16 = (parent_bits >> 4) & 0x3F;
248        let mut mask: u16 = 0;
249        if parent_mask != 0 && parent_q_rad > 0 {
250            let same_left: bool = (next_scissor.get_x() - parent_scissor.get_x()).abs() <= 0.5;
251            let same_top: bool = (next_scissor.get_y() - parent_scissor.get_y()).abs() <= 0.5;
252            let same_right: bool = (next_scissor.right() - parent_scissor.right()).abs() <= 0.5;
253            let same_bottom: bool = (next_scissor.bottom() - parent_scissor.bottom()).abs() <= 0.5;
254            if (parent_mask & 1) != 0 && same_left && same_top {
255                mask |= 1;
256            }
257            if (parent_mask & 2) != 0 && same_right && same_top {
258                mask |= 2;
259            }
260            if (parent_mask & 4) != 0 && same_right && same_bottom {
261                mask |= 4;
262            }
263            if (parent_mask & 8) != 0 && same_left && same_bottom {
264                mask |= 8;
265            }
266        }
267        let mut q_rad: u16 = if mask != 0 { parent_q_rad } else { 0 };
268        if let Some(rad) = pushed_radius_phys {
269            let cap_r: f32 = (pushed_rect.get_width() * 0.5)
270                .min(pushed_rect.get_height() * 0.5)
271                .max(0.0);
272            let r_tl: f32 = rad.get_top_left().min(cap_r);
273            let r_tr: f32 = rad.get_top_right().min(cap_r);
274            let r_br: f32 = rad.get_bottom_right().min(cap_r);
275            let r_bl: f32 = rad.get_bottom_left().min(cap_r);
276            let max_pushed_r: f32 = r_tl.max(r_tr).max(r_br).max(r_bl);
277            let pushed_q_rad: u16 = Self::encode_clip_radius_6bit(max_pushed_r);
278            if pushed_q_rad > 0 {
279                let touch_left: bool = (next_scissor.get_x() - pushed_rect.get_x()).abs() <= 0.5;
280                let touch_top: bool = (next_scissor.get_y() - pushed_rect.get_y()).abs() <= 0.5;
281                let touch_right: bool = (next_scissor.right() - pushed_rect.right()).abs() <= 0.5;
282                let touch_bottom: bool =
283                    (next_scissor.bottom() - pushed_rect.bottom()).abs() <= 0.5;
284                let mut pushed_mask: u16 = 0;
285                if r_tl > 0.25 && touch_left && touch_top {
286                    pushed_mask |= 1;
287                }
288                if r_tr > 0.25 && touch_right && touch_top {
289                    pushed_mask |= 2;
290                }
291                if r_br > 0.25 && touch_right && touch_bottom {
292                    pushed_mask |= 4;
293                }
294                if r_bl > 0.25 && touch_left && touch_bottom {
295                    pushed_mask |= 8;
296                }
297                if pushed_mask != 0 {
298                    mask |= pushed_mask;
299                    q_rad = q_rad.max(pushed_q_rad);
300                }
301            }
302        }
303        if mask == 0 || q_rad == 0 {
304            0
305        } else {
306            (mask & 0xF) | ((q_rad & 0x3F) << 4)
307        }
308    }
309
310    /// Attaches a 10-bit rounded-clip descriptor into `kind_flags` bits `[6..16]`, preserving `PrimKind` (`bits[0..4]`) and `VectorSubKind` (`bits[4..6]`).
311    ///
312    /// # Arguments
313    ///
314    /// - `Self` - Source primitive instance.
315    /// - `u16` - Encoded 10-bit rounded-clip descriptor.
316    ///
317    /// # Returns
318    ///
319    /// - `Self` - Updated primitive instance.
320    #[inline(always)]
321    #[must_use]
322    pub fn with_rounded_clip_bits(mut self, rounded_clip_bits: u16) -> Self {
323        if rounded_clip_bits != 0 {
324            let current_flags: u32 = self.get_kind_flags();
325            let next_flags: u32 =
326                (current_flags & !(0x3FF_u32 << 6)) | (((rounded_clip_bits as u32) & 0x3FF) << 6);
327            let _: &mut Self = self.set_kind_flags(next_flags);
328        }
329        self
330    }
331
332    /// Returns the texture slot index stored in `kind_flags` bits `[16..24]`.
333    ///
334    /// # Returns
335    ///
336    /// - `u8` - Bound texture slot.
337    #[must_use]
338    pub fn texture_slot(&self) -> u8 {
339        ((self.get_kind_flags() >> 16) & 0xFF) as u8
340    }
341
342    /// Returns the retained layer identifier stored in `kind_flags` bits `[24..32]`.
343    ///
344    /// # Returns
345    ///
346    /// - `u8` - Owning layer identifier.
347    #[must_use]
348    pub fn layer_id(&self) -> u8 {
349        ((self.get_kind_flags() >> 24) & 0xFF) as u8
350    }
351
352    /// Compiles a 64-byte `GpuPrimitiveInstance` from a legacy 96-byte `GpuQuadInstance`.
353    ///
354    /// # Arguments
355    ///
356    /// - `&GpuQuadInstance` - Source quad descriptor.
357    /// - `u8` - Active texture slot index.
358    /// - `u8` - Active retained layer identifier.
359    ///
360    /// # Returns
361    ///
362    /// - `Self` - Tightly packed 64-byte GPU primitive instance.
363    #[must_use]
364    pub fn from_quad_instance(quad: &GpuQuadInstance, tex_slot: u8, layer_id: u8) -> Self {
365        const {
366            assert!(size_of::<GpuPrimitiveInstance>() == GPU_PRIMITIVE_INSTANCE_BYTES);
367        }
368        let rect: [f32; 4] = quad.get_rect();
369        let clip_rect: [f32; 4] = quad.get_clip();
370        let color_rgba: u32 = Self::pack_rgba8_f32(quad.get_color());
371        let mut aux_color_rgba: u32 = Self::pack_rgba8_f32(quad.get_secondary_color());
372        let mut uv_rect: [u16; 4] = [0, 0, u16::MAX, u16::MAX];
373        let src_radii: [f32; 4] = quad.get_radii();
374        let radius_cap: f32 = Self::corner_radius_cap(rect, quad.get_kind(), quad.get_angle_rad());
375        let mut radii_border: [u16; 4] = [
376            Self::pack_u16_q4(src_radii[0].min(radius_cap)),
377            Self::pack_u16_q4(src_radii[1].min(radius_cap)),
378            Self::pack_u16_q4(src_radii[2].min(radius_cap)),
379            Self::pack_u16_q4(src_radii[3].min(radius_cap)),
380        ];
381        let (prim_kind, sub_kind): (PrimKind, u16) = match quad.get_kind() {
382            1 => (PrimKind::LinearGradientRect, 0),
383            2 => (PrimKind::Shadow, 0),
384            3 => {
385                let is_color_glyph: bool = (quad.get_reserved() & 0x8000_0000) != 0;
386                if is_color_glyph {
387                    (PrimKind::GlyphColorRgba8, 0)
388                } else {
389                    (PrimKind::GlyphAlpha8, 0)
390                }
391            }
392            4 => (PrimKind::ImageTexture, 0),
393            5 => (PrimKind::VectorShape, VectorSubKind::Circle as u16),
394            6 => {
395                let inv_w: f32 = 1.0 / rect[2].max(1.0);
396                let inv_h: f32 = 1.0 / rect[3].max(1.0);
397                let red_val: [f32; 4] = quad.get_radii();
398                uv_rect = [
399                    (((red_val[0] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
400                    (((red_val[1] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
401                    (((red_val[2] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
402                    (((red_val[3] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
403                ];
404                radii_border = [0; 4];
405                (PrimKind::VectorShape, VectorSubKind::Line as u16)
406            }
407            7 => {
408                let inv_w: f32 = 1.0 / rect[2].max(1.0);
409                let inv_h: f32 = 1.0 / rect[3].max(1.0);
410                let p0: [f32; 4] = quad.get_secondary_color();
411                let radius_val: [f32; 4] = quad.get_radii();
412                let p0_nx: f32 = ((p0[0] - rect[0]) * inv_w).clamp(0.0, 1.0);
413                let p0_ny: f32 = ((p0[1] - rect[1]) * inv_h).clamp(0.0, 1.0);
414                aux_color_rgba = Self::pack_rgba8_f32([p0_nx, p0_ny, 0.0, 1.0]);
415                uv_rect = [
416                    (((radius_val[0] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
417                    (((radius_val[1] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
418                    (((radius_val[2] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
419                    (((radius_val[3] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
420                ];
421                radii_border = [
422                    (p0_nx * 65535.0).round() as u16,
423                    (p0_ny * 65535.0).round() as u16,
424                    0,
425                    0,
426                ];
427                (PrimKind::VectorShape, VectorSubKind::Triangle as u16)
428            }
429            8 => (PrimKind::BackdropBlur, 0),
430            9 => (PrimKind::ExternalGpuSurface, 0),
431            _ => (PrimKind::RoundedRect, 0),
432        };
433        let kind_flags: u32 = Self::pack_kind_flags(prim_kind, sub_kind, tex_slot, layer_id);
434        let extra_param: u32 = Self::pack_f16x2(quad.get_stroke_or_blur(), quad.get_angle_rad());
435        Self {
436            rect,
437            clip_rect,
438            color_rgba,
439            aux_color_rgba,
440            uv_rect,
441            radii_border,
442            kind_flags,
443            extra_param,
444        }
445    }
446
447    /// Constructs a 64-byte `PrimKind::ExternalGpuSurface` instance for shared-device 3D game or video textures.
448    ///
449    /// # Arguments
450    ///
451    /// - `Rect` - Destination physical bounds.
452    /// - `Rect` - Active physical scissor clip rectangle.
453    /// - `[f32; 4]` - Per-corner physical clip radii `[tl, tr, br, bl]`.
454    /// - `[u16; 4]` - Normalized texture UV rectangle `[u0, v0, u1, v1]`.
455    /// - `u8` - External GPU texture slot.
456    /// - `u8` - Retained layer identifier.
457    ///
458    /// # Returns
459    ///
460    /// - `Self` - Packed 64-byte external GPU surface primitive instance.
461    #[must_use]
462    pub fn external_surface(
463        bounds: Rect,
464        clip: Rect,
465        radii: [f32; 4],
466        uv_rect: [u16; 4],
467        tex_slot: u8,
468        layer_id: u8,
469    ) -> Self {
470        Self {
471            rect: [
472                bounds.get_x(),
473                bounds.get_y(),
474                bounds.get_width(),
475                bounds.get_height(),
476            ],
477            clip_rect: [clip.get_x(), clip.get_y(), clip.right(), clip.bottom()],
478            color_rgba: 0xFFFF_FFFF,
479            aux_color_rgba: 0,
480            uv_rect,
481            radii_border: [
482                Self::pack_u16_q4(radii[0]),
483                Self::pack_u16_q4(radii[1]),
484                Self::pack_u16_q4(radii[2]),
485                Self::pack_u16_q4(radii[3]),
486            ],
487            kind_flags: Self::pack_kind_flags(PrimKind::ExternalGpuSurface, 0, tex_slot, layer_id),
488            extra_param: 0,
489        }
490    }
491}
492
493/// Construction helper for `GpuLayerUniform`.
494impl GpuLayerUniform {
495    /// Creates a 16-byte layer uniform carrying physical viewport dimensions and scroll translation.
496    ///
497    /// # Arguments
498    ///
499    /// - `f32` - Physical viewport width in pixels.
500    /// - `f32` - Physical viewport height in pixels.
501    /// - `[f32; 2]` - Retained layer scroll offset `[scroll_x, scroll_y]` in physical pixels.
502    ///
503    /// # Returns
504    ///
505    /// - `Self` - Packed 16-byte GPU layer uniform.
506    #[must_use]
507    pub fn new(viewport_w: f32, viewport_h: f32, scroll_offset: [f32; 2]) -> Self {
508        const {
509            assert!(size_of::<GpuLayerUniform>() == GPU_LAYER_UNIFORM_BYTES);
510        }
511        Self {
512            viewport_size: [viewport_w.max(1.0), viewport_h.max(1.0)],
513            scroll_offset,
514        }
515    }
516}
517
518/// `GpuDriver` implementation for `RecordingGpuDriver`.
519impl GpuDriver for RecordingGpuDriver {
520    /// Returns the configured backend tag.
521    ///
522    /// # Arguments
523    ///
524    /// - `&Self` - Driver reference.
525    ///
526    /// # Returns
527    ///
528    /// - `GraphicsBackend` - Active backend tag.
529    fn backend(&self) -> GraphicsBackend {
530        self.get_backend_kind()
531    }
532
533    /// Selects the canonical native shader source for this backend.
534    ///
535    /// # Arguments
536    ///
537    /// - `&Self` - Driver reference.
538    ///
539    /// # Returns
540    ///
541    /// - `&'static str` - Native shader source string.
542    fn shader_source(&self) -> &'static str {
543        match self.get_backend_kind() {
544            GraphicsBackend::Metal => MSL_UI_SHADER,
545            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => HLSL_UI_SHADER,
546            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => GLSL_ES3_UI_FRAGMENT_SHADER,
547            GraphicsBackend::WebGpu
548            | GraphicsBackend::Vulkan
549            | GraphicsBackend::SoftwareCpu
550            | GraphicsBackend::Canvas2d
551            | GraphicsBackend::Headless => WGSL_UI_SHADER,
552        }
553    }
554
555    /// Records submitted GPU batches and returns draw-call count.
556    ///
557    /// # Arguments
558    ///
559    /// - `&Self` - Mutable driver.
560    /// - `u32` - Surface width.
561    /// - `u32` - Surface height.
562    /// - `Color` - Clear color.
563    /// - `&[GpuBatch]` - Ordered batches.
564    ///
565    /// # Returns
566    ///
567    /// - `Result<usize, PlatformError>` - Submitted batch count.
568    fn submit_batches(
569        &mut self,
570        _width: u32,
571        _height: u32,
572        clear_color: Color,
573        batches: &[GpuBatch],
574    ) -> Result<usize, PlatformError> {
575        let count: usize = batches.len();
576        let instances: usize = batches
577            .iter()
578            .fold(0_usize, |acc: usize, blue_val: &GpuBatch| {
579                acc + blue_val
580                    .get_primitives()
581                    .len()
582                    .max(blue_val.get_instances().len())
583            });
584        self.set_last_clear(clear_color);
585        self.set_last_instance_count(instances);
586        self.set_total_draw_calls(self.get_total_draw_calls().saturating_add(count));
587        Ok(count)
588    }
589}
590
591/// Instanced batch builder, order-preserving coalescer, and telemetry methods for `HardwareRenderer`.
592impl HardwareRenderer {
593    /// Creates a hardware renderer bound to `backend` with optional deterministic pixel readback.
594    ///
595    /// # Arguments
596    ///
597    /// - `GraphicsBackend` - Selected GPU backend.
598    /// - `u32` - Initial physical width.
599    /// - `u32` - Initial physical height.
600    /// - `RenderConfig` - Rendering configuration.
601    /// - `bool` - Whether software readback mirror is enabled.
602    ///
603    /// # Returns
604    ///
605    /// - `Self` - Configured hardware renderer.
606    #[must_use]
607    pub fn with_backend(
608        backend: GraphicsBackend,
609        width: u32,
610        height: u32,
611        config: RenderConfig,
612        enable_readback: bool,
613    ) -> Self {
614        Self::with_backend_and_font(
615            backend,
616            width,
617            height,
618            config,
619            enable_readback,
620            NativeSystemFont::deterministic(),
621        )
622    }
623
624    /// Creates a hardware renderer bound to `backend` with an explicit font provider for readback.
625    ///
626    /// # Arguments
627    ///
628    /// - `GraphicsBackend` - Selected GPU backend.
629    /// - `u32` - Initial physical width.
630    /// - `u32` - Initial physical height.
631    /// - `RenderConfig` - Rendering configuration.
632    /// - `bool` - Whether software readback mirror is enabled.
633    /// - `NativeSystemFont` - Font provider used by the software readback mirror.
634    ///
635    /// # Returns
636    ///
637    /// - `Self` - Configured hardware renderer.
638    #[must_use]
639    pub fn with_backend_and_font(
640        backend: GraphicsBackend,
641        width: u32,
642        height: u32,
643        config: RenderConfig,
644        enable_readback: bool,
645        font_provider: NativeSystemFont,
646    ) -> Self {
647        let driver: NativeGpuDriver = NativeGpuDriver::probe(backend);
648        let per_glyph_atlas: bool = config.get_direct_gpu_present();
649        let mut batches: Vec<GpuBatch> = Vec::with_capacity(16);
650        for _ in 0..8usize {
651            let mut batch: GpuBatch = GpuBatch::default();
652            batch.get_mut_primitives().reserve(256);
653            batches.push(batch);
654        }
655        Self {
656            driver,
657            batches,
658            active_batches: 0,
659            clip_stack: Vec::with_capacity(16),
660            last_submitted_batches: 0,
661            last_coalesced_merges: 0,
662            last_culled_instances: 0,
663            last_uploaded_instances: 0,
664            last_uploaded_bytes: 0,
665            readback: SoftwareRenderer::with_font_provider(width, height, config, font_provider),
666            enable_readback,
667            resource_ring: GpuResourceRing::default(),
668            direct_gpu_frames: 0,
669            cpu_readback_frames: 0,
670            last_cpu_rgba_upload_bytes: 0,
671            has_unsupported_effect: false,
672            last_fence_id: 0,
673            blur_passes: Vec::with_capacity(8),
674            active_scroll_offset: [0.0, 0.0],
675            active_layer_id: 0,
676            last_uploaded_primitive_bytes: 0,
677            gpu_glyph_atlas: IncrementalGpuGlyphAtlas::default(),
678            gpu_image_atlas: IncrementalGpuImageAtlas::default(),
679            per_glyph_atlas,
680        }
681    }
682
683    /// Updates the native system font provider forwarded to the internal glyph atlas and CPU readback backend.
684    ///
685    /// # Arguments
686    ///
687    /// - `&Self` - Mutable hardware renderer.
688    /// - `NativeSystemFont` - Host font rasterizer provider.
689    ///
690    /// # Returns
691    ///
692    /// - `&mut Self` - Mutable hardware renderer for chaining.
693    pub fn set_font_provider(&mut self, font_provider: NativeSystemFont) -> &mut Self {
694        let _: &mut SoftwareRenderer = self.get_mut_readback().set_font_provider(font_provider);
695        self
696    }
697
698    /// Captures an on-demand CPU reference framebuffer readback without enabling steady-state CPU mirroring.
699    ///
700    /// # Arguments
701    ///
702    /// - `&Self` - Mutable hardware renderer.
703    /// - `&DisplayList` - Display list to rasterize through the CPU reference backend.
704    /// - `DamageRegion` - Damage region to rasterize.
705    ///
706    /// # Returns
707    ///
708    /// - `&Framebuffer` - Rendered reference RGBA8 framebuffer.
709    pub fn capture_reference_readback(
710        &mut self,
711        display_list: &DisplayList,
712        damage: DamageRegion,
713    ) -> &Framebuffer {
714        let (_, _): (usize, usize) = self.get_mut_readback().render(display_list, damage);
715        self.get_readback().get_framebuffer()
716    }
717
718    /// Signals completion of GPU submission `fence_id` to release staging ring slots and reclaim deferred resources.
719    ///
720    /// # Arguments
721    ///
722    /// - `&Self` - Mutable hardware renderer.
723    /// - `u64` - Completed monotonic GPU fence identifier.
724    ///
725    /// # Returns
726    ///
727    /// - `usize` - Number of deferred GPU resources reclaimed.
728    pub fn complete_gpu_fence(&mut self, fence_id: u64) -> usize {
729        self.get_mut_resource_ring().complete_fence(fence_id)
730    }
731
732    /// Trims invisible persistent GPU scroll tile caches under memory pressure according to `retain_ratio`.
733    ///
734    /// # Arguments
735    ///
736    /// - `&Self` - Mutable hardware renderer.
737    /// - `f32` - Retained budget fraction in `(0.0..=1.0]`.
738    ///
739    /// # Returns
740    ///
741    /// - `usize` - Number of cold scroll tiles evicted to fence-deferred reclamation.
742    pub fn trim_gpu_caches(&mut self, retain_ratio: f32) -> usize {
743        self.get_mut_resource_ring()
744            .apply_retention_ratio(retain_ratio)
745    }
746
747    /// Returns latest-frame GPU batching and upload telemetry `(batches, coalesced_merges, culled_instances, uploaded_instances, uploaded_bytes)`.
748    ///
749    /// # Arguments
750    ///
751    /// - `&Self` - Hardware renderer reference.
752    ///
753    /// # Returns
754    ///
755    /// - `(usize, usize, usize, usize, usize)` - Latest frame batching and upload telemetry tuple.
756    #[must_use]
757    pub fn last_frame_telemetry(&self) -> (usize, usize, usize, usize, usize) {
758        (
759            self.get_last_submitted_batches(),
760            self.get_last_coalesced_merges(),
761            self.get_last_culled_instances(),
762            self.get_last_uploaded_instances(),
763            self.get_last_uploaded_bytes(),
764        )
765    }
766
767    /// Returns the slice of active `GpuBatch` submissions populated for the latest rendered frame.
768    ///
769    /// # Arguments
770    ///
771    /// - `&Self` - Hardware renderer reference.
772    ///
773    /// # Returns
774    ///
775    /// - `&[GpuBatch]` - Active order-preserving GPU draw batches.
776    #[must_use]
777    pub fn active_batches_slice(&self) -> &[GpuBatch] {
778        let active: usize = self.get_active_batches().min(self.get_batches().len());
779        &self.get_batches()[..active]
780    }
781
782    /// Computes a deterministic 64-bit FNV-1a hash over all compiled GPU batch instances.
783    ///
784    /// # Arguments
785    ///
786    /// - `&Self` - Hardware renderer reference.
787    ///
788    /// # Returns
789    ///
790    /// - `u64` - Deterministic batch geometry hash.
791    #[must_use]
792    pub fn batch_hash(&self) -> u64 {
793        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
794        let active: usize = self.get_active_batches().min(self.get_batches().len());
795        for batch in self.get_batches()[..active].iter() {
796            if !batch.get_primitives().is_empty() {
797                for prim in batch.get_primitives().iter() {
798                    for item_val in prim.get_rect().iter().chain(prim.get_clip_rect().iter()) {
799                        hash ^= item_val.to_bits() as u64;
800                        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
801                    }
802                    for word in [
803                        prim.get_color_rgba(),
804                        prim.get_aux_color_rgba(),
805                        prim.get_kind_flags(),
806                        prim.get_extra_param(),
807                    ] {
808                        hash ^= word as u64;
809                        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
810                    }
811                    for lane in prim
812                        .get_uv_rect()
813                        .iter()
814                        .chain(prim.get_radii_border().iter())
815                    {
816                        hash ^= *lane as u64;
817                        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
818                    }
819                }
820            } else {
821                for inst in batch.get_instances().iter() {
822                    for item_val in inst
823                        .get_rect()
824                        .iter()
825                        .chain(inst.get_color().iter())
826                        .chain(inst.get_radii().iter())
827                    {
828                        hash ^= item_val.to_bits() as u64;
829                        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
830                    }
831                }
832            }
833        }
834        hash
835    }
836
837    /// Returns `true` when physical quad `quad = [x, y, w, h]` lies completely inside `container`.
838    ///
839    /// # Arguments
840    ///
841    /// - `[f32; 4]` - Physical quad bounds `[x, y, width, height]`.
842    /// - `Rect` - Enclosing physical clip rectangle.
843    ///
844    /// # Returns
845    ///
846    /// - `bool` - True when no fragment of `quad` extends outside `container`.
847    #[inline(always)]
848    #[must_use]
849    fn quad_inside_rect(quad: [f32; 4], container: Rect) -> bool {
850        let qx0: f32 = quad[0];
851        let qy0: f32 = quad[1];
852        let qx1: f32 = qx0 + quad[2];
853        let qy1: f32 = qy0 + quad[3];
854        let x_in: bool = qx0 >= container.get_x() && qx1 <= container.right();
855        let y_in: bool = qy0 >= container.get_y() && qy1 <= container.bottom();
856        container.get_width() > 0.0 && container.get_height() > 0.0 && x_in && y_in
857    }
858
859    /// Returns `true` when `quad` intersects `clip` with strictly positive area.
860    ///
861    /// # Arguments
862    ///
863    /// - `[f32; 4]` - Physical quad bounds `[x, y, width, height]`.
864    /// - `Rect` - Active physical scissor clip.
865    ///
866    /// # Returns
867    ///
868    /// - `bool` - True when at least part of `quad` falls inside `clip`.
869    #[inline(always)]
870    #[must_use]
871    fn quad_intersects_clip(quad: [f32; 4], clip: Rect) -> bool {
872        let qw: f32 = quad[2];
873        let qh: f32 = quad[3];
874        let quad_empty: bool = qw <= 0.0 || qh <= 0.0;
875        let clip_empty: bool = clip.get_width() <= 0.0 || clip.get_height() <= 0.0;
876        if quad_empty || clip_empty {
877            return false;
878        }
879        let qx0: f32 = quad[0];
880        let qy0: f32 = quad[1];
881        let qx1: f32 = qx0 + qw;
882        let qy1: f32 = qy0 + qh;
883        let x_hit: bool = qx1 > clip.get_x() && qx0 < clip.right();
884        let y_hit: bool = qy1 > clip.get_y() && qy0 < clip.bottom();
885        x_hit && y_hit
886    }
887
888    /// Returns `true` when `inner` lies completely inside `outer`.
889    ///
890    /// # Arguments
891    ///
892    /// - `Rect` - Candidate inner rectangle.
893    /// - `Rect` - Candidate outer enclosing rectangle.
894    ///
895    /// # Returns
896    ///
897    /// - `bool` - True when `inner` is contained inside `outer`.
898    #[inline(always)]
899    #[must_use]
900    fn rect_inside_rect(inner: Rect, outer: Rect) -> bool {
901        let x_in: bool = inner.get_x() >= outer.get_x() && inner.right() <= outer.right();
902        let y_in: bool = inner.get_y() >= outer.get_y() && inner.bottom() <= outer.bottom();
903        x_in && y_in
904    }
905
906    /// Returns the union bounding box of `existing` and physical quad `quad = [x, y, w, h]`.
907    ///
908    /// # Arguments
909    ///
910    /// - `Rect` - Existing bounding box.
911    /// - `[f32; 4]` - Newly appended quad bounds `[x, y, width, height]`.
912    ///
913    /// # Returns
914    ///
915    /// - `Rect` - Enclosing union rectangle.
916    #[inline(always)]
917    #[must_use]
918    fn union_rect_quad(existing: Rect, quad: [f32; 4]) -> Rect {
919        let x0: f32 = existing.get_x().min(quad[0]);
920        let y0: f32 = existing.get_y().min(quad[1]);
921        let x1: f32 = existing.right().max(quad[0] + quad[2]);
922        let y1: f32 = existing.bottom().max(quad[1] + quad[3]);
923        Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
924    }
925
926    /// Compiles `display_list` into order-preserving coalesced GPU instanced batches and submits them to the GPU driver.
927    ///
928    /// # Arguments
929    ///
930    /// - `&Self` - Mutable hardware renderer.
931    /// - `&DisplayList` - Backend-agnostic draw command stream.
932    /// - `DamageRegion` - Active damage region for readback mirroring.
933    ///
934    /// # Returns
935    ///
936    /// - `Result<(usize, usize), PlatformError>` - Tuple of `(draw_batches, pixels_shaded)`.
937    pub fn render(
938        &mut self,
939        display_list: &DisplayList,
940        damage: DamageRegion,
941    ) -> Result<(usize, usize), PlatformError> {
942        self.render_with_physical_size(display_list, damage, None)
943    }
944
945    /// Compiles `display_list` into 64-byte `GpuPrimitiveInstance` batches using authoritative physical backing dimensions when provided.
946    ///
947    /// # Arguments
948    ///
949    /// - `&Self` - Mutable hardware renderer.
950    /// - `&DisplayList` - Backend-agnostic draw command stream.
951    /// - `DamageRegion` - Active damage region for readback mirroring.
952    /// - `Option<(u32, u32)>` - Authoritative `(physical_width, physical_height)` preventing `(logical * scale).round()` drift.
953    ///
954    /// # Returns
955    ///
956    /// - `Result<(usize, usize), PlatformError>` - Tuple of `(draw_batches, pixels_shaded)`.
957    pub fn render_with_physical_size(
958        &mut self,
959        display_list: &DisplayList,
960        damage: DamageRegion,
961        physical_size: Option<(u32, u32)>,
962    ) -> Result<(usize, usize), PlatformError> {
963        let scale: f32 = display_list.get_scale_factor().clamp(0.25, 16.0);
964        let (phys_w, phys_h): (u32, u32) = match physical_size {
965            Some((width_px, height_px)) if width_px > 0 && height_px > 0 => (width_px, height_px),
966            _ => (
967                ((display_list.get_viewport().get_width() * scale).round() as u32).max(1),
968                ((display_list.get_viewport().get_height() * scale).round() as u32).max(1),
969            ),
970        };
971        let max_blur_px: f32 = (64.0 * scale).clamp(64.0, 512.0);
972        let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
973        let full_entry: GpuClipEntry = GpuClipEntry {
974            scissor: full_clip,
975            safe_inner: full_clip,
976            rounded_clip_bits: 0,
977        };
978        let Self {
979            driver,
980            batches,
981            active_batches,
982            clip_stack,
983            last_submitted_batches,
984            last_coalesced_merges,
985            last_culled_instances,
986            last_uploaded_instances,
987            last_uploaded_bytes,
988            readback,
989            enable_readback,
990            resource_ring,
991            direct_gpu_frames,
992            cpu_readback_frames,
993            last_cpu_rgba_upload_bytes,
994            has_unsupported_effect,
995            last_fence_id,
996            blur_passes,
997            active_scroll_offset,
998            active_layer_id,
999            last_uploaded_primitive_bytes,
1000            gpu_glyph_atlas,
1001            gpu_image_atlas,
1002            per_glyph_atlas,
1003        } = self;
1004        gpu_image_atlas.begin_frame();
1005        let glyph_h_before: u32 = gpu_glyph_atlas.get_height();
1006        let img_w_before: u32 = gpu_image_atlas.get_width();
1007        let img_h_before: u32 = gpu_image_atlas.get_height();
1008        clip_stack.clear();
1009        clip_stack.push(full_entry);
1010        blur_passes.clear();
1011        *active_batches = 0;
1012        *has_unsupported_effect = false;
1013        let layer_scroll: [f32; 2] = *active_scroll_offset;
1014        let layer_id: u8 = *active_layer_id;
1015        let gpu_supports_blur: bool = driver.supports_backdrop_blur_pass()
1016            || matches!(
1017                driver.backend(),
1018                GraphicsBackend::Metal
1019                    | GraphicsBackend::WebGl2
1020                    | GraphicsBackend::OpenGlEs
1021                    | GraphicsBackend::WebGpu
1022                    | GraphicsBackend::Vulkan
1023                    | GraphicsBackend::Direct3D12
1024                    | GraphicsBackend::Direct3D11
1025            );
1026        let mut tail_state: GpuBatchCoalesceState = GpuBatchCoalesceState {
1027            scroll_offset: layer_scroll,
1028            layer_id,
1029            ..GpuBatchCoalesceState::default()
1030        };
1031        let mut coalesced_merges: usize = 0;
1032        let mut culled_instances: usize = 0;
1033        let mut uploaded_instances: usize = 0;
1034        let mut clear_color: Color = COLOR_WHITE;
1035        for cmd in display_list.get_commands().iter() {
1036            let clip_entry: GpuClipEntry = clip_stack.last().copied().unwrap_or(full_entry);
1037            let active_clip: Rect = clip_entry.scissor;
1038            match cmd {
1039                DrawCommand::Clear(color_item) => {
1040                    clear_color = *color_item;
1041                }
1042                DrawCommand::PushClip(rect) => {
1043                    let phys: Rect = snap_physical_rect(*rect, scale);
1044                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
1045                    let next_safe: Rect = clip_entry.safe_inner.intersect(phys).unwrap_or_default();
1046                    let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
1047                        active_clip,
1048                        clip_entry.rounded_clip_bits,
1049                        next_scissor,
1050                        phys,
1051                        None,
1052                    );
1053                    clip_stack.push(GpuClipEntry {
1054                        scissor: next_scissor,
1055                        safe_inner: next_safe,
1056                        rounded_clip_bits: next_bits,
1057                    });
1058                }
1059                DrawCommand::PushRoundedClip { rect, radius } => {
1060                    let phys: Rect = snap_physical_rect(*rect, scale);
1061                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
1062                    let phys_radius: CornerRadius = CornerRadius::new(
1063                        radius.get_top_left() * scale,
1064                        radius.get_top_right() * scale,
1065                        radius.get_bottom_right() * scale,
1066                        radius.get_bottom_left() * scale,
1067                    );
1068                    let max_r: f32 = phys_radius.max_radius().ceil();
1069                    let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
1070                    let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
1071                    let rounded_safe: Rect =
1072                        Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
1073                    let next_safe: Rect = clip_entry
1074                        .safe_inner
1075                        .intersect(rounded_safe)
1076                        .unwrap_or_default();
1077                    let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
1078                        active_clip,
1079                        clip_entry.rounded_clip_bits,
1080                        next_scissor,
1081                        phys,
1082                        Some(phys_radius),
1083                    );
1084                    clip_stack.push(GpuClipEntry {
1085                        scissor: next_scissor,
1086                        safe_inner: next_safe,
1087                        rounded_clip_bits: next_bits,
1088                    });
1089                }
1090                DrawCommand::PopClip => {
1091                    if clip_stack.len() > 1 {
1092                        let _: Option<GpuClipEntry> = clip_stack.pop();
1093                    }
1094                }
1095                DrawCommand::FillRoundedRect {
1096                    rect,
1097                    color,
1098                    radius,
1099                    border,
1100                } => {
1101                    let snapped: Rect = snap_physical_rect(*rect, scale);
1102                    let quad: [f32; 4] = [
1103                        snapped.get_x(),
1104                        snapped.get_y(),
1105                        snapped.get_width(),
1106                        snapped.get_height(),
1107                    ];
1108                    if !Self::quad_intersects_clip(quad, active_clip) {
1109                        culled_instances += 1;
1110                        continue;
1111                    }
1112                    let border_width: f32 = if border.get_width() > 0.0 {
1113                        (border.get_width() * scale).max(1.0)
1114                    } else {
1115                        0.0
1116                    };
1117                    let inst: GpuQuadInstance = GpuQuadInstance {
1118                        rect: quad,
1119                        clip: [
1120                            active_clip.get_x(),
1121                            active_clip.get_y(),
1122                            active_clip.right(),
1123                            active_clip.bottom(),
1124                        ],
1125                        color: color.to_f32_array(),
1126                        secondary_color: border.get_color().to_f32_array(),
1127                        radii: [
1128                            radius.get_top_left() * scale,
1129                            radius.get_top_right() * scale,
1130                            radius.get_bottom_right() * scale,
1131                            radius.get_bottom_left() * scale,
1132                        ],
1133                        stroke_or_blur: border_width,
1134                        angle_rad: 0.0,
1135                        kind: GpuPrimitiveKind::RoundedRect as u32,
1136                        reserved: 0,
1137                    };
1138                    Self::push_instance_coalesced(
1139                        batches,
1140                        active_batches,
1141                        &mut tail_state,
1142                        clip_entry,
1143                        inst,
1144                        &mut coalesced_merges,
1145                    );
1146                    uploaded_instances += 1;
1147                }
1148                DrawCommand::LinearGradientRect {
1149                    rect,
1150                    gradient,
1151                    radius,
1152                } => {
1153                    let snapped: Rect = snap_physical_rect(*rect, scale);
1154                    let quad: [f32; 4] = [
1155                        snapped.get_x(),
1156                        snapped.get_y(),
1157                        snapped.get_width(),
1158                        snapped.get_height(),
1159                    ];
1160                    if !Self::quad_intersects_clip(quad, active_clip) {
1161                        culled_instances += 1;
1162                        continue;
1163                    }
1164                    let inst: GpuQuadInstance = GpuQuadInstance {
1165                        rect: quad,
1166                        clip: [
1167                            active_clip.get_x(),
1168                            active_clip.get_y(),
1169                            active_clip.right(),
1170                            active_clip.bottom(),
1171                        ],
1172                        color: gradient.get_start_color().to_f32_array(),
1173                        secondary_color: gradient.get_end_color().to_f32_array(),
1174                        radii: [
1175                            radius.get_top_left() * scale,
1176                            radius.get_top_right() * scale,
1177                            radius.get_bottom_right() * scale,
1178                            radius.get_bottom_left() * scale,
1179                        ],
1180                        stroke_or_blur: 0.0,
1181                        angle_rad: gradient.get_angle_deg().to_radians(),
1182                        kind: GpuPrimitiveKind::Gradient as u32,
1183                        reserved: 0,
1184                    };
1185                    Self::push_instance_coalesced(
1186                        batches,
1187                        active_batches,
1188                        &mut tail_state,
1189                        clip_entry,
1190                        inst,
1191                        &mut coalesced_merges,
1192                    );
1193                    uploaded_instances += 1;
1194                }
1195                DrawCommand::BoxShadow {
1196                    rect,
1197                    radius,
1198                    shadow,
1199                } => {
1200                    let spread: f32 = shadow.get_spread_radius() * scale;
1201                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(max_blur_px);
1202                    let sigma: f32 = (blur * 0.5).max(0.75);
1203                    let pad: f32 = (sigma * 3.0).ceil();
1204                    let base_rect: Rect = snap_physical_rect(*rect, scale);
1205                    let caster_x: f32 =
1206                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
1207                    let caster_y: f32 =
1208                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
1209                    let caster_w: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
1210                    let caster_h: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
1211                    let quad: [f32; 4] = [
1212                        caster_x - pad,
1213                        caster_y - pad,
1214                        caster_w + pad * 2.0,
1215                        caster_h + pad * 2.0,
1216                    ];
1217                    if !Self::quad_intersects_clip(quad, active_clip) {
1218                        culled_instances += 1;
1219                        continue;
1220                    }
1221                    let inst: GpuQuadInstance = GpuQuadInstance {
1222                        rect: quad,
1223                        clip: [
1224                            active_clip.get_x(),
1225                            active_clip.get_y(),
1226                            active_clip.right(),
1227                            active_clip.bottom(),
1228                        ],
1229                        color: shadow.get_color().to_f32_array(),
1230                        secondary_color: [0.0; 4],
1231                        radii: [
1232                            (radius.get_top_left() * scale + spread).max(0.0),
1233                            (radius.get_top_right() * scale + spread).max(0.0),
1234                            (radius.get_bottom_right() * scale + spread).max(0.0),
1235                            (radius.get_bottom_left() * scale + spread).max(0.0),
1236                        ],
1237                        stroke_or_blur: sigma,
1238                        angle_rad: pad,
1239                        kind: GpuPrimitiveKind::Shadow as u32,
1240                        reserved: 0,
1241                    };
1242                    Self::push_instance_coalesced(
1243                        batches,
1244                        active_batches,
1245                        &mut tail_state,
1246                        clip_entry,
1247                        inst,
1248                        &mut coalesced_merges,
1249                    );
1250                    uploaded_instances += 1;
1251                }
1252                DrawCommand::BackdropBlur {
1253                    rect,
1254                    radius,
1255                    blur_radius,
1256                } => {
1257                    if !gpu_supports_blur {
1258                        *has_unsupported_effect = true;
1259                    }
1260                    let snapped: Rect = snap_physical_rect(*rect, scale);
1261                    let quad: [f32; 4] = [
1262                        snapped.get_x(),
1263                        snapped.get_y(),
1264                        snapped.get_width(),
1265                        snapped.get_height(),
1266                    ];
1267                    if !Self::quad_intersects_clip(quad, active_clip) {
1268                        culled_instances += 1;
1269                        continue;
1270                    }
1271                    let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, max_blur_px);
1272                    let radii_px: [f32; 4] = [
1273                        radius.get_top_left() * scale,
1274                        radius.get_top_right() * scale,
1275                        radius.get_bottom_right() * scale,
1276                        radius.get_bottom_left() * scale,
1277                    ];
1278                    let halo: Rect = Rect::new(
1279                        (snapped.get_x() - phys_blur).max(0.0),
1280                        (snapped.get_y() - phys_blur).max(0.0),
1281                        (snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
1282                        (snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
1283                    );
1284                    blur_passes.push(GpuBackdropBlurPass {
1285                        bounds: snapped,
1286                        input_bounds: halo,
1287                        clip_rect: active_clip,
1288                        radii: radii_px,
1289                        blur_radius: phys_blur,
1290                        layer_id,
1291                    });
1292                    let inv_vp_w: f32 = 1.0 / (phys_w.max(1) as f32);
1293                    let inv_vp_h: f32 = 1.0 / (phys_h.max(1) as f32);
1294                    let blur_uv: [u16; 4] = [
1295                        (snapped.get_x() * inv_vp_w * 65535.0)
1296                            .round()
1297                            .clamp(0.0, 65535.0) as u16,
1298                        (snapped.get_y() * inv_vp_h * 65535.0)
1299                            .round()
1300                            .clamp(0.0, 65535.0) as u16,
1301                        (snapped.right() * inv_vp_w * 65535.0)
1302                            .round()
1303                            .clamp(0.0, 65535.0) as u16,
1304                        (snapped.bottom() * inv_vp_h * 65535.0)
1305                            .round()
1306                            .clamp(0.0, 65535.0) as u16,
1307                    ];
1308                    let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
1309                    let blur_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
1310                        rect: quad,
1311                        clip_rect: [
1312                            active_clip.get_x(),
1313                            active_clip.get_y(),
1314                            active_clip.right(),
1315                            active_clip.bottom(),
1316                        ],
1317                        color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
1318                        aux_color_rgba: 0,
1319                        uv_rect: blur_uv,
1320                        radii_border: [
1321                            GpuPrimitiveInstance::pack_u16_q4(radii_px[0].min(radius_cap)),
1322                            GpuPrimitiveInstance::pack_u16_q4(radii_px[1].min(radius_cap)),
1323                            GpuPrimitiveInstance::pack_u16_q4(radii_px[2].min(radius_cap)),
1324                            GpuPrimitiveInstance::pack_u16_q4(radii_px[3].min(radius_cap)),
1325                        ],
1326                        kind_flags: GpuPrimitiveInstance::pack_kind_flags(
1327                            PrimKind::BackdropBlur,
1328                            0,
1329                            0,
1330                            tail_state.layer_id,
1331                        ),
1332                        extra_param: GpuPrimitiveInstance::pack_f16x2(phys_blur, 0.0),
1333                    };
1334                    Self::push_primitive_coalesced(
1335                        batches,
1336                        active_batches,
1337                        &mut tail_state,
1338                        clip_entry,
1339                        blur_prim,
1340                        true,
1341                        &mut coalesced_merges,
1342                    );
1343                    uploaded_instances += 1;
1344                }
1345                DrawCommand::TextRun { rect, text, style } => {
1346                    let run_quad: [f32; 4] = [
1347                        rect.get_x() * scale,
1348                        rect.get_y() * scale,
1349                        rect.get_width() * scale,
1350                        rect.get_height() * scale,
1351                    ];
1352                    if !Self::quad_intersects_clip(run_quad, active_clip) {
1353                        culled_instances += 1;
1354                        continue;
1355                    }
1356                    if *per_glyph_atlas {
1357                        let wrap_w: Option<f32> = if matches!(
1358                            style.get_overflow(),
1359                            TextOverflow::Wrap | TextOverflow::Ellipsis
1360                        ) {
1361                            Some(rect.get_width().max(1.0))
1362                        } else {
1363                            None
1364                        };
1365                        let layout_res: TextLayoutResult =
1366                            DeterministicTextMeasurer.measure(text, *style, wrap_w);
1367                        let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
1368                        let letter_sp: f32 = style.get_letter_spacing() * scale;
1369                        let line_h_phys: f32 = layout_res.get_line_height_px() * scale;
1370                        let font_provider: NativeSystemFont = readback.get_font_provider().clone();
1371                        let cpu_atlas: &mut GlyphAtlas = readback.get_mut_glyph_atlas();
1372                        let text_color_u32: u32 =
1373                            GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
1374                        let clip_arr: [f32; 4] = [
1375                            active_clip.get_x(),
1376                            active_clip.get_y(),
1377                            active_clip.right(),
1378                            active_clip.bottom(),
1379                        ];
1380                        let box_w_phys: f32 = rect.get_width() * scale;
1381                        let base_x_phys: f32 = (rect.get_x() * scale).round();
1382                        let mut line_glyphs: Vec<(Option<GpuGlyphPlacement>, f32)> =
1383                            Vec::with_capacity(32);
1384                        for (line_idx, line) in layout_res.get_lines().iter().enumerate() {
1385                            let line_y: f32 =
1386                                (rect.get_y() * scale + (line_idx as f32) * line_h_phys).round();
1387                            line_glyphs.clear();
1388                            let mut actual_line_w: f32 = 0.0;
1389                            for ch in line.get_text().chars() {
1390                                if ch == ' ' || ch == '\t' {
1391                                    let space_adv: f32 =
1392                                        measure_char_advance(ch, *style) * scale + letter_sp;
1393                                    actual_line_w += space_adv;
1394                                    line_glyphs.push((None, space_adv));
1395                                } else {
1396                                    let key: GlyphKey =
1397                                        GlyphKey::from_text_style(ch, phys_font_px, *style);
1398                                    let raster: &RasterizedGlyph =
1399                                        cpu_atlas.get_or_rasterize_with(key, &font_provider);
1400                                    let adv_phys: f32 =
1401                                        (raster.get_advance() as f32).max(1.0) + letter_sp;
1402                                    let placement: GpuGlyphPlacement =
1403                                        gpu_glyph_atlas.insert_or_get(key, raster);
1404                                    actual_line_w += adv_phys;
1405                                    line_glyphs.push((Some(placement), adv_phys));
1406                                }
1407                            }
1408                            let fit_scale: f32 =
1409                                if box_w_phys > 1.0 && actual_line_w > box_w_phys + 1.0 {
1410                                    (box_w_phys / actual_line_w).clamp(0.72, 1.0)
1411                                } else {
1412                                    1.0
1413                                };
1414                            let fitted_w: f32 = actual_line_w * fit_scale;
1415                            let align_x: f32 = match style.get_align() {
1416                                TextAlign::Left => 0.0,
1417                                TextAlign::Center => ((box_w_phys - fitted_w) * 0.5).max(0.0),
1418                                TextAlign::Right => (box_w_phys - fitted_w).max(0.0),
1419                            };
1420                            let mut pen_x: f32 = base_x_phys + align_x.round();
1421                            for &(placement_opt, adv_phys) in line_glyphs.iter() {
1422                                if let Some(placement) = placement_opt
1423                                    && placement.get_width() > 0
1424                                    && placement.get_height() > 0
1425                                {
1426                                    let gw: f32 = placement.get_width() as f32;
1427                                    let gh: f32 = placement.get_height() as f32;
1428                                    let glyph_y: f32 = line_y + ((line_h_phys - gh) * 0.5).round();
1429                                    let glyph_quad: [f32; 4] = [pen_x.round(), glyph_y, gw, gh];
1430                                    if Self::quad_intersects_clip(glyph_quad, active_clip) {
1431                                        let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
1432                                            PrimKind::GlyphAlpha8,
1433                                            0,
1434                                            0,
1435                                            tail_state.layer_id,
1436                                        );
1437                                        let glyph_prim: GpuPrimitiveInstance =
1438                                            GpuPrimitiveInstance {
1439                                                rect: glyph_quad,
1440                                                clip_rect: clip_arr,
1441                                                color_rgba: text_color_u32,
1442                                                aux_color_rgba: 0,
1443                                                uv_rect: placement.get_uv_rect(),
1444                                                radii_border: [0; 4],
1445                                                kind_flags,
1446                                                extra_param: 0,
1447                                            };
1448                                        Self::push_primitive_coalesced(
1449                                            batches,
1450                                            active_batches,
1451                                            &mut tail_state,
1452                                            clip_entry,
1453                                            glyph_prim,
1454                                            false,
1455                                            &mut coalesced_merges,
1456                                        );
1457                                        uploaded_instances += 1;
1458                                    } else {
1459                                        culled_instances += 1;
1460                                    }
1461                                }
1462                                pen_x += adv_phys * fit_scale;
1463                            }
1464                        }
1465                    } else {
1466                        let glyph_count: usize = if text.is_ascii() {
1467                            text.as_bytes()
1468                                .iter()
1469                                .filter(|byte_item: &&u8| **byte_item != b' ')
1470                                .count()
1471                                .max(1)
1472                        } else {
1473                            text.chars()
1474                                .filter(|char_item: &char| *char_item != ' ')
1475                                .count()
1476                                .max(1)
1477                        };
1478                        let text_instance: GpuQuadInstance = GpuQuadInstance {
1479                            rect: run_quad,
1480                            clip: [
1481                                active_clip.get_x(),
1482                                active_clip.get_y(),
1483                                active_clip.right(),
1484                                active_clip.bottom(),
1485                            ],
1486                            color: style.get_color().to_f32_array(),
1487                            secondary_color: [0.0; 4],
1488                            radii: [0.0; 4],
1489                            stroke_or_blur: style.get_font_size() * scale,
1490                            angle_rad: 0.0,
1491                            kind: GpuPrimitiveKind::Glyph as u32,
1492                            reserved: glyph_count as u32,
1493                        };
1494                        Self::push_instance_coalesced(
1495                            batches,
1496                            active_batches,
1497                            &mut tail_state,
1498                            clip_entry,
1499                            text_instance,
1500                            &mut coalesced_merges,
1501                        );
1502                        uploaded_instances += 1;
1503                    }
1504                }
1505                DrawCommand::TextCaret {
1506                    text_rect,
1507                    content_rect,
1508                    text,
1509                    style,
1510                    caret_height,
1511                    color,
1512                    multiline,
1513                } => {
1514                    if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
1515                        culled_instances += 1;
1516                        continue;
1517                    }
1518                    let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
1519                        text,
1520                        *style,
1521                        if *multiline {
1522                            Some(content_rect.get_width().max(1.0))
1523                        } else {
1524                            None
1525                        },
1526                    );
1527                    let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
1528                    let letter_sp: f32 = style.get_letter_spacing() * scale;
1529                    let last_w_phys: f32 = if let Some(line) = meas.get_lines().last() {
1530                        let font_provider: NativeSystemFont = readback.get_font_provider().clone();
1531                        let atlas: &mut GlyphAtlas = readback.get_mut_glyph_atlas();
1532                        let mut acc: f32 = 0.0;
1533                        for ch in line.get_text().chars() {
1534                            if ch == ' ' || ch == '\t' {
1535                                acc += measure_char_advance(ch, *style) * scale + letter_sp;
1536                            } else {
1537                                let key: GlyphKey =
1538                                    GlyphKey::from_text_style(ch, phys_font_px, *style);
1539                                let green_val: &RasterizedGlyph =
1540                                    atlas.get_or_rasterize_with(key, &font_provider);
1541                                acc += (green_val.get_advance() as f32).max(1.0) + letter_sp;
1542                            }
1543                        }
1544                        acc
1545                    } else {
1546                        0.0
1547                    };
1548                    let line_idx: usize = meas.get_lines().len().saturating_sub(1);
1549                    let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
1550                    let min_x_phys: f32 = content_rect.get_x() * scale;
1551                    let max_x_phys: f32 = ((content_rect.right() - 2.0) * scale).max(min_x_phys);
1552                    let caret_x_phys: f32 =
1553                        (text_rect.get_x() * scale + last_w_phys + trailing_gap_phys)
1554                            .min(max_x_phys)
1555                            .max(min_x_phys);
1556                    let caret_y: f32 = if *multiline {
1557                        (content_rect.get_y()
1558                            + (line_idx as f32) * meas.get_line_height_px()
1559                            + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
1560                        .min(content_rect.bottom() - caret_height)
1561                        .max(content_rect.get_y())
1562                    } else {
1563                        content_rect.get_y()
1564                            + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
1565                    };
1566                    let quad: [f32; 4] = [
1567                        caret_x_phys.round(),
1568                        (caret_y * scale).round(),
1569                        (1.5 * scale).max(1.0),
1570                        (caret_height * scale).max(2.0),
1571                    ];
1572                    if !Self::quad_intersects_clip(quad, active_clip) {
1573                        culled_instances += 1;
1574                        continue;
1575                    }
1576                    let inst: GpuQuadInstance = GpuQuadInstance {
1577                        rect: quad,
1578                        clip: [
1579                            active_clip.get_x(),
1580                            active_clip.get_y(),
1581                            active_clip.right(),
1582                            active_clip.bottom(),
1583                        ],
1584                        color: color.to_f32_array(),
1585                        secondary_color: [0.0; 4],
1586                        radii: [0.5 * scale; 4],
1587                        stroke_or_blur: 0.0,
1588                        angle_rad: 0.0,
1589                        kind: GpuPrimitiveKind::RoundedRect as u32,
1590                        reserved: 0,
1591                    };
1592                    Self::push_instance_coalesced(
1593                        batches,
1594                        active_batches,
1595                        &mut tail_state,
1596                        clip_entry,
1597                        inst,
1598                        &mut coalesced_merges,
1599                    );
1600                    uploaded_instances += 1;
1601                }
1602                DrawCommand::Image {
1603                    rect,
1604                    buffer,
1605                    radius,
1606                } => {
1607                    let snapped: Rect = snap_physical_rect(*rect, scale);
1608                    let quad: [f32; 4] = [
1609                        snapped.get_x(),
1610                        snapped.get_y(),
1611                        snapped.get_width(),
1612                        snapped.get_height(),
1613                    ];
1614                    if !Self::quad_intersects_clip(quad, active_clip) {
1615                        culled_instances += 1;
1616                        continue;
1617                    }
1618                    let uv_rect: [u16; 4] = gpu_image_atlas
1619                        .insert_or_get(
1620                            buffer.get_width(),
1621                            buffer.get_height(),
1622                            buffer.get_pixels().as_ref(),
1623                        )
1624                        .map_or([0, 0, u16::MAX, u16::MAX], |slot: GpuImagePlacement| {
1625                            slot.get_uv_rect()
1626                        });
1627                    let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
1628                    let img_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
1629                        rect: quad,
1630                        clip_rect: [
1631                            active_clip.get_x(),
1632                            active_clip.get_y(),
1633                            active_clip.right(),
1634                            active_clip.bottom(),
1635                        ],
1636                        color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
1637                        aux_color_rgba: 0,
1638                        uv_rect,
1639                        radii_border: [
1640                            GpuPrimitiveInstance::pack_u16_q4(
1641                                (radius.get_top_left() * scale).min(radius_cap),
1642                            ),
1643                            GpuPrimitiveInstance::pack_u16_q4(
1644                                (radius.get_top_right() * scale).min(radius_cap),
1645                            ),
1646                            GpuPrimitiveInstance::pack_u16_q4(
1647                                (radius.get_bottom_right() * scale).min(radius_cap),
1648                            ),
1649                            GpuPrimitiveInstance::pack_u16_q4(
1650                                (radius.get_bottom_left() * scale).min(radius_cap),
1651                            ),
1652                        ],
1653                        kind_flags: GpuPrimitiveInstance::pack_kind_flags(
1654                            PrimKind::ImageTexture,
1655                            0,
1656                            0,
1657                            tail_state.layer_id,
1658                        ),
1659                        extra_param: 0,
1660                    };
1661                    Self::push_primitive_coalesced(
1662                        batches,
1663                        active_batches,
1664                        &mut tail_state,
1665                        clip_entry,
1666                        img_prim,
1667                        false,
1668                        &mut coalesced_merges,
1669                    );
1670                    uploaded_instances += 1;
1671                }
1672                DrawCommand::SharedImage {
1673                    rect,
1674                    width,
1675                    height,
1676                    pixels,
1677                    radius,
1678                } => {
1679                    let snapped: Rect = snap_physical_rect(*rect, scale);
1680                    let quad: [f32; 4] = [
1681                        snapped.get_x(),
1682                        snapped.get_y(),
1683                        snapped.get_width(),
1684                        snapped.get_height(),
1685                    ];
1686                    if !Self::quad_intersects_clip(quad, active_clip) {
1687                        culled_instances += 1;
1688                        continue;
1689                    }
1690                    let uv_rect: [u16; 4] = gpu_image_atlas
1691                        .insert_or_get(*width, *height, pixels.as_slice())
1692                        .map_or([0, 0, u16::MAX, u16::MAX], |slot: GpuImagePlacement| {
1693                            slot.get_uv_rect()
1694                        });
1695                    let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
1696                    let img_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
1697                        rect: quad,
1698                        clip_rect: [
1699                            active_clip.get_x(),
1700                            active_clip.get_y(),
1701                            active_clip.right(),
1702                            active_clip.bottom(),
1703                        ],
1704                        color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
1705                        aux_color_rgba: 0,
1706                        uv_rect,
1707                        radii_border: [
1708                            GpuPrimitiveInstance::pack_u16_q4(
1709                                (radius.get_top_left() * scale).min(radius_cap),
1710                            ),
1711                            GpuPrimitiveInstance::pack_u16_q4(
1712                                (radius.get_top_right() * scale).min(radius_cap),
1713                            ),
1714                            GpuPrimitiveInstance::pack_u16_q4(
1715                                (radius.get_bottom_right() * scale).min(radius_cap),
1716                            ),
1717                            GpuPrimitiveInstance::pack_u16_q4(
1718                                (radius.get_bottom_left() * scale).min(radius_cap),
1719                            ),
1720                        ],
1721                        kind_flags: GpuPrimitiveInstance::pack_kind_flags(
1722                            PrimKind::ImageTexture,
1723                            0,
1724                            0,
1725                            tail_state.layer_id,
1726                        ),
1727                        extra_param: 0,
1728                    };
1729                    Self::push_primitive_coalesced(
1730                        batches,
1731                        active_batches,
1732                        &mut tail_state,
1733                        clip_entry,
1734                        img_prim,
1735                        false,
1736                        &mut coalesced_merges,
1737                    );
1738                    uploaded_instances += 1;
1739                }
1740                DrawCommand::Circle {
1741                    center,
1742                    radius,
1743                    color,
1744                } => {
1745                    let red_val: f32 = radius * scale;
1746                    let pad: f32 = 1.5;
1747                    let extent: f32 = red_val + pad;
1748                    let quad: [f32; 4] = [
1749                        center.get_x() * scale - extent,
1750                        center.get_y() * scale - extent,
1751                        extent * 2.0,
1752                        extent * 2.0,
1753                    ];
1754                    if !Self::quad_intersects_clip(quad, active_clip) {
1755                        culled_instances += 1;
1756                        continue;
1757                    }
1758                    let inst: GpuQuadInstance = GpuQuadInstance {
1759                        rect: quad,
1760                        clip: [
1761                            active_clip.get_x(),
1762                            active_clip.get_y(),
1763                            active_clip.right(),
1764                            active_clip.bottom(),
1765                        ],
1766                        color: color.to_f32_array(),
1767                        secondary_color: [0.0; 4],
1768                        radii: [red_val; 4],
1769                        stroke_or_blur: red_val,
1770                        angle_rad: 0.0,
1771                        kind: GpuPrimitiveKind::Circle as u32,
1772                        reserved: 0,
1773                    };
1774                    Self::push_instance_coalesced(
1775                        batches,
1776                        active_batches,
1777                        &mut tail_state,
1778                        clip_entry,
1779                        inst,
1780                        &mut coalesced_merges,
1781                    );
1782                    uploaded_instances += 1;
1783                }
1784                DrawCommand::Line {
1785                    from,
1786                    to,
1787                    color,
1788                    width,
1789                } => {
1790                    let fx0: f32 = from.get_x() * scale;
1791                    let fy0: f32 = from.get_y() * scale;
1792                    let fx1: f32 = to.get_x() * scale;
1793                    let fy1: f32 = to.get_y() * scale;
1794                    let dx: f32 = fx1 - fx0;
1795                    let dy: f32 = fy1 - fy0;
1796                    let stroke_px: f32 = (width * scale).max(1.0);
1797                    let pad: f32 = stroke_px * 0.5 + 1.5;
1798                    let min_x: f32 = fx0.min(fx1) - pad;
1799                    let min_y: f32 = fy0.min(fy1) - pad;
1800                    let max_x: f32 = fx0.max(fx1) + pad;
1801                    let max_y: f32 = fy0.max(fy1) + pad;
1802                    let quad: [f32; 4] = [
1803                        min_x,
1804                        min_y,
1805                        (max_x - min_x).max(2.0),
1806                        (max_y - min_y).max(2.0),
1807                    ];
1808                    if !Self::quad_intersects_clip(quad, active_clip) {
1809                        culled_instances += 1;
1810                        continue;
1811                    }
1812                    let inst: GpuQuadInstance = GpuQuadInstance {
1813                        rect: quad,
1814                        clip: [
1815                            active_clip.get_x(),
1816                            active_clip.get_y(),
1817                            active_clip.right(),
1818                            active_clip.bottom(),
1819                        ],
1820                        color: color.to_f32_array(),
1821                        secondary_color: [0.0; 4],
1822                        radii: [fx0, fy0, fx1, fy1],
1823                        stroke_or_blur: stroke_px,
1824                        angle_rad: dy.atan2(dx),
1825                        kind: GpuPrimitiveKind::Line as u32,
1826                        reserved: 0,
1827                    };
1828                    Self::push_instance_coalesced(
1829                        batches,
1830                        active_batches,
1831                        &mut tail_state,
1832                        clip_entry,
1833                        inst,
1834                        &mut coalesced_merges,
1835                    );
1836                    uploaded_instances += 1;
1837                }
1838                DrawCommand::Triangle { p0, p1, p2, color } => {
1839                    let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
1840                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
1841                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
1842                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
1843                    let quad: [f32; 4] = [
1844                        min_x,
1845                        min_y,
1846                        (max_x - min_x).max(2.0),
1847                        (max_y - min_y).max(2.0),
1848                    ];
1849                    if !Self::quad_intersects_clip(quad, active_clip) {
1850                        culled_instances += 1;
1851                        continue;
1852                    }
1853                    let inst: GpuQuadInstance = GpuQuadInstance {
1854                        rect: quad,
1855                        clip: [
1856                            active_clip.get_x(),
1857                            active_clip.get_y(),
1858                            active_clip.right(),
1859                            active_clip.bottom(),
1860                        ],
1861                        color: color.to_f32_array(),
1862                        secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
1863                        radii: [
1864                            p1.get_x() * scale,
1865                            p1.get_y() * scale,
1866                            p2.get_x() * scale,
1867                            p2.get_y() * scale,
1868                        ],
1869                        stroke_or_blur: 0.0,
1870                        angle_rad: 0.0,
1871                        kind: GpuPrimitiveKind::Triangle as u32,
1872                        reserved: 3,
1873                    };
1874                    Self::push_instance_coalesced(
1875                        batches,
1876                        active_batches,
1877                        &mut tail_state,
1878                        clip_entry,
1879                        inst,
1880                        &mut coalesced_merges,
1881                    );
1882                    uploaded_instances += 1;
1883                }
1884                DrawCommand::SpriteRegion {
1885                    rect,
1886                    buffer,
1887                    src_rect,
1888                    tint,
1889                } => {
1890                    let snapped: Rect = snap_physical_rect(*rect, scale);
1891                    let quad: [f32; 4] = [
1892                        snapped.get_x(),
1893                        snapped.get_y(),
1894                        snapped.get_width(),
1895                        snapped.get_height(),
1896                    ];
1897                    if !Self::quad_intersects_clip(quad, active_clip) {
1898                        culled_instances += 1;
1899                        continue;
1900                    }
1901                    let uv_rect: [u16; 4] = gpu_image_atlas
1902                        .insert_or_get(
1903                            buffer.get_width(),
1904                            buffer.get_height(),
1905                            buffer.get_pixels().as_ref(),
1906                        )
1907                        .map_or([0, 0, u16::MAX, u16::MAX], |slot: GpuImagePlacement| {
1908                            gpu_image_atlas.sub_uv_rect(
1909                                slot,
1910                                buffer.get_width(),
1911                                buffer.get_height(),
1912                                *src_rect,
1913                            )
1914                        });
1915                    let sprite_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
1916                        rect: quad,
1917                        clip_rect: [
1918                            active_clip.get_x(),
1919                            active_clip.get_y(),
1920                            active_clip.right(),
1921                            active_clip.bottom(),
1922                        ],
1923                        color_rgba: GpuPrimitiveInstance::pack_color_rgba8(*tint),
1924                        aux_color_rgba: 0,
1925                        uv_rect,
1926                        radii_border: [0; 4],
1927                        kind_flags: GpuPrimitiveInstance::pack_kind_flags(
1928                            PrimKind::ImageTexture,
1929                            0,
1930                            0,
1931                            tail_state.layer_id,
1932                        ),
1933                        extra_param: 0,
1934                    };
1935                    Self::push_primitive_coalesced(
1936                        batches,
1937                        active_batches,
1938                        &mut tail_state,
1939                        clip_entry,
1940                        sprite_prim,
1941                        false,
1942                        &mut coalesced_merges,
1943                    );
1944                    uploaded_instances += 1;
1945                }
1946                DrawCommand::ExternalSurface { rect, radius } => {
1947                    let snapped: Rect = snap_physical_rect(*rect, scale);
1948                    let quad: [f32; 4] = [
1949                        snapped.get_x(),
1950                        snapped.get_y(),
1951                        snapped.get_width(),
1952                        snapped.get_height(),
1953                    ];
1954                    if !Self::quad_intersects_clip(quad, active_clip) {
1955                        culled_instances += 1;
1956                        continue;
1957                    }
1958                    let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
1959                    let ext_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
1960                        rect: quad,
1961                        clip_rect: [
1962                            active_clip.get_x(),
1963                            active_clip.get_y(),
1964                            active_clip.right(),
1965                            active_clip.bottom(),
1966                        ],
1967                        color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
1968                        aux_color_rgba: 0,
1969                        uv_rect: [0, 0, u16::MAX, u16::MAX],
1970                        radii_border: [
1971                            GpuPrimitiveInstance::pack_u16_q4(
1972                                (radius.get_top_left() * scale).min(radius_cap),
1973                            ),
1974                            GpuPrimitiveInstance::pack_u16_q4(
1975                                (radius.get_top_right() * scale).min(radius_cap),
1976                            ),
1977                            GpuPrimitiveInstance::pack_u16_q4(
1978                                (radius.get_bottom_right() * scale).min(radius_cap),
1979                            ),
1980                            GpuPrimitiveInstance::pack_u16_q4(
1981                                (radius.get_bottom_left() * scale).min(radius_cap),
1982                            ),
1983                        ],
1984                        kind_flags: GpuPrimitiveInstance::pack_kind_flags(
1985                            PrimKind::ExternalGpuSurface,
1986                            0,
1987                            0,
1988                            tail_state.layer_id,
1989                        ),
1990                        extra_param: 0,
1991                    };
1992                    Self::push_primitive_coalesced(
1993                        batches,
1994                        active_batches,
1995                        &mut tail_state,
1996                        clip_entry,
1997                        ext_prim,
1998                        false,
1999                        &mut coalesced_merges,
2000                    );
2001                    uploaded_instances += 1;
2002                }
2003            }
2004        }
2005        let glyph_h_after: u32 = gpu_glyph_atlas.get_height();
2006        let img_w_after: u32 = gpu_image_atlas.get_width();
2007        let img_h_after: u32 = gpu_image_atlas.get_height();
2008        if glyph_h_after != glyph_h_before && glyph_h_after > 0 {
2009            let v_scale: f32 = (glyph_h_before as f32) / (glyph_h_after as f32);
2010            for batch in batches.iter_mut().take(*active_batches) {
2011                for prim in batch.get_mut_primitives().iter_mut() {
2012                    if prim.prim_kind() == PrimKind::GlyphAlpha8 {
2013                        let mut uv: [u16; 4] = prim.get_uv_rect();
2014                        uv[1] = ((f32::from(uv[1]) * v_scale).round().clamp(0.0, 65535.0)) as u16;
2015                        uv[3] = ((f32::from(uv[3]) * v_scale).round().clamp(0.0, 65535.0)) as u16;
2016                        prim.set_uv_rect(uv);
2017                    }
2018                }
2019            }
2020        }
2021        if (img_w_after != img_w_before || img_h_after != img_h_before)
2022            && img_w_after > 0
2023            && img_h_after > 0
2024        {
2025            let u_scale: f32 = (img_w_before as f32) / (img_w_after as f32);
2026            let v_scale: f32 = (img_h_before as f32) / (img_h_after as f32);
2027            for batch in batches.iter_mut().take(*active_batches) {
2028                for prim in batch.get_mut_primitives().iter_mut() {
2029                    if prim.prim_kind() == PrimKind::ImageTexture {
2030                        let mut uv: [u16; 4] = prim.get_uv_rect();
2031                        uv[0] = ((f32::from(uv[0]) * u_scale).round().clamp(0.0, 65535.0)) as u16;
2032                        uv[1] = ((f32::from(uv[1]) * v_scale).round().clamp(0.0, 65535.0)) as u16;
2033                        uv[2] = ((f32::from(uv[2]) * u_scale).round().clamp(0.0, 65535.0)) as u16;
2034                        uv[3] = ((f32::from(uv[3]) * v_scale).round().clamp(0.0, 65535.0)) as u16;
2035                        prim.set_uv_rect(uv);
2036                    }
2037                }
2038            }
2039        }
2040        let prim_upload_bytes: usize =
2041            uploaded_instances.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
2042        let upload_bytes: usize = prim_upload_bytes;
2043        let acquired_fence: u64 = match resource_ring
2044            .acquire_staging(prim_upload_bytes, GpuUploadPriority::RequiredFrame)
2045        {
2046            GpuRingAcquireResult::Acquired { fence_id, .. } => fence_id,
2047            GpuRingAcquireResult::DeferredFrameRingFull
2048            | GpuRingAcquireResult::DroppedPrefetchRingFull => {
2049                let prev: u64 =
2050                    GpuResourceRing::next_monotonic_fence(resource_ring.get_completed_fence_id());
2051                let _: usize = resource_ring.complete_fence(prev);
2052                match resource_ring
2053                    .acquire_staging(prim_upload_bytes, GpuUploadPriority::RequiredFrame)
2054                {
2055                    GpuRingAcquireResult::Acquired { fence_id, .. } => fence_id,
2056                    GpuRingAcquireResult::DeferredFrameRingFull
2057                    | GpuRingAcquireResult::DroppedPrefetchRingFull => {
2058                        resource_ring.get_next_fence_id()
2059                    }
2060                }
2061            }
2062        };
2063        if driver.get_surface_layer_handle() != 0 {
2064            let _: usize = gpu_glyph_atlas.flush_to_driver(driver);
2065            if !blur_passes.is_empty() && driver.supports_backdrop_blur_pass() {
2066                let _: usize = driver.execute_dual_kawase_blur_passes(phys_w, phys_h, blur_passes);
2067            }
2068        } else {
2069            gpu_glyph_atlas.get_mut_pending_dirty_rects().clear();
2070            gpu_glyph_atlas.set_needs_full_upload(false);
2071        }
2072        let active_slice: &[GpuBatch] = &batches[..(*active_batches).min(batches.len())];
2073        let submitted: usize = driver.submit_batches(phys_w, phys_h, clear_color, active_slice)?;
2074        *last_fence_id = acquired_fence;
2075        let hw_done: u64 = completed_gpu_fence();
2076        if driver.get_device_handle() != 0 && hw_done > 0 {
2077            let _: usize = resource_ring.complete_fence(hw_done.min(acquired_fence));
2078        } else {
2079            let retire_window: u64 = acquired_fence.saturating_sub(2);
2080            if retire_window > 0 {
2081                let _: usize = resource_ring.complete_fence(retire_window);
2082            }
2083        }
2084        *last_submitted_batches = submitted;
2085        *last_coalesced_merges = coalesced_merges;
2086        *last_culled_instances = culled_instances;
2087        *last_uploaded_instances = uploaded_instances;
2088        *last_uploaded_bytes = upload_bytes;
2089        *last_uploaded_primitive_bytes = prim_upload_bytes;
2090        let pixels: usize = if *enable_readback {
2091            let (_, px): (usize, usize) = readback.render(display_list, damage);
2092            *cpu_readback_frames = cpu_readback_frames.saturating_add(1);
2093            *last_cpu_rgba_upload_bytes = (phys_w as usize)
2094                .saturating_mul(phys_h as usize)
2095                .saturating_mul(4);
2096            px
2097        } else {
2098            *direct_gpu_frames = direct_gpu_frames.saturating_add(1);
2099            *last_cpu_rgba_upload_bytes = 0;
2100            (phys_w as usize).saturating_mul(phys_h as usize)
2101        };
2102        Ok((submitted, pixels))
2103    }
2104
2105    /// Converts `instance` into a 64-byte `GpuPrimitiveInstance` and appends it without allocating legacy 96-byte quad storage.
2106    ///
2107    /// # Arguments
2108    ///
2109    /// - `&mut Vec<GpuBatch>` - Persistent batch pool vector.
2110    /// - `&mut usize` - Active batch watermark for the current frame.
2111    /// - `&mut GpuBatchCoalesceState` - Unclipped containment and layer metadata for the active tail batch.
2112    /// - `GpuClipEntry` - Active physical scissor and corner-free interior safe clip rectangle.
2113    /// - `GpuQuadInstance` - Instance data compiled into 64-byte `GpuPrimitiveInstance`.
2114    /// - `&mut usize` - Running counter of cross-clip batch splits avoided by coalescing.
2115    fn push_instance_coalesced(
2116        batches: &mut Vec<GpuBatch>,
2117        active_batches: &mut usize,
2118        tail_state: &mut GpuBatchCoalesceState,
2119        clip_entry: GpuClipEntry,
2120        instance: GpuQuadInstance,
2121        coalesced_merges: &mut usize,
2122    ) {
2123        let is_blur: bool = instance.kind == GpuPrimitiveKind::BackdropBlur as u32;
2124        let base_prim: GpuPrimitiveInstance =
2125            GpuPrimitiveInstance::from_quad_instance(&instance, 0, tail_state.layer_id);
2126        Self::push_primitive_coalesced(
2127            batches,
2128            active_batches,
2129            tail_state,
2130            clip_entry,
2131            base_prim,
2132            is_blur,
2133            coalesced_merges,
2134        );
2135    }
2136
2137    /// Appends a 64-byte `GpuPrimitiveInstance` directly into the tail `GpuBatch` with zero legacy 96-byte `instances` duplication.
2138    ///
2139    /// # Arguments
2140    ///
2141    /// - `&mut Vec<GpuBatch>` - Persistent batch pool vector.
2142    /// - `&mut usize` - Active batch watermark for the current frame.
2143    /// - `&mut GpuBatchCoalesceState` - Unclipped containment and layer metadata for the active tail batch.
2144    /// - `GpuClipEntry` - Active physical scissor and corner-free interior safe clip rectangle.
2145    /// - `GpuPrimitiveInstance` - Tightly packed 64-byte GPU primitive record.
2146    /// - `bool` - True when the primitive is a backdrop blur boundary.
2147    /// - `&mut usize` - Running counter of cross-clip batch splits avoided by coalescing.
2148    fn push_primitive_coalesced(
2149        batches: &mut Vec<GpuBatch>,
2150        active_batches: &mut usize,
2151        tail_state: &mut GpuBatchCoalesceState,
2152        clip_entry: GpuClipEntry,
2153        base_prim: GpuPrimitiveInstance,
2154        is_blur: bool,
2155        coalesced_merges: &mut usize,
2156    ) {
2157        let scissor: Rect = clip_entry.scissor;
2158        let quad_rect: [f32; 4] = base_prim.get_rect();
2159        let inst_unclipped: bool =
2160            !is_blur && Self::quad_inside_rect(quad_rect, clip_entry.safe_inner);
2161        let prim: GpuPrimitiveInstance = if inst_unclipped {
2162            base_prim
2163        } else {
2164            base_prim.with_rounded_clip_bits(clip_entry.rounded_clip_bits)
2165        };
2166        let count: usize = *active_batches;
2167        if count > 0 {
2168            let last: &mut GpuBatch = &mut batches[count - 1];
2169            if last.get_primitives().len() < MAX_QUADS_PER_BATCH
2170                && last.get_layer_id() == tail_state.layer_id
2171                && last.get_scroll_offset() == tail_state.scroll_offset
2172            {
2173                let last_scissor: Rect = last.get_scissor();
2174                let blur_boundary: bool = tail_state.has_backdrop_blur || is_blur;
2175                if last_scissor == scissor && !blur_boundary {
2176                    last.get_mut_primitives().push(prim);
2177                    tail_state.all_unclipped = tail_state.all_unclipped && inst_unclipped;
2178                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, quad_rect);
2179                    return;
2180                }
2181                if !blur_boundary
2182                    && inst_unclipped
2183                    && Self::quad_inside_rect(quad_rect, last_scissor)
2184                {
2185                    last.get_mut_primitives().push(prim);
2186                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, quad_rect);
2187                    *coalesced_merges += 1;
2188                    return;
2189                }
2190                if !blur_boundary
2191                    && tail_state.all_unclipped
2192                    && Self::rect_inside_rect(tail_state.bounds, scissor)
2193                {
2194                    last.set_scissor(scissor);
2195                    last.get_mut_primitives().push(prim);
2196                    tail_state.all_unclipped = inst_unclipped;
2197                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, quad_rect);
2198                    *coalesced_merges += 1;
2199                    return;
2200                }
2201            }
2202        }
2203        if count < batches.len() {
2204            let slot: &mut GpuBatch = &mut batches[count];
2205            slot.set_scissor(scissor);
2206            slot.set_scroll_offset(tail_state.scroll_offset);
2207            slot.set_layer_id(tail_state.layer_id);
2208            slot.get_mut_instances().clear();
2209            slot.get_mut_primitives().clear();
2210            slot.get_mut_primitives().push(prim);
2211        } else {
2212            let mut batch: GpuBatch = GpuBatch::default();
2213            batch.set_scissor(scissor);
2214            batch.set_scroll_offset(tail_state.scroll_offset);
2215            batch.set_layer_id(tail_state.layer_id);
2216            batch.get_mut_primitives().reserve(512);
2217            batch.get_mut_primitives().push(prim);
2218            batches.push(batch);
2219        }
2220        *active_batches = count + 1;
2221        tail_state.all_unclipped = inst_unclipped;
2222        tail_state.has_backdrop_blur = is_blur;
2223        tail_state.bounds = Rect::new(quad_rect[0], quad_rect[1], quad_rect[2], quad_rect[3]);
2224    }
2225}