Skip to main content

dream_soft_render/renderer/
egui_frame.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! The egui half of the renderer: running a UI frame, applying egui's texture uploads,
4//! tessellating, skipping unchanged frames, and the diagnostics Dream-INI logs. Everything
5//! here converts into the core's own types before any pixel is drawn.
6
7use std::io;
8use std::time::{Duration, Instant};
9
10use super::quad::has_four_unique_indices;
11#[allow(
12    clippy::wildcard_imports,
13    reason = "this module is the renderer's egui half"
14)]
15use super::*;
16use crate::egui_adapter::{format_repaint_delay, raster_mesh_from_egui, vertices_from_egui};
17use crate::raster::{ClearElisionQuadRejection, clear_elision_quad_evidence, usize_to_f32};
18use crate::render_benchmark::{
19    SampledRectModulatedWorkload, SampledRectModulatedWorkloadStats, background_color,
20};
21use crate::texture::{TextureDeltaStats, TextureKey};
22
23/// Per-frame inputs and logging switches for [`SoftwareRenderer::render_egui`].
24pub struct RenderFrame<'a> {
25    /// The egui context the frame's UI runs in.
26    pub context: &'a egui::Context,
27    /// Sink for diagnostic log lines; `None` discards them.
28    pub log: Option<&'a dyn Fn(&str)>,
29    /// Log per-frame surface and timing summaries.
30    pub log_frame: bool,
31    /// Collect and log deep primitive/raster statistics.
32    pub log_render_stats: bool,
33    /// When set, timings are measured even on frames that are not logged.
34    pub hitch_log_threshold: Option<Duration>,
35    /// Frame counter echoed in log lines.
36    pub frame_index: u64,
37    /// Whether a repaint was already due when the frame started (logged only).
38    pub repaint_request_due_before_frame: bool,
39    /// Rasterize this synthetic workload instead of running the UI.
40    pub synthetic_workload: Option<&'a SampledRectModulatedWorkload>,
41}
42
43impl<'a> RenderFrame<'a> {
44    /// A frame for `context` with logging, stats, and the synthetic benchmark off.
45    #[must_use]
46    pub const fn new(context: &'a egui::Context) -> Self {
47        Self {
48            context,
49            log: None,
50            log_frame: false,
51            log_render_stats: false,
52            hitch_log_threshold: None,
53            frame_index: 0,
54            repaint_request_due_before_frame: false,
55            synthetic_workload: None,
56        }
57    }
58}
59
60impl RenderFrame<'_> {
61    fn write_log(&self, message: impl AsRef<str>) {
62        if let Some(log) = self.log {
63            log(message.as_ref());
64        }
65    }
66}
67
68impl SoftwareRenderer {
69    /// Runs `run_ui` for one egui frame sized `width`x`height`, applies egui's texture
70    /// changes, tessellates the output, and rasterizes it into the surface.
71    ///
72    /// egui meshes can show textures made with [`SoftwareRenderer::create_texture`] through
73    /// [`crate::egui_adapter::egui_texture_id`].
74    ///
75    /// # Errors
76    ///
77    /// Returns an error if the surface cannot be sized, a texture delta is malformed or would
78    /// exceed [`MAX_TEXTURE_BYTES`](crate::MAX_TEXTURE_BYTES), a mesh's index count is not a
79    /// multiple of three or an index is past its vertices, a clip rectangle is not finite, or
80    /// egui emits a paint callback. Mesh errors carry the [`Error`](crate::Error) that
81    /// [`Frame::mesh`](crate::Frame::mesh) would return for the same indices.
82    pub fn render_egui(
83        &mut self,
84        width: usize,
85        height: usize,
86        frame: &RenderFrame<'_>,
87        run_ui: impl FnMut(&mut egui::Ui),
88    ) -> io::Result<RenderOutcome> {
89        let log_timings = frame.log_frame || frame.hitch_log_threshold.is_some();
90        let total_start = log_timings.then(Instant::now);
91        let (surface_resized, cleared_this_frame, resize_clear_elapsed) =
92            self.prepare_surface(width, height, log_timings)?;
93
94        if let Some(workload) = frame.synthetic_workload {
95            return self.render_synthetic_benchmark(
96                workload,
97                frame,
98                total_start,
99                resize_clear_elapsed,
100                surface_resized,
101            );
102        }
103
104        let stage_start = log_timings.then(Instant::now);
105        let raw_input = egui::RawInput {
106            screen_rect: Some(egui::Rect::from_min_size(
107                egui::Pos2::ZERO,
108                egui::vec2(usize_to_f32(width), usize_to_f32(height)),
109            )),
110            max_texture_side: Some(1024),
111            ..Default::default()
112        };
113        let mut output = frame.context.run_ui(raw_input, run_ui);
114        let repaint_delay = root_repaint_delay(&output);
115        let egui_run_elapsed = elapsed_micros(stage_start);
116
117        let stage_start = log_timings.then(Instant::now);
118        let had_texture_updates = !output.textures_delta.set.is_empty();
119        let texture_delta_stats = self.apply_egui_textures(&mut output.textures_delta)?;
120        let texture_apply_elapsed = elapsed_micros(stage_start);
121
122        let stage_start = log_timings.then(Instant::now);
123        let primitives = frame.context.tessellate(output.shapes, 1.0);
124        let primitive_count = primitives.len();
125        let tessellate_elapsed = elapsed_micros(stage_start);
126        log_surface_stats(
127            frame,
128            &self.surface,
129            &self.textures,
130            &texture_delta_stats,
131            primitive_count,
132            surface_resized,
133            cleared_this_frame,
134        );
135
136        let stage_start = log_timings.then(Instant::now);
137        let unchanged = self.frame_is_unchanged(surface_resized, had_texture_updates, &primitives);
138        let collect_stats = !unchanged && should_collect_deep_stats(frame.log_render_stats);
139        let mut primitive_stats = collect_stats.then(PrimitiveStats::default);
140        let mut raster_stats = collect_stats.then(RasterStats::default);
141        let mut raster_timings = collect_stats.then(RasterTimings::default);
142        let clear_elision_stats = collect_stats.then(|| self.probe_clear_elision(&primitives));
143        let rasterize_result = if unchanged {
144            Ok(())
145        } else {
146            self.rasterize(
147                &primitives,
148                primitive_stats.as_mut(),
149                raster_stats.as_mut(),
150                raster_timings.as_mut(),
151            )
152        };
153        self.previous_frame_valid = rasterize_result.is_ok();
154        self.previous_primitives = primitives;
155        let rasterize_elapsed = elapsed_micros(stage_start);
156        log_raster_stats(
157            frame,
158            &self.surface,
159            clear_elision_stats.as_ref(),
160            primitive_stats.as_ref(),
161            raster_stats.as_ref(),
162            raster_timings.as_ref(),
163        );
164        let stage_start = log_timings.then(Instant::now);
165        self.free_egui_textures(&output.textures_delta.free);
166        output.textures_delta.clear();
167        rasterize_result?;
168        let texture_free_elapsed = elapsed_micros(stage_start);
169        let texture_evidence = self.texture_evidence(&texture_delta_stats);
170        let total_elapsed = elapsed_micros(total_start);
171        let timings = log_timings.then_some(RenderTimings {
172            resize_clear: resize_clear_elapsed,
173            egui_run: egui_run_elapsed,
174            texture_apply: texture_apply_elapsed,
175            tessellate: tessellate_elapsed,
176            rasterize: rasterize_elapsed,
177            texture_free: texture_free_elapsed,
178            total: total_elapsed,
179        });
180        log_render_timings(frame, timings, repaint_delay, unchanged);
181        Ok(RenderOutcome {
182            repaint_delay,
183            timings,
184            primitive_count,
185            texture_evidence,
186            surface_changed: !unchanged,
187        })
188    }
189
190    /// Applies egui's texture uploads. When one fails, those before it have still changed their
191    /// textures, so the surface no longer shows what the store holds, and the frame's releases
192    /// are freed now because the frame ends here.
193    fn apply_egui_textures(
194        &mut self,
195        delta: &mut egui::TexturesDelta,
196    ) -> io::Result<TextureDeltaStats> {
197        self.textures.apply(delta).inspect_err(|_| {
198            self.previous_frame_valid = false;
199            self.free_egui_textures(&delta.free);
200            delta.clear();
201        })
202    }
203
204    /// Frees the textures egui released this frame. egui names them only once, so every way out
205    /// of a frame frees them, failed frames included.
206    fn free_egui_textures<'a>(&mut self, released: impl IntoIterator<Item = &'a egui::TextureId>) {
207        for &id in released {
208            self.textures.free_egui(id);
209        }
210    }
211
212    fn frame_is_unchanged(
213        &self,
214        surface_resized: bool,
215        had_texture_updates: bool,
216        primitives: &[egui::ClippedPrimitive],
217    ) -> bool {
218        self.skip_unchanged_frames
219            && self.previous_frame_valid
220            && !surface_resized
221            && !had_texture_updates
222            && same_primitives(&self.previous_primitives, primitives)
223    }
224
225    fn texture_evidence(&self, delta: &TextureDeltaStats) -> TextureEvidence {
226        TextureEvidence {
227            count: self.textures.len(),
228            bytes: self.textures.bytes_used(),
229            set_count: delta.set_count,
230            set_bytes: delta.set_bytes,
231            full_upload_count: delta.full_upload_count,
232            partial_update_count: delta.partial_update_count,
233        }
234    }
235
236    /// Whether egui frames whose tessellated output is bit-identical to the previous frame, with no
237    /// texture uploads, skip rasterization and keep the previous surface. Enabled by default.
238    pub const fn set_skip_unchanged_frames(&mut self, skip: bool) {
239        self.skip_unchanged_frames = skip;
240    }
241
242    fn prepare_surface(
243        &mut self,
244        width: usize,
245        height: usize,
246        log_timings: bool,
247    ) -> io::Result<(bool, bool, u128)> {
248        let stage_start = log_timings.then(Instant::now);
249        let surface_resized = self.surface.resize(width, height)?;
250        if surface_resized {
251            self.surface.clear(crate::Color::TRANSPARENT.to_array());
252        }
253        Ok((
254            surface_resized,
255            surface_resized,
256            elapsed_micros(stage_start),
257        ))
258    }
259
260    fn render_synthetic_benchmark(
261        &mut self,
262        workload: &SampledRectModulatedWorkload,
263        frame: &RenderFrame<'_>,
264        total_start: Option<Instant>,
265        resize_clear_elapsed: u128,
266        surface_resized: bool,
267    ) -> io::Result<RenderOutcome> {
268        self.previous_frame_valid = false;
269        self.surface.clear(background_color());
270        let collect_stats = should_collect_deep_stats(frame.log_render_stats);
271        let mut primitive_stats = collect_stats.then(PrimitiveStats::default);
272        let mut raster_stats = collect_stats.then(RasterStats::default);
273        let mut raster_timings = collect_stats.then(RasterTimings::default);
274        let rasterize_start = Instant::now();
275        let (workload_stats, texture_bytes, clear_elision_stats) = {
276            let clear_elision_stats = collect_stats.then(|| {
277                synthetic_clear_elision_stats(workload, self.surface.width, self.surface.height)
278            });
279            self.rasterize_synthetic_workload(
280                workload,
281                primitive_stats.as_mut(),
282                raster_stats.as_mut(),
283                raster_timings.as_mut(),
284            )?;
285            (
286                workload.stats(),
287                workload.texture().pixels.len(),
288                clear_elision_stats,
289            )
290        };
291        let rasterize_elapsed = rasterize_start.elapsed().as_micros();
292        log_synthetic_surface_stats(
293            frame,
294            &self.surface,
295            workload_stats,
296            texture_bytes,
297            surface_resized,
298        );
299        log_raster_stats(
300            frame,
301            &self.surface,
302            clear_elision_stats.as_ref(),
303            primitive_stats.as_ref(),
304            raster_stats.as_ref(),
305            raster_timings.as_ref(),
306        );
307        let timings =
308            (frame.log_frame || frame.hitch_log_threshold.is_some()).then_some(RenderTimings {
309                resize_clear: resize_clear_elapsed,
310                egui_run: 0,
311                texture_apply: 0,
312                tessellate: 0,
313                rasterize: rasterize_elapsed,
314                texture_free: 0,
315                total: elapsed_micros(total_start),
316            });
317        log_render_timings(frame, timings, Duration::ZERO, false);
318        Ok(RenderOutcome {
319            repaint_delay: Duration::ZERO,
320            timings,
321            primitive_count: 1,
322            texture_evidence: TextureEvidence {
323                count: 1,
324                bytes: texture_bytes,
325                set_count: 0,
326                set_bytes: 0,
327                full_upload_count: 0,
328                partial_update_count: 0,
329            },
330            surface_changed: true,
331        })
332    }
333
334    fn rasterize_synthetic_workload(
335        &mut self,
336        workload: &SampledRectModulatedWorkload,
337        mut stats: Option<&mut PrimitiveStats>,
338        mut raster_stats: Option<&mut RasterStats>,
339        mut raster_timings: Option<&mut RasterTimings>,
340    ) -> io::Result<()> {
341        if let Some(stats) = borrow_optional_mut(&mut stats) {
342            stats.mesh_primitives += 1;
343            stats.mesh_indices += workload.mesh().indices.len();
344        }
345        let clip = ClipBounds::full(self.surface.width, self.surface.height);
346        let mut context = MeshRasterContext {
347            surface: &mut self.surface,
348            fan_polygon_scratch: &mut self.solid_fan_polygon_scratch,
349            fan_seen_boundary_scratch: &mut self.solid_fan_seen_boundary_scratch,
350            fan_span_cache: &mut self.solid_fan_span_cache,
351            mesh: workload.mesh(),
352            texture: workload.texture(),
353            clip,
354            primitive_index: 0,
355            solid_fan_polygon_scratch_budget: SOLID_FAN_POLYGON_SCRATCH_CAPACITY,
356        };
357        rasterize_mesh_contents(
358            &mut context,
359            &mut stats,
360            &mut raster_stats,
361            &mut raster_timings,
362        )?;
363        if let Some(stats) = raster_stats {
364            self.solid_fan_span_cache.record_stats(stats);
365        }
366        Ok(())
367    }
368
369    fn probe_clear_elision(&self, primitives: &[egui::ClippedPrimitive]) -> ClearElisionFrameStats {
370        let mut stats = ClearElisionFrameStats {
371            probe_frames: 1,
372            ..Default::default()
373        };
374        for primitive in primitives {
375            let egui::epaint::Primitive::Mesh(mesh) = &primitive.primitive else {
376                stats.reject_first_visible_not_rect = 1;
377                return stats;
378            };
379            let Some(texture) = self
380                .textures
381                .get(TextureKey::for_egui_mesh(mesh.texture_id))
382            else {
383                continue;
384            };
385            let Ok(clip) =
386                egui_clip_bounds(primitive.clip_rect, self.surface.width, self.surface.height)
387            else {
388                stats.reject_first_visible_not_rect = 1;
389                return stats;
390            };
391            if clip.is_empty() {
392                continue;
393            }
394            let Some(evidence) = probe_mesh_clear_elision(
395                raster_mesh_from_egui(mesh),
396                texture,
397                clip,
398                self.surface.width,
399                self.surface.height,
400            ) else {
401                continue;
402            };
403            stats.record_quad_evidence(evidence);
404            return stats;
405        }
406        stats.reject_no_primitives = 1;
407        stats
408    }
409
410    pub(super) fn rasterize(
411        &mut self,
412        primitives: &[egui::ClippedPrimitive],
413        mut stats: Option<&mut PrimitiveStats>,
414        mut raster_stats: Option<&mut RasterStats>,
415        mut raster_timings: Option<&mut RasterTimings>,
416    ) -> io::Result<()> {
417        for (primitive_index, primitive) in primitives.iter().enumerate() {
418            match &primitive.primitive {
419                egui::epaint::Primitive::Mesh(mesh) => {
420                    if let Some(stats) = borrow_optional_mut(&mut stats) {
421                        stats.mesh_primitives += 1;
422                    }
423                    self.rasterize_mesh(
424                        mesh,
425                        primitive.clip_rect,
426                        primitive_index,
427                        borrow_optional_mut(&mut stats),
428                        borrow_optional_mut(&mut raster_stats),
429                        borrow_optional_mut(&mut raster_timings),
430                    )?;
431                }
432                egui::epaint::Primitive::Callback(_) => {
433                    if let Some(stats) = borrow_optional_mut(&mut stats) {
434                        stats.callback_primitives += 1;
435                    }
436                    return Err(io::Error::other(
437                        "unsupported egui paint callback in software renderer",
438                    ));
439                }
440            }
441        }
442        if let Some(stats) = raster_stats {
443            self.solid_fan_span_cache.record_stats(stats);
444        }
445        Ok(())
446    }
447
448    fn rasterize_mesh(
449        &mut self,
450        mesh: &egui::Mesh,
451        clip_rect: egui::Rect,
452        primitive_index: usize,
453        mut stats: Option<&mut PrimitiveStats>,
454        mut raster_stats: Option<&mut RasterStats>,
455        mut raster_timings: Option<&mut RasterTimings>,
456    ) -> io::Result<()> {
457        check_egui_mesh_indices(mesh)?;
458        if let Some(stats) = borrow_optional_mut(&mut stats) {
459            stats.mesh_indices += mesh.indices.len();
460        }
461        let Some(texture) = self
462            .textures
463            .get(TextureKey::for_egui_mesh(mesh.texture_id))
464        else {
465            if let Some(stats) = borrow_optional_mut(&mut stats) {
466                stats.missing_texture_meshes += 1;
467            }
468            return Ok(());
469        };
470        let clip = egui_clip_bounds(clip_rect, self.surface.width, self.surface.height)?;
471        if clip.is_empty() {
472            if let Some(stats) = borrow_optional_mut(&mut stats) {
473                stats.empty_clip_meshes += 1;
474            }
475            return Ok(());
476        }
477        self.solid_fan_polygon_scratch.clear();
478        self.solid_fan_seen_boundary_scratch.clear();
479        let mut context = MeshRasterContext {
480            surface: &mut self.surface,
481            fan_polygon_scratch: &mut self.solid_fan_polygon_scratch,
482            fan_seen_boundary_scratch: &mut self.solid_fan_seen_boundary_scratch,
483            fan_span_cache: &mut self.solid_fan_span_cache,
484            mesh: raster_mesh_from_egui(mesh),
485            texture,
486            clip,
487            primitive_index,
488            solid_fan_polygon_scratch_budget: SOLID_FAN_POLYGON_SCRATCH_CAPACITY,
489        };
490        rasterize_mesh_contents(
491            &mut context,
492            &mut stats,
493            &mut raster_stats,
494            &mut raster_timings,
495        )?;
496        Ok(())
497    }
498}
499
500#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
501struct ClearElisionFrameStats {
502    probe_frames: usize,
503    eligible_frames: usize,
504    reject_no_primitives: usize,
505    reject_first_visible_not_rect: usize,
506    reject_clip_not_full_surface: usize,
507    reject_alpha_not_opaque: usize,
508    reject_texture_not_constant_white: usize,
509    reject_not_full_surface_opaque_rect: usize,
510    full_surface_opaque_rect_frames: usize,
511    near_full_surface_opaque_rect_frames: usize,
512    max_opaque_cover_basis_points: usize,
513}
514
515impl ClearElisionFrameStats {
516    fn record_quad_evidence(&mut self, evidence: crate::raster::ClearElisionQuadEvidence) {
517        if evidence.opaque_rect {
518            self.max_opaque_cover_basis_points = evidence.cover_basis_points;
519        }
520        if evidence.full_surface_opaque_rect {
521            self.eligible_frames = 1;
522            self.full_surface_opaque_rect_frames = 1;
523        }
524        if evidence.near_full_surface_opaque_rect {
525            self.near_full_surface_opaque_rect_frames = 1;
526        }
527        match evidence.rejection {
528            None => {}
529            Some(ClearElisionQuadRejection::NotRect) => self.reject_first_visible_not_rect = 1,
530            Some(ClearElisionQuadRejection::ClipNotFullSurface) => {
531                self.reject_clip_not_full_surface = 1;
532            }
533            Some(ClearElisionQuadRejection::AlphaNotOpaque) => {
534                self.reject_alpha_not_opaque = 1;
535            }
536            Some(ClearElisionQuadRejection::TextureNotConstantWhite) => {
537                self.reject_texture_not_constant_white = 1;
538            }
539            Some(ClearElisionQuadRejection::NotFullSurfaceOpaqueRect) => {
540                self.reject_not_full_surface_opaque_rect = 1;
541            }
542        }
543    }
544}
545
546/// What one [`SoftwareRenderer::render_egui`] call produced.
547#[derive(Clone, Copy, Debug)]
548pub struct RenderOutcome {
549    /// How long egui wants to wait before the next frame; `Duration::MAX` means no repaint was
550    /// requested.
551    pub repaint_delay: Duration,
552    /// Stage timings, measured only when [`RenderFrame::log_frame`] or
553    /// [`RenderFrame::hitch_log_threshold`] asked for them.
554    pub timings: Option<RenderTimings>,
555    /// Clipped primitives egui produced.
556    pub primitive_count: usize,
557    /// Texture storage after the frame, and this frame's uploads.
558    pub texture_evidence: TextureEvidence,
559    /// False when the frame matched the previous one and the surface was left untouched,
560    /// so presenting it again can be skipped.
561    pub surface_changed: bool,
562}
563
564/// Texture store totals and this frame's texture upload counts.
565#[derive(Clone, Copy, Debug, Eq, PartialEq)]
566pub struct TextureEvidence {
567    /// Textures stored after the frame.
568    pub count: usize,
569    /// Bytes of texture pixels stored after the frame.
570    pub bytes: usize,
571    /// Texture uploads egui made this frame.
572    pub set_count: usize,
573    /// Bytes those uploads carried.
574    pub set_bytes: usize,
575    /// Uploads that replaced a whole texture.
576    pub full_upload_count: usize,
577    /// Uploads that patched part of an existing texture.
578    pub partial_update_count: usize,
579}
580
581/// Per-stage render durations in microseconds.
582#[derive(Clone, Copy, Debug)]
583pub struct RenderTimings {
584    /// Sizing the surface, and clearing it if the size changed.
585    pub resize_clear: u128,
586    /// Running the UI closure.
587    pub egui_run: u128,
588    /// Applying egui's texture uploads.
589    pub texture_apply: u128,
590    /// Tessellating egui's shapes into meshes.
591    pub tessellate: u128,
592    /// Rasterizing the meshes, or for a frame skipped as unchanged, finding that it was.
593    pub rasterize: u128,
594    /// Freeing textures egui released.
595    pub texture_free: u128,
596    /// The whole call.
597    pub total: u128,
598}
599
600fn log_surface_stats(
601    frame: &RenderFrame<'_>,
602    surface: &SoftwareSurface,
603    textures: &TextureStore,
604    texture_delta_stats: &TextureDeltaStats,
605    primitive_count: usize,
606    surface_resized: bool,
607    cleared_this_frame: bool,
608) {
609    if frame.log_frame {
610        frame.write_log(format!(
611                "software renderer frame={} surface={}x{} bytes={} textures={} texture_bytes={} primitives={}",
612                frame.frame_index,
613                surface.width,
614                surface.height,
615                surface.pixels.len(),
616                textures.len(),
617                textures.bytes_used(),
618                primitive_count,
619            ),
620        );
621    }
622    if frame.log_render_stats {
623        frame.write_log(format!(
624                "software renderer render_stats frame={} surface={}x{} surface_bytes={} texture_sets={} texture_set_bytes={} texture_full_uploads={} texture_partial_updates={} clipped_primitives={} repaint_request_due_before_frame={} requested_repaint_after_egui={} cleared_this_frame={} surface_resized={}",
625                frame.frame_index,
626                surface.width,
627                surface.height,
628                surface.pixels.len(),
629                texture_delta_stats.set_count,
630                texture_delta_stats.set_bytes,
631                texture_delta_stats.full_upload_count,
632                texture_delta_stats.partial_update_count,
633                primitive_count,
634                frame.repaint_request_due_before_frame,
635                frame.context.has_requested_repaint(),
636                cleared_this_frame,
637                surface_resized,
638            ),
639        );
640    }
641}
642
643fn log_synthetic_surface_stats(
644    frame: &RenderFrame<'_>,
645    surface: &SoftwareSurface,
646    stats: SampledRectModulatedWorkloadStats,
647    texture_bytes: usize,
648    surface_resized: bool,
649) {
650    if frame.log_frame {
651        frame.write_log(format!(
652                "software renderer frame={} surface={}x{} bytes={} textures=1 texture_bytes={} primitives=1 benchmark=sampled-rect-modulated benchmark_rects={} benchmark_pixels={}",
653                frame.frame_index,
654                surface.width,
655                surface.height,
656                surface.pixels.len(),
657                texture_bytes,
658                stats.rects,
659                stats.pixels,
660            ),
661        );
662    }
663    if frame.log_render_stats {
664        frame.write_log(format!(
665                "software renderer render_stats frame={} surface={}x{} surface_bytes={} texture_sets=0 texture_set_bytes=0 texture_full_uploads=0 texture_partial_updates=0 clipped_primitives=1 repaint_request_due_before_frame={} requested_repaint_after_egui=false cleared_this_frame=true surface_resized={} benchmark=sampled-rect-modulated benchmark_span_px_lt4={} benchmark_span_px_4_7={} benchmark_span_px_8_15={} benchmark_span_px_16_plus=0",
666                frame.frame_index,
667                surface.width,
668                surface.height,
669                surface.pixels.len(),
670                frame.repaint_request_due_before_frame,
671                surface_resized,
672                stats.lt4_pixels,
673                stats.mid_pixels,
674                stats.wide_pixels,
675            ),
676        );
677    }
678}
679
680fn synthetic_clear_elision_stats(
681    workload: &SampledRectModulatedWorkload,
682    surface_width: usize,
683    surface_height: usize,
684) -> ClearElisionFrameStats {
685    let clip = ClipBounds::full(surface_width, surface_height);
686    let evidence = mesh_quad_vertices(workload.mesh(), &workload.mesh().indices[..6])
687        .ok()
688        .flatten()
689        .map(|vertices| {
690            clear_elision_quad_evidence(
691                vertices,
692                workload.texture(),
693                clip,
694                surface_width,
695                surface_height,
696            )
697        });
698    let mut stats = ClearElisionFrameStats {
699        probe_frames: 1,
700        ..Default::default()
701    };
702    if let Some(evidence) = evidence {
703        stats.record_quad_evidence(evidence);
704    } else {
705        stats.reject_first_visible_not_rect = 1;
706    }
707    stats
708}
709
710fn log_raster_stats(
711    frame: &RenderFrame<'_>,
712    surface: &SoftwareSurface,
713    clear_elision_stats: Option<&ClearElisionFrameStats>,
714    primitive_stats: Option<&PrimitiveStats>,
715    raster_stats: Option<&RasterStats>,
716    raster_timings: Option<&RasterTimings>,
717) {
718    if let Some(stats) = primitive_stats {
719        frame.write_log(stats.log_line(frame.frame_index));
720        if let Some(log_line) = stats.solid_triangle_offenders_log_line() {
721            frame.write_log(log_line);
722        }
723        if let Some(log_line) = stats.textured_triangle_offenders_log_line() {
724            frame.write_log(log_line);
725        }
726        if let Some(log_line) = stats.textured_quad_reject_offenders_log_line() {
727            frame.write_log(log_line);
728        }
729        if let Some(log_line) = stats.solid_fan_offenders_log_line() {
730            frame.write_log(log_line);
731        }
732    }
733    if let Some(stats) = raster_stats {
734        if frame.log_render_stats {
735            frame.write_log(clear_evidence_log_line(
736                frame.frame_index,
737                surface.width,
738                surface.height,
739                stats,
740                clear_elision_stats,
741            ));
742        }
743        frame.write_log(stats.log_line());
744    }
745    if let Some(timings) = raster_timings {
746        frame.write_log(timings.log_line());
747    }
748}
749
750fn log_render_timings(
751    frame: &RenderFrame<'_>,
752    timings: Option<RenderTimings>,
753    repaint_delay: Duration,
754    raster_skipped: bool,
755) {
756    if !frame.log_frame {
757        return;
758    }
759    let Some(timings) = timings else {
760        return;
761    };
762    let repaint_delay = format_repaint_delay(repaint_delay);
763    frame.write_log(format!(
764            "software renderer timings frame={} resize_clear_us={} egui_run_us={} texture_apply_us={} tessellate_us={} rasterize_us={} texture_free_us={} repaint_delay={repaint_delay} raster_skipped={raster_skipped} total_us={}",
765            frame.frame_index,
766            timings.resize_clear,
767            timings.egui_run,
768            timings.texture_apply,
769            timings.tessellate,
770            timings.rasterize,
771            timings.texture_free,
772            timings.total,
773        ),
774    );
775}
776
777fn clear_evidence_log_line(
778    frame_index: u64,
779    width: usize,
780    height: usize,
781    stats: &RasterStats,
782    clear_elision_stats: Option<&ClearElisionFrameStats>,
783) -> String {
784    let clear_elision_stats = clear_elision_stats.copied().unwrap_or_default();
785    let clear_pixels = width.saturating_mul(height);
786    let clear_bytes = clear_pixels.saturating_mul(4);
787    let opaque_drawn_pixels = stats.opaque_px;
788    let opaque_drawn_percent = opaque_drawn_pixels
789        .saturating_mul(100)
790        .checked_div(clear_pixels)
791        .unwrap_or(0);
792    format!(
793        "software renderer clear_evidence frame={frame_index} clear_pixels={clear_pixels} clear_bytes={clear_bytes} opaque_drawn_pixels={opaque_drawn_pixels} opaque_drawn_percent_of_surface={opaque_drawn_percent} clear_elision_probe_frames={} clear_elision_eligible_frames={} clear_elision_reject_no_primitives={} clear_elision_reject_first_visible_not_rect={} clear_elision_reject_clip_not_full_surface={} clear_elision_reject_alpha_not_opaque={} clear_elision_reject_texture_not_constant_white={} clear_elision_reject_not_full_surface_opaque_rect={} clear_elision_full_surface_opaque_rect_frames={} clear_elision_near_full_surface_opaque_rect_frames={} clear_elision_max_opaque_cover_basis_points={}",
794        clear_elision_stats.probe_frames,
795        clear_elision_stats.eligible_frames,
796        clear_elision_stats.reject_no_primitives,
797        clear_elision_stats.reject_first_visible_not_rect,
798        clear_elision_stats.reject_clip_not_full_surface,
799        clear_elision_stats.reject_alpha_not_opaque,
800        clear_elision_stats.reject_texture_not_constant_white,
801        clear_elision_stats.reject_not_full_surface_opaque_rect,
802        clear_elision_stats.full_surface_opaque_rect_frames,
803        clear_elision_stats.near_full_surface_opaque_rect_frames,
804        clear_elision_stats.max_opaque_cover_basis_points,
805    )
806}
807
808fn probe_mesh_clear_elision(
809    mesh: RasterMesh<'_>,
810    texture: &TextureImage,
811    clip: ClipBounds,
812    surface_width: usize,
813    surface_height: usize,
814) -> Option<crate::raster::ClearElisionQuadEvidence> {
815    let mut index_offset = 0;
816    while index_offset + 2 < mesh.indices.len() {
817        if index_offset + 5 >= mesh.indices.len() {
818            return Some(crate::raster::ClearElisionQuadEvidence {
819                visible_px: 0,
820                cover_basis_points: 0,
821                opaque_rect: false,
822                full_surface_opaque_rect: false,
823                near_full_surface_opaque_rect: false,
824                rejection: Some(ClearElisionQuadRejection::NotRect),
825            });
826        }
827        let quad = &mesh.indices[index_offset..index_offset + 6];
828        if !has_four_unique_indices(quad) {
829            return Some(crate::raster::ClearElisionQuadEvidence {
830                visible_px: 0,
831                cover_basis_points: 0,
832                opaque_rect: false,
833                full_surface_opaque_rect: false,
834                near_full_surface_opaque_rect: false,
835                rejection: Some(ClearElisionQuadRejection::NotRect),
836            });
837        }
838        let Ok(Some(vertices)) = mesh_quad_vertices(mesh, quad) else {
839            return Some(crate::raster::ClearElisionQuadEvidence {
840                visible_px: 0,
841                cover_basis_points: 0,
842                opaque_rect: false,
843                full_surface_opaque_rect: false,
844                near_full_surface_opaque_rect: false,
845                rejection: Some(ClearElisionQuadRejection::NotRect),
846            });
847        };
848        let evidence =
849            clear_elision_quad_evidence(vertices, texture, clip, surface_width, surface_height);
850        if evidence.visible_px == 0
851            && !matches!(evidence.rejection, Some(ClearElisionQuadRejection::NotRect))
852        {
853            index_offset += 6;
854            continue;
855        }
856        return Some(evidence);
857    }
858    None
859}
860
861/// Bitwise comparison, so any difference that could change a rasterized pixel (including
862/// `-0.0` versus `0.0` and NaN payloads) counts as a change.
863fn same_primitives(
864    previous: &[egui::ClippedPrimitive],
865    current: &[egui::ClippedPrimitive],
866) -> bool {
867    fn same_rect(left: egui::Rect, right: egui::Rect) -> bool {
868        let bits =
869            |rect: egui::Rect| [rect.min.x, rect.min.y, rect.max.x, rect.max.y].map(f32::to_bits);
870        bits(left) == bits(right)
871    }
872    fn same_mesh(left: &egui::Mesh, right: &egui::Mesh) -> bool {
873        let bits = |vertex: &Vertex| {
874            (
875                vertex.pos.map(f32::to_bits),
876                vertex.uv.map(f32::to_bits),
877                vertex.color,
878            )
879        };
880        let (left_vertices, right_vertices) = (
881            vertices_from_egui(&left.vertices),
882            vertices_from_egui(&right.vertices),
883        );
884        left.texture_id == right.texture_id
885            && left.indices == right.indices
886            && left_vertices.len() == right_vertices.len()
887            && left_vertices
888                .iter()
889                .zip(right_vertices)
890                .all(|(left, right)| bits(left) == bits(right))
891    }
892    previous.len() == current.len()
893        && previous.iter().zip(current).all(|(previous, current)| {
894            same_rect(previous.clip_rect, current.clip_rect)
895                && match (&previous.primitive, &current.primitive) {
896                    (egui::epaint::Primitive::Mesh(left), egui::epaint::Primitive::Mesh(right)) => {
897                        same_mesh(left, right)
898                    }
899                    _ => false,
900                }
901        })
902}
903
904/// Holds an egui mesh's indices to what [`Frame::mesh`] requires of its own: whole triangles,
905/// and no index past the vertices. egui checks meshes only in debug builds.
906fn check_egui_mesh_indices(mesh: &egui::Mesh) -> io::Result<()> {
907    let index_count = mesh.indices.len();
908    if !index_count.is_multiple_of(3) {
909        return Err(io::Error::other(crate::Error::IndexCount(index_count)));
910    }
911    let vertex_count = mesh.vertices.len();
912    let out_of_range =
913        |index: &u32| usize::try_from(*index).is_ok_and(|index| index >= vertex_count);
914    // The largest index is one pass that vectorizes; the first offender is only looked for once
915    // there is one.
916    if mesh.indices.iter().max().is_some_and(out_of_range)
917        && let Some(&index) = mesh.indices.iter().find(|index| out_of_range(index))
918    {
919        return Err(io::Error::other(crate::Error::IndexOutOfRange {
920            index,
921            vertex_count,
922        }));
923    }
924    Ok(())
925}
926
927/// An egui clip rectangle as pixel bounds: grown outward to whole pixels, clamped to the
928/// surface, and an error if any edge is not finite.
929fn egui_clip_bounds(rect: egui::Rect, width: usize, height: usize) -> io::Result<ClipBounds> {
930    ClipBounds::from_float_edges(
931        [rect.min.x, rect.min.y, rect.max.x, rect.max.y],
932        width,
933        height,
934    )
935}
936
937fn root_repaint_delay(output: &egui::FullOutput) -> Duration {
938    output
939        .viewport_output
940        .get(&egui::ViewportId::ROOT)
941        .map_or(Duration::MAX, |output| output.repaint_delay)
942}
943
944fn elapsed_micros(start: Option<Instant>) -> u128 {
945    start.map_or(0, |start| start.elapsed().as_micros())
946}
947
948const fn should_collect_deep_stats(log_render_stats: bool) -> bool {
949    log_render_stats
950}
951
952// These tests drive the renderer through egui meshes and texture uploads.
953#[cfg(test)]
954mod tests {
955    use super::*;
956    use crate::Color;
957    use crate::geometry::pos2;
958
959    #[test]
960    fn coarse_frame_logging_does_not_enable_deep_stats_collection() {
961        assert!(!should_collect_deep_stats(false));
962        assert!(should_collect_deep_stats(true));
963    }
964
965    #[test]
966    fn renderer_stats_count_textured_quad_fast_path_without_generic_triangles() {
967        let texture_id = egui::TextureId::Managed(1);
968        let mut renderer = SoftwareRenderer::default();
969        renderer.surface.resize(8, 8).expect("surface");
970        renderer.surface.clear([0, 0, 0, 255]);
971        renderer
972            .textures
973            .apply(&mut texture_delta(texture_id))
974            .expect("texture");
975        let mesh = textured_quad_mesh(texture_id);
976        let mut stats = PrimitiveStats::default();
977
978        renderer
979            .rasterize_mesh(
980                &mesh,
981                egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(8.0, 8.0)),
982                0,
983                Some(&mut stats),
984                None,
985                None,
986            )
987            .expect("rasterize mesh");
988
989        assert_eq!(stats.textured_quad_fast_path_hits, 1);
990        assert_eq!(stats.generic_triangles_rasterized, 0);
991        assert_eq!(stats.generic_textured_triangles, 0);
992    }
993
994    #[test]
995    fn renderer_stats_count_textured_quad_fast_path_rejection() {
996        let texture_id = egui::TextureId::Managed(1);
997        let mut renderer = SoftwareRenderer::default();
998        renderer.surface.resize(8, 8).expect("surface");
999        renderer.surface.clear([0, 0, 0, 255]);
1000        renderer
1001            .textures
1002            .apply(&mut texture_delta(texture_id))
1003            .expect("texture");
1004        let mut mesh = textured_quad_mesh(texture_id);
1005        mesh.vertices[3].uv = egui::pos2(0.75, 1.0);
1006        let mut stats = PrimitiveStats::default();
1007
1008        renderer
1009            .rasterize_mesh(
1010                &mesh,
1011                egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(8.0, 8.0)),
1012                0,
1013                Some(&mut stats),
1014                None,
1015                None,
1016            )
1017            .expect("rasterize mesh");
1018
1019        assert_eq!(stats.textured_quad_fast_path_hits, 0);
1020        assert_eq!(stats.textured_quad_reject_non_affine_uv, 1);
1021        assert_eq!(stats.generic_triangles_rasterized, 2);
1022        assert!(
1023            stats
1024                .textured_quad_reject_offenders_log_line()
1025                .expect("textured quad reject offenders")
1026                .contains("offender0_reason=non_affine_uv")
1027        );
1028    }
1029
1030    #[test]
1031    fn clear_elision_probe_counts_full_surface_opaque_white_quad_as_eligible() {
1032        let texture_id = egui::TextureId::Managed(1);
1033        let renderer = renderer_with_white_texture(texture_id, 8, 8);
1034        let primitive =
1035            clipped_mesh_primitive(full_surface_quad_mesh(texture_id, 8.0, 8.0), 8.0, 8.0);
1036
1037        let stats = renderer.probe_clear_elision(&[primitive]);
1038
1039        assert_eq!(stats.probe_frames, 1);
1040        assert_eq!(stats.eligible_frames, 1);
1041        assert_eq!(stats.full_surface_opaque_rect_frames, 1);
1042        assert_eq!(stats.near_full_surface_opaque_rect_frames, 1);
1043        assert_eq!(stats.max_opaque_cover_basis_points, 10_000);
1044    }
1045
1046    #[test]
1047    fn clear_elision_probe_counts_near_full_surface_as_evidence_only() {
1048        let texture_id = egui::TextureId::Managed(1);
1049        let renderer = renderer_with_white_texture(texture_id, 20, 20);
1050        let primitive =
1051            clipped_mesh_primitive(full_surface_quad_mesh(texture_id, 20.0, 18.5), 20.0, 20.0);
1052
1053        let stats = renderer.probe_clear_elision(&[primitive]);
1054
1055        assert_eq!(stats.eligible_frames, 0);
1056        assert_eq!(stats.full_surface_opaque_rect_frames, 0);
1057        assert_eq!(stats.near_full_surface_opaque_rect_frames, 1);
1058        assert_eq!(stats.reject_not_full_surface_opaque_rect, 1);
1059        assert_eq!(stats.max_opaque_cover_basis_points, 9_500);
1060    }
1061
1062    #[test]
1063    fn clear_elision_probe_rejects_translucent_first_rect() {
1064        let texture_id = egui::TextureId::Managed(1);
1065        let renderer = renderer_with_white_texture(texture_id, 8, 8);
1066        let mut mesh = full_surface_quad_mesh(texture_id, 8.0, 8.0);
1067        for vertex in &mut mesh.vertices {
1068            vertex.color = egui::Color32::from_rgba_premultiplied(128, 128, 128, 128);
1069        }
1070        let primitive = clipped_mesh_primitive(mesh, 8.0, 8.0);
1071
1072        let stats = renderer.probe_clear_elision(&[primitive]);
1073
1074        assert_eq!(stats.eligible_frames, 0);
1075        assert_eq!(stats.reject_alpha_not_opaque, 1);
1076    }
1077
1078    #[test]
1079    fn renderer_solid_fan_path_matches_per_triangle_reference() {
1080        let texture_id = egui::TextureId::Managed(1);
1081        let mut renderer = SoftwareRenderer::default();
1082        renderer.surface.resize(12, 12).expect("surface");
1083        renderer.surface.clear([0, 0, 0, 255]);
1084        renderer
1085            .textures
1086            .apply(&mut texture_delta(texture_id))
1087            .expect("texture");
1088        let mesh = solid_fan_mesh(texture_id, [128, 32, 0, 128]);
1089        let clip_rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(12.0, 12.0));
1090        let mut primitive_stats = PrimitiveStats::default();
1091        let mut raster_stats = RasterStats::default();
1092        let mut raster_timings = RasterTimings::default();
1093
1094        renderer
1095            .rasterize_mesh(
1096                &mesh,
1097                clip_rect,
1098                0,
1099                Some(&mut primitive_stats),
1100                Some(&mut raster_stats),
1101                Some(&mut raster_timings),
1102            )
1103            .expect("rasterize mesh");
1104        let fan_pixels = renderer.surface.pixels.clone();
1105
1106        let texture = renderer
1107            .textures
1108            .get(TextureKey::Egui(texture_id))
1109            .expect("stored texture");
1110        let reference = render_solid_fan_reference(&mesh, texture, clip_bounds(12, 12));
1111        assert_eq!(fan_pixels, reference);
1112        assert_accepted_solid_fan_primitive_stats(&primitive_stats);
1113        assert_eq!(primitive_stats.generic_triangles_rasterized, 0);
1114        assert_eq!(raster_stats.solid_fan_calls, 1);
1115        assert_eq!(raster_stats.solid_fan_triangles, 4);
1116        assert!(raster_stats.solid_fan_rows > 0);
1117        assert!(raster_stats.solid_fan_px > 0);
1118        assert_eq!(raster_stats.translucent_px, raster_stats.solid_fan_px);
1119        assert_eq!(raster_timings.generic_solid_triangle, 0);
1120        assert_eq!(raster_timings.generic_textured_triangle, 0);
1121        assert_eq!(raster_timings.solid_fan_rejected_probe, 0);
1122        assert!(
1123            primitive_stats
1124                .solid_fan_offenders_log_line()
1125                .expect("solid fan offenders")
1126                .contains("offender0_triangles=4 offender0_polygon_vertices=6 offender0_alpha=128")
1127        );
1128    }
1129
1130    #[test]
1131    fn renderer_preflight_skips_too_short_solid_fan_probe_and_uses_generic_triangles() {
1132        let texture_id = egui::TextureId::Managed(1);
1133        let mut renderer = SoftwareRenderer::default();
1134        renderer.surface.resize(12, 12).expect("surface");
1135        renderer.surface.clear([0, 0, 0, 255]);
1136        renderer
1137            .textures
1138            .apply(&mut texture_delta(texture_id))
1139            .expect("texture");
1140        let mesh = too_short_mixed_triangle_mesh(texture_id);
1141        let clip_rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(12.0, 12.0));
1142        let mut primitive_stats = PrimitiveStats::default();
1143        let mut raster_stats = RasterStats::default();
1144
1145        renderer
1146            .rasterize_mesh(
1147                &mesh,
1148                clip_rect,
1149                0,
1150                Some(&mut primitive_stats),
1151                Some(&mut raster_stats),
1152                None,
1153            )
1154            .expect("rasterize mesh");
1155
1156        let texture = renderer
1157            .textures
1158            .get(TextureKey::Egui(texture_id))
1159            .expect("stored texture");
1160        let reference = render_solid_fan_reference(&mesh, texture, clip_bounds(12, 12));
1161        assert_eq!(renderer.surface.pixels, reference);
1162        assert_eq!(primitive_stats.solid_fan_probe.probe_calls, 0);
1163        assert_eq!(
1164            primitive_stats
1165                .solid_fan_probe
1166                .preflight_reject_too_few_triangles,
1167            3
1168        );
1169        assert_eq!(primitive_stats.solid_fan_probe.rejected_probe_calls, 0);
1170        assert_eq!(primitive_stats.solid_fan_runs, 0);
1171        assert_eq!(primitive_stats.generic_triangles_rasterized, 3);
1172        assert_eq!(primitive_stats.generic_solid_triangles, 1);
1173        assert_eq!(primitive_stats.generic_textured_triangles, 2);
1174        assert_eq!(primitive_stats.generic_textured_constant_texel_triangles, 1);
1175        assert_eq!(primitive_stats.generic_textured_sampled_triangles, 1);
1176        assert_eq!(raster_stats.solid_fan_calls, 0);
1177        assert_eq!(raster_stats.solid_triangle_calls, 1);
1178        assert_eq!(raster_stats.textured_triangle_calls, 2);
1179    }
1180
1181    #[test]
1182    fn renderer_solid_fan_preflight_rejects_when_second_triangle_cannot_continue() {
1183        let texture_id = egui::TextureId::Managed(1);
1184        let mut renderer = renderer_with_white_texture(texture_id, 12, 12);
1185        let mesh = disconnected_solid_triangles_mesh(texture_id);
1186        let clip_rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(12.0, 12.0));
1187        let mut primitive_stats = PrimitiveStats::default();
1188        let mut raster_stats = RasterStats::default();
1189
1190        renderer
1191            .rasterize_mesh(
1192                &mesh,
1193                clip_rect,
1194                0,
1195                Some(&mut primitive_stats),
1196                Some(&mut raster_stats),
1197                None,
1198            )
1199            .expect("rasterize mesh");
1200
1201        let texture = renderer
1202            .textures
1203            .get(TextureKey::Egui(texture_id))
1204            .expect("stored texture");
1205        let reference = render_solid_fan_reference(&mesh, texture, clip_bounds(12, 12));
1206        assert_eq!(renderer.surface.pixels, reference);
1207        assert_eq!(primitive_stats.solid_fan_probe.probe_calls, 1);
1208        assert_eq!(primitive_stats.solid_fan_probe.rejected_probe_calls, 1);
1209        assert_eq!(
1210            primitive_stats
1211                .solid_fan_probe
1212                .preflight_second_triangle_checks,
1213            1
1214        );
1215        assert_eq!(
1216            primitive_stats
1217                .solid_fan_probe
1218                .preflight_reject_no_second_triangle_continuation,
1219            1
1220        );
1221        assert_eq!(
1222            primitive_stats
1223                .solid_fan_probe
1224                .preflight_center_slots_allowed,
1225            0
1226        );
1227        assert_eq!(
1228            primitive_stats
1229                .solid_fan_probe
1230                .preflight_center_slots_rejected,
1231            3
1232        );
1233        assert_eq!(primitive_stats.solid_fan_probe.center_slot_attempts, 0);
1234        assert_eq!(primitive_stats.solid_fan_probe.cheap_candidate_attempts, 0);
1235        assert_eq!(
1236            primitive_stats.solid_fan_probe.candidate_triangles_scanned,
1237            0
1238        );
1239        assert_eq!(primitive_stats.solid_fan_runs, 0);
1240        assert_eq!(primitive_stats.generic_triangles_rasterized, 4);
1241        assert_eq!(raster_stats.solid_fan_calls, 0);
1242        assert_eq!(raster_stats.solid_triangle_calls, 4);
1243    }
1244
1245    #[test]
1246    fn renderer_reports_resident_solid_fan_cache_without_fan_call_in_frame() {
1247        let texture_id = egui::TextureId::Managed(1);
1248        let mut renderer = SoftwareRenderer::default();
1249        renderer.surface.resize(12, 12).expect("surface");
1250        renderer.surface.clear([0, 0, 0, 255]);
1251        renderer
1252            .textures
1253            .apply(&mut texture_delta(texture_id))
1254            .expect("texture");
1255        let clip_rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(12.0, 12.0));
1256
1257        let mut first_frame_stats = RasterStats::default();
1258        let first_frame = egui::ClippedPrimitive {
1259            clip_rect,
1260            primitive: egui::epaint::Primitive::Mesh(solid_fan_mesh(texture_id, [128, 32, 0, 128])),
1261        };
1262        renderer
1263            .rasterize(&[first_frame], None, Some(&mut first_frame_stats), None)
1264            .expect("rasterize first frame");
1265        assert_eq!(first_frame_stats.solid_fan_span_cache_misses, 1);
1266        assert_eq!(first_frame_stats.solid_fan_span_cache_resident_entries, 1);
1267        assert!(first_frame_stats.solid_fan_span_cache_resident_rows > 0);
1268
1269        let mut second_frame_stats = RasterStats::default();
1270        let second_frame = egui::ClippedPrimitive {
1271            clip_rect,
1272            primitive: egui::epaint::Primitive::Mesh(textured_quad_mesh(texture_id)),
1273        };
1274        renderer
1275            .rasterize(&[second_frame], None, Some(&mut second_frame_stats), None)
1276            .expect("rasterize second frame");
1277
1278        assert_eq!(second_frame_stats.solid_fan_calls, 0);
1279        assert_eq!(second_frame_stats.solid_fan_span_cache_hits, 0);
1280        assert_eq!(second_frame_stats.solid_fan_span_cache_misses, 0);
1281        assert_eq!(second_frame_stats.solid_fan_span_cache_stored_rows, 0);
1282        assert_eq!(second_frame_stats.solid_fan_span_cache_resident_entries, 1);
1283        assert_eq!(
1284            second_frame_stats.solid_fan_span_cache_resident_rows,
1285            first_frame_stats.solid_fan_span_cache_resident_rows
1286        );
1287    }
1288
1289    #[test]
1290    fn renderer_solid_fan_scratch_overflow_falls_back_to_generic_triangles() {
1291        let texture_id = egui::TextureId::Managed(1);
1292        let mut renderer = SoftwareRenderer::default();
1293        renderer.surface.resize(12, 12).expect("surface");
1294        renderer.surface.clear([0, 0, 0, 255]);
1295        renderer
1296            .textures
1297            .apply(&mut texture_delta(texture_id))
1298            .expect("texture");
1299        let mesh = solid_fan_mesh(texture_id, [128, 32, 0, 128]);
1300        let clip = clip_bounds(12, 12);
1301        let reference = render_solid_fan_reference(
1302            &mesh,
1303            renderer
1304                .textures
1305                .get(TextureKey::Egui(texture_id))
1306                .expect("stored texture"),
1307            clip,
1308        );
1309        let mut primitive_stats = PrimitiveStats::default();
1310        let mut raster_stats = RasterStats::default();
1311
1312        {
1313            let mut stats = Some(&mut primitive_stats);
1314            let mut raster_stats = Some(&mut raster_stats);
1315            let mut raster_timings = None;
1316            let mut context = MeshRasterContext {
1317                surface: &mut renderer.surface,
1318                fan_polygon_scratch: &mut renderer.solid_fan_polygon_scratch,
1319                fan_seen_boundary_scratch: &mut renderer.solid_fan_seen_boundary_scratch,
1320                fan_span_cache: &mut renderer.solid_fan_span_cache,
1321                mesh: raster_mesh_from_egui(&mesh),
1322                texture: renderer
1323                    .textures
1324                    .get(TextureKey::Egui(texture_id))
1325                    .expect("stored texture"),
1326                clip,
1327                primitive_index: 0,
1328                solid_fan_polygon_scratch_budget: 5,
1329            };
1330            rasterize_mesh_contents(
1331                &mut context,
1332                &mut stats,
1333                &mut raster_stats,
1334                &mut raster_timings,
1335            )
1336            .expect("rasterize mesh");
1337        }
1338
1339        assert_eq!(renderer.surface.pixels, reference);
1340        assert_eq!(primitive_stats.solid_fan_probe.reject_scratch_overflow, 1);
1341        assert_eq!(primitive_stats.solid_fan_probe.polygon_builds, 0);
1342        assert_eq!(primitive_stats.solid_fan_probe.accepted_runs, 0);
1343        assert_eq!(primitive_stats.solid_fan_runs, 0);
1344        assert_eq!(primitive_stats.generic_triangles_rasterized, 4);
1345        assert_eq!(raster_stats.solid_fan_calls, 0);
1346    }
1347
1348    // egui checks a mesh's indices only in debug builds, so release builds hand a mesh that names
1349    // vertices it does not have to the renderer, which skipped those triangles in silence.
1350    #[test]
1351    fn egui_meshes_with_bad_indices_fail_the_frame() {
1352        let texture_id = egui::TextureId::Managed(1);
1353        let mut renderer = renderer_with_white_texture(texture_id, 8, 8);
1354        let mut out_of_range = full_surface_quad_mesh(texture_id, 8.0, 8.0);
1355        out_of_range.indices[4] = 9;
1356        out_of_range.indices[5] = 4;
1357        let mut partial_triangle = full_surface_quad_mesh(texture_id, 8.0, 8.0);
1358        partial_triangle.indices.pop();
1359
1360        for (mesh, expected) in [
1361            (
1362                out_of_range,
1363                crate::Error::IndexOutOfRange {
1364                    index: 9,
1365                    vertex_count: 4,
1366                },
1367            ),
1368            (partial_triangle, crate::Error::IndexCount(5)),
1369        ] {
1370            let error = renderer
1371                .rasterize(&[clipped_mesh_primitive(mesh, 8.0, 8.0)], None, None, None)
1372                .expect_err("malformed mesh");
1373            assert_eq!(
1374                error
1375                    .get_ref()
1376                    .and_then(|inner| inner.downcast_ref::<crate::Error>()),
1377                Some(&expected)
1378            );
1379            assert_eq!(error.to_string(), expected.to_string());
1380        }
1381        assert!(
1382            renderer
1383                .surface
1384                .pixels
1385                .as_chunks::<4>()
1386                .0
1387                .iter()
1388                .all(|pixel| *pixel == [0, 0, 0, 255])
1389        );
1390    }
1391
1392    // egui frees a texture once its last handle drops, and says so only in that frame's output,
1393    // so a frame that fails must still free it or it holds texture budget for good.
1394    #[test]
1395    fn a_failed_frame_still_frees_the_textures_egui_released() {
1396        let context = egui::Context::default();
1397        let mut renderer = SoftwareRenderer::default();
1398        let image = context.load_texture(
1399            "image",
1400            egui::ColorImage::new([2, 2], vec![egui::Color32::RED; 4]),
1401            egui::TextureOptions::NEAREST,
1402        );
1403        let before = renderer
1404            .render_egui(8, 8, &RenderFrame::new(&context), |_| {})
1405            .expect("upload frame")
1406            .texture_evidence;
1407
1408        drop(image);
1409        let paint_callback = |ui: &mut egui::Ui| {
1410            struct NoGpu;
1411            ui.painter().add(egui::PaintCallback {
1412                rect: egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(4.0, 4.0)),
1413                callback: std::sync::Arc::new(NoGpu),
1414            });
1415        };
1416        assert!(
1417            renderer
1418                .render_egui(8, 8, &RenderFrame::new(&context), paint_callback)
1419                .is_err()
1420        );
1421
1422        let after = renderer
1423            .render_egui(8, 8, &RenderFrame::new(&context), |_| {})
1424            .expect("next frame")
1425            .texture_evidence;
1426        assert_eq!(after.count, before.count - 1);
1427        assert_eq!(after.bytes, before.bytes - 2 * 2 * 4);
1428    }
1429
1430    // Uploads that fail part way have already changed the textures before the failing one, and
1431    // egui does not send them again, so the next frame cannot count as unchanged.
1432    #[test]
1433    fn a_frame_after_a_failed_texture_upload_is_rasterized() {
1434        let context = egui::Context::default();
1435        let mut renderer = SoftwareRenderer::default();
1436        let solid = |color| egui::ColorImage::new([2, 2], vec![color; 4]);
1437        let mut image = context.load_texture(
1438            "image",
1439            solid(egui::Color32::RED),
1440            egui::TextureOptions::NEAREST,
1441        );
1442        let image_id = image.id();
1443        let draw = |ui: &mut egui::Ui| {
1444            ui.painter().image(
1445                image_id,
1446                egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(4.0, 4.0)),
1447                egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
1448                egui::Color32::WHITE,
1449            );
1450        };
1451        renderer
1452            .render_egui(8, 8, &RenderFrame::new(&context), draw)
1453            .expect("first frame");
1454        assert_eq!(renderer.surface().pixels[..4], [255, 0, 0, 255]);
1455
1456        // The recolor applies; two 4 MiB images then pass the texture budget on the second.
1457        image.set(solid(egui::Color32::BLUE), egui::TextureOptions::NEAREST);
1458        let side = 1024;
1459        let _over_budget: Vec<egui::TextureHandle> = (0..2)
1460            .map(|index| {
1461                context.load_texture(
1462                    format!("large {index}"),
1463                    egui::ColorImage::new([side, side], vec![egui::Color32::WHITE; side * side]),
1464                    egui::TextureOptions::NEAREST,
1465                )
1466            })
1467            .collect();
1468        assert!(
1469            renderer
1470                .render_egui(8, 8, &RenderFrame::new(&context), draw)
1471                .is_err()
1472        );
1473
1474        let outcome = renderer
1475            .render_egui(8, 8, &RenderFrame::new(&context), draw)
1476            .expect("third frame");
1477        assert!(outcome.surface_changed);
1478        assert_eq!(renderer.surface().pixels[..4], [0, 0, 255, 255]);
1479    }
1480
1481    fn quad_vertices() -> [Vertex; 4] {
1482        [
1483            test_vertex(1.0, 1.0),
1484            test_vertex(4.0, 1.0),
1485            test_vertex(1.0, 3.0),
1486            test_vertex(4.0, 3.0),
1487        ]
1488    }
1489
1490    fn textured_quad_mesh(texture_id: egui::TextureId) -> egui::Mesh {
1491        let mut vertices = quad_vertices();
1492        vertices[0].uv = [0.0, 0.0];
1493        vertices[1].uv = [1.0, 0.0];
1494        vertices[2].uv = [0.0, 1.0];
1495        vertices[3].uv = [1.0, 1.0];
1496        egui::Mesh {
1497            indices: vec![0, 1, 2, 1, 3, 2],
1498            vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
1499            texture_id,
1500        }
1501    }
1502
1503    fn full_surface_quad_mesh(texture_id: egui::TextureId, width: f32, height: f32) -> egui::Mesh {
1504        let mut vertices = [
1505            test_vertex(0.0, 0.0),
1506            test_vertex(width, 0.0),
1507            test_vertex(0.0, height),
1508            test_vertex(width, height),
1509        ];
1510        for vertex in &mut vertices {
1511            vertex.uv = [0.0, 0.0];
1512        }
1513        egui::Mesh {
1514            indices: vec![0, 1, 2, 1, 3, 2],
1515            vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
1516            texture_id,
1517        }
1518    }
1519
1520    fn clipped_mesh_primitive(mesh: egui::Mesh, width: f32, height: f32) -> egui::ClippedPrimitive {
1521        egui::ClippedPrimitive {
1522            clip_rect: egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(width, height)),
1523            primitive: egui::epaint::Primitive::Mesh(mesh),
1524        }
1525    }
1526
1527    fn renderer_with_white_texture(
1528        texture_id: egui::TextureId,
1529        width: usize,
1530        height: usize,
1531    ) -> SoftwareRenderer {
1532        let mut renderer = SoftwareRenderer::default();
1533        renderer.surface.resize(width, height).expect("surface");
1534        renderer.surface.clear([0, 0, 0, 255]);
1535        renderer
1536            .textures
1537            .apply(&mut solid_texture_delta(texture_id, Color::WHITE))
1538            .expect("texture");
1539        renderer
1540    }
1541
1542    fn solid_fan_mesh(texture_id: egui::TextureId, color: [u8; 4]) -> egui::Mesh {
1543        let color = Color::from_rgba_premultiplied(color[0], color[1], color[2], color[3]);
1544        let vertices = [
1545            pos2(1.0, 5.0),
1546            pos2(2.0, 1.0),
1547            pos2(6.0, 1.0),
1548            pos2(9.0, 3.0),
1549            pos2(8.0, 8.0),
1550            pos2(3.0, 9.0),
1551        ]
1552        .map(|pos| Vertex {
1553            pos: [pos.x, pos.y],
1554            uv: [0.0, 0.0],
1555            color,
1556        });
1557        egui::Mesh {
1558            indices: vec![1, 0, 2, 2, 0, 3, 3, 0, 4, 4, 0, 5],
1559            vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
1560            texture_id,
1561        }
1562    }
1563
1564    fn too_short_mixed_triangle_mesh(texture_id: egui::TextureId) -> egui::Mesh {
1565        let mut vertices = [
1566            test_vertex(1.0, 1.0),
1567            test_vertex(4.0, 1.0),
1568            test_vertex(1.0, 4.0),
1569            test_vertex(5.0, 1.0),
1570            test_vertex(8.0, 1.0),
1571            test_vertex(5.0, 4.0),
1572            test_vertex(1.0, 5.0),
1573            test_vertex(4.0, 5.0),
1574            test_vertex(1.0, 8.0),
1575        ];
1576        vertices[5].color = Color::BLACK;
1577        vertices[7].uv = [1.0, 0.0];
1578        vertices[8].uv = [0.0, 1.0];
1579        egui::Mesh {
1580            indices: vec![0, 1, 2, 3, 4, 5, 6, 7, 8],
1581            vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
1582            texture_id,
1583        }
1584    }
1585
1586    fn disconnected_solid_triangles_mesh(texture_id: egui::TextureId) -> egui::Mesh {
1587        let vertices = [
1588            test_vertex(1.0, 1.0),
1589            test_vertex(3.0, 1.0),
1590            test_vertex(1.0, 3.0),
1591            test_vertex(5.0, 1.0),
1592            test_vertex(7.0, 1.0),
1593            test_vertex(5.0, 3.0),
1594            test_vertex(1.0, 5.0),
1595            test_vertex(3.0, 5.0),
1596            test_vertex(1.0, 7.0),
1597            test_vertex(5.0, 5.0),
1598            test_vertex(7.0, 5.0),
1599            test_vertex(5.0, 7.0),
1600        ];
1601        egui::Mesh {
1602            indices: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
1603            vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
1604            texture_id,
1605        }
1606    }
1607
1608    fn assert_accepted_solid_fan_primitive_stats(primitive_stats: &PrimitiveStats) {
1609        assert_eq!(primitive_stats.solid_fan_runs, 1);
1610        assert_eq!(primitive_stats.solid_fan_triangles, 4);
1611        assert_eq!(primitive_stats.solid_fan_probe.probe_calls, 1);
1612        assert_eq!(primitive_stats.solid_fan_probe.rejected_probe_calls, 0);
1613        assert_eq!(
1614            primitive_stats
1615                .solid_fan_probe
1616                .preflight_second_triangle_checks,
1617            1
1618        );
1619        assert_eq!(
1620            primitive_stats
1621                .solid_fan_probe
1622                .preflight_reject_no_second_triangle_continuation,
1623            0
1624        );
1625        assert_eq!(
1626            primitive_stats
1627                .solid_fan_probe
1628                .preflight_center_slots_allowed,
1629            2
1630        );
1631        assert_eq!(
1632            primitive_stats
1633                .solid_fan_probe
1634                .preflight_center_slots_rejected,
1635            1
1636        );
1637        assert_eq!(primitive_stats.solid_fan_probe.center_slot_attempts, 1);
1638        assert_eq!(primitive_stats.solid_fan_probe.cheap_candidate_attempts, 1);
1639        assert_eq!(
1640            primitive_stats.solid_fan_probe.candidate_triangles_scanned,
1641            4
1642        );
1643        assert_eq!(
1644            primitive_stats
1645                .solid_fan_probe
1646                .accepted_candidate_triangles_scanned,
1647            4
1648        );
1649        assert_eq!(
1650            primitive_stats
1651                .solid_fan_probe
1652                .rejected_candidate_triangles_scanned,
1653            0
1654        );
1655        assert_eq!(primitive_stats.solid_fan_probe.repeated_boundary_checks, 3);
1656        assert_eq!(
1657            primitive_stats
1658                .solid_fan_probe
1659                .repeated_boundary_comparisons,
1660            9
1661        );
1662        assert_eq!(primitive_stats.solid_fan_probe.reject_no_candidate, 0);
1663        assert_eq!(primitive_stats.solid_fan_probe.accepted_runs, 1);
1664        assert_eq!(primitive_stats.solid_fan_probe.accepted_triangles, 4);
1665        assert_eq!(primitive_stats.solid_fan_probe.polygon_builds, 1);
1666        assert_eq!(primitive_stats.solid_fan_probe.max_candidate_triangles, 4);
1667        assert_eq!(primitive_stats.solid_fan_probe.max_accepted_triangles, 4);
1668    }
1669
1670    fn render_solid_fan_reference(
1671        mesh: &egui::Mesh,
1672        texture: &TextureImage,
1673        clip: ClipBounds,
1674    ) -> Vec<u8> {
1675        let mut surface = SoftwareSurface::default();
1676        surface.resize(12, 12).expect("surface");
1677        surface.clear([0, 0, 0, 255]);
1678        let vertices = vertices_from_egui(&mesh.vertices);
1679        for triangle in mesh.indices.as_chunks::<3>().0 {
1680            let v0 = &vertices[usize::try_from(triangle[0]).expect("index")];
1681            let v1 = &vertices[usize::try_from(triangle[1]).expect("index")];
1682            let v2 = &vertices[usize::try_from(triangle[2]).expect("index")];
1683            rasterize_triangle(&mut surface, v0, v1, v2, texture, clip, None);
1684        }
1685        surface.pixels
1686    }
1687
1688    fn texture_delta(texture_id: egui::TextureId) -> egui::TexturesDelta {
1689        let image = egui::ColorImage::new(
1690            [2, 2],
1691            vec![
1692                egui::Color32::from_rgb(10, 0, 0),
1693                egui::Color32::from_rgb(20, 0, 0),
1694                egui::Color32::from_rgb(30, 0, 0),
1695                egui::Color32::from_rgb(40, 0, 0),
1696            ],
1697        );
1698        egui::TexturesDelta {
1699            set: [(
1700                texture_id,
1701                [egui::epaint::ImageDelta::full(
1702                    image,
1703                    egui::TextureOptions::NEAREST,
1704                )]
1705                .into_iter()
1706                .collect(),
1707            )]
1708            .into_iter()
1709            .collect(),
1710            free: [].into_iter().collect(),
1711        }
1712    }
1713
1714    fn solid_texture_delta(texture_id: egui::TextureId, color: Color) -> egui::TexturesDelta {
1715        let image = egui::ColorImage::new([2, 2], vec![color.to_egui(); 4]);
1716        egui::TexturesDelta {
1717            set: [(
1718                texture_id,
1719                [egui::epaint::ImageDelta::full(
1720                    image,
1721                    egui::TextureOptions::NEAREST,
1722                )]
1723                .into_iter()
1724                .collect(),
1725            )]
1726            .into_iter()
1727            .collect(),
1728            free: [].into_iter().collect(),
1729        }
1730    }
1731
1732    fn clip_bounds(width: usize, height: usize) -> ClipBounds {
1733        ClipBounds::full(width, height)
1734    }
1735
1736    fn test_vertex(x: f32, y: f32) -> Vertex {
1737        Vertex {
1738            pos: [x, y],
1739            uv: [0.0, 0.0],
1740            color: Color::WHITE,
1741        }
1742    }
1743}