egui-sdl2 0.8.2

egui integration for SDL2: event handling and software, OpenGL, or wgpu rendering
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Canvas backend for egui-sdl2.
//!
//! This module provides [`Painter`], which integrates egui rendering with an
//! SDL2 [`Canvas`] — a window's, or a surface's when the app draws offscreen.

use egui::epaint::{ImageDelta, Primitive};
use egui::{ClippedPrimitive, ImageData, TexturesDelta};
use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::render::{BlendMode, Canvas, RenderTarget, Texture, TextureCreator};
use sdl2::surface::{Surface, SurfaceContext};
use sdl2::sys::{SDL_Color, SDL_FPoint, SDL_Vertex};
use sdl2::video::{Window, WindowContext};
use std::collections::HashMap;
use std::os::raw::c_int;

#[cfg(target_endian = "little")]
pub(crate) const PIXEL_FORMAT: PixelFormatEnum = PixelFormatEnum::ABGR8888;
#[cfg(target_endian = "big")]
pub(crate) const PIXEL_FORMAT: PixelFormatEnum = PixelFormatEnum::RGBA8888;

const BYTES_PER_PIXEL: usize = 4;

/// An Canvas painter using [`sdl2`].
///
/// This is responsible for painting egui and managing egui textures. The
/// [`Canvas`] stays owned by the caller and is passed in per paint call, so egui
/// can draw over content the application already rendered.
///
/// This struct must be destroyed with [`Painter::destroy`] before dropping, to ensure
/// objects have been properly deleted and are not leaked.
///
/// NOTE: all egui viewports share the same painter.
pub struct Painter<C = WindowContext> {
    textures: HashMap<egui::TextureId, Texture>,
    texture_creator: TextureCreator<C>,
    /// Reused across meshes and frames so `paint_mesh` repacks egui vertices
    /// into SDL's layout without allocating a fresh `Vec` per mesh.
    vertex_scratch: Vec<SDL_Vertex>,
    /// Clip rect currently applied to the canvas within a `paint_primitives`
    /// run, so meshes sharing a clip skip a redundant `SDL_RenderSetClipRect`.
    /// Reset to `None` at the start of each run because the caller draws to the
    /// same canvas between runs.
    last_clip: Option<Rect>,
    /// Triangles waiting to be drawn, so a run of them is still one SDL call.
    index_scratch: Vec<u32>,
    /// Reused for the straight-alpha copy an upload needs; the atlas is uploaded
    /// whole whenever it grows, which is not the frame to be allocating in.
    pixel_scratch: Vec<u8>,
    /// This renderer's texture size limit, for egui to lay its atlas out within.
    max_texture_side: Option<usize>,
}

impl Painter<WindowContext> {
    /// Textures are created from `canvas`'s renderer, so pass the same canvas to
    /// the paint calls.
    pub fn new(canvas: &Canvas<Window>) -> Self {
        Self::with_creator(canvas.texture_creator(), max_texture_side(canvas))
    }
}

impl<'s> Painter<SurfaceContext<'s>> {
    /// Paint into a surface instead of a window, for drivers that only present
    /// texture copies (see [`crate::Renderer::CanvasBlit`]).
    pub fn for_surface(canvas: &Canvas<Surface<'s>>) -> Self {
        Self::with_creator(canvas.texture_creator(), max_texture_side(canvas))
    }
}

impl<C> Painter<C> {
    fn with_creator(texture_creator: TextureCreator<C>, max_texture_side: Option<usize>) -> Self {
        Self {
            textures: HashMap::new(),
            texture_creator,
            vertex_scratch: Vec::new(),
            index_scratch: Vec::new(),
            pixel_scratch: Vec::new(),
            last_clip: None,
            max_texture_side,
        }
    }

    /// The largest texture this renderer accepts, `None` if it reports no limit.
    /// Feed [`crate::State::set_max_texture_side`]: egui's atlas defaults to
    /// 2048, past what handheld drivers hold (Miyoo Mini: 1920x1080).
    pub fn max_texture_side(&self) -> Option<usize> {
        self.max_texture_side
    }

    /// This function must be called before [`Painter`] is dropped, as [`Painter`] has some objects
    /// that should be deleted.
    pub fn destroy(&mut self) {
        let textures = std::mem::replace(&mut self.textures, HashMap::with_capacity(0));
        for (_id, tex) in textures {
            unsafe {
                tex.destroy();
            }
        }
    }

    /// You are expected to have cleared the color buffer before calling this.
    pub fn paint_and_update_textures<T: RenderTarget<Context = C>>(
        &mut self,
        canvas: &mut Canvas<T>,
        pixels_per_point: f32,
        textures_delta: &TexturesDelta,
        paint_jobs: Vec<ClippedPrimitive>,
    ) -> Result<(), String> {
        for (id, delta) in &textures_delta.set {
            self.set_texture(*id, delta);
        }

        self.paint_primitives(canvas, pixels_per_point, paint_jobs);

        for &id in &textures_delta.free {
            self.free_texture(&id);
        }

        Ok(())
    }

    /// Main entry-point for painting a frame.
    pub fn paint_primitives<T: RenderTarget<Context = C>>(
        &mut self,
        canvas: &mut Canvas<T>,
        pixels_per_point: f32,
        paint_jobs: Vec<ClippedPrimitive>,
    ) {
        // The caller may have drawn to the canvas (and changed its clip) since
        // the last run, so don't assume any clip is still applied.
        self.last_clip = None;
        // Untextured geometry and rectangle fills blend by the renderer's mode,
        // which SDL leaves at `None` — so a half-transparent fill would overwrite
        // instead of blending. Textures carry their own mode (`create_texture`).
        let caller_blend = canvas.blend_mode();
        canvas.set_blend_mode(BlendMode::Blend);
        for job in paint_jobs.into_iter() {
            match job.primitive {
                Primitive::Mesh(mesh) => {
                    self.paint_mesh(canvas, pixels_per_point, job.clip_rect, mesh)
                }
                Primitive::Callback(_callback) => {
                    // TODO
                    log::warn!("PaintCallbacks are not supported")
                }
            }
        }
        // Clear the clip once, after all meshes, so content the caller draws
        // after `paint()` isn't clipped to the last mesh's rect. Guard on
        // `last_clip`: a frame that drew no meshes never set a clip, so leave
        // the caller's own clip untouched.
        if self.last_clip.is_some() {
            canvas.set_clip_rect(None);
        }
        canvas.set_blend_mode(caller_blend);
    }

    pub fn set_texture(&mut self, id: egui::TextureId, delta: &ImageDelta) {
        let ImageData::Color(img) = &delta.image;
        // Straight alpha, to match the vertex colours: see `into_sdl_vertex`. The
        // font atlas arrives as premultiplied white coverage, and becomes white
        // with the coverage in alpha, which is what modulating a texture expects.
        self.pixel_scratch.clear();
        self.pixel_scratch
            .reserve(img.pixels.len() * BYTES_PER_PIXEL);
        for pixel in img.pixels.iter() {
            self.pixel_scratch
                .extend_from_slice(&pixel.to_srgba_unmultiplied());
        }
        let w = img.width() as u32;
        let h = img.height() as u32;
        let pitch = (w as usize) * BYTES_PER_PIXEL;

        if delta.pos.is_none() {
            if let Some(tex) = self.textures.get(&id) {
                let q = tex.query();
                if q.width != w || q.height != h {
                    self.free_texture(&id);
                }
            }
        }

        let tex = self
            .textures
            .entry(id)
            .or_insert_with(|| create_texture(&self.texture_creator, w, h));
        let rect = delta.pos.map(|[x, y]| Rect::new(x as i32, y as i32, w, h));
        tex.update(rect, &self.pixel_scratch, pitch).unwrap();
    }

    #[inline]
    pub fn free_texture(&mut self, id: &egui::TextureId) {
        if let Some(tex) = self.textures.remove(id) {
            unsafe {
                tex.destroy();
            }
        }
    }

    #[inline]
    fn paint_mesh<T: RenderTarget<Context = C>>(
        &mut self,
        canvas: &mut Canvas<T>,
        pixels_per_point: f32,
        clip_rect: egui::Rect,
        mesh: egui::Mesh,
    ) {
        // egui may draw untextured shapes (nullptr in SDL_RenderGeometry).
        let (texture_ptr, texture_size) = match self.textures.get(&mesh.texture_id) {
            Some(tex) => {
                let q = tex.query();
                (tex.raw(), Some((q.width as f32, q.height as f32)))
            }
            None => (std::ptr::null_mut(), None),
        };

        let min = clip_rect.min * pixels_per_point;
        let max = clip_rect.max * pixels_per_point;
        let clip_rect = sdl2::rect::Rect::new(
            min.x as i32,
            min.y as i32,
            (max.x - min.x) as u32,
            (max.y - min.y) as u32,
        );
        // Adjacent meshes (e.g. all glyphs in one panel) usually share a clip;
        // only hit `SDL_RenderSetClipRect` when it actually changes.
        if self.last_clip != Some(clip_rect) {
            canvas.set_clip_rect(clip_rect);
            self.last_clip = Some(clip_rect);
        }

        // Text and rectangles tessellate to axis-aligned quads: blit those, they
        // are exact and cheap. Rounded corners, circles and feathering stay on
        // the triangle path. Flushing before each blit keeps egui's draw order.
        self.index_scratch.clear();
        for corners in mesh.indices.chunks(6) {
            match as_axis_aligned_quad(&mesh.vertices, corners, pixels_per_point) {
                Some(quad) => {
                    self.flush_triangles(canvas, texture_ptr, &mesh, pixels_per_point);
                    quad.blit(canvas, texture_ptr, texture_size);
                }
                None => self.index_scratch.extend_from_slice(corners),
            }
        }
        self.flush_triangles(canvas, texture_ptr, &mesh, pixels_per_point);
    }

    /// Draw whatever indices have accumulated in `index_scratch` as triangles.
    fn flush_triangles<T: RenderTarget<Context = C>>(
        &mut self,
        canvas: &mut Canvas<T>,
        texture_ptr: *mut sdl2_sys::SDL_Texture,
        mesh: &egui::Mesh,
        pixels_per_point: f32,
    ) {
        if self.index_scratch.is_empty() {
            return;
        }
        // A blit may have left a colour mod; vertex colours carry their own tint.
        if !texture_ptr.is_null() {
            unsafe {
                sdl2_sys::SDL_SetTextureColorMod(texture_ptr, 255, 255, 255);
                sdl2_sys::SDL_SetTextureAlphaMod(texture_ptr, 255);
            }
        }

        // Repack egui vertices into SDL's layout in a reused buffer. A zero-copy
        // cast is impossible (SDL_Vertex is {position, color, tex_coord} vs egui
        // {pos, uv, color}, and position is scaled by ppp), but reusing the
        // allocation across meshes/frames avoids a malloc+free per mesh.
        self.vertex_scratch.clear();
        self.vertex_scratch.reserve(mesh.vertices.len());
        self.vertex_scratch.extend(
            mesh.vertices
                .iter()
                .map(|v| into_sdl_vertex(v, pixels_per_point)),
        );
        // A feather vertex is fully transparent and epaint gives it no hue, so
        // SDL's straight-alpha interpolation would fade it to black. With its
        // triangle's own hue the ramp stays on colour — antialiasing, not a
        // dark fringe. Corners are only shared within one path, so a triangle
        // may safely write the hue its path owns.
        for triangle in self.index_scratch.chunks_exact(3) {
            let hue = triangle
                .iter()
                .map(|&i| self.vertex_scratch[i as usize].color)
                .find(|c| c.a != 0);
            let Some(hue) = hue else { continue };
            for &i in triangle {
                let c = &mut self.vertex_scratch[i as usize].color;
                if c.a == 0 {
                    (c.r, c.g, c.b) = (hue.r, hue.g, hue.b);
                }
            }
        }
        let verts_len = self.vertex_scratch.len() as c_int;
        let indcs_len = self.index_scratch.len() as c_int;

        let result = unsafe {
            sdl2_sys::SDL_RenderGeometry(
                canvas.raw(),
                texture_ptr,
                if verts_len == 0 {
                    std::ptr::null()
                } else {
                    self.vertex_scratch.as_ptr()
                },
                verts_len,
                self.index_scratch.as_ptr() as *const c_int,
                indcs_len,
            )
        };
        self.index_scratch.clear();

        if result != 0 {
            log::error!("SDL_RenderGeometry failed: {}", result);
        }
    }
}

/// An axis-aligned, single-colour quad: a glyph, or a plain rectangle.
struct Quad {
    dst: sdl2_sys::SDL_FRect,
    /// Normalized, as egui gives it; scaled to texels at blit time.
    uv: egui::Rect,
    color: egui::Color32,
    textured: bool,
}

impl Quad {
    fn blit<T: RenderTarget>(
        &self,
        canvas: &mut Canvas<T>,
        texture_ptr: *mut sdl2_sys::SDL_Texture,
        texture_size: Option<(f32, f32)>,
    ) {
        let [r, g, b, a] = self.color.to_srgba_unmultiplied();
        let result = match (self.textured, texture_size) {
            (true, Some((tw, th))) => unsafe {
                // The atlas is white with coverage in alpha; modulating it matches
                // what the triangle path does per vertex.
                sdl2_sys::SDL_SetTextureColorMod(texture_ptr, r, g, b);
                sdl2_sys::SDL_SetTextureAlphaMod(texture_ptr, a);
                let src = sdl2_sys::SDL_Rect {
                    x: (self.uv.min.x * tw).round() as i32,
                    y: (self.uv.min.y * th).round() as i32,
                    w: (self.uv.width() * tw).round() as i32,
                    h: (self.uv.height() * th).round() as i32,
                };
                sdl2_sys::SDL_RenderCopyF(canvas.raw(), texture_ptr, &src, &self.dst)
            },
            _ => unsafe {
                sdl2_sys::SDL_SetRenderDrawColor(canvas.raw(), r, g, b, a);
                sdl2_sys::SDL_RenderFillRectF(canvas.raw(), &self.dst)
            },
        };
        if result != 0 {
            log::error!("blitting a quad failed: {result}");
        }
    }
}

/// The two triangles of an unrotated, single-colour quad, if that is what these
/// indices are; otherwise `None`, for [`Painter::flush_triangles`].
fn as_axis_aligned_quad(
    vertices: &[egui::epaint::Vertex],
    corners: &[u32],
    pixels_per_point: f32,
) -> Option<Quad> {
    if corners.len() != 6 {
        return None;
    }
    let mut uniq: Vec<&egui::epaint::Vertex> = Vec::with_capacity(4);
    for &i in corners {
        let v = vertices.get(i as usize)?;
        if !uniq.iter().any(|u| u.pos == v.pos && u.uv == v.uv) {
            uniq.push(v);
        }
    }
    if uniq.len() != 4 {
        return None;
    }
    let color = uniq[0].color;
    if uniq.iter().any(|v| v.color != color) {
        return None;
    }

    let rect = egui::Rect::from_points(&uniq.iter().map(|v| v.pos).collect::<Vec<_>>());
    let uv = egui::Rect::from_points(&uniq.iter().map(|v| v.uv).collect::<Vec<_>>());
    if rect.width() <= 0.0 || rect.height() <= 0.0 {
        return None;
    }
    // A degenerate uv means the mesh samples egui's single white texel: a fill.
    let textured = uv.width() > 0.0 && uv.height() > 0.0;

    for v in &uniq {
        let at_min_x = v.pos.x == rect.min.x;
        let at_min_y = v.pos.y == rect.min.y;
        if !(at_min_x || v.pos.x == rect.max.x) || !(at_min_y || v.pos.y == rect.max.y) {
            return None; // a vertex off the corners: not a rectangle
        }
        // Reject rotated and mirrored mappings; SDL_RenderCopy cannot express them.
        if textured && (at_min_x != (v.uv.x == uv.min.x) || at_min_y != (v.uv.y == uv.min.y)) {
            return None;
        }
    }

    Some(Quad {
        dst: sdl2_sys::SDL_FRect {
            x: rect.min.x * pixels_per_point,
            y: rect.min.y * pixels_per_point,
            w: rect.width() * pixels_per_point,
            h: rect.height() * pixels_per_point,
        },
        uv,
        color,
        textured,
    })
}

/// SDL leaves the fields at 0 for drivers with no limit, its software one included.
fn max_texture_side<T: RenderTarget>(canvas: &Canvas<T>) -> Option<usize> {
    let info = canvas.info();
    let side = match (info.max_texture_width, info.max_texture_height) {
        (0, 0) => return None,
        (0, h) => h,
        (w, 0) => w,
        (w, h) => w.min(h),
    };
    Some(side as usize)
}

#[inline]
fn create_texture<C>(texture_creator: &TextureCreator<C>, w: u32, h: u32) -> Texture {
    let mut tex = texture_creator
        .create_texture_streaming(PIXEL_FORMAT, w, h) // ABGR8888 on Little-Endian
        .unwrap_or_else(|e| {
            // Reached only if egui asked for more than the renderer's limit,
            // which `Painter::max_texture_side` exists to prevent — so the
            // integration failed to pass it on.
            panic!("failed to create a {w}x{h} sdl2 texture: {e}")
        });
    tex.set_blend_mode(BlendMode::Blend);

    tex
}
/// egui's colours are premultiplied; SDL's `BLEND` is `src*a + dst*(1-a)`, which
/// multiplies by alpha a second time. Undo the premultiplication and the two
/// agree — otherwise everything drawn with partial alpha comes out too dark, and
/// an untextured fill (whose blend mode SDL defaults to `NONE`) loses the
/// destination entirely, so egui's fade-in of a new panel reads as a dark flash.
#[inline]
fn into_sdl_vertex(vertex: &egui::epaint::Vertex, pixels_per_point: f32) -> SDL_Vertex {
    let [r, g, b, a] = vertex.color.to_srgba_unmultiplied();
    SDL_Vertex {
        position: SDL_FPoint {
            x: vertex.pos.x * pixels_per_point,
            y: vertex.pos.y * pixels_per_point,
        },
        color: SDL_Color { r, g, b, a },
        tex_coord: SDL_FPoint {
            x: vertex.uv.x,
            y: vertex.uv.y,
        },
    }
}