// SPDX-License-Identifier: MIT OR Apache-2.0
//! The egui half of the renderer: running a UI frame, applying egui's texture uploads,
//! tessellating, skipping unchanged frames, and the diagnostics Dream-INI logs. Everything
//! here converts into the core's own types before any pixel is drawn.
use std::io;
use std::time::{Duration, Instant};
use super::quad::has_four_unique_indices;
#[allow(
clippy::wildcard_imports,
reason = "this module is the renderer's egui half"
)]
use super::*;
use crate::egui_adapter::{format_repaint_delay, raster_mesh_from_egui, vertices_from_egui};
use crate::raster::{ClearElisionQuadRejection, clear_elision_quad_evidence, usize_to_f32};
use crate::render_benchmark::{
SampledRectModulatedWorkload, SampledRectModulatedWorkloadStats, background_color,
};
use crate::texture::{TextureDeltaStats, TextureKey};
/// Per-frame inputs and logging switches for [`SoftwareRenderer::render_egui`].
pub struct RenderFrame<'a> {
/// The egui context the frame's UI runs in.
pub context: &'a egui::Context,
/// Sink for diagnostic log lines; `None` discards them.
pub log: Option<&'a dyn Fn(&str)>,
/// Log per-frame surface and timing summaries.
pub log_frame: bool,
/// Collect and log deep primitive/raster statistics.
pub log_render_stats: bool,
/// When set, timings are measured even on frames that are not logged.
pub hitch_log_threshold: Option<Duration>,
/// Frame counter echoed in log lines.
pub frame_index: u64,
/// Whether a repaint was already due when the frame started (logged only).
pub repaint_request_due_before_frame: bool,
/// Rasterize this synthetic workload instead of running the UI.
pub synthetic_workload: Option<&'a SampledRectModulatedWorkload>,
}
impl<'a> RenderFrame<'a> {
/// A frame for `context` with logging, stats, and the synthetic benchmark off.
#[must_use]
pub const fn new(context: &'a egui::Context) -> Self {
Self {
context,
log: None,
log_frame: false,
log_render_stats: false,
hitch_log_threshold: None,
frame_index: 0,
repaint_request_due_before_frame: false,
synthetic_workload: None,
}
}
}
impl RenderFrame<'_> {
fn write_log(&self, message: impl AsRef<str>) {
if let Some(log) = self.log {
log(message.as_ref());
}
}
}
impl SoftwareRenderer {
/// Runs `run_ui` for one egui frame sized `width`x`height`, applies egui's texture
/// changes, tessellates the output, and rasterizes it into the surface.
///
/// egui meshes can show textures made with [`SoftwareRenderer::create_texture`] through
/// [`crate::egui_adapter::egui_texture_id`].
///
/// # Errors
///
/// Returns an error if the surface cannot be sized, a texture delta is malformed or would
/// exceed [`MAX_TEXTURE_BYTES`](crate::MAX_TEXTURE_BYTES), a mesh's index count is not a
/// multiple of three or an index is past its vertices, a clip rectangle is not finite, or
/// egui emits a paint callback. Mesh errors carry the [`Error`](crate::Error) that
/// [`Frame::mesh`](crate::Frame::mesh) would return for the same indices.
pub fn render_egui(
&mut self,
width: usize,
height: usize,
frame: &RenderFrame<'_>,
run_ui: impl FnMut(&mut egui::Ui),
) -> io::Result<RenderOutcome> {
let log_timings = frame.log_frame || frame.hitch_log_threshold.is_some();
let total_start = log_timings.then(Instant::now);
let (surface_resized, cleared_this_frame, resize_clear_elapsed) =
self.prepare_surface(width, height, log_timings)?;
if let Some(workload) = frame.synthetic_workload {
return self.render_synthetic_benchmark(
workload,
frame,
total_start,
resize_clear_elapsed,
surface_resized,
);
}
let stage_start = log_timings.then(Instant::now);
let raw_input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(usize_to_f32(width), usize_to_f32(height)),
)),
max_texture_side: Some(1024),
..Default::default()
};
let mut output = frame.context.run_ui(raw_input, run_ui);
let repaint_delay = root_repaint_delay(&output);
let egui_run_elapsed = elapsed_micros(stage_start);
let stage_start = log_timings.then(Instant::now);
let had_texture_updates = !output.textures_delta.set.is_empty();
let texture_delta_stats = self.apply_egui_textures(&mut output.textures_delta)?;
let texture_apply_elapsed = elapsed_micros(stage_start);
let stage_start = log_timings.then(Instant::now);
let primitives = frame.context.tessellate(output.shapes, 1.0);
let primitive_count = primitives.len();
let tessellate_elapsed = elapsed_micros(stage_start);
log_surface_stats(
frame,
&self.surface,
&self.textures,
&texture_delta_stats,
primitive_count,
surface_resized,
cleared_this_frame,
);
let stage_start = log_timings.then(Instant::now);
let unchanged = self.frame_is_unchanged(surface_resized, had_texture_updates, &primitives);
let collect_stats = !unchanged && should_collect_deep_stats(frame.log_render_stats);
let mut primitive_stats = collect_stats.then(PrimitiveStats::default);
let mut raster_stats = collect_stats.then(RasterStats::default);
let mut raster_timings = collect_stats.then(RasterTimings::default);
let clear_elision_stats = collect_stats.then(|| self.probe_clear_elision(&primitives));
let rasterize_result = if unchanged {
Ok(())
} else {
self.rasterize(
&primitives,
primitive_stats.as_mut(),
raster_stats.as_mut(),
raster_timings.as_mut(),
)
};
self.previous_frame_valid = rasterize_result.is_ok();
self.previous_primitives = primitives;
let rasterize_elapsed = elapsed_micros(stage_start);
log_raster_stats(
frame,
&self.surface,
clear_elision_stats.as_ref(),
primitive_stats.as_ref(),
raster_stats.as_ref(),
raster_timings.as_ref(),
);
let stage_start = log_timings.then(Instant::now);
self.free_egui_textures(&output.textures_delta.free);
output.textures_delta.clear();
rasterize_result?;
let texture_free_elapsed = elapsed_micros(stage_start);
let texture_evidence = self.texture_evidence(&texture_delta_stats);
let total_elapsed = elapsed_micros(total_start);
let timings = log_timings.then_some(RenderTimings {
resize_clear: resize_clear_elapsed,
egui_run: egui_run_elapsed,
texture_apply: texture_apply_elapsed,
tessellate: tessellate_elapsed,
rasterize: rasterize_elapsed,
texture_free: texture_free_elapsed,
total: total_elapsed,
});
log_render_timings(frame, timings, repaint_delay, unchanged);
Ok(RenderOutcome {
repaint_delay,
timings,
primitive_count,
texture_evidence,
surface_changed: !unchanged,
})
}
/// Applies egui's texture uploads. When one fails, those before it have still changed their
/// textures, so the surface no longer shows what the store holds, and the frame's releases
/// are freed now because the frame ends here.
fn apply_egui_textures(
&mut self,
delta: &mut egui::TexturesDelta,
) -> io::Result<TextureDeltaStats> {
self.textures.apply(delta).inspect_err(|_| {
self.previous_frame_valid = false;
self.free_egui_textures(&delta.free);
delta.clear();
})
}
/// Frees the textures egui released this frame. egui names them only once, so every way out
/// of a frame frees them, failed frames included.
fn free_egui_textures<'a>(&mut self, released: impl IntoIterator<Item = &'a egui::TextureId>) {
for &id in released {
self.textures.free_egui(id);
}
}
fn frame_is_unchanged(
&self,
surface_resized: bool,
had_texture_updates: bool,
primitives: &[egui::ClippedPrimitive],
) -> bool {
self.skip_unchanged_frames
&& self.previous_frame_valid
&& !surface_resized
&& !had_texture_updates
&& same_primitives(&self.previous_primitives, primitives)
}
fn texture_evidence(&self, delta: &TextureDeltaStats) -> TextureEvidence {
TextureEvidence {
count: self.textures.len(),
bytes: self.textures.bytes_used(),
set_count: delta.set_count,
set_bytes: delta.set_bytes,
full_upload_count: delta.full_upload_count,
partial_update_count: delta.partial_update_count,
}
}
/// Whether egui frames whose tessellated output is bit-identical to the previous frame, with no
/// texture uploads, skip rasterization and keep the previous surface. Enabled by default.
pub const fn set_skip_unchanged_frames(&mut self, skip: bool) {
self.skip_unchanged_frames = skip;
}
fn prepare_surface(
&mut self,
width: usize,
height: usize,
log_timings: bool,
) -> io::Result<(bool, bool, u128)> {
let stage_start = log_timings.then(Instant::now);
let surface_resized = self.surface.resize(width, height)?;
if surface_resized {
self.surface.clear(crate::Color::TRANSPARENT.to_array());
}
Ok((
surface_resized,
surface_resized,
elapsed_micros(stage_start),
))
}
fn render_synthetic_benchmark(
&mut self,
workload: &SampledRectModulatedWorkload,
frame: &RenderFrame<'_>,
total_start: Option<Instant>,
resize_clear_elapsed: u128,
surface_resized: bool,
) -> io::Result<RenderOutcome> {
self.previous_frame_valid = false;
self.surface.clear(background_color());
let collect_stats = should_collect_deep_stats(frame.log_render_stats);
let mut primitive_stats = collect_stats.then(PrimitiveStats::default);
let mut raster_stats = collect_stats.then(RasterStats::default);
let mut raster_timings = collect_stats.then(RasterTimings::default);
let rasterize_start = Instant::now();
let (workload_stats, texture_bytes, clear_elision_stats) = {
let clear_elision_stats = collect_stats.then(|| {
synthetic_clear_elision_stats(workload, self.surface.width, self.surface.height)
});
self.rasterize_synthetic_workload(
workload,
primitive_stats.as_mut(),
raster_stats.as_mut(),
raster_timings.as_mut(),
)?;
(
workload.stats(),
workload.texture().pixels.len(),
clear_elision_stats,
)
};
let rasterize_elapsed = rasterize_start.elapsed().as_micros();
log_synthetic_surface_stats(
frame,
&self.surface,
workload_stats,
texture_bytes,
surface_resized,
);
log_raster_stats(
frame,
&self.surface,
clear_elision_stats.as_ref(),
primitive_stats.as_ref(),
raster_stats.as_ref(),
raster_timings.as_ref(),
);
let timings =
(frame.log_frame || frame.hitch_log_threshold.is_some()).then_some(RenderTimings {
resize_clear: resize_clear_elapsed,
egui_run: 0,
texture_apply: 0,
tessellate: 0,
rasterize: rasterize_elapsed,
texture_free: 0,
total: elapsed_micros(total_start),
});
log_render_timings(frame, timings, Duration::ZERO, false);
Ok(RenderOutcome {
repaint_delay: Duration::ZERO,
timings,
primitive_count: 1,
texture_evidence: TextureEvidence {
count: 1,
bytes: texture_bytes,
set_count: 0,
set_bytes: 0,
full_upload_count: 0,
partial_update_count: 0,
},
surface_changed: true,
})
}
fn rasterize_synthetic_workload(
&mut self,
workload: &SampledRectModulatedWorkload,
mut stats: Option<&mut PrimitiveStats>,
mut raster_stats: Option<&mut RasterStats>,
mut raster_timings: Option<&mut RasterTimings>,
) -> io::Result<()> {
if let Some(stats) = borrow_optional_mut(&mut stats) {
stats.mesh_primitives += 1;
stats.mesh_indices += workload.mesh().indices.len();
}
let clip = ClipBounds::full(self.surface.width, self.surface.height);
let mut context = MeshRasterContext {
surface: &mut self.surface,
fan_polygon_scratch: &mut self.solid_fan_polygon_scratch,
fan_seen_boundary_scratch: &mut self.solid_fan_seen_boundary_scratch,
fan_span_cache: &mut self.solid_fan_span_cache,
mesh: workload.mesh(),
texture: workload.texture(),
clip,
primitive_index: 0,
solid_fan_polygon_scratch_budget: SOLID_FAN_POLYGON_SCRATCH_CAPACITY,
};
rasterize_mesh_contents(
&mut context,
&mut stats,
&mut raster_stats,
&mut raster_timings,
)?;
if let Some(stats) = raster_stats {
self.solid_fan_span_cache.record_stats(stats);
}
Ok(())
}
fn probe_clear_elision(&self, primitives: &[egui::ClippedPrimitive]) -> ClearElisionFrameStats {
let mut stats = ClearElisionFrameStats {
probe_frames: 1,
..Default::default()
};
for primitive in primitives {
let egui::epaint::Primitive::Mesh(mesh) = &primitive.primitive else {
stats.reject_first_visible_not_rect = 1;
return stats;
};
let Some(texture) = self
.textures
.get(TextureKey::for_egui_mesh(mesh.texture_id))
else {
continue;
};
let Ok(clip) =
egui_clip_bounds(primitive.clip_rect, self.surface.width, self.surface.height)
else {
stats.reject_first_visible_not_rect = 1;
return stats;
};
if clip.is_empty() {
continue;
}
let Some(evidence) = probe_mesh_clear_elision(
raster_mesh_from_egui(mesh),
texture,
clip,
self.surface.width,
self.surface.height,
) else {
continue;
};
stats.record_quad_evidence(evidence);
return stats;
}
stats.reject_no_primitives = 1;
stats
}
pub(super) fn rasterize(
&mut self,
primitives: &[egui::ClippedPrimitive],
mut stats: Option<&mut PrimitiveStats>,
mut raster_stats: Option<&mut RasterStats>,
mut raster_timings: Option<&mut RasterTimings>,
) -> io::Result<()> {
for (primitive_index, primitive) in primitives.iter().enumerate() {
match &primitive.primitive {
egui::epaint::Primitive::Mesh(mesh) => {
if let Some(stats) = borrow_optional_mut(&mut stats) {
stats.mesh_primitives += 1;
}
self.rasterize_mesh(
mesh,
primitive.clip_rect,
primitive_index,
borrow_optional_mut(&mut stats),
borrow_optional_mut(&mut raster_stats),
borrow_optional_mut(&mut raster_timings),
)?;
}
egui::epaint::Primitive::Callback(_) => {
if let Some(stats) = borrow_optional_mut(&mut stats) {
stats.callback_primitives += 1;
}
return Err(io::Error::other(
"unsupported egui paint callback in software renderer",
));
}
}
}
if let Some(stats) = raster_stats {
self.solid_fan_span_cache.record_stats(stats);
}
Ok(())
}
fn rasterize_mesh(
&mut self,
mesh: &egui::Mesh,
clip_rect: egui::Rect,
primitive_index: usize,
mut stats: Option<&mut PrimitiveStats>,
mut raster_stats: Option<&mut RasterStats>,
mut raster_timings: Option<&mut RasterTimings>,
) -> io::Result<()> {
check_egui_mesh_indices(mesh)?;
if let Some(stats) = borrow_optional_mut(&mut stats) {
stats.mesh_indices += mesh.indices.len();
}
let Some(texture) = self
.textures
.get(TextureKey::for_egui_mesh(mesh.texture_id))
else {
if let Some(stats) = borrow_optional_mut(&mut stats) {
stats.missing_texture_meshes += 1;
}
return Ok(());
};
let clip = egui_clip_bounds(clip_rect, self.surface.width, self.surface.height)?;
if clip.is_empty() {
if let Some(stats) = borrow_optional_mut(&mut stats) {
stats.empty_clip_meshes += 1;
}
return Ok(());
}
self.solid_fan_polygon_scratch.clear();
self.solid_fan_seen_boundary_scratch.clear();
let mut context = MeshRasterContext {
surface: &mut self.surface,
fan_polygon_scratch: &mut self.solid_fan_polygon_scratch,
fan_seen_boundary_scratch: &mut self.solid_fan_seen_boundary_scratch,
fan_span_cache: &mut self.solid_fan_span_cache,
mesh: raster_mesh_from_egui(mesh),
texture,
clip,
primitive_index,
solid_fan_polygon_scratch_budget: SOLID_FAN_POLYGON_SCRATCH_CAPACITY,
};
rasterize_mesh_contents(
&mut context,
&mut stats,
&mut raster_stats,
&mut raster_timings,
)?;
Ok(())
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct ClearElisionFrameStats {
probe_frames: usize,
eligible_frames: usize,
reject_no_primitives: usize,
reject_first_visible_not_rect: usize,
reject_clip_not_full_surface: usize,
reject_alpha_not_opaque: usize,
reject_texture_not_constant_white: usize,
reject_not_full_surface_opaque_rect: usize,
full_surface_opaque_rect_frames: usize,
near_full_surface_opaque_rect_frames: usize,
max_opaque_cover_basis_points: usize,
}
impl ClearElisionFrameStats {
fn record_quad_evidence(&mut self, evidence: crate::raster::ClearElisionQuadEvidence) {
if evidence.opaque_rect {
self.max_opaque_cover_basis_points = evidence.cover_basis_points;
}
if evidence.full_surface_opaque_rect {
self.eligible_frames = 1;
self.full_surface_opaque_rect_frames = 1;
}
if evidence.near_full_surface_opaque_rect {
self.near_full_surface_opaque_rect_frames = 1;
}
match evidence.rejection {
None => {}
Some(ClearElisionQuadRejection::NotRect) => self.reject_first_visible_not_rect = 1,
Some(ClearElisionQuadRejection::ClipNotFullSurface) => {
self.reject_clip_not_full_surface = 1;
}
Some(ClearElisionQuadRejection::AlphaNotOpaque) => {
self.reject_alpha_not_opaque = 1;
}
Some(ClearElisionQuadRejection::TextureNotConstantWhite) => {
self.reject_texture_not_constant_white = 1;
}
Some(ClearElisionQuadRejection::NotFullSurfaceOpaqueRect) => {
self.reject_not_full_surface_opaque_rect = 1;
}
}
}
}
/// What one [`SoftwareRenderer::render_egui`] call produced.
#[derive(Clone, Copy, Debug)]
pub struct RenderOutcome {
/// How long egui wants to wait before the next frame; `Duration::MAX` means no repaint was
/// requested.
pub repaint_delay: Duration,
/// Stage timings, measured only when [`RenderFrame::log_frame`] or
/// [`RenderFrame::hitch_log_threshold`] asked for them.
pub timings: Option<RenderTimings>,
/// Clipped primitives egui produced.
pub primitive_count: usize,
/// Texture storage after the frame, and this frame's uploads.
pub texture_evidence: TextureEvidence,
/// False when the frame matched the previous one and the surface was left untouched,
/// so presenting it again can be skipped.
pub surface_changed: bool,
}
/// Texture store totals and this frame's texture upload counts.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TextureEvidence {
/// Textures stored after the frame.
pub count: usize,
/// Bytes of texture pixels stored after the frame.
pub bytes: usize,
/// Texture uploads egui made this frame.
pub set_count: usize,
/// Bytes those uploads carried.
pub set_bytes: usize,
/// Uploads that replaced a whole texture.
pub full_upload_count: usize,
/// Uploads that patched part of an existing texture.
pub partial_update_count: usize,
}
/// Per-stage render durations in microseconds.
#[derive(Clone, Copy, Debug)]
pub struct RenderTimings {
/// Sizing the surface, and clearing it if the size changed.
pub resize_clear: u128,
/// Running the UI closure.
pub egui_run: u128,
/// Applying egui's texture uploads.
pub texture_apply: u128,
/// Tessellating egui's shapes into meshes.
pub tessellate: u128,
/// Rasterizing the meshes, or for a frame skipped as unchanged, finding that it was.
pub rasterize: u128,
/// Freeing textures egui released.
pub texture_free: u128,
/// The whole call.
pub total: u128,
}
fn log_surface_stats(
frame: &RenderFrame<'_>,
surface: &SoftwareSurface,
textures: &TextureStore,
texture_delta_stats: &TextureDeltaStats,
primitive_count: usize,
surface_resized: bool,
cleared_this_frame: bool,
) {
if frame.log_frame {
frame.write_log(format!(
"software renderer frame={} surface={}x{} bytes={} textures={} texture_bytes={} primitives={}",
frame.frame_index,
surface.width,
surface.height,
surface.pixels.len(),
textures.len(),
textures.bytes_used(),
primitive_count,
),
);
}
if frame.log_render_stats {
frame.write_log(format!(
"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={}",
frame.frame_index,
surface.width,
surface.height,
surface.pixels.len(),
texture_delta_stats.set_count,
texture_delta_stats.set_bytes,
texture_delta_stats.full_upload_count,
texture_delta_stats.partial_update_count,
primitive_count,
frame.repaint_request_due_before_frame,
frame.context.has_requested_repaint(),
cleared_this_frame,
surface_resized,
),
);
}
}
fn log_synthetic_surface_stats(
frame: &RenderFrame<'_>,
surface: &SoftwareSurface,
stats: SampledRectModulatedWorkloadStats,
texture_bytes: usize,
surface_resized: bool,
) {
if frame.log_frame {
frame.write_log(format!(
"software renderer frame={} surface={}x{} bytes={} textures=1 texture_bytes={} primitives=1 benchmark=sampled-rect-modulated benchmark_rects={} benchmark_pixels={}",
frame.frame_index,
surface.width,
surface.height,
surface.pixels.len(),
texture_bytes,
stats.rects,
stats.pixels,
),
);
}
if frame.log_render_stats {
frame.write_log(format!(
"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",
frame.frame_index,
surface.width,
surface.height,
surface.pixels.len(),
frame.repaint_request_due_before_frame,
surface_resized,
stats.lt4_pixels,
stats.mid_pixels,
stats.wide_pixels,
),
);
}
}
fn synthetic_clear_elision_stats(
workload: &SampledRectModulatedWorkload,
surface_width: usize,
surface_height: usize,
) -> ClearElisionFrameStats {
let clip = ClipBounds::full(surface_width, surface_height);
let evidence = mesh_quad_vertices(workload.mesh(), &workload.mesh().indices[..6])
.ok()
.flatten()
.map(|vertices| {
clear_elision_quad_evidence(
vertices,
workload.texture(),
clip,
surface_width,
surface_height,
)
});
let mut stats = ClearElisionFrameStats {
probe_frames: 1,
..Default::default()
};
if let Some(evidence) = evidence {
stats.record_quad_evidence(evidence);
} else {
stats.reject_first_visible_not_rect = 1;
}
stats
}
fn log_raster_stats(
frame: &RenderFrame<'_>,
surface: &SoftwareSurface,
clear_elision_stats: Option<&ClearElisionFrameStats>,
primitive_stats: Option<&PrimitiveStats>,
raster_stats: Option<&RasterStats>,
raster_timings: Option<&RasterTimings>,
) {
if let Some(stats) = primitive_stats {
frame.write_log(stats.log_line(frame.frame_index));
if let Some(log_line) = stats.solid_triangle_offenders_log_line() {
frame.write_log(log_line);
}
if let Some(log_line) = stats.textured_triangle_offenders_log_line() {
frame.write_log(log_line);
}
if let Some(log_line) = stats.textured_quad_reject_offenders_log_line() {
frame.write_log(log_line);
}
if let Some(log_line) = stats.solid_fan_offenders_log_line() {
frame.write_log(log_line);
}
}
if let Some(stats) = raster_stats {
if frame.log_render_stats {
frame.write_log(clear_evidence_log_line(
frame.frame_index,
surface.width,
surface.height,
stats,
clear_elision_stats,
));
}
frame.write_log(stats.log_line());
}
if let Some(timings) = raster_timings {
frame.write_log(timings.log_line());
}
}
fn log_render_timings(
frame: &RenderFrame<'_>,
timings: Option<RenderTimings>,
repaint_delay: Duration,
raster_skipped: bool,
) {
if !frame.log_frame {
return;
}
let Some(timings) = timings else {
return;
};
let repaint_delay = format_repaint_delay(repaint_delay);
frame.write_log(format!(
"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={}",
frame.frame_index,
timings.resize_clear,
timings.egui_run,
timings.texture_apply,
timings.tessellate,
timings.rasterize,
timings.texture_free,
timings.total,
),
);
}
fn clear_evidence_log_line(
frame_index: u64,
width: usize,
height: usize,
stats: &RasterStats,
clear_elision_stats: Option<&ClearElisionFrameStats>,
) -> String {
let clear_elision_stats = clear_elision_stats.copied().unwrap_or_default();
let clear_pixels = width.saturating_mul(height);
let clear_bytes = clear_pixels.saturating_mul(4);
let opaque_drawn_pixels = stats.opaque_px;
let opaque_drawn_percent = opaque_drawn_pixels
.saturating_mul(100)
.checked_div(clear_pixels)
.unwrap_or(0);
format!(
"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={}",
clear_elision_stats.probe_frames,
clear_elision_stats.eligible_frames,
clear_elision_stats.reject_no_primitives,
clear_elision_stats.reject_first_visible_not_rect,
clear_elision_stats.reject_clip_not_full_surface,
clear_elision_stats.reject_alpha_not_opaque,
clear_elision_stats.reject_texture_not_constant_white,
clear_elision_stats.reject_not_full_surface_opaque_rect,
clear_elision_stats.full_surface_opaque_rect_frames,
clear_elision_stats.near_full_surface_opaque_rect_frames,
clear_elision_stats.max_opaque_cover_basis_points,
)
}
fn probe_mesh_clear_elision(
mesh: RasterMesh<'_>,
texture: &TextureImage,
clip: ClipBounds,
surface_width: usize,
surface_height: usize,
) -> Option<crate::raster::ClearElisionQuadEvidence> {
let mut index_offset = 0;
while index_offset + 2 < mesh.indices.len() {
if index_offset + 5 >= mesh.indices.len() {
return Some(crate::raster::ClearElisionQuadEvidence {
visible_px: 0,
cover_basis_points: 0,
opaque_rect: false,
full_surface_opaque_rect: false,
near_full_surface_opaque_rect: false,
rejection: Some(ClearElisionQuadRejection::NotRect),
});
}
let quad = &mesh.indices[index_offset..index_offset + 6];
if !has_four_unique_indices(quad) {
return Some(crate::raster::ClearElisionQuadEvidence {
visible_px: 0,
cover_basis_points: 0,
opaque_rect: false,
full_surface_opaque_rect: false,
near_full_surface_opaque_rect: false,
rejection: Some(ClearElisionQuadRejection::NotRect),
});
}
let Ok(Some(vertices)) = mesh_quad_vertices(mesh, quad) else {
return Some(crate::raster::ClearElisionQuadEvidence {
visible_px: 0,
cover_basis_points: 0,
opaque_rect: false,
full_surface_opaque_rect: false,
near_full_surface_opaque_rect: false,
rejection: Some(ClearElisionQuadRejection::NotRect),
});
};
let evidence =
clear_elision_quad_evidence(vertices, texture, clip, surface_width, surface_height);
if evidence.visible_px == 0
&& !matches!(evidence.rejection, Some(ClearElisionQuadRejection::NotRect))
{
index_offset += 6;
continue;
}
return Some(evidence);
}
None
}
/// Bitwise comparison, so any difference that could change a rasterized pixel (including
/// `-0.0` versus `0.0` and NaN payloads) counts as a change.
fn same_primitives(
previous: &[egui::ClippedPrimitive],
current: &[egui::ClippedPrimitive],
) -> bool {
fn same_rect(left: egui::Rect, right: egui::Rect) -> bool {
let bits =
|rect: egui::Rect| [rect.min.x, rect.min.y, rect.max.x, rect.max.y].map(f32::to_bits);
bits(left) == bits(right)
}
fn same_mesh(left: &egui::Mesh, right: &egui::Mesh) -> bool {
let bits = |vertex: &Vertex| {
(
vertex.pos.map(f32::to_bits),
vertex.uv.map(f32::to_bits),
vertex.color,
)
};
let (left_vertices, right_vertices) = (
vertices_from_egui(&left.vertices),
vertices_from_egui(&right.vertices),
);
left.texture_id == right.texture_id
&& left.indices == right.indices
&& left_vertices.len() == right_vertices.len()
&& left_vertices
.iter()
.zip(right_vertices)
.all(|(left, right)| bits(left) == bits(right))
}
previous.len() == current.len()
&& previous.iter().zip(current).all(|(previous, current)| {
same_rect(previous.clip_rect, current.clip_rect)
&& match (&previous.primitive, ¤t.primitive) {
(egui::epaint::Primitive::Mesh(left), egui::epaint::Primitive::Mesh(right)) => {
same_mesh(left, right)
}
_ => false,
}
})
}
/// Holds an egui mesh's indices to what [`Frame::mesh`] requires of its own: whole triangles,
/// and no index past the vertices. egui checks meshes only in debug builds.
fn check_egui_mesh_indices(mesh: &egui::Mesh) -> io::Result<()> {
let index_count = mesh.indices.len();
if !index_count.is_multiple_of(3) {
return Err(io::Error::other(crate::Error::IndexCount(index_count)));
}
let vertex_count = mesh.vertices.len();
let out_of_range =
|index: &u32| usize::try_from(*index).is_ok_and(|index| index >= vertex_count);
// The largest index is one pass that vectorizes; the first offender is only looked for once
// there is one.
if mesh.indices.iter().max().is_some_and(out_of_range)
&& let Some(&index) = mesh.indices.iter().find(|index| out_of_range(index))
{
return Err(io::Error::other(crate::Error::IndexOutOfRange {
index,
vertex_count,
}));
}
Ok(())
}
/// An egui clip rectangle as pixel bounds: grown outward to whole pixels, clamped to the
/// surface, and an error if any edge is not finite.
fn egui_clip_bounds(rect: egui::Rect, width: usize, height: usize) -> io::Result<ClipBounds> {
ClipBounds::from_float_edges(
[rect.min.x, rect.min.y, rect.max.x, rect.max.y],
width,
height,
)
}
fn root_repaint_delay(output: &egui::FullOutput) -> Duration {
output
.viewport_output
.get(&egui::ViewportId::ROOT)
.map_or(Duration::MAX, |output| output.repaint_delay)
}
fn elapsed_micros(start: Option<Instant>) -> u128 {
start.map_or(0, |start| start.elapsed().as_micros())
}
const fn should_collect_deep_stats(log_render_stats: bool) -> bool {
log_render_stats
}
// These tests drive the renderer through egui meshes and texture uploads.
#[cfg(test)]
mod tests {
use super::*;
use crate::Color;
use crate::geometry::pos2;
#[test]
fn coarse_frame_logging_does_not_enable_deep_stats_collection() {
assert!(!should_collect_deep_stats(false));
assert!(should_collect_deep_stats(true));
}
#[test]
fn renderer_stats_count_textured_quad_fast_path_without_generic_triangles() {
let texture_id = egui::TextureId::Managed(1);
let mut renderer = SoftwareRenderer::default();
renderer.surface.resize(8, 8).expect("surface");
renderer.surface.clear([0, 0, 0, 255]);
renderer
.textures
.apply(&mut texture_delta(texture_id))
.expect("texture");
let mesh = textured_quad_mesh(texture_id);
let mut stats = PrimitiveStats::default();
renderer
.rasterize_mesh(
&mesh,
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(8.0, 8.0)),
0,
Some(&mut stats),
None,
None,
)
.expect("rasterize mesh");
assert_eq!(stats.textured_quad_fast_path_hits, 1);
assert_eq!(stats.generic_triangles_rasterized, 0);
assert_eq!(stats.generic_textured_triangles, 0);
}
#[test]
fn renderer_stats_count_textured_quad_fast_path_rejection() {
let texture_id = egui::TextureId::Managed(1);
let mut renderer = SoftwareRenderer::default();
renderer.surface.resize(8, 8).expect("surface");
renderer.surface.clear([0, 0, 0, 255]);
renderer
.textures
.apply(&mut texture_delta(texture_id))
.expect("texture");
let mut mesh = textured_quad_mesh(texture_id);
mesh.vertices[3].uv = egui::pos2(0.75, 1.0);
let mut stats = PrimitiveStats::default();
renderer
.rasterize_mesh(
&mesh,
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(8.0, 8.0)),
0,
Some(&mut stats),
None,
None,
)
.expect("rasterize mesh");
assert_eq!(stats.textured_quad_fast_path_hits, 0);
assert_eq!(stats.textured_quad_reject_non_affine_uv, 1);
assert_eq!(stats.generic_triangles_rasterized, 2);
assert!(
stats
.textured_quad_reject_offenders_log_line()
.expect("textured quad reject offenders")
.contains("offender0_reason=non_affine_uv")
);
}
#[test]
fn clear_elision_probe_counts_full_surface_opaque_white_quad_as_eligible() {
let texture_id = egui::TextureId::Managed(1);
let renderer = renderer_with_white_texture(texture_id, 8, 8);
let primitive =
clipped_mesh_primitive(full_surface_quad_mesh(texture_id, 8.0, 8.0), 8.0, 8.0);
let stats = renderer.probe_clear_elision(&[primitive]);
assert_eq!(stats.probe_frames, 1);
assert_eq!(stats.eligible_frames, 1);
assert_eq!(stats.full_surface_opaque_rect_frames, 1);
assert_eq!(stats.near_full_surface_opaque_rect_frames, 1);
assert_eq!(stats.max_opaque_cover_basis_points, 10_000);
}
#[test]
fn clear_elision_probe_counts_near_full_surface_as_evidence_only() {
let texture_id = egui::TextureId::Managed(1);
let renderer = renderer_with_white_texture(texture_id, 20, 20);
let primitive =
clipped_mesh_primitive(full_surface_quad_mesh(texture_id, 20.0, 18.5), 20.0, 20.0);
let stats = renderer.probe_clear_elision(&[primitive]);
assert_eq!(stats.eligible_frames, 0);
assert_eq!(stats.full_surface_opaque_rect_frames, 0);
assert_eq!(stats.near_full_surface_opaque_rect_frames, 1);
assert_eq!(stats.reject_not_full_surface_opaque_rect, 1);
assert_eq!(stats.max_opaque_cover_basis_points, 9_500);
}
#[test]
fn clear_elision_probe_rejects_translucent_first_rect() {
let texture_id = egui::TextureId::Managed(1);
let renderer = renderer_with_white_texture(texture_id, 8, 8);
let mut mesh = full_surface_quad_mesh(texture_id, 8.0, 8.0);
for vertex in &mut mesh.vertices {
vertex.color = egui::Color32::from_rgba_premultiplied(128, 128, 128, 128);
}
let primitive = clipped_mesh_primitive(mesh, 8.0, 8.0);
let stats = renderer.probe_clear_elision(&[primitive]);
assert_eq!(stats.eligible_frames, 0);
assert_eq!(stats.reject_alpha_not_opaque, 1);
}
#[test]
fn renderer_solid_fan_path_matches_per_triangle_reference() {
let texture_id = egui::TextureId::Managed(1);
let mut renderer = SoftwareRenderer::default();
renderer.surface.resize(12, 12).expect("surface");
renderer.surface.clear([0, 0, 0, 255]);
renderer
.textures
.apply(&mut texture_delta(texture_id))
.expect("texture");
let mesh = solid_fan_mesh(texture_id, [128, 32, 0, 128]);
let clip_rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(12.0, 12.0));
let mut primitive_stats = PrimitiveStats::default();
let mut raster_stats = RasterStats::default();
let mut raster_timings = RasterTimings::default();
renderer
.rasterize_mesh(
&mesh,
clip_rect,
0,
Some(&mut primitive_stats),
Some(&mut raster_stats),
Some(&mut raster_timings),
)
.expect("rasterize mesh");
let fan_pixels = renderer.surface.pixels.clone();
let texture = renderer
.textures
.get(TextureKey::Egui(texture_id))
.expect("stored texture");
let reference = render_solid_fan_reference(&mesh, texture, clip_bounds(12, 12));
assert_eq!(fan_pixels, reference);
assert_accepted_solid_fan_primitive_stats(&primitive_stats);
assert_eq!(primitive_stats.generic_triangles_rasterized, 0);
assert_eq!(raster_stats.solid_fan_calls, 1);
assert_eq!(raster_stats.solid_fan_triangles, 4);
assert!(raster_stats.solid_fan_rows > 0);
assert!(raster_stats.solid_fan_px > 0);
assert_eq!(raster_stats.translucent_px, raster_stats.solid_fan_px);
assert_eq!(raster_timings.generic_solid_triangle, 0);
assert_eq!(raster_timings.generic_textured_triangle, 0);
assert_eq!(raster_timings.solid_fan_rejected_probe, 0);
assert!(
primitive_stats
.solid_fan_offenders_log_line()
.expect("solid fan offenders")
.contains("offender0_triangles=4 offender0_polygon_vertices=6 offender0_alpha=128")
);
}
#[test]
fn renderer_preflight_skips_too_short_solid_fan_probe_and_uses_generic_triangles() {
let texture_id = egui::TextureId::Managed(1);
let mut renderer = SoftwareRenderer::default();
renderer.surface.resize(12, 12).expect("surface");
renderer.surface.clear([0, 0, 0, 255]);
renderer
.textures
.apply(&mut texture_delta(texture_id))
.expect("texture");
let mesh = too_short_mixed_triangle_mesh(texture_id);
let clip_rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(12.0, 12.0));
let mut primitive_stats = PrimitiveStats::default();
let mut raster_stats = RasterStats::default();
renderer
.rasterize_mesh(
&mesh,
clip_rect,
0,
Some(&mut primitive_stats),
Some(&mut raster_stats),
None,
)
.expect("rasterize mesh");
let texture = renderer
.textures
.get(TextureKey::Egui(texture_id))
.expect("stored texture");
let reference = render_solid_fan_reference(&mesh, texture, clip_bounds(12, 12));
assert_eq!(renderer.surface.pixels, reference);
assert_eq!(primitive_stats.solid_fan_probe.probe_calls, 0);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_reject_too_few_triangles,
3
);
assert_eq!(primitive_stats.solid_fan_probe.rejected_probe_calls, 0);
assert_eq!(primitive_stats.solid_fan_runs, 0);
assert_eq!(primitive_stats.generic_triangles_rasterized, 3);
assert_eq!(primitive_stats.generic_solid_triangles, 1);
assert_eq!(primitive_stats.generic_textured_triangles, 2);
assert_eq!(primitive_stats.generic_textured_constant_texel_triangles, 1);
assert_eq!(primitive_stats.generic_textured_sampled_triangles, 1);
assert_eq!(raster_stats.solid_fan_calls, 0);
assert_eq!(raster_stats.solid_triangle_calls, 1);
assert_eq!(raster_stats.textured_triangle_calls, 2);
}
#[test]
fn renderer_solid_fan_preflight_rejects_when_second_triangle_cannot_continue() {
let texture_id = egui::TextureId::Managed(1);
let mut renderer = renderer_with_white_texture(texture_id, 12, 12);
let mesh = disconnected_solid_triangles_mesh(texture_id);
let clip_rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(12.0, 12.0));
let mut primitive_stats = PrimitiveStats::default();
let mut raster_stats = RasterStats::default();
renderer
.rasterize_mesh(
&mesh,
clip_rect,
0,
Some(&mut primitive_stats),
Some(&mut raster_stats),
None,
)
.expect("rasterize mesh");
let texture = renderer
.textures
.get(TextureKey::Egui(texture_id))
.expect("stored texture");
let reference = render_solid_fan_reference(&mesh, texture, clip_bounds(12, 12));
assert_eq!(renderer.surface.pixels, reference);
assert_eq!(primitive_stats.solid_fan_probe.probe_calls, 1);
assert_eq!(primitive_stats.solid_fan_probe.rejected_probe_calls, 1);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_second_triangle_checks,
1
);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_reject_no_second_triangle_continuation,
1
);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_center_slots_allowed,
0
);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_center_slots_rejected,
3
);
assert_eq!(primitive_stats.solid_fan_probe.center_slot_attempts, 0);
assert_eq!(primitive_stats.solid_fan_probe.cheap_candidate_attempts, 0);
assert_eq!(
primitive_stats.solid_fan_probe.candidate_triangles_scanned,
0
);
assert_eq!(primitive_stats.solid_fan_runs, 0);
assert_eq!(primitive_stats.generic_triangles_rasterized, 4);
assert_eq!(raster_stats.solid_fan_calls, 0);
assert_eq!(raster_stats.solid_triangle_calls, 4);
}
#[test]
fn renderer_reports_resident_solid_fan_cache_without_fan_call_in_frame() {
let texture_id = egui::TextureId::Managed(1);
let mut renderer = SoftwareRenderer::default();
renderer.surface.resize(12, 12).expect("surface");
renderer.surface.clear([0, 0, 0, 255]);
renderer
.textures
.apply(&mut texture_delta(texture_id))
.expect("texture");
let clip_rect = egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(12.0, 12.0));
let mut first_frame_stats = RasterStats::default();
let first_frame = egui::ClippedPrimitive {
clip_rect,
primitive: egui::epaint::Primitive::Mesh(solid_fan_mesh(texture_id, [128, 32, 0, 128])),
};
renderer
.rasterize(&[first_frame], None, Some(&mut first_frame_stats), None)
.expect("rasterize first frame");
assert_eq!(first_frame_stats.solid_fan_span_cache_misses, 1);
assert_eq!(first_frame_stats.solid_fan_span_cache_resident_entries, 1);
assert!(first_frame_stats.solid_fan_span_cache_resident_rows > 0);
let mut second_frame_stats = RasterStats::default();
let second_frame = egui::ClippedPrimitive {
clip_rect,
primitive: egui::epaint::Primitive::Mesh(textured_quad_mesh(texture_id)),
};
renderer
.rasterize(&[second_frame], None, Some(&mut second_frame_stats), None)
.expect("rasterize second frame");
assert_eq!(second_frame_stats.solid_fan_calls, 0);
assert_eq!(second_frame_stats.solid_fan_span_cache_hits, 0);
assert_eq!(second_frame_stats.solid_fan_span_cache_misses, 0);
assert_eq!(second_frame_stats.solid_fan_span_cache_stored_rows, 0);
assert_eq!(second_frame_stats.solid_fan_span_cache_resident_entries, 1);
assert_eq!(
second_frame_stats.solid_fan_span_cache_resident_rows,
first_frame_stats.solid_fan_span_cache_resident_rows
);
}
#[test]
fn renderer_solid_fan_scratch_overflow_falls_back_to_generic_triangles() {
let texture_id = egui::TextureId::Managed(1);
let mut renderer = SoftwareRenderer::default();
renderer.surface.resize(12, 12).expect("surface");
renderer.surface.clear([0, 0, 0, 255]);
renderer
.textures
.apply(&mut texture_delta(texture_id))
.expect("texture");
let mesh = solid_fan_mesh(texture_id, [128, 32, 0, 128]);
let clip = clip_bounds(12, 12);
let reference = render_solid_fan_reference(
&mesh,
renderer
.textures
.get(TextureKey::Egui(texture_id))
.expect("stored texture"),
clip,
);
let mut primitive_stats = PrimitiveStats::default();
let mut raster_stats = RasterStats::default();
{
let mut stats = Some(&mut primitive_stats);
let mut raster_stats = Some(&mut raster_stats);
let mut raster_timings = None;
let mut context = MeshRasterContext {
surface: &mut renderer.surface,
fan_polygon_scratch: &mut renderer.solid_fan_polygon_scratch,
fan_seen_boundary_scratch: &mut renderer.solid_fan_seen_boundary_scratch,
fan_span_cache: &mut renderer.solid_fan_span_cache,
mesh: raster_mesh_from_egui(&mesh),
texture: renderer
.textures
.get(TextureKey::Egui(texture_id))
.expect("stored texture"),
clip,
primitive_index: 0,
solid_fan_polygon_scratch_budget: 5,
};
rasterize_mesh_contents(
&mut context,
&mut stats,
&mut raster_stats,
&mut raster_timings,
)
.expect("rasterize mesh");
}
assert_eq!(renderer.surface.pixels, reference);
assert_eq!(primitive_stats.solid_fan_probe.reject_scratch_overflow, 1);
assert_eq!(primitive_stats.solid_fan_probe.polygon_builds, 0);
assert_eq!(primitive_stats.solid_fan_probe.accepted_runs, 0);
assert_eq!(primitive_stats.solid_fan_runs, 0);
assert_eq!(primitive_stats.generic_triangles_rasterized, 4);
assert_eq!(raster_stats.solid_fan_calls, 0);
}
// egui checks a mesh's indices only in debug builds, so release builds hand a mesh that names
// vertices it does not have to the renderer, which skipped those triangles in silence.
#[test]
fn egui_meshes_with_bad_indices_fail_the_frame() {
let texture_id = egui::TextureId::Managed(1);
let mut renderer = renderer_with_white_texture(texture_id, 8, 8);
let mut out_of_range = full_surface_quad_mesh(texture_id, 8.0, 8.0);
out_of_range.indices[4] = 9;
out_of_range.indices[5] = 4;
let mut partial_triangle = full_surface_quad_mesh(texture_id, 8.0, 8.0);
partial_triangle.indices.pop();
for (mesh, expected) in [
(
out_of_range,
crate::Error::IndexOutOfRange {
index: 9,
vertex_count: 4,
},
),
(partial_triangle, crate::Error::IndexCount(5)),
] {
let error = renderer
.rasterize(&[clipped_mesh_primitive(mesh, 8.0, 8.0)], None, None, None)
.expect_err("malformed mesh");
assert_eq!(
error
.get_ref()
.and_then(|inner| inner.downcast_ref::<crate::Error>()),
Some(&expected)
);
assert_eq!(error.to_string(), expected.to_string());
}
assert!(
renderer
.surface
.pixels
.as_chunks::<4>()
.0
.iter()
.all(|pixel| *pixel == [0, 0, 0, 255])
);
}
// egui frees a texture once its last handle drops, and says so only in that frame's output,
// so a frame that fails must still free it or it holds texture budget for good.
#[test]
fn a_failed_frame_still_frees_the_textures_egui_released() {
let context = egui::Context::default();
let mut renderer = SoftwareRenderer::default();
let image = context.load_texture(
"image",
egui::ColorImage::new([2, 2], vec![egui::Color32::RED; 4]),
egui::TextureOptions::NEAREST,
);
let before = renderer
.render_egui(8, 8, &RenderFrame::new(&context), |_| {})
.expect("upload frame")
.texture_evidence;
drop(image);
let paint_callback = |ui: &mut egui::Ui| {
struct NoGpu;
ui.painter().add(egui::PaintCallback {
rect: egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(4.0, 4.0)),
callback: std::sync::Arc::new(NoGpu),
});
};
assert!(
renderer
.render_egui(8, 8, &RenderFrame::new(&context), paint_callback)
.is_err()
);
let after = renderer
.render_egui(8, 8, &RenderFrame::new(&context), |_| {})
.expect("next frame")
.texture_evidence;
assert_eq!(after.count, before.count - 1);
assert_eq!(after.bytes, before.bytes - 2 * 2 * 4);
}
// Uploads that fail part way have already changed the textures before the failing one, and
// egui does not send them again, so the next frame cannot count as unchanged.
#[test]
fn a_frame_after_a_failed_texture_upload_is_rasterized() {
let context = egui::Context::default();
let mut renderer = SoftwareRenderer::default();
let solid = |color| egui::ColorImage::new([2, 2], vec![color; 4]);
let mut image = context.load_texture(
"image",
solid(egui::Color32::RED),
egui::TextureOptions::NEAREST,
);
let image_id = image.id();
let draw = |ui: &mut egui::Ui| {
ui.painter().image(
image_id,
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(4.0, 4.0)),
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
egui::Color32::WHITE,
);
};
renderer
.render_egui(8, 8, &RenderFrame::new(&context), draw)
.expect("first frame");
assert_eq!(renderer.surface().pixels[..4], [255, 0, 0, 255]);
// The recolor applies; two 4 MiB images then pass the texture budget on the second.
image.set(solid(egui::Color32::BLUE), egui::TextureOptions::NEAREST);
let side = 1024;
let _over_budget: Vec<egui::TextureHandle> = (0..2)
.map(|index| {
context.load_texture(
format!("large {index}"),
egui::ColorImage::new([side, side], vec![egui::Color32::WHITE; side * side]),
egui::TextureOptions::NEAREST,
)
})
.collect();
assert!(
renderer
.render_egui(8, 8, &RenderFrame::new(&context), draw)
.is_err()
);
let outcome = renderer
.render_egui(8, 8, &RenderFrame::new(&context), draw)
.expect("third frame");
assert!(outcome.surface_changed);
assert_eq!(renderer.surface().pixels[..4], [0, 0, 255, 255]);
}
fn quad_vertices() -> [Vertex; 4] {
[
test_vertex(1.0, 1.0),
test_vertex(4.0, 1.0),
test_vertex(1.0, 3.0),
test_vertex(4.0, 3.0),
]
}
fn textured_quad_mesh(texture_id: egui::TextureId) -> egui::Mesh {
let mut vertices = quad_vertices();
vertices[0].uv = [0.0, 0.0];
vertices[1].uv = [1.0, 0.0];
vertices[2].uv = [0.0, 1.0];
vertices[3].uv = [1.0, 1.0];
egui::Mesh {
indices: vec![0, 1, 2, 1, 3, 2],
vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
texture_id,
}
}
fn full_surface_quad_mesh(texture_id: egui::TextureId, width: f32, height: f32) -> egui::Mesh {
let mut vertices = [
test_vertex(0.0, 0.0),
test_vertex(width, 0.0),
test_vertex(0.0, height),
test_vertex(width, height),
];
for vertex in &mut vertices {
vertex.uv = [0.0, 0.0];
}
egui::Mesh {
indices: vec![0, 1, 2, 1, 3, 2],
vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
texture_id,
}
}
fn clipped_mesh_primitive(mesh: egui::Mesh, width: f32, height: f32) -> egui::ClippedPrimitive {
egui::ClippedPrimitive {
clip_rect: egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(width, height)),
primitive: egui::epaint::Primitive::Mesh(mesh),
}
}
fn renderer_with_white_texture(
texture_id: egui::TextureId,
width: usize,
height: usize,
) -> SoftwareRenderer {
let mut renderer = SoftwareRenderer::default();
renderer.surface.resize(width, height).expect("surface");
renderer.surface.clear([0, 0, 0, 255]);
renderer
.textures
.apply(&mut solid_texture_delta(texture_id, Color::WHITE))
.expect("texture");
renderer
}
fn solid_fan_mesh(texture_id: egui::TextureId, color: [u8; 4]) -> egui::Mesh {
let color = Color::from_rgba_premultiplied(color[0], color[1], color[2], color[3]);
let vertices = [
pos2(1.0, 5.0),
pos2(2.0, 1.0),
pos2(6.0, 1.0),
pos2(9.0, 3.0),
pos2(8.0, 8.0),
pos2(3.0, 9.0),
]
.map(|pos| Vertex {
pos: [pos.x, pos.y],
uv: [0.0, 0.0],
color,
});
egui::Mesh {
indices: vec![1, 0, 2, 2, 0, 3, 3, 0, 4, 4, 0, 5],
vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
texture_id,
}
}
fn too_short_mixed_triangle_mesh(texture_id: egui::TextureId) -> egui::Mesh {
let mut vertices = [
test_vertex(1.0, 1.0),
test_vertex(4.0, 1.0),
test_vertex(1.0, 4.0),
test_vertex(5.0, 1.0),
test_vertex(8.0, 1.0),
test_vertex(5.0, 4.0),
test_vertex(1.0, 5.0),
test_vertex(4.0, 5.0),
test_vertex(1.0, 8.0),
];
vertices[5].color = Color::BLACK;
vertices[7].uv = [1.0, 0.0];
vertices[8].uv = [0.0, 1.0];
egui::Mesh {
indices: vec![0, 1, 2, 3, 4, 5, 6, 7, 8],
vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
texture_id,
}
}
fn disconnected_solid_triangles_mesh(texture_id: egui::TextureId) -> egui::Mesh {
let vertices = [
test_vertex(1.0, 1.0),
test_vertex(3.0, 1.0),
test_vertex(1.0, 3.0),
test_vertex(5.0, 1.0),
test_vertex(7.0, 1.0),
test_vertex(5.0, 3.0),
test_vertex(1.0, 5.0),
test_vertex(3.0, 5.0),
test_vertex(1.0, 7.0),
test_vertex(5.0, 5.0),
test_vertex(7.0, 5.0),
test_vertex(5.0, 7.0),
];
egui::Mesh {
indices: vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
vertices: vertices.iter().map(|vertex| vertex.to_egui()).collect(),
texture_id,
}
}
fn assert_accepted_solid_fan_primitive_stats(primitive_stats: &PrimitiveStats) {
assert_eq!(primitive_stats.solid_fan_runs, 1);
assert_eq!(primitive_stats.solid_fan_triangles, 4);
assert_eq!(primitive_stats.solid_fan_probe.probe_calls, 1);
assert_eq!(primitive_stats.solid_fan_probe.rejected_probe_calls, 0);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_second_triangle_checks,
1
);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_reject_no_second_triangle_continuation,
0
);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_center_slots_allowed,
2
);
assert_eq!(
primitive_stats
.solid_fan_probe
.preflight_center_slots_rejected,
1
);
assert_eq!(primitive_stats.solid_fan_probe.center_slot_attempts, 1);
assert_eq!(primitive_stats.solid_fan_probe.cheap_candidate_attempts, 1);
assert_eq!(
primitive_stats.solid_fan_probe.candidate_triangles_scanned,
4
);
assert_eq!(
primitive_stats
.solid_fan_probe
.accepted_candidate_triangles_scanned,
4
);
assert_eq!(
primitive_stats
.solid_fan_probe
.rejected_candidate_triangles_scanned,
0
);
assert_eq!(primitive_stats.solid_fan_probe.repeated_boundary_checks, 3);
assert_eq!(
primitive_stats
.solid_fan_probe
.repeated_boundary_comparisons,
9
);
assert_eq!(primitive_stats.solid_fan_probe.reject_no_candidate, 0);
assert_eq!(primitive_stats.solid_fan_probe.accepted_runs, 1);
assert_eq!(primitive_stats.solid_fan_probe.accepted_triangles, 4);
assert_eq!(primitive_stats.solid_fan_probe.polygon_builds, 1);
assert_eq!(primitive_stats.solid_fan_probe.max_candidate_triangles, 4);
assert_eq!(primitive_stats.solid_fan_probe.max_accepted_triangles, 4);
}
fn render_solid_fan_reference(
mesh: &egui::Mesh,
texture: &TextureImage,
clip: ClipBounds,
) -> Vec<u8> {
let mut surface = SoftwareSurface::default();
surface.resize(12, 12).expect("surface");
surface.clear([0, 0, 0, 255]);
let vertices = vertices_from_egui(&mesh.vertices);
for triangle in mesh.indices.as_chunks::<3>().0 {
let v0 = &vertices[usize::try_from(triangle[0]).expect("index")];
let v1 = &vertices[usize::try_from(triangle[1]).expect("index")];
let v2 = &vertices[usize::try_from(triangle[2]).expect("index")];
rasterize_triangle(&mut surface, v0, v1, v2, texture, clip, None);
}
surface.pixels
}
fn texture_delta(texture_id: egui::TextureId) -> egui::TexturesDelta {
let image = egui::ColorImage::new(
[2, 2],
vec![
egui::Color32::from_rgb(10, 0, 0),
egui::Color32::from_rgb(20, 0, 0),
egui::Color32::from_rgb(30, 0, 0),
egui::Color32::from_rgb(40, 0, 0),
],
);
egui::TexturesDelta {
set: [(
texture_id,
[egui::epaint::ImageDelta::full(
image,
egui::TextureOptions::NEAREST,
)]
.into_iter()
.collect(),
)]
.into_iter()
.collect(),
free: [].into_iter().collect(),
}
}
fn solid_texture_delta(texture_id: egui::TextureId, color: Color) -> egui::TexturesDelta {
let image = egui::ColorImage::new([2, 2], vec![color.to_egui(); 4]);
egui::TexturesDelta {
set: [(
texture_id,
[egui::epaint::ImageDelta::full(
image,
egui::TextureOptions::NEAREST,
)]
.into_iter()
.collect(),
)]
.into_iter()
.collect(),
free: [].into_iter().collect(),
}
}
fn clip_bounds(width: usize, height: usize) -> ClipBounds {
ClipBounds::full(width, height)
}
fn test_vertex(x: f32, y: f32) -> Vertex {
Vertex {
pos: [x, y],
uv: [0.0, 0.0],
color: Color::WHITE,
}
}
}