Skip to main content

euv_core/render/hardware/
impl.rs

1use super::*;
2
3/// `GpuDriver` implementation for `RecordingGpuDriver`.
4impl GpuDriver for RecordingGpuDriver {
5    /// Returns the configured backend tag.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Driver reference.
10    ///
11    /// # Returns
12    ///
13    /// - `GraphicsBackend` - Active backend tag.
14    fn backend(&self) -> GraphicsBackend {
15        self.get_backend_kind()
16    }
17
18    /// Selects the canonical native shader source for this backend.
19    ///
20    /// # Arguments
21    ///
22    /// - `&Self` - Driver reference.
23    ///
24    /// # Returns
25    ///
26    /// - `&'static str` - Native shader source string.
27    fn shader_source(&self) -> &'static str {
28        match self.get_backend_kind() {
29            GraphicsBackend::Metal => MSL_UI_SHADER,
30            GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => HLSL_UI_SHADER,
31            GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => GLSL_ES3_UI_FRAGMENT_SHADER,
32            GraphicsBackend::WebGpu
33            | GraphicsBackend::Vulkan
34            | GraphicsBackend::SoftwareCpu
35            | GraphicsBackend::Canvas2d
36            | GraphicsBackend::Headless => WGSL_UI_SHADER,
37        }
38    }
39
40    /// Records submitted GPU batches and returns draw-call count.
41    ///
42    /// # Arguments
43    ///
44    /// - `&Self` - Mutable driver.
45    /// - `u32` - Surface width.
46    /// - `u32` - Surface height.
47    /// - `Color` - Clear color.
48    /// - `&[GpuBatch]` - Ordered batches.
49    ///
50    /// # Returns
51    ///
52    /// - `Result<usize, PlatformError>` - Submitted batch count.
53    fn submit_batches(
54        &mut self,
55        _width: u32,
56        _height: u32,
57        clear_color: Color,
58        batches: &[GpuBatch],
59    ) -> Result<usize, PlatformError> {
60        let count: usize = batches.len();
61        let instances: usize = batches.iter().fold(0_usize, |acc: usize, b: &GpuBatch| {
62            acc + b.get_instances().len()
63        });
64        self.set_last_clear(clear_color);
65        self.set_last_instance_count(instances);
66        self.set_total_draw_calls(self.get_total_draw_calls().saturating_add(count));
67        Ok(count)
68    }
69}
70
71/// Instanced batch builder, order-preserving coalescer, and telemetry methods for `HardwareRenderer`.
72impl HardwareRenderer {
73    /// Creates a hardware renderer bound to `backend` with optional deterministic pixel readback.
74    ///
75    /// # Arguments
76    ///
77    /// - `GraphicsBackend` - Selected GPU backend.
78    /// - `u32` - Initial physical width.
79    /// - `u32` - Initial physical height.
80    /// - `RenderConfig` - Rendering configuration.
81    /// - `bool` - Whether software readback mirror is enabled.
82    ///
83    /// # Returns
84    ///
85    /// - `Self` - Configured hardware renderer.
86    #[must_use]
87    pub fn with_backend(
88        backend: GraphicsBackend,
89        width: u32,
90        height: u32,
91        config: RenderConfig,
92        enable_readback: bool,
93    ) -> Self {
94        Self::with_backend_and_font(
95            backend,
96            width,
97            height,
98            config,
99            enable_readback,
100            NativeSystemFont::deterministic(),
101        )
102    }
103
104    /// Creates a hardware renderer bound to `backend` with an explicit font provider for readback.
105    ///
106    /// # Arguments
107    ///
108    /// - `GraphicsBackend` - Selected GPU backend.
109    /// - `u32` - Initial physical width.
110    /// - `u32` - Initial physical height.
111    /// - `RenderConfig` - Rendering configuration.
112    /// - `bool` - Whether software readback mirror is enabled.
113    /// - `NativeSystemFont` - Font provider used by the software readback mirror.
114    ///
115    /// # Returns
116    ///
117    /// - `Self` - Configured hardware renderer.
118    #[must_use]
119    pub fn with_backend_and_font(
120        backend: GraphicsBackend,
121        width: u32,
122        height: u32,
123        config: RenderConfig,
124        enable_readback: bool,
125        font_provider: NativeSystemFont,
126    ) -> Self {
127        let driver: NativeGpuDriver = NativeGpuDriver::probe(backend);
128        Self {
129            driver,
130            batches: Vec::with_capacity(16),
131            active_batches: 0,
132            clip_stack: Vec::with_capacity(16),
133            last_submitted_batches: 0,
134            last_coalesced_merges: 0,
135            last_culled_instances: 0,
136            last_uploaded_instances: 0,
137            last_uploaded_bytes: 0,
138            readback: SoftwareRenderer::with_font_provider(width, height, config, font_provider),
139            enable_readback,
140            resource_ring: GpuResourceRing::default(),
141            direct_gpu_frames: 0,
142            cpu_readback_frames: 0,
143            last_cpu_rgba_upload_bytes: 0,
144            has_unsupported_effect: false,
145            last_fence_id: 0,
146        }
147    }
148
149    /// Captures an on-demand CPU reference framebuffer readback without enabling steady-state CPU mirroring.
150    ///
151    /// # Arguments
152    ///
153    /// - `&Self` - Mutable hardware renderer.
154    /// - `&DisplayList` - Display list to rasterize through the CPU reference backend.
155    /// - `DamageRegion` - Damage region to rasterize.
156    ///
157    /// # Returns
158    ///
159    /// - `&Framebuffer` - Rendered reference RGBA8 framebuffer.
160    pub fn capture_reference_readback(
161        &mut self,
162        display_list: &DisplayList,
163        damage: DamageRegion,
164    ) -> &Framebuffer {
165        let (_, _): (usize, usize) = self.get_mut_readback().render(display_list, damage);
166        self.get_readback().get_framebuffer()
167    }
168
169    /// Signals completion of GPU submission `fence_id` to release staging ring slots and reclaim deferred resources.
170    ///
171    /// # Arguments
172    ///
173    /// - `&Self` - Mutable hardware renderer.
174    /// - `u64` - Completed monotonic GPU fence identifier.
175    ///
176    /// # Returns
177    ///
178    /// - `usize` - Number of deferred GPU resources reclaimed.
179    pub fn complete_gpu_fence(&mut self, fence_id: u64) -> usize {
180        self.get_mut_resource_ring().complete_fence(fence_id)
181    }
182
183    /// Trims invisible persistent GPU scroll tile caches under memory pressure according to `retain_ratio`.
184    ///
185    /// # Arguments
186    ///
187    /// - `&Self` - Mutable hardware renderer.
188    /// - `f32` - Retained budget fraction in `(0.0..=1.0]`.
189    ///
190    /// # Returns
191    ///
192    /// - `usize` - Number of cold scroll tiles evicted to fence-deferred reclamation.
193    pub fn trim_gpu_caches(&mut self, retain_ratio: f32) -> usize {
194        self.get_mut_resource_ring()
195            .apply_retention_ratio(retain_ratio)
196    }
197
198    /// Returns latest-frame GPU batching and upload telemetry `(batches, coalesced_merges, culled_instances, uploaded_instances, uploaded_bytes)`.
199    ///
200    /// # Arguments
201    ///
202    /// - `&Self` - Hardware renderer reference.
203    ///
204    /// # Returns
205    ///
206    /// - `(usize, usize, usize, usize, usize)` - Latest frame batching and upload telemetry tuple.
207    #[must_use]
208    pub fn last_frame_telemetry(&self) -> (usize, usize, usize, usize, usize) {
209        (
210            self.get_last_submitted_batches(),
211            self.get_last_coalesced_merges(),
212            self.get_last_culled_instances(),
213            self.get_last_uploaded_instances(),
214            self.get_last_uploaded_bytes(),
215        )
216    }
217
218    /// Computes a deterministic 64-bit FNV-1a hash over all compiled GPU batch instances.
219    ///
220    /// # Arguments
221    ///
222    /// - `&Self` - Hardware renderer reference.
223    ///
224    /// # Returns
225    ///
226    /// - `u64` - Deterministic batch geometry hash.
227    #[must_use]
228    pub fn batch_hash(&self) -> u64 {
229        let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
230        let active: usize = self.get_active_batches().min(self.get_batches().len());
231        for batch in self.get_batches()[..active].iter() {
232            for inst in batch.get_instances().iter() {
233                for v in inst
234                    .get_rect()
235                    .iter()
236                    .chain(inst.get_color().iter())
237                    .chain(inst.get_radii().iter())
238                {
239                    hash ^= v.to_bits() as u64;
240                    hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
241                }
242            }
243        }
244        hash
245    }
246
247    /// Returns `true` when physical quad `quad = [x, y, w, h]` lies completely inside `container`.
248    ///
249    /// # Arguments
250    ///
251    /// - `[f32; 4]` - Physical quad bounds `[x, y, width, height]`.
252    /// - `Rect` - Enclosing physical clip rectangle.
253    ///
254    /// # Returns
255    ///
256    /// - `bool` - True when no fragment of `quad` extends outside `container`.
257    #[inline(always)]
258    #[must_use]
259    fn quad_inside_rect(quad: [f32; 4], container: Rect) -> bool {
260        let qx0: f32 = quad[0];
261        let qy0: f32 = quad[1];
262        let qx1: f32 = qx0 + quad[2];
263        let qy1: f32 = qy0 + quad[3];
264        let x_in: bool = qx0 >= container.get_x() && qx1 <= container.right();
265        let y_in: bool = qy0 >= container.get_y() && qy1 <= container.bottom();
266        container.get_width() > 0.0 && container.get_height() > 0.0 && x_in && y_in
267    }
268
269    /// Returns `true` when `quad` intersects `clip` with strictly positive area.
270    ///
271    /// # Arguments
272    ///
273    /// - `[f32; 4]` - Physical quad bounds `[x, y, width, height]`.
274    /// - `Rect` - Active physical scissor clip.
275    ///
276    /// # Returns
277    ///
278    /// - `bool` - True when at least part of `quad` falls inside `clip`.
279    #[inline(always)]
280    #[must_use]
281    fn quad_intersects_clip(quad: [f32; 4], clip: Rect) -> bool {
282        let qw: f32 = quad[2];
283        let qh: f32 = quad[3];
284        let quad_empty: bool = qw <= 0.0 || qh <= 0.0;
285        let clip_empty: bool = clip.get_width() <= 0.0 || clip.get_height() <= 0.0;
286        if quad_empty || clip_empty {
287            return false;
288        }
289        let qx0: f32 = quad[0];
290        let qy0: f32 = quad[1];
291        let qx1: f32 = qx0 + qw;
292        let qy1: f32 = qy0 + qh;
293        let x_hit: bool = qx1 > clip.get_x() && qx0 < clip.right();
294        let y_hit: bool = qy1 > clip.get_y() && qy0 < clip.bottom();
295        x_hit && y_hit
296    }
297
298    /// Returns `true` when `inner` lies completely inside `outer`.
299    ///
300    /// # Arguments
301    ///
302    /// - `Rect` - Candidate inner rectangle.
303    /// - `Rect` - Candidate outer enclosing rectangle.
304    ///
305    /// # Returns
306    ///
307    /// - `bool` - True when `inner` is contained inside `outer`.
308    #[inline(always)]
309    #[must_use]
310    fn rect_inside_rect(inner: Rect, outer: Rect) -> bool {
311        let x_in: bool = inner.get_x() >= outer.get_x() && inner.right() <= outer.right();
312        let y_in: bool = inner.get_y() >= outer.get_y() && inner.bottom() <= outer.bottom();
313        x_in && y_in
314    }
315
316    /// Returns the union bounding box of `existing` and physical quad `quad = [x, y, w, h]`.
317    ///
318    /// # Arguments
319    ///
320    /// - `Rect` - Existing bounding box.
321    /// - `[f32; 4]` - Newly appended quad bounds `[x, y, width, height]`.
322    ///
323    /// # Returns
324    ///
325    /// - `Rect` - Enclosing union rectangle.
326    #[inline(always)]
327    #[must_use]
328    fn union_rect_quad(existing: Rect, quad: [f32; 4]) -> Rect {
329        let x0: f32 = existing.get_x().min(quad[0]);
330        let y0: f32 = existing.get_y().min(quad[1]);
331        let x1: f32 = existing.right().max(quad[0] + quad[2]);
332        let y1: f32 = existing.bottom().max(quad[1] + quad[3]);
333        Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
334    }
335
336    /// Compiles `display_list` into order-preserving coalesced GPU instanced batches and submits them to the GPU driver.
337    ///
338    /// # Arguments
339    ///
340    /// - `&Self` - Mutable hardware renderer.
341    /// - `&DisplayList` - Backend-agnostic draw command stream.
342    /// - `DamageRegion` - Active damage region for readback mirroring.
343    ///
344    /// # Returns
345    ///
346    /// - `Result<(usize, usize), PlatformError>` - Tuple of `(draw_batches, pixels_shaded)`.
347    pub fn render(
348        &mut self,
349        display_list: &DisplayList,
350        damage: DamageRegion,
351    ) -> Result<(usize, usize), PlatformError> {
352        let scale: f32 = display_list.get_scale_factor().max(0.5);
353        let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
354        let phys_h: u32 =
355            ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
356        let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
357        let full_entry: GpuClipEntry = GpuClipEntry {
358            scissor: full_clip,
359            safe_inner: full_clip,
360        };
361        let Self {
362            driver,
363            batches,
364            active_batches,
365            clip_stack,
366            last_submitted_batches,
367            last_coalesced_merges,
368            last_culled_instances,
369            last_uploaded_instances,
370            last_uploaded_bytes,
371            readback,
372            enable_readback,
373            resource_ring,
374            direct_gpu_frames,
375            cpu_readback_frames,
376            last_cpu_rgba_upload_bytes,
377            has_unsupported_effect,
378            last_fence_id,
379        } = self;
380        clip_stack.clear();
381        clip_stack.push(full_entry);
382        *active_batches = 0;
383        *has_unsupported_effect = false;
384        let mut tail_state: GpuBatchCoalesceState = GpuBatchCoalesceState::default();
385        let mut coalesced_merges: usize = 0;
386        let mut culled_instances: usize = 0;
387        let mut uploaded_instances: usize = 0;
388        let mut clear_color: Color = COLOR_WHITE;
389        for cmd in display_list.get_commands().iter() {
390            let clip_entry: GpuClipEntry = clip_stack.last().copied().unwrap_or(full_entry);
391            let active_clip: Rect = clip_entry.scissor;
392            match cmd {
393                DrawCommand::Clear(c) => {
394                    clear_color = *c;
395                }
396                DrawCommand::PushClip(rect) => {
397                    let phys: Rect = snap_physical_rect(*rect, scale);
398                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
399                    let next_safe: Rect = clip_entry.safe_inner.intersect(phys).unwrap_or_default();
400                    clip_stack.push(GpuClipEntry {
401                        scissor: next_scissor,
402                        safe_inner: next_safe,
403                    });
404                }
405                DrawCommand::PushRoundedClip { rect, radius } => {
406                    let phys: Rect = snap_physical_rect(*rect, scale);
407                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
408                    let max_r: f32 = (radius.max_radius() * scale).ceil();
409                    let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
410                    let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
411                    let rounded_safe: Rect =
412                        Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
413                    let next_safe: Rect = clip_entry
414                        .safe_inner
415                        .intersect(rounded_safe)
416                        .unwrap_or_default();
417                    clip_stack.push(GpuClipEntry {
418                        scissor: next_scissor,
419                        safe_inner: next_safe,
420                    });
421                }
422                DrawCommand::PopClip => {
423                    if clip_stack.len() > 1 {
424                        let _: Option<GpuClipEntry> = clip_stack.pop();
425                    }
426                }
427                DrawCommand::FillRoundedRect {
428                    rect,
429                    color,
430                    radius,
431                    border,
432                } => {
433                    let snapped: Rect = snap_physical_rect(*rect, scale);
434                    let quad: [f32; 4] = [
435                        snapped.get_x(),
436                        snapped.get_y(),
437                        snapped.get_width(),
438                        snapped.get_height(),
439                    ];
440                    if !Self::quad_intersects_clip(quad, active_clip) {
441                        culled_instances += 1;
442                        continue;
443                    }
444                    let bw: f32 = if border.get_width() > 0.0 {
445                        (border.get_width() * scale).max(1.0)
446                    } else {
447                        0.0
448                    };
449                    let inst: GpuQuadInstance = GpuQuadInstance {
450                        rect: quad,
451                        clip: [
452                            active_clip.get_x(),
453                            active_clip.get_y(),
454                            active_clip.right(),
455                            active_clip.bottom(),
456                        ],
457                        color: color.to_f32_array(),
458                        secondary_color: border.get_color().to_f32_array(),
459                        radii: [
460                            radius.get_top_left() * scale,
461                            radius.get_top_right() * scale,
462                            radius.get_bottom_right() * scale,
463                            radius.get_bottom_left() * scale,
464                        ],
465                        stroke_or_blur: bw,
466                        angle_rad: 0.0,
467                        kind: GpuPrimitiveKind::RoundedRect as u32,
468                        reserved: 0,
469                    };
470                    Self::push_instance_coalesced(
471                        batches,
472                        active_batches,
473                        &mut tail_state,
474                        clip_entry,
475                        inst,
476                        &mut coalesced_merges,
477                    );
478                    uploaded_instances += 1;
479                }
480                DrawCommand::LinearGradientRect {
481                    rect,
482                    gradient,
483                    radius,
484                } => {
485                    let snapped: Rect = snap_physical_rect(*rect, scale);
486                    let quad: [f32; 4] = [
487                        snapped.get_x(),
488                        snapped.get_y(),
489                        snapped.get_width(),
490                        snapped.get_height(),
491                    ];
492                    if !Self::quad_intersects_clip(quad, active_clip) {
493                        culled_instances += 1;
494                        continue;
495                    }
496                    let inst: GpuQuadInstance = GpuQuadInstance {
497                        rect: quad,
498                        clip: [
499                            active_clip.get_x(),
500                            active_clip.get_y(),
501                            active_clip.right(),
502                            active_clip.bottom(),
503                        ],
504                        color: gradient.get_start_color().to_f32_array(),
505                        secondary_color: gradient.get_end_color().to_f32_array(),
506                        radii: [
507                            radius.get_top_left() * scale,
508                            radius.get_top_right() * scale,
509                            radius.get_bottom_right() * scale,
510                            radius.get_bottom_left() * scale,
511                        ],
512                        stroke_or_blur: 0.0,
513                        angle_rad: gradient.get_angle_deg().to_radians(),
514                        kind: GpuPrimitiveKind::Gradient as u32,
515                        reserved: 0,
516                    };
517                    Self::push_instance_coalesced(
518                        batches,
519                        active_batches,
520                        &mut tail_state,
521                        clip_entry,
522                        inst,
523                        &mut coalesced_merges,
524                    );
525                    uploaded_instances += 1;
526                }
527                DrawCommand::BoxShadow {
528                    rect,
529                    radius,
530                    shadow,
531                } => {
532                    let spread: f32 = shadow.get_spread_radius() * scale;
533                    let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(96.0);
534                    let sigma: f32 = (blur * 0.5).max(0.75);
535                    let pad: f32 = (sigma * 3.0).ceil();
536                    let base_rect: Rect = snap_physical_rect(*rect, scale);
537                    let caster_x: f32 =
538                        base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
539                    let caster_y: f32 =
540                        base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
541                    let caster_w: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
542                    let caster_h: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
543                    let quad: [f32; 4] = [
544                        caster_x - pad,
545                        caster_y - pad,
546                        caster_w + pad * 2.0,
547                        caster_h + pad * 2.0,
548                    ];
549                    if !Self::quad_intersects_clip(quad, active_clip) {
550                        culled_instances += 1;
551                        continue;
552                    }
553                    let inst: GpuQuadInstance = GpuQuadInstance {
554                        rect: quad,
555                        clip: [
556                            active_clip.get_x(),
557                            active_clip.get_y(),
558                            active_clip.right(),
559                            active_clip.bottom(),
560                        ],
561                        color: shadow.get_color().to_f32_array(),
562                        secondary_color: [0.0; 4],
563                        radii: [
564                            (radius.get_top_left() * scale + spread).max(0.0),
565                            (radius.get_top_right() * scale + spread).max(0.0),
566                            (radius.get_bottom_right() * scale + spread).max(0.0),
567                            (radius.get_bottom_left() * scale + spread).max(0.0),
568                        ],
569                        stroke_or_blur: sigma,
570                        angle_rad: pad,
571                        kind: GpuPrimitiveKind::Shadow as u32,
572                        reserved: 0,
573                    };
574                    Self::push_instance_coalesced(
575                        batches,
576                        active_batches,
577                        &mut tail_state,
578                        clip_entry,
579                        inst,
580                        &mut coalesced_merges,
581                    );
582                    uploaded_instances += 1;
583                }
584                DrawCommand::BackdropBlur {
585                    rect,
586                    radius,
587                    blur_radius,
588                } => {
589                    *has_unsupported_effect = true;
590                    let snapped: Rect = snap_physical_rect(*rect, scale);
591                    let quad: [f32; 4] = [
592                        snapped.get_x(),
593                        snapped.get_y(),
594                        snapped.get_width(),
595                        snapped.get_height(),
596                    ];
597                    if !Self::quad_intersects_clip(quad, active_clip) {
598                        culled_instances += 1;
599                        continue;
600                    }
601                    let inst: GpuQuadInstance = GpuQuadInstance {
602                        rect: quad,
603                        clip: [
604                            active_clip.get_x(),
605                            active_clip.get_y(),
606                            active_clip.right(),
607                            active_clip.bottom(),
608                        ],
609                        color: [1.0, 1.0, 1.0, 1.0],
610                        secondary_color: [0.0; 4],
611                        radii: [
612                            radius.get_top_left() * scale,
613                            radius.get_top_right() * scale,
614                            radius.get_bottom_right() * scale,
615                            radius.get_bottom_left() * scale,
616                        ],
617                        stroke_or_blur: (*blur_radius * scale).clamp(0.5, 96.0),
618                        angle_rad: 0.0,
619                        kind: GpuPrimitiveKind::BackdropBlur as u32,
620                        reserved: 0,
621                    };
622                    Self::push_instance_coalesced(
623                        batches,
624                        active_batches,
625                        &mut tail_state,
626                        clip_entry,
627                        inst,
628                        &mut coalesced_merges,
629                    );
630                    uploaded_instances += 1;
631                }
632                DrawCommand::TextRun { rect, text, style } => {
633                    let quad: [f32; 4] = [
634                        rect.get_x() * scale,
635                        rect.get_y() * scale,
636                        rect.get_width() * scale,
637                        rect.get_height() * scale,
638                    ];
639                    if !Self::quad_intersects_clip(quad, active_clip) {
640                        culled_instances += 1;
641                        continue;
642                    }
643                    let glyph_count: usize = if text.is_ascii() {
644                        text.as_bytes()
645                            .iter()
646                            .filter(|b: &&u8| **b != b' ')
647                            .count()
648                            .max(1)
649                    } else {
650                        text.chars().filter(|c: &char| *c != ' ').count().max(1)
651                    };
652                    let inst: GpuQuadInstance = GpuQuadInstance {
653                        rect: quad,
654                        clip: [
655                            active_clip.get_x(),
656                            active_clip.get_y(),
657                            active_clip.right(),
658                            active_clip.bottom(),
659                        ],
660                        color: style.get_color().to_f32_array(),
661                        secondary_color: [0.0; 4],
662                        radii: [0.0; 4],
663                        stroke_or_blur: style.get_font_size() * scale,
664                        angle_rad: 0.0,
665                        kind: GpuPrimitiveKind::Glyph as u32,
666                        reserved: glyph_count as u32,
667                    };
668                    Self::push_instance_coalesced(
669                        batches,
670                        active_batches,
671                        &mut tail_state,
672                        clip_entry,
673                        inst,
674                        &mut coalesced_merges,
675                    );
676                    uploaded_instances += 1;
677                }
678                DrawCommand::TextCaret {
679                    text_rect,
680                    content_rect,
681                    text,
682                    style,
683                    caret_height,
684                    color,
685                    multiline,
686                } => {
687                    if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
688                        culled_instances += 1;
689                        continue;
690                    }
691                    let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
692                        text,
693                        *style,
694                        if *multiline {
695                            Some(content_rect.get_width().max(1.0))
696                        } else {
697                            None
698                        },
699                    );
700                    let last_w: f32 = meas
701                        .get_lines()
702                        .last()
703                        .map(TextLine::get_width)
704                        .unwrap_or(0.0);
705                    let line_idx: usize = meas.get_lines().len().saturating_sub(1);
706                    let trailing_gap: f32 = if last_w > 0.0 { 1.5 } else { 0.0 };
707                    let min_x: f32 = content_rect.get_x();
708                    let max_x: f32 = (content_rect.right() - 2.0).max(min_x);
709                    let caret_x: f32 = (text_rect.get_x() + last_w + trailing_gap)
710                        .min(max_x)
711                        .max(min_x);
712                    let caret_y: f32 = if *multiline {
713                        (content_rect.get_y()
714                            + (line_idx as f32) * meas.get_line_height_px()
715                            + ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
716                        .min(content_rect.bottom() - caret_height)
717                        .max(content_rect.get_y())
718                    } else {
719                        content_rect.get_y()
720                            + ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
721                    };
722                    let quad: [f32; 4] = [
723                        caret_x * scale,
724                        caret_y * scale,
725                        (1.5 * scale).max(1.0),
726                        (caret_height * scale).max(2.0),
727                    ];
728                    if !Self::quad_intersects_clip(quad, active_clip) {
729                        culled_instances += 1;
730                        continue;
731                    }
732                    let inst: GpuQuadInstance = GpuQuadInstance {
733                        rect: quad,
734                        clip: [
735                            active_clip.get_x(),
736                            active_clip.get_y(),
737                            active_clip.right(),
738                            active_clip.bottom(),
739                        ],
740                        color: color.to_f32_array(),
741                        secondary_color: [0.0; 4],
742                        radii: [0.5 * scale; 4],
743                        stroke_or_blur: 0.0,
744                        angle_rad: 0.0,
745                        kind: GpuPrimitiveKind::RoundedRect as u32,
746                        reserved: 0,
747                    };
748                    Self::push_instance_coalesced(
749                        batches,
750                        active_batches,
751                        &mut tail_state,
752                        clip_entry,
753                        inst,
754                        &mut coalesced_merges,
755                    );
756                    uploaded_instances += 1;
757                }
758                DrawCommand::Image { rect, radius, .. } => {
759                    let snapped: Rect = snap_physical_rect(*rect, scale);
760                    let quad: [f32; 4] = [
761                        snapped.get_x(),
762                        snapped.get_y(),
763                        snapped.get_width(),
764                        snapped.get_height(),
765                    ];
766                    if !Self::quad_intersects_clip(quad, active_clip) {
767                        culled_instances += 1;
768                        continue;
769                    }
770                    let inst: GpuQuadInstance = GpuQuadInstance {
771                        rect: quad,
772                        clip: [
773                            active_clip.get_x(),
774                            active_clip.get_y(),
775                            active_clip.right(),
776                            active_clip.bottom(),
777                        ],
778                        color: [1.0, 1.0, 1.0, 1.0],
779                        secondary_color: [0.0; 4],
780                        radii: [
781                            radius.get_top_left() * scale,
782                            radius.get_top_right() * scale,
783                            radius.get_bottom_right() * scale,
784                            radius.get_bottom_left() * scale,
785                        ],
786                        stroke_or_blur: 0.0,
787                        angle_rad: 0.0,
788                        kind: GpuPrimitiveKind::TexturedQuad as u32,
789                        reserved: 0,
790                    };
791                    Self::push_instance_coalesced(
792                        batches,
793                        active_batches,
794                        &mut tail_state,
795                        clip_entry,
796                        inst,
797                        &mut coalesced_merges,
798                    );
799                    uploaded_instances += 1;
800                }
801                DrawCommand::Circle {
802                    center,
803                    radius,
804                    color,
805                } => {
806                    let r: f32 = radius * scale;
807                    let quad: [f32; 4] = [
808                        center.get_x() * scale - r,
809                        center.get_y() * scale - r,
810                        r * 2.0,
811                        r * 2.0,
812                    ];
813                    if !Self::quad_intersects_clip(quad, active_clip) {
814                        culled_instances += 1;
815                        continue;
816                    }
817                    let inst: GpuQuadInstance = GpuQuadInstance {
818                        rect: quad,
819                        clip: [
820                            active_clip.get_x(),
821                            active_clip.get_y(),
822                            active_clip.right(),
823                            active_clip.bottom(),
824                        ],
825                        color: color.to_f32_array(),
826                        secondary_color: [0.0; 4],
827                        radii: [r; 4],
828                        stroke_or_blur: 0.0,
829                        angle_rad: 0.0,
830                        kind: GpuPrimitiveKind::Circle as u32,
831                        reserved: 0,
832                    };
833                    Self::push_instance_coalesced(
834                        batches,
835                        active_batches,
836                        &mut tail_state,
837                        clip_entry,
838                        inst,
839                        &mut coalesced_merges,
840                    );
841                    uploaded_instances += 1;
842                }
843                DrawCommand::Line {
844                    from,
845                    to,
846                    color,
847                    width,
848                } => {
849                    let dx: f32 = (to.get_x() - from.get_x()) * scale;
850                    let dy: f32 = (to.get_y() - from.get_y()) * scale;
851                    let x0: f32 = from.get_x().min(to.get_x()) * scale;
852                    let y0: f32 = from.get_y().min(to.get_y()) * scale;
853                    let w: f32 = dx.abs().max(width * scale);
854                    let h: f32 = dy.abs().max(width * scale);
855                    let quad: [f32; 4] = [x0, y0, w, h];
856                    if !Self::quad_intersects_clip(quad, active_clip) {
857                        culled_instances += 1;
858                        continue;
859                    }
860                    let inst: GpuQuadInstance = GpuQuadInstance {
861                        rect: quad,
862                        clip: [
863                            active_clip.get_x(),
864                            active_clip.get_y(),
865                            active_clip.right(),
866                            active_clip.bottom(),
867                        ],
868                        color: color.to_f32_array(),
869                        secondary_color: [0.0; 4],
870                        radii: [
871                            from.get_x() * scale,
872                            from.get_y() * scale,
873                            to.get_x() * scale,
874                            to.get_y() * scale,
875                        ],
876                        stroke_or_blur: width * scale,
877                        angle_rad: dy.atan2(dx),
878                        kind: GpuPrimitiveKind::Line as u32,
879                        reserved: 0,
880                    };
881                    Self::push_instance_coalesced(
882                        batches,
883                        active_batches,
884                        &mut tail_state,
885                        clip_entry,
886                        inst,
887                        &mut coalesced_merges,
888                    );
889                    uploaded_instances += 1;
890                }
891                DrawCommand::Triangle { p0, p1, p2, color } => {
892                    let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale;
893                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale;
894                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale;
895                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale;
896                    let quad: [f32; 4] = [
897                        min_x,
898                        min_y,
899                        (max_x - min_x).max(1.0),
900                        (max_y - min_y).max(1.0),
901                    ];
902                    if !Self::quad_intersects_clip(quad, active_clip) {
903                        culled_instances += 1;
904                        continue;
905                    }
906                    let inst: GpuQuadInstance = GpuQuadInstance {
907                        rect: quad,
908                        clip: [
909                            active_clip.get_x(),
910                            active_clip.get_y(),
911                            active_clip.right(),
912                            active_clip.bottom(),
913                        ],
914                        color: color.to_f32_array(),
915                        secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
916                        radii: [
917                            p1.get_x() * scale,
918                            p1.get_y() * scale,
919                            p2.get_x() * scale,
920                            p2.get_y() * scale,
921                        ],
922                        stroke_or_blur: 0.0,
923                        angle_rad: 0.0,
924                        kind: GpuPrimitiveKind::Triangle as u32,
925                        reserved: 3,
926                    };
927                    Self::push_instance_coalesced(
928                        batches,
929                        active_batches,
930                        &mut tail_state,
931                        clip_entry,
932                        inst,
933                        &mut coalesced_merges,
934                    );
935                    uploaded_instances += 1;
936                }
937                DrawCommand::SpriteRegion { rect, tint, .. } => {
938                    let snapped: Rect = snap_physical_rect(*rect, scale);
939                    let quad: [f32; 4] = [
940                        snapped.get_x(),
941                        snapped.get_y(),
942                        snapped.get_width(),
943                        snapped.get_height(),
944                    ];
945                    if !Self::quad_intersects_clip(quad, active_clip) {
946                        culled_instances += 1;
947                        continue;
948                    }
949                    let inst: GpuQuadInstance = GpuQuadInstance {
950                        rect: quad,
951                        clip: [
952                            active_clip.get_x(),
953                            active_clip.get_y(),
954                            active_clip.right(),
955                            active_clip.bottom(),
956                        ],
957                        color: tint.to_f32_array(),
958                        secondary_color: [0.0; 4],
959                        radii: [0.0; 4],
960                        stroke_or_blur: 0.0,
961                        angle_rad: 0.0,
962                        kind: GpuPrimitiveKind::TexturedQuad as u32,
963                        reserved: 1,
964                    };
965                    Self::push_instance_coalesced(
966                        batches,
967                        active_batches,
968                        &mut tail_state,
969                        clip_entry,
970                        inst,
971                        &mut coalesced_merges,
972                    );
973                    uploaded_instances += 1;
974                }
975            }
976        }
977        let upload_bytes: usize = uploaded_instances.saturating_mul(GPU_QUAD_INSTANCE_BYTES);
978        let acquired_fence: u64 = match resource_ring
979            .acquire_staging(upload_bytes, GpuUploadPriority::RequiredFrame)
980        {
981            GpuRingAcquireResult::Acquired { fence_id, .. } => fence_id,
982            GpuRingAcquireResult::DeferredFrameRingFull
983            | GpuRingAcquireResult::DroppedPrefetchRingFull => {
984                let prev: u64 = resource_ring.get_completed_fence_id().saturating_add(1);
985                let _: usize = resource_ring.complete_fence(prev);
986                match resource_ring.acquire_staging(upload_bytes, GpuUploadPriority::RequiredFrame)
987                {
988                    GpuRingAcquireResult::Acquired { fence_id, .. } => fence_id,
989                    GpuRingAcquireResult::DeferredFrameRingFull
990                    | GpuRingAcquireResult::DroppedPrefetchRingFull => {
991                        resource_ring.get_next_fence_id()
992                    }
993                }
994            }
995        };
996        let active_slice: &[GpuBatch] = &batches[..(*active_batches).min(batches.len())];
997        let submitted: usize = driver.submit_batches(phys_w, phys_h, clear_color, active_slice)?;
998        *last_fence_id = acquired_fence;
999        let retire_window: u64 = acquired_fence.saturating_sub(2);
1000        if retire_window > 0 {
1001            let _: usize = resource_ring.complete_fence(retire_window);
1002        }
1003        *last_submitted_batches = submitted;
1004        *last_coalesced_merges = coalesced_merges;
1005        *last_culled_instances = culled_instances;
1006        *last_uploaded_instances = uploaded_instances;
1007        *last_uploaded_bytes = upload_bytes;
1008        let pixels: usize = if *enable_readback {
1009            let (_, px): (usize, usize) = readback.render(display_list, damage);
1010            *cpu_readback_frames = cpu_readback_frames.saturating_add(1);
1011            *last_cpu_rgba_upload_bytes = (phys_w as usize)
1012                .saturating_mul(phys_h as usize)
1013                .saturating_mul(4);
1014            px
1015        } else {
1016            *direct_gpu_frames = direct_gpu_frames.saturating_add(1);
1017            *last_cpu_rgba_upload_bytes = 0;
1018            (phys_w as usize).saturating_mul(phys_h as usize)
1019        };
1020        Ok((submitted, pixels))
1021    }
1022
1023    /// Appends `instance` in strict draw order into the tail `GpuBatch` when clip-compatible, or opens the next reusable batch slot.
1024    ///
1025    /// # Arguments
1026    ///
1027    /// - `&mut Vec<GpuBatch>` - Persistent batch pool vector.
1028    /// - `&mut usize` - Active batch watermark for the current frame.
1029    /// - `&mut GpuBatchCoalesceState` - Unclipped containment metadata for the active tail batch.
1030    /// - `GpuClipEntry` - Active physical scissor and corner-free interior safe clip rectangle.
1031    /// - `GpuQuadInstance` - Instance data to batch in exact back-to-front order.
1032    /// - `&mut usize` - Running counter of cross-clip batch splits avoided by coalescing.
1033    fn push_instance_coalesced(
1034        batches: &mut Vec<GpuBatch>,
1035        active_batches: &mut usize,
1036        tail_state: &mut GpuBatchCoalesceState,
1037        clip_entry: GpuClipEntry,
1038        instance: GpuQuadInstance,
1039        coalesced_merges: &mut usize,
1040    ) {
1041        let scissor: Rect = clip_entry.scissor;
1042        let is_blur: bool = instance.kind == GpuPrimitiveKind::BackdropBlur as u32;
1043        let inst_unclipped: bool =
1044            !is_blur && Self::quad_inside_rect(instance.rect, clip_entry.safe_inner);
1045        let count: usize = *active_batches;
1046        if count > 0 {
1047            let last: &mut GpuBatch = &mut batches[count - 1];
1048            if last.get_instances().len() < MAX_QUADS_PER_BATCH {
1049                let last_scissor: Rect = last.get_scissor();
1050                let blur_boundary: bool = tail_state.has_backdrop_blur || is_blur;
1051                if last_scissor == scissor && !blur_boundary {
1052                    last.get_mut_instances().push(instance);
1053                    tail_state.all_unclipped = tail_state.all_unclipped && inst_unclipped;
1054                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, instance.rect);
1055                    return;
1056                }
1057                if !blur_boundary
1058                    && inst_unclipped
1059                    && Self::quad_inside_rect(instance.rect, last_scissor)
1060                {
1061                    last.get_mut_instances().push(instance);
1062                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, instance.rect);
1063                    *coalesced_merges += 1;
1064                    return;
1065                }
1066                if !blur_boundary
1067                    && tail_state.all_unclipped
1068                    && Self::rect_inside_rect(tail_state.bounds, scissor)
1069                {
1070                    last.set_scissor(scissor);
1071                    last.get_mut_instances().push(instance);
1072                    tail_state.all_unclipped = inst_unclipped;
1073                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, instance.rect);
1074                    *coalesced_merges += 1;
1075                    return;
1076                }
1077            }
1078        }
1079        if count < batches.len() {
1080            let slot: &mut GpuBatch = &mut batches[count];
1081            slot.set_scissor(scissor);
1082            slot.get_mut_instances().clear();
1083            slot.get_mut_instances().push(instance);
1084        } else {
1085            let mut batch: GpuBatch = GpuBatch::default();
1086            batch.set_scissor(scissor);
1087            batch.get_mut_instances().push(instance);
1088            batches.push(batch);
1089        }
1090        *active_batches = count + 1;
1091        tail_state.all_unclipped = inst_unclipped;
1092        tail_state.has_backdrop_blur = is_blur;
1093        tail_state.bounds = Rect::new(
1094            instance.rect[0],
1095            instance.rect[1],
1096            instance.rect[2],
1097            instance.rect[3],
1098        );
1099    }
1100}