dear-imgui-sdl3 0.11.0

SDL3 platform backend with optional OpenGL3 renderer for dear-imgui-rs
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! SDL3 platform backend bindings for `dear-imgui-rs`.
//!
//! This crate is a thin, opinionated wrapper around the official C++ SDL3
//! platform backend (`imgui_impl_sdl3.cpp`). When the `opengl3-renderer`
//! feature is enabled, the renderer path uses the shared OpenGL3 backend shim
//! exported by `dear-imgui-sys`.
//!
//! The intent is to provide a simple, safe-ish API that:
//! - plugs into an existing `dear-imgui-rs::Context`
//! - integrates with an SDL3 window and OpenGL context
//! - supports Dear ImGui multi-viewport via the official backend behavior.
//!
//! By default, this crate builds the SDL3 platform backend only. Enable
//! `opengl3-renderer` to pair it with the official OpenGL3 renderer shim
//! or `sdlrenderer3-renderer` to pair it with the official SDLRenderer3 shim.

#[cfg(feature = "opengl3-renderer")]
use std::ffi::CString;
use std::ffi::c_void;

use dear_imgui_rs::Context;
#[cfg(any(feature = "opengl3-renderer", feature = "sdlrenderer3-renderer"))]
use dear_imgui_rs::{TextureData, render::DrawData};
#[cfg(any(feature = "opengl3-renderer", feature = "sdlrenderer3-renderer"))]
use dear_imgui_sys as sys;
#[cfg(feature = "opengl3-renderer")]
use dear_imgui_sys::backend_shim::opengl3 as opengl3_backend;
#[cfg(feature = "sdlrenderer3-renderer")]
use dear_imgui_sys::backend_shim::sdlrenderer3 as sdlrenderer3_backend;
#[cfg(feature = "sdlrenderer3-renderer")]
use sdl3::render::WindowCanvas;
use sdl3::video::{GLContext, Window};
use sdl3_sys::events::SDL_Event;

/// FFI bindings to the C wrappers defined in `wrapper.cpp`.
mod ffi {
    use super::*;

    unsafe extern "C" {
        pub fn ImGui_ImplSDL3_InitForOpenGL_Rust(
            window: *mut sdl3_sys::video::SDL_Window,
            sdl_gl_context: *mut c_void,
        ) -> bool;
        pub fn ImGui_ImplSDL3_InitForVulkan_Rust(window: *mut sdl3_sys::video::SDL_Window) -> bool;
        pub fn ImGui_ImplSDL3_InitForD3D_Rust(window: *mut sdl3_sys::video::SDL_Window) -> bool;
        pub fn ImGui_ImplSDL3_InitForMetal_Rust(window: *mut sdl3_sys::video::SDL_Window) -> bool;
        pub fn ImGui_ImplSDL3_InitForSDLRenderer_Rust(
            window: *mut sdl3_sys::video::SDL_Window,
            renderer: *mut sdl3_sys::render::SDL_Renderer,
        ) -> bool;
        pub fn ImGui_ImplSDL3_InitForSDLGPU_Rust(window: *mut sdl3_sys::video::SDL_Window) -> bool;
        pub fn ImGui_ImplSDL3_InitForOther_Rust(window: *mut sdl3_sys::video::SDL_Window) -> bool;
        pub fn ImGui_ImplSDL3_Shutdown_Rust();
        pub fn ImGui_ImplSDL3_NewFrame_Rust();
        pub fn ImGui_ImplSDL3_ProcessEvent_Rust(event: *const SDL_Event) -> bool;

        pub fn ImGui_ImplSDL3_SetGamepadMode_AutoFirst_Rust();
        pub fn ImGui_ImplSDL3_SetGamepadMode_AutoAll_Rust();
        pub fn ImGui_ImplSDL3_SetGamepadMode_Manual_Rust(
            manual_gamepads_array: *const *mut sdl3_sys::gamepad::SDL_Gamepad,
            manual_gamepads_count: i32,
        );
    }
}

/// Errors that can occur when setting up the SDL3 + OpenGL backend.
#[derive(Debug, thiserror::Error)]
pub enum Sdl3BackendError {
    #[error("ImGui_ImplSDL3_InitForOpenGL returned false")]
    Sdl3InitFailed,
    #[error("ImGui_ImplOpenGL3_Init returned false")]
    OpenGlInitFailed,
    #[error("Invalid GLSL version string")]
    InvalidGlslVersion,
    #[error("ImGui_ImplSDLRenderer3_Init returned false")]
    Renderer3InitFailed,
}

/// Gamepad handling mode used by the SDL3 backend.
///
/// This controls how many SDL3 gamepads are opened and merged into ImGui's
/// gamepad input state.
#[derive(Copy, Clone, Debug)]
pub enum GamepadMode {
    /// Automatically open the first available gamepad (Dear ImGui default).
    AutoFirst,
    /// Automatically open all available gamepads and merge their state.
    AutoAll,
}

/// Configure how the SDL3 backend handles gamepads.
///
/// Call this after [`init_for_opengl`] or [`init_for_other`] if you want a
/// mode other than the default `AutoFirst`.
pub fn set_gamepad_mode(mode: GamepadMode) {
    unsafe {
        match mode {
            GamepadMode::AutoFirst => ffi::ImGui_ImplSDL3_SetGamepadMode_AutoFirst_Rust(),
            GamepadMode::AutoAll => ffi::ImGui_ImplSDL3_SetGamepadMode_AutoAll_Rust(),
        }
    }
}

/// Configure SDL3 backend to use manual gamepad selection.
///
/// # Safety
///
/// - The caller must ensure every pointer in `gamepads` is a valid, opened `SDL_Gamepad`.
/// - The caller is responsible for keeping those gamepads alive for the duration of ImGui usage.
/// - The slice itself is only read during this call; the backend copies the pointers.
pub unsafe fn set_gamepad_mode_manual(gamepads: &[*mut sdl3_sys::gamepad::SDL_Gamepad]) {
    unsafe {
        ffi::ImGui_ImplSDL3_SetGamepadMode_Manual_Rust(gamepads.as_ptr(), gamepads.len() as i32);
    }
}

/// Enable native IME UI for SDL3 (recommended on IME-heavy platforms).
///
/// This should be called before creating any SDL3 windows so that the
/// underlying backend can display the OS IME UI correctly.
pub fn enable_native_ime_ui() {
    // Best-effort: ignore return value; missing hints are not fatal.
    let _ = sdl3::hint::set("SDL_HINT_IME_SHOW_UI", "1");
}

/// Initialize the Dear ImGui SDL3 + OpenGL3 backends.
///
/// This assumes that:
/// - a `dear_imgui_rs::Context` already exists;
/// - `window` has an active OpenGL context (`gl_context`);
/// - the same context will be current when rendering.
///
/// `glsl_version` should be a GLSL version string such as `"#version 150"`.
///
/// Requires the `opengl3-renderer` feature.
#[cfg(feature = "opengl3-renderer")]
pub fn init_for_opengl(
    _imgui: &mut Context,
    window: &Window,
    gl_context: &GLContext,
    glsl_version: &str,
) -> Result<(), Sdl3BackendError> {
    let glsl = CString::new(glsl_version).map_err(|_| Sdl3BackendError::InvalidGlslVersion)?;

    let sdl_window = window.raw();
    let sdl_gl = unsafe { gl_context.raw() };

    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForOpenGL_Rust(sdl_window, sdl_gl as *mut c_void) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
        if !opengl3_backend::dear_imgui_backend_opengl3_init(glsl.as_ptr()) {
            return Err(Sdl3BackendError::OpenGlInitFailed);
        }
    }

    Ok(())
}

/// Initialize the Dear ImGui SDL3 + OpenGL3 backends using the default GLSL version.
///
/// This matches the upstream behavior of passing `nullptr` for `glsl_version`.
///
/// Requires the `opengl3-renderer` feature.
#[cfg(feature = "opengl3-renderer")]
pub fn init_for_opengl_default(
    _imgui: &mut Context,
    window: &Window,
    gl_context: &GLContext,
) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();
    let sdl_gl = unsafe { gl_context.raw() };

    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForOpenGL_Rust(sdl_window, sdl_gl as *mut c_void) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
        if !opengl3_backend::dear_imgui_backend_opengl3_init(std::ptr::null()) {
            return Err(Sdl3BackendError::OpenGlInitFailed);
        }
    }

    Ok(())
}

/// Initialize only the Dear ImGui SDL3 *platform* backend for an OpenGL context.
///
/// This is useful when you want to use a Rust renderer (e.g. `dear-imgui-glow`)
/// instead of the official C++ OpenGL3 renderer. It:
/// - configures the SDL3 platform backend (including multi-viewport support);
/// - does **not** initialize `imgui_impl_opengl3`.
///
/// This assumes that:
/// - a `dear_imgui_rs::Context` already exists;
/// - `window` has an active OpenGL context (`gl_context`);
/// - the same context will be current when rendering.
pub fn init_platform_for_opengl(
    _imgui: &mut Context,
    window: &Window,
    gl_context: &GLContext,
) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();
    let sdl_gl = unsafe { gl_context.raw() };

    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForOpenGL_Rust(sdl_window, sdl_gl as *mut c_void) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
    }

    Ok(())
}

/// Initialize the Dear ImGui SDL3 platform backend only.
///
/// This is useful when using a non-OpenGL renderer (e.g. WGPU) and only
/// want SDL3 to drive the platform layer.
///
/// This assumes that:
/// - a `dear_imgui_rs::Context` already exists;
/// - `window` is a valid SDL3 window handle.
pub fn init_for_other(_imgui: &mut Context, window: &Window) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();

    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForOther_Rust(sdl_window) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
    }

    Ok(())
}

/// Initialize the Dear ImGui SDL3 platform backend for Vulkan renderers.
///
/// This is equivalent to `ImGui_ImplSDL3_InitForVulkan` and is required for
/// Vulkan multi-viewport support (sets Vulkan window flags for secondary viewports).
pub fn init_for_vulkan(_imgui: &mut Context, window: &Window) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();
    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForVulkan_Rust(sdl_window) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
    }
    Ok(())
}

/// Initialize the Dear ImGui SDL3 platform backend for Direct3D (Windows only).
pub fn init_for_d3d(_imgui: &mut Context, window: &Window) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();
    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForD3D_Rust(sdl_window) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
    }
    Ok(())
}

/// Initialize the Dear ImGui SDL3 platform backend for Metal renderers.
pub fn init_for_metal(_imgui: &mut Context, window: &Window) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();
    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForMetal_Rust(sdl_window) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
    }
    Ok(())
}

/// Initialize the Dear ImGui SDL3 platform backend for SDL_Renderer-based renderers.
///
/// # Safety
///
/// The caller must provide a valid `SDL_Renderer` pointer associated with `window`.
pub unsafe fn init_for_sdl_renderer(
    _imgui: &mut Context,
    window: &Window,
    renderer: *mut sdl3_sys::render::SDL_Renderer,
) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();
    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForSDLRenderer_Rust(sdl_window, renderer) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
    }
    Ok(())
}

/// Initialize the Dear ImGui SDL3 platform backend for SDL GPU (SDL_gpu3) renderers.
pub fn init_for_sdl_gpu(_imgui: &mut Context, window: &Window) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();
    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForSDLGPU_Rust(sdl_window) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
    }
    Ok(())
}

/// Initialize the Dear ImGui SDL3 + SDLRenderer3 backend.
///
/// This assumes that:
/// - a `dear_imgui_rs::Context` already exists;
/// - the window related to the renderer/canvas.
/// - the canvas will exist for at least until `shutdown_for_canvas` is called.
///
/// Requires the `sdlrenderer3-renderer` feature.
#[cfg(feature = "sdlrenderer3-renderer")]
pub fn init_for_canvas(
    _imgui: &mut Context,
    window: &Window,
    canvas: &WindowCanvas,
) -> Result<(), Sdl3BackendError> {
    let sdl_window = window.raw();
    let sdl_renderer = canvas.raw();

    unsafe {
        if !ffi::ImGui_ImplSDL3_InitForSDLRenderer_Rust(sdl_window, sdl_renderer) {
            return Err(Sdl3BackendError::Sdl3InitFailed);
        }
        if !sdlrenderer3_backend::dear_imgui_backend_sdlrenderer3_init(
            sdl_renderer as *mut std::ffi::c_void,
        ) {
            return Err(Sdl3BackendError::Renderer3InitFailed);
        }
    }

    Ok(())
}

/// Shutdown the SDL3 + OpenGL3 backends.
///
/// Call this before destroying the ImGui context or the SDL3 window.
#[cfg(feature = "opengl3-renderer")]
pub fn shutdown_for_opengl(_imgui: &mut Context) {
    unsafe {
        opengl3_backend::dear_imgui_backend_opengl3_shutdown();
        ffi::ImGui_ImplSDL3_Shutdown_Rust();
    }
}

/// Shutdown the SDL3 platform backend only.
///
/// This is the counterpart to [`init_for_other`] and should be called before
/// destroying the ImGui context when using a non-OpenGL renderer (e.g. WGPU).
pub fn shutdown(_imgui: &mut Context) {
    unsafe {
        ffi::ImGui_ImplSDL3_Shutdown_Rust();
    }
}

/// Shutdown the SDL3 + SDLRenderer3 backend.
///
/// Call this before destroying the ImGui context or the SDL3 canvas or window.
#[cfg(feature = "sdlrenderer3-renderer")]
pub fn shutdown_for_canvas(_imgui: &mut Context) {
    unsafe {
        sdlrenderer3_backend::dear_imgui_backend_sdlrenderer3_shutdown();
        ffi::ImGui_ImplSDL3_Shutdown_Rust();
    }
}

/// Begin a new ImGui frame for SDL3 + OpenGL.
///
/// Call this before `imgui.frame()`.
#[cfg(feature = "opengl3-renderer")]
pub fn new_frame(_imgui: &mut Context) {
    unsafe {
        opengl3_backend::dear_imgui_backend_opengl3_new_frame();
        ffi::ImGui_ImplSDL3_NewFrame_Rust();
    }
}

/// Begin a new ImGui frame for SDL3 platform backend only.
///
/// This is intended for non-OpenGL renderers such as WGPU.
pub fn sdl3_new_frame(_imgui: &mut Context) {
    unsafe {
        ffi::ImGui_ImplSDL3_NewFrame_Rust();
    }
}

/// Begin a new ImGui frame for SDL3 + SDLRenderer3.
///
/// Call this before `imgui.frame()`.
#[cfg(feature = "sdlrenderer3-renderer")]
pub fn canvas_new_frame(_imgui: &mut Context) {
    unsafe {
        sdlrenderer3_backend::dear_imgui_backend_sdlrenderer3_new_frame();
        ffi::ImGui_ImplSDL3_NewFrame_Rust();
    }
}

/// Poll the next SDL3 event as a low-level `SDL_Event`.
///
/// This mirrors the C++ SDL3 examples and is useful when you want to feed both
/// Dear ImGui and your own event handling from the same low-level event stream.
pub fn sdl3_poll_event_ll() -> Option<SDL_Event> {
    let mut raw = std::mem::MaybeUninit::<SDL_Event>::uninit();
    let has_event = unsafe { sdl3_sys::events::SDL_PollEvent(raw.as_mut_ptr()) };
    if has_event {
        Some(unsafe { raw.assume_init() })
    } else {
        None
    }
}

/// Process a single low-level SDL3 event with ImGui's SDL3 backend.
///
/// Returns `true` if Dear ImGui consumed the event.
pub fn process_sys_event(event: &SDL_Event) -> bool {
    unsafe { ffi::ImGui_ImplSDL3_ProcessEvent_Rust(event) }
}

/// Render Dear ImGui draw data using the OpenGL3 backend.
///
/// This assumes an OpenGL context is current.
#[cfg(feature = "opengl3-renderer")]
pub fn render(draw_data: &DrawData) {
    // Render main viewport
    unsafe {
        let raw = draw_data as *const DrawData as *const sys::ImDrawData;
        opengl3_backend::dear_imgui_backend_opengl3_render_draw_data(raw);
    }
}

/// Render Dear ImGui draw data using the SDLRenderer3 backend.
#[cfg(feature = "sdlrenderer3-renderer")]
pub fn canvas_render(draw_data: &DrawData, canvas: &WindowCanvas) {
    let sdl_renderer = canvas.raw();
    // Render main viewport
    unsafe {
        let raw = draw_data as *const DrawData as *const sys::ImDrawData;
        sdlrenderer3_backend::dear_imgui_backend_sdlrenderer3_render_draw_data(
            raw,
            sdl_renderer as *mut std::ffi::c_void,
        );
    }
}

/// Update a single ImGui texture using the OpenGL3 backend.
///
/// This is an advanced helper that delegates to `ImGui_ImplOpenGL3_UpdateTexture`.
#[cfg(feature = "opengl3-renderer")]
pub fn update_texture(tex: &mut TextureData) {
    unsafe {
        opengl3_backend::dear_imgui_backend_opengl3_update_texture(tex.as_raw_mut());
    }
}

/// Update a single ImGui texture using the SDLRenderer3 backend.
///
/// This is an advanced helper that delegates to `ImGui_ImplSDLRenderer3_UpdateTexture`.
#[cfg(feature = "sdlrenderer3-renderer")]
pub fn canvas_update_texture(tex: &mut TextureData) {
    unsafe {
        sdlrenderer3_backend::dear_imgui_backend_sdlrenderer3_update_texture(tex.as_raw_mut());
    }
}

/// Create OpenGL3 renderer device objects.
///
/// This is an optional advanced helper mirroring `ImGui_ImplOpenGL3_CreateDeviceObjects`.
#[cfg(feature = "opengl3-renderer")]
pub fn create_device_objects() -> bool {
    unsafe { opengl3_backend::dear_imgui_backend_opengl3_create_device_objects() }
}

/// Destroy OpenGL3 renderer device objects.
///
/// This is an optional advanced helper mirroring `ImGui_ImplOpenGL3_DestroyDeviceObjects`.
#[cfg(feature = "opengl3-renderer")]
pub fn destroy_device_objects() {
    unsafe {
        opengl3_backend::dear_imgui_backend_opengl3_destroy_device_objects();
    }
}

/// Create SDLRenderer3 renderer device objects.
///
/// This is an optional advanced helper mirroring `ImGui_ImplSDLRenderer3_CreateDeviceObjects`.
#[cfg(feature = "sdlrenderer3-renderer")]
pub fn canvas_create_device_objects() {
    unsafe { sdlrenderer3_backend::dear_imgui_backend_sdlrenderer3_create_device_objects() }
}

/// Destroy SDLRenderer3 renderer device objects.
///
/// This is an optional advanced helper mirroring `ImGui_ImplSDLRenderer3_DestroyDeviceObjects`.
#[cfg(feature = "sdlrenderer3-renderer")]
pub fn canvas_destroy_device_objects() {
    unsafe {
        sdlrenderer3_backend::dear_imgui_backend_sdlrenderer3_destroy_device_objects();
    }
}