35.2 KB、705行 生 Blame 履歴
1// dear imgui: Renderer + Platform Backend for Allegro 5
2// (Info: Allegro 5 is a cross-platform general purpose library for handling windows, inputs, graphics, etc.)
3
4// Implemented features:
5// [X] Renderer: User texture binding. Use 'ALLEGRO_BITMAP*' as texture identifier. Read the FAQ about ImTextureID/ImTextureRef!
6// [X] Renderer: Texture updates support for dynamic font atlas (ImGuiBackendFlags_RendererHasTextures).
7// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy ALLEGRO_KEY_* values are obsolete since 1.87 and not supported since 1.91.5]
8// [X] Platform: Clipboard support (from Allegro 5.1.12).
9// [X] Platform: Mouse cursor shape and visibility (ImGuiBackendFlags_HasMouseCursors). Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
10// Missing features or Issues:
11// [ ] Renderer: The renderer is suboptimal as we need to unindex our buffers and convert vertices manually.
12// [ ] Renderer: Missing support for DrawCallback_SetSamplerLinear, DrawCallback_SetSamplerNearest callbacks: Allegro5 cannot enable/disable LINEAR bitmap flags after creation.
13// [ ] Platform: Missing gamepad support.
14// [ ] Renderer: Multi-viewport support (multiple windows).
15
16// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
17// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
18// Learn about Dear ImGui:
19// - FAQ https://dearimgui.com/faq
20// - Getting Started https://dearimgui.com/getting-started
21// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
22// - Introduction, links and more at the top of imgui.cpp
23
24// CHANGELOG
25// (minor and older changes stripped away, please see git history for details)
26// 2026-04-23: Added support for standard draw callbacks (in platform_io): DrawCallback_ResetRenderState (others cannot be supported by Allegro5). (#9378)
27// 2025-09-18: Call platform_io.ClearRendererHandlers() and platform_io.ClearPlatformHandlers() on shutdown.
28// 2025-08-12: Inputs: fixed missing support for ImGuiKey_PrintScreen under Windows, as raw Allegro 5 does not receive it.
29// 2025-08-12: Added ImGui_ImplAllegro5_SetDisplay() function to change current ALLEGRO_DISPLAY, as Allegro applications often need to do that.
30// 2025-07-07: Fixed texture update broken on some platforms where ALLEGRO_LOCK_WRITEONLY needed all texels to be rewritten.
31// 2025-06-11: Added support for ImGuiBackendFlags_RendererHasTextures, for dynamic font atlas. Removed ImGui_ImplSDLGPU3_CreateFontsTexture() and ImGui_ImplSDLGPU3_DestroyFontsTexture().
32// 2025-02-18: Added ImGuiMouseCursor_Wait and ImGuiMouseCursor_Progress mouse cursor support.
33// 2025-01-06: Avoid calling al_set_mouse_cursor() repeatedly since it appears to leak on on X11 (#8256).
34// 2024-08-22: moved some OS/backend related function pointers from ImGuiIO to ImGuiPlatformIO:
35// - io.GetClipboardTextFn -> platform_io.Platform_GetClipboardTextFn
36// - io.SetClipboardTextFn -> platform_io.Platform_SetClipboardTextFn
37// 2022-11-30: Renderer: Restoring using al_draw_indexed_prim() when Allegro version is >= 5.2.5.
38// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
39// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
40// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
41// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
42// 2022-01-17: Inputs: always calling io.AddKeyModsEvent() next and before key event (not in NewFrame) to fix input queue with very low framerates.
43// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
44// 2021-12-08: Renderer: Fixed mishandling of the ImDrawCmd::IdxOffset field! This is an old bug but it never had an effect until some internal rendering changes in 1.86.
45// 2021-08-17: Calling io.AddFocusEvent() on ALLEGRO_EVENT_DISPLAY_SWITCH_OUT/ALLEGRO_EVENT_DISPLAY_SWITCH_IN events.
46// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
47// 2021-05-19: Renderer: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
48// 2021-02-18: Change blending equation to preserve alpha in output buffer.
49// 2020-08-10: Inputs: Fixed horizontal mouse wheel direction.
50// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
51// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
52// 2019-05-11: Inputs: Don't filter character value from ALLEGRO_EVENT_KEY_CHAR before calling AddInputCharacter().
53// 2019-04-30: Renderer: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
54// 2018-11-30: Platform: Added touchscreen support.
55// 2018-11-30: Misc: Setting up io.BackendPlatformName/io.BackendRendererName so they can be displayed in the About Window.
56// 2018-06-13: Platform: Added clipboard support (from Allegro 5.1.12).
57// 2018-06-13: Renderer: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
58// 2018-06-13: Renderer: Stopped using al_draw_indexed_prim() as it is buggy in Allegro's DX9 backend.
59// 2018-06-13: Renderer: Backup/restore transform and clipping rectangle.
60// 2018-06-11: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
61// 2018-04-18: Misc: Renamed file from imgui_impl_a5.cpp to imgui_impl_allegro5.cpp.
62// 2018-04-18: Misc: Added support for 32-bit vertex indices to avoid conversion at runtime. Added imconfig_allegro5.h to enforce 32-bit indices when included from imgui.h.
63// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplAllegro5_RenderDrawData() in the .h file so you can call it yourself.
64// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
65// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
66
67#include "imgui.h"
68#ifndef IMGUI_DISABLE
69#include "imgui_impl_allegro5.h"
70#include <stdint.h> // uint64_t
71#include <cstring> // memcpy
72
73// Allegro
74#include <allegro5/allegro.h>
75#include <allegro5/allegro_primitives.h>
76#ifdef _WIN32
77#include <allegro5/allegro_windows.h>
78#endif
79#define ALLEGRO_HAS_CLIPBOARD ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (1 << 16) | (12 << 8))) // Clipboard only supported from Allegro 5.1.12
80#define ALLEGRO_HAS_DRAW_INDEXED_PRIM ((ALLEGRO_VERSION_INT & ~ALLEGRO_UNSTABLE_BIT) >= ((5 << 24) | (2 << 16) | ( 5 << 8))) // DX9 implementation of al_draw_indexed_prim() got fixed in Allegro 5.2.5
81
82// Visual Studio warnings
83#ifdef _MSC_VER
84#pragma warning (disable: 4127) // condition expression is constant
85#endif
86
87struct ImDrawVertAllegro
88{
89 ImVec2 pos;
90 ImVec2 uv;
91 ALLEGRO_COLOR col;
92};
93
94// FIXME-OPT: Unfortunately Allegro doesn't support 32-bit packed colors so we have to convert them to 4 float as well..
95// FIXME-OPT: Consider inlining al_map_rgba()?
96// see https://github.com/liballeg/allegro5/blob/master/src/pixels.c#L554
97// and https://github.com/liballeg/allegro5/blob/master/include/allegro5/internal/aintern_pixels.h
98#define DRAW_VERT_IMGUI_TO_ALLEGRO(DST, SRC) { (DST)->pos = (SRC)->pos; (DST)->uv = (SRC)->uv; unsigned char* c = (unsigned char*)&(SRC)->col; (DST)->col = al_map_rgba(c[0], c[1], c[2], c[3]); }
99
100// Allegro Data
101struct ImGui_ImplAllegro5_Data
102{
103 ALLEGRO_DISPLAY* Display;
104 ALLEGRO_BITMAP* Texture;
105 double Time;
106 ALLEGRO_MOUSE_CURSOR* MouseCursorInvisible;
107 ALLEGRO_VERTEX_DECL* VertexDecl;
108 char* ClipboardTextData;
109 ImGuiMouseCursor LastCursor;
110
111 ImVector<ImDrawVertAllegro> BufVertices;
112 ImVector<int> BufIndices;
113
114 ImGui_ImplAllegro5_Data() { memset((void*)this, 0, sizeof(*this)); }
115};
116
117// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
118// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
119// FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
120static ImGui_ImplAllegro5_Data* ImGui_ImplAllegro5_GetBackendData() { return ImGui::GetCurrentContext() ? (ImGui_ImplAllegro5_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr; }
121
122static void ImGui_ImplAllegro5_SetupRenderState(ImDrawData* draw_data)
123{
124 // Setup blending
125 al_set_separate_blender(ALLEGRO_ADD, ALLEGRO_ALPHA, ALLEGRO_INVERSE_ALPHA, ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
126
127 // Setup orthographic projection matrix
128 // Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
129 {
130 float L = draw_data->DisplayPos.x;
131 float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
132 float T = draw_data->DisplayPos.y;
133 float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
134 ALLEGRO_TRANSFORM transform;
135 al_identity_transform(&transform);
136 al_use_transform(&transform);
137 al_orthographic_transform(&transform, L, T, 1.0f, R, B, -1.0f);
138 al_use_projection_transform(&transform);
139 }
140}
141
142// Draw callbacks
143static void ImGui_ImplAllegro5_DrawCallback_ResetRenderState(const ImDrawList*, const ImDrawCmd*) {} // Intentionally empty. Used as an identifier for rendering loop to call its code. Simpler to implement this way.
144
145// Render function
146void ImGui_ImplAllegro5_RenderDrawData(ImDrawData* draw_data)
147{
148 // Avoid rendering when minimized
149 if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
150 return;
151
152 // Catch up with texture updates. Most of the times, the list will have 1 element with an OK status, aka nothing to do.
153 // (This almost always points to ImGui::GetPlatformIO().Textures[] but is part of ImDrawData to allow overriding or disabling texture updates).
154 if (draw_data->Textures != nullptr)
155 for (ImTextureData* tex : *draw_data->Textures)
156 if (tex->Status != ImTextureStatus_OK)
157 ImGui_ImplAllegro5_UpdateTexture(tex);
158
159 // Backup Allegro state that will be modified
160 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
161 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
162 ALLEGRO_TRANSFORM last_transform = *al_get_current_transform();
163 ALLEGRO_TRANSFORM last_projection_transform = *al_get_current_projection_transform();
164 int last_clip_x, last_clip_y, last_clip_w, last_clip_h;
165 al_get_clipping_rectangle(&last_clip_x, &last_clip_y, &last_clip_w, &last_clip_h);
166 int last_blender_op, last_blender_src, last_blender_dst;
167 al_get_blender(&last_blender_op, &last_blender_src, &last_blender_dst);
168
169 // Setup desired render state
170 ImGui_ImplAllegro5_SetupRenderState(draw_data);
171
172 // Render command lists
173 for (const ImDrawList* draw_list : draw_data->CmdLists)
174 {
175 ImVector<ImDrawVertAllegro>& vertices = bd->BufVertices;
176#if ALLEGRO_HAS_DRAW_INDEXED_PRIM
177 vertices.resize(draw_list->VtxBuffer.Size);
178 for (int i = 0; i < draw_list->VtxBuffer.Size; i++)
179 {
180 const ImDrawVert* src_v = &draw_list->VtxBuffer[i];
181 ImDrawVertAllegro* dst_v = &vertices[i];
182 DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v);
183 }
184 const int* indices = nullptr;
185 if (sizeof(ImDrawIdx) == 2)
186 {
187 // FIXME-OPT: Allegro doesn't support 16-bit indices.
188 // You can '#define ImDrawIdx int' in imconfig.h to request Dear ImGui to output 32-bit indices.
189 // Otherwise, we convert them from 16-bit to 32-bit at runtime here, which works perfectly but is a little wasteful.
190 bd->BufIndices.resize(draw_list->IdxBuffer.Size);
191 for (int i = 0; i < draw_list->IdxBuffer.Size; ++i)
192 bd->BufIndices[i] = (int)draw_list->IdxBuffer.Data[i];
193 indices = bd->BufIndices.Data;
194 }
195 else if (sizeof(ImDrawIdx) == 4)
196 {
197 indices = (const int*)draw_list->IdxBuffer.Data;
198 }
199#else
200 // Allegro's implementation of al_draw_indexed_prim() for DX9 was broken until 5.2.5. Unindex buffers ourselves while converting vertex format.
201 vertices.resize(draw_list->IdxBuffer.Size);
202 for (int i = 0; i < draw_list->IdxBuffer.Size; i++)
203 {
204 const ImDrawVert* src_v = &draw_list->VtxBuffer[draw_list->IdxBuffer[i]];
205 ImDrawVertAllegro* dst_v = &vertices[i];
206 DRAW_VERT_IMGUI_TO_ALLEGRO(dst_v, src_v);
207 }
208#endif
209
210 // Render command lists
211 ImVec2 clip_off = draw_data->DisplayPos;
212 for (int cmd_i = 0; cmd_i < draw_list->CmdBuffer.Size; cmd_i++)
213 {
214 const ImDrawCmd* pcmd = &draw_list->CmdBuffer[cmd_i];
215 if (pcmd->UserCallback)
216 {
217 // User callback, registered via ImDrawList::AddCallback()
218 if (pcmd->UserCallback == ImGui_ImplAllegro5_DrawCallback_ResetRenderState)
219 ImGui_ImplAllegro5_SetupRenderState(draw_data);
220 else
221 pcmd->UserCallback(draw_list, pcmd);
222 }
223 else
224 {
225 // Project scissor/clipping rectangles into framebuffer space
226 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
227 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
228 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
229 continue;
230
231 // Apply scissor/clipping rectangle, Draw
232 ALLEGRO_BITMAP* texture = (ALLEGRO_BITMAP*)pcmd->GetTexID();
233 al_set_clipping_rectangle(clip_min.x, clip_min.y, clip_max.x - clip_min.x, clip_max.y - clip_min.y);
234#if ALLEGRO_HAS_DRAW_INDEXED_PRIM
235 al_draw_indexed_prim(&vertices[0], bd->VertexDecl, texture, &indices[pcmd->IdxOffset], pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST);
236#else
237 al_draw_prim(&vertices[0], bd->VertexDecl, texture, pcmd->IdxOffset, pcmd->IdxOffset + pcmd->ElemCount, ALLEGRO_PRIM_TRIANGLE_LIST);
238#endif
239 }
240 }
241 }
242
243 // Restore modified Allegro state
244 al_set_blender(last_blender_op, last_blender_src, last_blender_dst);
245 al_set_clipping_rectangle(last_clip_x, last_clip_y, last_clip_w, last_clip_h);
246 al_use_transform(&last_transform);
247 al_use_projection_transform(&last_projection_transform);
248}
249
250bool ImGui_ImplAllegro5_CreateDeviceObjects()
251{
252 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
253
254 // Create an invisible mouse cursor
255 // Because al_hide_mouse_cursor() seems to mess up with the actual inputs..
256 ALLEGRO_BITMAP* mouse_cursor = al_create_bitmap(8, 8);
257 bd->MouseCursorInvisible = al_create_mouse_cursor(mouse_cursor, 0, 0);
258 al_destroy_bitmap(mouse_cursor);
259
260 return true;
261}
262
263void ImGui_ImplAllegro5_UpdateTexture(ImTextureData* tex)
264{
265 if (tex->Status == ImTextureStatus_WantCreate)
266 {
267 // Create and upload new texture to graphics system
268 //IMGUI_DEBUG_LOG("UpdateTexture #%03d: WantCreate %dx%d\n", tex->UniqueID, tex->Width, tex->Height);
269 IM_ASSERT(tex->TexID == ImTextureID_Invalid && tex->BackendUserData == nullptr);
270 IM_ASSERT(tex->Format == ImTextureFormat_RGBA32);
271
272 // Create texture
273 // (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
274 const int new_bitmap_flags = al_get_new_bitmap_flags();
275 int new_bitmap_format = al_get_new_bitmap_format();
276 al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP | ALLEGRO_MIN_LINEAR | ALLEGRO_MAG_LINEAR);
277 al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ABGR_8888_LE);
278 ALLEGRO_BITMAP* cpu_bitmap = al_create_bitmap(tex->Width, tex->Height);
279 IM_ASSERT(cpu_bitmap != nullptr && "Backend failed to create texture!");
280
281 // Upload pixels
282 ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap(cpu_bitmap, al_get_bitmap_format(cpu_bitmap), ALLEGRO_LOCK_WRITEONLY);
283 IM_ASSERT(locked_region != nullptr && "Backend failed to create texture!");
284 memcpy(locked_region->data, tex->GetPixels(), tex->GetSizeInBytes());
285 al_unlock_bitmap(cpu_bitmap);
286
287 // Convert software texture to hardware texture.
288 al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);
289 al_set_new_bitmap_format(ALLEGRO_PIXEL_FORMAT_ANY_32_WITH_ALPHA);
290 ALLEGRO_BITMAP* gpu_bitmap = al_clone_bitmap(cpu_bitmap);
291 al_destroy_bitmap(cpu_bitmap);
292 IM_ASSERT(gpu_bitmap != nullptr && "Backend failed to create texture!");
293
294 al_set_new_bitmap_flags(new_bitmap_flags);
295 al_set_new_bitmap_format(new_bitmap_format);
296
297 // Store identifiers
298 tex->SetTexID((ImTextureID)(intptr_t)gpu_bitmap);
299 tex->SetStatus(ImTextureStatus_OK);
300 }
301 else if (tex->Status == ImTextureStatus_WantUpdates)
302 {
303 // Update selected blocks. We only ever write to textures regions which have never been used before!
304 // This backend choose to use tex->Updates[] but you can use tex->UpdateRect to upload a single region.
305 ImTextureRect r = tex->UpdateRect; // Bounding box encompassing all individual updates
306 ALLEGRO_BITMAP* gpu_bitmap = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID;
307 ALLEGRO_LOCKED_REGION* locked_region = al_lock_bitmap_region(gpu_bitmap, r.x, r.y, r.w, r.h, al_get_bitmap_format(gpu_bitmap), ALLEGRO_LOCK_WRITEONLY);
308 IM_ASSERT(locked_region && "Backend failed to update texture!");
309 for (int y = 0; y < r.h; y++)
310 memcpy((unsigned char*)locked_region->data + locked_region->pitch * y, tex->GetPixelsAt(r.x, r.y + y), r.w * tex->BytesPerPixel); // dst, src, block pitch
311 al_unlock_bitmap(gpu_bitmap);
312 tex->SetStatus(ImTextureStatus_OK);
313 }
314 else if (tex->Status == ImTextureStatus_WantDestroy)
315 {
316 ALLEGRO_BITMAP* backend_tex = (ALLEGRO_BITMAP*)(intptr_t)tex->TexID;
317 if (backend_tex)
318 al_destroy_bitmap(backend_tex);
319
320 // Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
321 tex->SetTexID(ImTextureID_Invalid);
322 tex->SetStatus(ImTextureStatus_Destroyed);
323 }
324}
325
326void ImGui_ImplAllegro5_InvalidateDeviceObjects()
327{
328 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
329
330 // Destroy all textures
331 for (ImTextureData* tex : ImGui::GetPlatformIO().Textures)
332 if (tex->RefCount == 1)
333 {
334 tex->SetStatus(ImTextureStatus_WantDestroy);
335 ImGui_ImplAllegro5_UpdateTexture(tex);
336 }
337
338 // Destroy mouse cursor
339 if (bd->MouseCursorInvisible)
340 {
341 al_destroy_mouse_cursor(bd->MouseCursorInvisible);
342 bd->MouseCursorInvisible = nullptr;
343 }
344}
345
346#if ALLEGRO_HAS_CLIPBOARD
347static const char* ImGui_ImplAllegro5_GetClipboardText(ImGuiContext*)
348{
349 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
350 if (bd->ClipboardTextData)
351 al_free(bd->ClipboardTextData);
352 bd->ClipboardTextData = al_get_clipboard_text(bd->Display);
353 return bd->ClipboardTextData;
354}
355
356static void ImGui_ImplAllegro5_SetClipboardText(ImGuiContext*, const char* text)
357{
358 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
359 al_set_clipboard_text(bd->Display, text);
360}
361#endif
362
363// Not static to allow third-party code to use that if they want to (but undocumented)
364ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code);
365ImGuiKey ImGui_ImplAllegro5_KeyCodeToImGuiKey(int key_code)
366{
367 switch (key_code)
368 {
369 case ALLEGRO_KEY_TAB: return ImGuiKey_Tab;
370 case ALLEGRO_KEY_LEFT: return ImGuiKey_LeftArrow;
371 case ALLEGRO_KEY_RIGHT: return ImGuiKey_RightArrow;
372 case ALLEGRO_KEY_UP: return ImGuiKey_UpArrow;
373 case ALLEGRO_KEY_DOWN: return ImGuiKey_DownArrow;
374 case ALLEGRO_KEY_PGUP: return ImGuiKey_PageUp;
375 case ALLEGRO_KEY_PGDN: return ImGuiKey_PageDown;
376 case ALLEGRO_KEY_HOME: return ImGuiKey_Home;
377 case ALLEGRO_KEY_END: return ImGuiKey_End;
378 case ALLEGRO_KEY_INSERT: return ImGuiKey_Insert;
379 case ALLEGRO_KEY_DELETE: return ImGuiKey_Delete;
380 case ALLEGRO_KEY_BACKSPACE: return ImGuiKey_Backspace;
381 case ALLEGRO_KEY_SPACE: return ImGuiKey_Space;
382 case ALLEGRO_KEY_ENTER: return ImGuiKey_Enter;
383 case ALLEGRO_KEY_ESCAPE: return ImGuiKey_Escape;
384 case ALLEGRO_KEY_QUOTE: return ImGuiKey_Apostrophe;
385 case ALLEGRO_KEY_COMMA: return ImGuiKey_Comma;
386 case ALLEGRO_KEY_MINUS: return ImGuiKey_Minus;
387 case ALLEGRO_KEY_FULLSTOP: return ImGuiKey_Period;
388 case ALLEGRO_KEY_SLASH: return ImGuiKey_Slash;
389 case ALLEGRO_KEY_SEMICOLON: return ImGuiKey_Semicolon;
390 case ALLEGRO_KEY_EQUALS: return ImGuiKey_Equal;
391 case ALLEGRO_KEY_OPENBRACE: return ImGuiKey_LeftBracket;
392 case ALLEGRO_KEY_BACKSLASH: return ImGuiKey_Backslash;
393 case ALLEGRO_KEY_CLOSEBRACE: return ImGuiKey_RightBracket;
394 case ALLEGRO_KEY_TILDE: return ImGuiKey_GraveAccent;
395 case ALLEGRO_KEY_CAPSLOCK: return ImGuiKey_CapsLock;
396 case ALLEGRO_KEY_SCROLLLOCK: return ImGuiKey_ScrollLock;
397 case ALLEGRO_KEY_NUMLOCK: return ImGuiKey_NumLock;
398 case ALLEGRO_KEY_PRINTSCREEN: return ImGuiKey_PrintScreen;
399 case ALLEGRO_KEY_PAUSE: return ImGuiKey_Pause;
400 case ALLEGRO_KEY_PAD_0: return ImGuiKey_Keypad0;
401 case ALLEGRO_KEY_PAD_1: return ImGuiKey_Keypad1;
402 case ALLEGRO_KEY_PAD_2: return ImGuiKey_Keypad2;
403 case ALLEGRO_KEY_PAD_3: return ImGuiKey_Keypad3;
404 case ALLEGRO_KEY_PAD_4: return ImGuiKey_Keypad4;
405 case ALLEGRO_KEY_PAD_5: return ImGuiKey_Keypad5;
406 case ALLEGRO_KEY_PAD_6: return ImGuiKey_Keypad6;
407 case ALLEGRO_KEY_PAD_7: return ImGuiKey_Keypad7;
408 case ALLEGRO_KEY_PAD_8: return ImGuiKey_Keypad8;
409 case ALLEGRO_KEY_PAD_9: return ImGuiKey_Keypad9;
410 case ALLEGRO_KEY_PAD_DELETE: return ImGuiKey_KeypadDecimal;
411 case ALLEGRO_KEY_PAD_SLASH: return ImGuiKey_KeypadDivide;
412 case ALLEGRO_KEY_PAD_ASTERISK: return ImGuiKey_KeypadMultiply;
413 case ALLEGRO_KEY_PAD_MINUS: return ImGuiKey_KeypadSubtract;
414 case ALLEGRO_KEY_PAD_PLUS: return ImGuiKey_KeypadAdd;
415 case ALLEGRO_KEY_PAD_ENTER: return ImGuiKey_KeypadEnter;
416 case ALLEGRO_KEY_PAD_EQUALS: return ImGuiKey_KeypadEqual;
417 case ALLEGRO_KEY_LCTRL: return ImGuiKey_LeftCtrl;
418 case ALLEGRO_KEY_LSHIFT: return ImGuiKey_LeftShift;
419 case ALLEGRO_KEY_ALT: return ImGuiKey_LeftAlt;
420 case ALLEGRO_KEY_LWIN: return ImGuiKey_LeftSuper;
421 case ALLEGRO_KEY_RCTRL: return ImGuiKey_RightCtrl;
422 case ALLEGRO_KEY_RSHIFT: return ImGuiKey_RightShift;
423 case ALLEGRO_KEY_ALTGR: return ImGuiKey_RightAlt;
424 case ALLEGRO_KEY_RWIN: return ImGuiKey_RightSuper;
425 case ALLEGRO_KEY_MENU: return ImGuiKey_Menu;
426 case ALLEGRO_KEY_0: return ImGuiKey_0;
427 case ALLEGRO_KEY_1: return ImGuiKey_1;
428 case ALLEGRO_KEY_2: return ImGuiKey_2;
429 case ALLEGRO_KEY_3: return ImGuiKey_3;
430 case ALLEGRO_KEY_4: return ImGuiKey_4;
431 case ALLEGRO_KEY_5: return ImGuiKey_5;
432 case ALLEGRO_KEY_6: return ImGuiKey_6;
433 case ALLEGRO_KEY_7: return ImGuiKey_7;
434 case ALLEGRO_KEY_8: return ImGuiKey_8;
435 case ALLEGRO_KEY_9: return ImGuiKey_9;
436 case ALLEGRO_KEY_A: return ImGuiKey_A;
437 case ALLEGRO_KEY_B: return ImGuiKey_B;
438 case ALLEGRO_KEY_C: return ImGuiKey_C;
439 case ALLEGRO_KEY_D: return ImGuiKey_D;
440 case ALLEGRO_KEY_E: return ImGuiKey_E;
441 case ALLEGRO_KEY_F: return ImGuiKey_F;
442 case ALLEGRO_KEY_G: return ImGuiKey_G;
443 case ALLEGRO_KEY_H: return ImGuiKey_H;
444 case ALLEGRO_KEY_I: return ImGuiKey_I;
445 case ALLEGRO_KEY_J: return ImGuiKey_J;
446 case ALLEGRO_KEY_K: return ImGuiKey_K;
447 case ALLEGRO_KEY_L: return ImGuiKey_L;
448 case ALLEGRO_KEY_M: return ImGuiKey_M;
449 case ALLEGRO_KEY_N: return ImGuiKey_N;
450 case ALLEGRO_KEY_O: return ImGuiKey_O;
451 case ALLEGRO_KEY_P: return ImGuiKey_P;
452 case ALLEGRO_KEY_Q: return ImGuiKey_Q;
453 case ALLEGRO_KEY_R: return ImGuiKey_R;
454 case ALLEGRO_KEY_S: return ImGuiKey_S;
455 case ALLEGRO_KEY_T: return ImGuiKey_T;
456 case ALLEGRO_KEY_U: return ImGuiKey_U;
457 case ALLEGRO_KEY_V: return ImGuiKey_V;
458 case ALLEGRO_KEY_W: return ImGuiKey_W;
459 case ALLEGRO_KEY_X: return ImGuiKey_X;
460 case ALLEGRO_KEY_Y: return ImGuiKey_Y;
461 case ALLEGRO_KEY_Z: return ImGuiKey_Z;
462 case ALLEGRO_KEY_F1: return ImGuiKey_F1;
463 case ALLEGRO_KEY_F2: return ImGuiKey_F2;
464 case ALLEGRO_KEY_F3: return ImGuiKey_F3;
465 case ALLEGRO_KEY_F4: return ImGuiKey_F4;
466 case ALLEGRO_KEY_F5: return ImGuiKey_F5;
467 case ALLEGRO_KEY_F6: return ImGuiKey_F6;
468 case ALLEGRO_KEY_F7: return ImGuiKey_F7;
469 case ALLEGRO_KEY_F8: return ImGuiKey_F8;
470 case ALLEGRO_KEY_F9: return ImGuiKey_F9;
471 case ALLEGRO_KEY_F10: return ImGuiKey_F10;
472 case ALLEGRO_KEY_F11: return ImGuiKey_F11;
473 case ALLEGRO_KEY_F12: return ImGuiKey_F12;
474 default: return ImGuiKey_None;
475 }
476}
477
478bool ImGui_ImplAllegro5_Init(ALLEGRO_DISPLAY* display)
479{
480 ImGuiIO& io = ImGui::GetIO();
481 IMGUI_CHECKVERSION();
482 IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
483
484 // Setup backend capabilities flags
485 ImGui_ImplAllegro5_Data* bd = IM_NEW(ImGui_ImplAllegro5_Data)();
486 io.BackendPlatformUserData = (void*)bd;
487 io.BackendPlatformName = io.BackendRendererName = "imgui_impl_allegro5";
488 io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
489 io.BackendFlags |= ImGuiBackendFlags_RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
490
491 bd->LastCursor = ALLEGRO_SYSTEM_MOUSE_CURSOR_NONE;
492
493 ImGui_ImplAllegro5_SetDisplay(display);
494
495 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
496#if ALLEGRO_HAS_CLIPBOARD
497 platform_io.Platform_SetClipboardTextFn = ImGui_ImplAllegro5_SetClipboardText;
498 platform_io.Platform_GetClipboardTextFn = ImGui_ImplAllegro5_GetClipboardText;
499#endif
500 platform_io.DrawCallback_ResetRenderState = ImGui_ImplAllegro5_DrawCallback_ResetRenderState;
501
502 return true;
503}
504
505void ImGui_ImplAllegro5_Shutdown()
506{
507 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
508 IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
509 ImGuiIO& io = ImGui::GetIO();
510 ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
511
512 ImGui_ImplAllegro5_InvalidateDeviceObjects();
513 if (bd->VertexDecl)
514 al_destroy_vertex_decl(bd->VertexDecl);
515 if (bd->ClipboardTextData)
516 al_free(bd->ClipboardTextData);
517
518 io.BackendPlatformName = io.BackendRendererName = nullptr;
519 io.BackendPlatformUserData = nullptr;
520 io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_RendererHasTextures);
521 platform_io.ClearRendererHandlers();
522 platform_io.ClearPlatformHandlers();
523 IM_DELETE(bd);
524}
525
526void ImGui_ImplAllegro5_SetDisplay(ALLEGRO_DISPLAY* display)
527{
528 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
529 bd->Display = display;
530
531 if (bd->VertexDecl)
532 {
533 al_destroy_vertex_decl(bd->VertexDecl);
534 bd->VertexDecl = nullptr;
535 }
536
537 if (bd->Display && !bd->VertexDecl)
538 {
539 // Create custom vertex declaration.
540 // Unfortunately Allegro doesn't support 32-bits packed colors so we have to convert them to 4 floats.
541 // We still use a custom declaration to use 'ALLEGRO_PRIM_TEX_COORD' instead of 'ALLEGRO_PRIM_TEX_COORD_PIXEL' else we can't do a reliable conversion.
542 ALLEGRO_VERTEX_ELEMENT elems[] =
543 {
544 { ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, pos) },
545 { ALLEGRO_PRIM_TEX_COORD, ALLEGRO_PRIM_FLOAT_2, offsetof(ImDrawVertAllegro, uv) },
546 { ALLEGRO_PRIM_COLOR_ATTR, 0, offsetof(ImDrawVertAllegro, col) },
547 { 0, 0, 0 }
548 };
549 bd->VertexDecl = al_create_vertex_decl(elems, sizeof(ImDrawVertAllegro));
550 }
551}
552
553// ev->keyboard.modifiers seems always zero so using that...
554static void ImGui_ImplAllegro5_UpdateKeyModifiers()
555{
556 ImGuiIO& io = ImGui::GetIO();
557 ALLEGRO_KEYBOARD_STATE keys;
558 al_get_keyboard_state(&keys);
559 io.AddKeyEvent(ImGuiMod_Ctrl, al_key_down(&keys, ALLEGRO_KEY_LCTRL) || al_key_down(&keys, ALLEGRO_KEY_RCTRL));
560 io.AddKeyEvent(ImGuiMod_Shift, al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT));
561 io.AddKeyEvent(ImGuiMod_Alt, al_key_down(&keys, ALLEGRO_KEY_ALT) || al_key_down(&keys, ALLEGRO_KEY_ALTGR));
562 io.AddKeyEvent(ImGuiMod_Super, al_key_down(&keys, ALLEGRO_KEY_LWIN) || al_key_down(&keys, ALLEGRO_KEY_RWIN));
563}
564
565// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
566// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
567// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
568// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
569bool ImGui_ImplAllegro5_ProcessEvent(ALLEGRO_EVENT* ev)
570{
571 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
572 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
573 ImGuiIO& io = ImGui::GetIO();
574
575 switch (ev->type)
576 {
577 case ALLEGRO_EVENT_MOUSE_AXES:
578 if (ev->mouse.display == bd->Display)
579 {
580 io.AddMousePosEvent(ev->mouse.x, ev->mouse.y);
581 io.AddMouseWheelEvent(-ev->mouse.dw, ev->mouse.dz);
582 }
583 return true;
584 case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN:
585 case ALLEGRO_EVENT_MOUSE_BUTTON_UP:
586 if (ev->mouse.display == bd->Display && ev->mouse.button > 0 && ev->mouse.button <= 5)
587 io.AddMouseButtonEvent(ev->mouse.button - 1, ev->type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN);
588 return true;
589 case ALLEGRO_EVENT_TOUCH_MOVE:
590 if (ev->touch.display == bd->Display)
591 io.AddMousePosEvent(ev->touch.x, ev->touch.y);
592 return true;
593 case ALLEGRO_EVENT_TOUCH_BEGIN:
594 case ALLEGRO_EVENT_TOUCH_END:
595 case ALLEGRO_EVENT_TOUCH_CANCEL:
596 if (ev->touch.display == bd->Display && ev->touch.primary)
597 io.AddMouseButtonEvent(0, ev->type == ALLEGRO_EVENT_TOUCH_BEGIN);
598 return true;
599 case ALLEGRO_EVENT_MOUSE_LEAVE_DISPLAY:
600 if (ev->mouse.display == bd->Display)
601 io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
602 return true;
603 case ALLEGRO_EVENT_KEY_CHAR:
604 if (ev->keyboard.display == bd->Display)
605 if (ev->keyboard.unichar != 0)
606 io.AddInputCharacter((unsigned int)ev->keyboard.unichar);
607 return true;
608 case ALLEGRO_EVENT_KEY_DOWN:
609 case ALLEGRO_EVENT_KEY_UP:
610 if (ev->keyboard.display == bd->Display)
611 {
612 ImGui_ImplAllegro5_UpdateKeyModifiers();
613 ImGuiKey key = ImGui_ImplAllegro5_KeyCodeToImGuiKey(ev->keyboard.keycode);
614 io.AddKeyEvent(key, (ev->type == ALLEGRO_EVENT_KEY_DOWN));
615 io.SetKeyEventNativeData(key, ev->keyboard.keycode, -1); // To support legacy indexing (<1.87 user code)
616 }
617 return true;
618 case ALLEGRO_EVENT_DISPLAY_SWITCH_OUT:
619 if (ev->display.source == bd->Display)
620 io.AddFocusEvent(false);
621 return true;
622 case ALLEGRO_EVENT_DISPLAY_SWITCH_IN:
623 if (ev->display.source == bd->Display)
624 {
625 io.AddFocusEvent(true);
626#if defined(ALLEGRO_UNSTABLE)
627 al_clear_keyboard_state(bd->Display);
628#endif
629 }
630 return true;
631 }
632 return false;
633}
634
635static void ImGui_ImplAllegro5_UpdateMouseCursor()
636{
637 ImGuiIO& io = ImGui::GetIO();
638 if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
639 return;
640
641 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
642 ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
643
644 // Hide OS mouse cursor if imgui is drawing it
645 if (io.MouseDrawCursor)
646 imgui_cursor = ImGuiMouseCursor_None;
647
648 if (bd->LastCursor == imgui_cursor)
649 return;
650 bd->LastCursor = imgui_cursor;
651 if (imgui_cursor == ImGuiMouseCursor_None)
652 {
653 al_set_mouse_cursor(bd->Display, bd->MouseCursorInvisible);
654 }
655 else
656 {
657 ALLEGRO_SYSTEM_MOUSE_CURSOR cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT;
658 switch (imgui_cursor)
659 {
660 case ImGuiMouseCursor_TextInput: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_EDIT; break;
661 case ImGuiMouseCursor_ResizeAll: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_MOVE; break;
662 case ImGuiMouseCursor_ResizeNS: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_N; break;
663 case ImGuiMouseCursor_ResizeEW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_E; break;
664 case ImGuiMouseCursor_ResizeNESW: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NE; break;
665 case ImGuiMouseCursor_ResizeNWSE: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_RESIZE_NW; break;
666 case ImGuiMouseCursor_Wait: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_BUSY; break;
667 case ImGuiMouseCursor_Progress: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_PROGRESS; break;
668 case ImGuiMouseCursor_NotAllowed: cursor_id = ALLEGRO_SYSTEM_MOUSE_CURSOR_UNAVAILABLE; break;
669 }
670 al_set_system_mouse_cursor(bd->Display, cursor_id);
671 }
672}
673
674void ImGui_ImplAllegro5_NewFrame()
675{
676 ImGui_ImplAllegro5_Data* bd = ImGui_ImplAllegro5_GetBackendData();
677 IM_ASSERT(bd != nullptr && "Context or backend not initialized! Did you call ImGui_ImplAllegro5_Init()?");
678
679 if (!bd->MouseCursorInvisible)
680 ImGui_ImplAllegro5_CreateDeviceObjects();
681
682 // Setup display size (every frame to accommodate for window resizing)
683 ImGuiIO& io = ImGui::GetIO();
684 int w, h;
685 w = al_get_display_width(bd->Display);
686 h = al_get_display_height(bd->Display);
687 io.DisplaySize = ImVec2((float)w, (float)h);
688
689 // Setup time step
690 double current_time = al_get_time();
691 io.DeltaTime = bd->Time > 0.0 ? (float)(current_time - bd->Time) : (float)(1.0f / 60.0f);
692 bd->Time = current_time;
693
694 // Allegro 5 doesn't receive PrintScreen under Windows
695#ifdef _WIN32
696 io.AddKeyEvent(ImGuiKey_PrintScreen, (::GetAsyncKeyState(VK_SNAPSHOT) & 0x8000) != 0);
697#endif
698
699 // Setup mouse cursor shape
700 ImGui_ImplAllegro5_UpdateMouseCursor();
701}
702
703//-----------------------------------------------------------------------------
704
705#endif // #ifndef IMGUI_DISABLE