Skip to content

Commit aeb3a51

Browse files
author
Anthony Debucquoy
committed
adding sdl2 and sdl3 SDL_Renderer backend
This commit might be directly incompatible with zig-gamedev#51
1 parent c73edd8 commit aeb3a51

10 files changed

+822
-2
lines changed

build.zig

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ pub const Backend = enum {
1111
sdl2_opengl3,
1212
osx_metal,
1313
sdl2,
14+
sdl2_renderer,
1415
sdl3,
15-
sdl3_gpu,
1616
sdl3_opengl3,
17+
sdl3_renderer,
18+
sdl3_gpu,
1719
};
1820

1921
pub fn build(b: *std.Build) void {
@@ -348,6 +350,18 @@ pub fn build(b: *std.Build) void {
348350
.flags = cflags,
349351
});
350352
},
353+
.sdl2_renderer => {
354+
if (b.lazyDependency("zsdl", .{})) |zsdl| {
355+
imgui.addIncludePath(zsdl.path("libs/sdl2/include"));
356+
}
357+
imgui.addCSourceFiles(.{
358+
.files = &.{
359+
"libs/imgui/backends/imgui_impl_sdl2.cpp",
360+
"libs/imgui/backends/imgui_impl_sdlrenderer2.cpp",
361+
},
362+
.flags = cflags,
363+
});
364+
},
351365
.sdl3_gpu => {
352366
if (b.lazyDependency("zsdl", .{})) |zsdl| {
353367
imgui.addIncludePath(zsdl.path("libs/sdl3/include"));
@@ -360,6 +374,18 @@ pub fn build(b: *std.Build) void {
360374
.flags = cflags,
361375
});
362376
},
377+
.sdl3_renderer => {
378+
if (b.lazyDependency("zsdl", .{})) |zsdl| {
379+
imgui.addIncludePath(zsdl.path("libs/sdl3/include"));
380+
}
381+
imgui.addCSourceFiles(.{
382+
.files = &.{
383+
"libs/imgui/backends/imgui_impl_sdl3.cpp",
384+
"libs/imgui/backends/imgui_impl_sdlrenderer3.cpp",
385+
},
386+
.flags = cflags,
387+
});
388+
},
363389
.sdl3_opengl3 => {
364390
if (b.lazyDependency("zsdl", .{})) |zsdl| {
365391
imgui.addIncludePath(zsdl.path("libs/sdl3/include/SDL3"));
Lines changed: 278 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
1+
// dear imgui: Renderer Backend for SDL_Renderer for SDL2
2+
// (Requires: SDL 2.0.17+)
3+
4+
// Note that SDL_Renderer is an _optional_ component of SDL2, which IMHO is now largely obsolete.
5+
// For a multi-platform app consider using other technologies:
6+
// - SDL3+SDL_GPU: SDL_GPU is SDL3 new graphics abstraction API. You will need to update to SDL3.
7+
// - SDL2+DirectX, SDL2+OpenGL, SDL2+Vulkan: combine SDL with dedicated renderers.
8+
// If your application wants to render any non trivial amount of graphics other than UI,
9+
// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user
10+
// and it might be difficult to step out of those boundaries.
11+
12+
// Implemented features:
13+
// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
14+
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
15+
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
16+
17+
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
18+
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
19+
// Learn about Dear ImGui:
20+
// - FAQ https://dearimgui.com/faq
21+
// - Getting Started https://dearimgui.com/getting-started
22+
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
23+
// - Introduction, links and more at the top of imgui.cpp
24+
25+
// CHANGELOG
26+
// 2025-01-18: Use endian-dependent RGBA32 texture format, to match SDL_Color.
27+
// 2024-10-09: Expose selected render state in ImGui_ImplSDLRenderer2_RenderState, which you can access in 'void* platform_io.Renderer_RenderState' during draw callbacks.
28+
// 2024-05-14: *BREAKING CHANGE* ImGui_ImplSDLRenderer3_RenderDrawData() requires SDL_Renderer* passed as parameter.
29+
// 2023-05-30: Renamed imgui_impl_sdlrenderer.h/.cpp to imgui_impl_sdlrenderer2.h/.cpp to accommodate for upcoming SDL3.
30+
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
31+
// 2021-12-21: Update SDL_RenderGeometryRaw() format to work with SDL 2.0.19.
32+
// 2021-12-03: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
33+
// 2021-10-06: Backup and restore modified ClipRect/Viewport.
34+
// 2021-09-21: Initial version.
35+
36+
#include "imgui.h"
37+
#ifndef IMGUI_DISABLE
38+
#include "imgui_impl_sdlrenderer2.h"
39+
#include <stdint.h> // intptr_t
40+
41+
// Clang warnings with -Weverything
42+
#if defined(__clang__)
43+
#pragma clang diagnostic push
44+
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
45+
#endif
46+
47+
// SDL
48+
#include <SDL.h>
49+
#if !SDL_VERSION_ATLEAST(2,0,17)
50+
#error This backend requires SDL 2.0.17+ because of SDL_RenderGeometry() function
51+
#endif
52+
53+
// SDL_Renderer data
54+
struct ImGui_ImplSDLRenderer2_Data
55+
{
56+
SDL_Renderer* Renderer; // Main viewport's renderer
57+
SDL_Texture* FontTexture;
58+
ImGui_ImplSDLRenderer2_Data() { memset((void*)this, 0, sizeof(*this)); }
59+
};
60+
61+
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
62+
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
63+
static ImGui_ImplSDLRenderer2_Data* ImGui_ImplSDLRenderer2_GetBackendData()
64+
{
65+
return ImGui::GetCurrentContext() ? (ImGui_ImplSDLRenderer2_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
66+
}
67+
68+
// Functions
69+
bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer)
70+
{
71+
ImGuiIO& io = ImGui::GetIO();
72+
IMGUI_CHECKVERSION();
73+
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
74+
IM_ASSERT(renderer != nullptr && "SDL_Renderer not initialized!");
75+
76+
// Setup backend capabilities flags
77+
ImGui_ImplSDLRenderer2_Data* bd = IM_NEW(ImGui_ImplSDLRenderer2_Data)();
78+
io.BackendRendererUserData = (void*)bd;
79+
io.BackendRendererName = "imgui_impl_sdlrenderer2";
80+
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
81+
82+
bd->Renderer = renderer;
83+
84+
return true;
85+
}
86+
87+
void ImGui_ImplSDLRenderer2_Shutdown()
88+
{
89+
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
90+
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
91+
ImGuiIO& io = ImGui::GetIO();
92+
93+
ImGui_ImplSDLRenderer2_DestroyDeviceObjects();
94+
95+
io.BackendRendererName = nullptr;
96+
io.BackendRendererUserData = nullptr;
97+
io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
98+
IM_DELETE(bd);
99+
}
100+
101+
static void ImGui_ImplSDLRenderer2_SetupRenderState(SDL_Renderer* renderer)
102+
{
103+
// Clear out any viewports and cliprect set by the user
104+
// FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
105+
SDL_RenderSetViewport(renderer, nullptr);
106+
SDL_RenderSetClipRect(renderer, nullptr);
107+
}
108+
109+
void ImGui_ImplSDLRenderer2_NewFrame()
110+
{
111+
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
112+
IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplSDLRenderer2_Init()?");
113+
114+
if (!bd->FontTexture)
115+
ImGui_ImplSDLRenderer2_CreateDeviceObjects();
116+
}
117+
118+
void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer)
119+
{
120+
// If there's a scale factor set by the user, use that instead
121+
// If the user has specified a scale factor to SDL_Renderer already via SDL_RenderSetScale(), SDL will scale whatever we pass
122+
// to SDL_RenderGeometryRaw() by that scale factor. In that case we don't want to be also scaling it ourselves here.
123+
float rsx = 1.0f;
124+
float rsy = 1.0f;
125+
SDL_RenderGetScale(renderer, &rsx, &rsy);
126+
ImVec2 render_scale;
127+
render_scale.x = (rsx == 1.0f) ? draw_data->FramebufferScale.x : 1.0f;
128+
render_scale.y = (rsy == 1.0f) ? draw_data->FramebufferScale.y : 1.0f;
129+
130+
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
131+
int fb_width = (int)(draw_data->DisplaySize.x * render_scale.x);
132+
int fb_height = (int)(draw_data->DisplaySize.y * render_scale.y);
133+
if (fb_width == 0 || fb_height == 0)
134+
return;
135+
136+
// Backup SDL_Renderer state that will be modified to restore it afterwards
137+
struct BackupSDLRendererState
138+
{
139+
SDL_Rect Viewport;
140+
bool ClipEnabled;
141+
SDL_Rect ClipRect;
142+
};
143+
BackupSDLRendererState old = {};
144+
old.ClipEnabled = SDL_RenderIsClipEnabled(renderer) == SDL_TRUE;
145+
SDL_RenderGetViewport(renderer, &old.Viewport);
146+
SDL_RenderGetClipRect(renderer, &old.ClipRect);
147+
148+
// Setup desired state
149+
ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
150+
151+
// Setup render state structure (for callbacks and custom texture bindings)
152+
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
153+
ImGui_ImplSDLRenderer2_RenderState render_state;
154+
render_state.Renderer = renderer;
155+
platform_io.Renderer_RenderState = &render_state;
156+
157+
// Will project scissor/clipping rectangles into framebuffer space
158+
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
159+
ImVec2 clip_scale = render_scale;
160+
161+
// Render command lists
162+
for (int n = 0; n < draw_data->CmdListsCount; n++)
163+
{
164+
const ImDrawList* draw_list = draw_data->CmdLists[n];
165+
const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data;
166+
const ImDrawIdx* idx_buffer = draw_list->IdxBuffer.Data;
167+
168+
for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
169+
{
170+
const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
171+
if (pcmd->UserCallback)
172+
{
173+
// User callback, registered via ImDrawList::AddCallback()
174+
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
175+
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
176+
ImGui_ImplSDLRenderer2_SetupRenderState(renderer);
177+
else
178+
pcmd->UserCallback(draw_list, pcmd);
179+
}
180+
else
181+
{
182+
// Project scissor/clipping rectangles into framebuffer space
183+
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
184+
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
185+
if (clip_min.x < 0.0f) { clip_min.x = 0.0f; }
186+
if (clip_min.y < 0.0f) { clip_min.y = 0.0f; }
187+
if (clip_max.x > (float)fb_width) { clip_max.x = (float)fb_width; }
188+
if (clip_max.y > (float)fb_height) { clip_max.y = (float)fb_height; }
189+
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
190+
continue;
191+
192+
SDL_Rect r = { (int)(clip_min.x), (int)(clip_min.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y) };
193+
SDL_RenderSetClipRect(renderer, &r);
194+
195+
const float* xy = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, pos));
196+
const float* uv = (const float*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, uv));
197+
#if SDL_VERSION_ATLEAST(2,0,19)
198+
const SDL_Color* color = (const SDL_Color*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.19+
199+
#else
200+
const int* color = (const int*)(const void*)((const char*)(vtx_buffer + pcmd->VtxOffset) + offsetof(ImDrawVert, col)); // SDL 2.0.17 and 2.0.18
201+
#endif
202+
203+
// Bind texture, Draw
204+
SDL_Texture* tex = (SDL_Texture*)pcmd->GetTexID();
205+
SDL_RenderGeometryRaw(renderer, tex,
206+
xy, (int)sizeof(ImDrawVert),
207+
color, (int)sizeof(ImDrawVert),
208+
uv, (int)sizeof(ImDrawVert),
209+
draw_list->VtxBuffer.Size - pcmd->VtxOffset,
210+
idx_buffer + pcmd->IdxOffset, pcmd->ElemCount, sizeof(ImDrawIdx));
211+
}
212+
}
213+
}
214+
platform_io.Renderer_RenderState = nullptr;
215+
216+
// Restore modified SDL_Renderer state
217+
SDL_RenderSetViewport(renderer, &old.Viewport);
218+
SDL_RenderSetClipRect(renderer, old.ClipEnabled ? &old.ClipRect : nullptr);
219+
}
220+
221+
// Called by Init/NewFrame/Shutdown
222+
bool ImGui_ImplSDLRenderer2_CreateFontsTexture()
223+
{
224+
ImGuiIO& io = ImGui::GetIO();
225+
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
226+
227+
// Build texture atlas
228+
unsigned char* pixels;
229+
int width, height;
230+
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
231+
232+
// Upload texture to graphics system
233+
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
234+
bd->FontTexture = SDL_CreateTexture(bd->Renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, width, height);
235+
if (bd->FontTexture == nullptr)
236+
{
237+
SDL_Log("error creating texture");
238+
return false;
239+
}
240+
SDL_UpdateTexture(bd->FontTexture, nullptr, pixels, 4 * width);
241+
SDL_SetTextureBlendMode(bd->FontTexture, SDL_BLENDMODE_BLEND);
242+
SDL_SetTextureScaleMode(bd->FontTexture, SDL_ScaleModeLinear);
243+
244+
// Store our identifier
245+
io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
246+
247+
return true;
248+
}
249+
250+
void ImGui_ImplSDLRenderer2_DestroyFontsTexture()
251+
{
252+
ImGuiIO& io = ImGui::GetIO();
253+
ImGui_ImplSDLRenderer2_Data* bd = ImGui_ImplSDLRenderer2_GetBackendData();
254+
if (bd->FontTexture)
255+
{
256+
io.Fonts->SetTexID(0);
257+
SDL_DestroyTexture(bd->FontTexture);
258+
bd->FontTexture = nullptr;
259+
}
260+
}
261+
262+
bool ImGui_ImplSDLRenderer2_CreateDeviceObjects()
263+
{
264+
return ImGui_ImplSDLRenderer2_CreateFontsTexture();
265+
}
266+
267+
void ImGui_ImplSDLRenderer2_DestroyDeviceObjects()
268+
{
269+
ImGui_ImplSDLRenderer2_DestroyFontsTexture();
270+
}
271+
272+
//-----------------------------------------------------------------------------
273+
274+
#if defined(__clang__)
275+
#pragma clang diagnostic pop
276+
#endif
277+
278+
#endif // #ifndef IMGUI_DISABLE
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
// dear imgui: Renderer Backend for SDL_Renderer for SDL2
2+
// (Requires: SDL 2.0.17+)
3+
4+
// Note that SDL_Renderer is an _optional_ component of SDL2, which IMHO is now largely obsolete.
5+
// For a multi-platform app consider using other technologies:
6+
// - SDL3+SDL_GPU: SDL_GPU is SDL3 new graphics abstraction API. You will need to update to SDL3.
7+
// - SDL2+DirectX, SDL2+OpenGL, SDL2+Vulkan: combine SDL with dedicated renderers.
8+
// If your application wants to render any non trivial amount of graphics other than UI,
9+
// please be aware that SDL_Renderer currently offers a limited graphic API to the end-user
10+
// and it might be difficult to step out of those boundaries.
11+
12+
// Implemented features:
13+
// [X] Renderer: User texture binding. Use 'SDL_Texture*' as ImTextureID. Read the FAQ about ImTextureID!
14+
// [X] Renderer: Large meshes support (64k+ vertices) even with 16-bit indices (ImGuiBackendFlags_RendererHasVtxOffset).
15+
// [X] Renderer: Expose selected render state for draw callbacks to use. Access in '(ImGui_ImplXXXX_RenderState*)GetPlatformIO().Renderer_RenderState'.
16+
17+
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
18+
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
19+
// Learn about Dear ImGui:
20+
// - FAQ https://dearimgui.com/faq
21+
// - Getting Started https://dearimgui.com/getting-started
22+
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
23+
// - Introduction, links and more at the top of imgui.cpp
24+
25+
#pragma once
26+
#ifndef IMGUI_DISABLE
27+
#include "imgui.h" // IMGUI_IMPL_API
28+
29+
struct SDL_Renderer;
30+
31+
// Follow "Getting Started" link and check examples/ folder to learn about using backends!
32+
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_Init(SDL_Renderer* renderer);
33+
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_Shutdown();
34+
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_NewFrame();
35+
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_RenderDrawData(ImDrawData* draw_data, SDL_Renderer* renderer);
36+
37+
// Called by Init/NewFrame/Shutdown
38+
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateFontsTexture();
39+
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyFontsTexture();
40+
IMGUI_IMPL_API bool ImGui_ImplSDLRenderer2_CreateDeviceObjects();
41+
IMGUI_IMPL_API void ImGui_ImplSDLRenderer2_DestroyDeviceObjects();
42+
43+
// [BETA] Selected render state data shared with callbacks.
44+
// This is temporarily stored in GetPlatformIO().Renderer_RenderState during the ImGui_ImplSDLRenderer2_RenderDrawData() call.
45+
// (Please open an issue if you feel you need access to more data)
46+
struct ImGui_ImplSDLRenderer2_RenderState
47+
{
48+
SDL_Renderer* Renderer;
49+
};
50+
51+
#endif // #ifndef IMGUI_DISABLE

0 commit comments

Comments
 (0)