rlImGui.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. /**********************************************************************************************
  2. *
  3. * raylibExtras * Utilities and Shared Components for Raylib
  4. *
  5. * rlImGui * basic ImGui integration
  6. *
  7. * LICENSE: ZLIB
  8. *
  9. * Copyright (c) 2024 Jeffery Myers
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in all
  19. * copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  27. * SOFTWARE.
  28. *
  29. **********************************************************************************************/
  30. #include "rlImGui.h"
  31. #include "imgui_impl_raylib.h"
  32. #include "raylib.h"
  33. #include "rlgl.h"
  34. #include <math.h>
  35. #include <map>
  36. #include <limits>
  37. #ifndef NO_FONT_AWESOME
  38. #include "extras/FA6FreeSolidFontData.h"
  39. #endif
  40. static ImGuiMouseCursor CurrentMouseCursor = ImGuiMouseCursor_COUNT;
  41. static MouseCursor MouseCursorMap[ImGuiMouseCursor_COUNT];
  42. ImGuiContext* GlobalContext = nullptr;
  43. static std::map<KeyboardKey, ImGuiKey> RaylibKeyMap;
  44. static bool LastFrameFocused = false;
  45. static bool LastControlPressed = false;
  46. static bool LastShiftPressed = false;
  47. static bool LastAltPressed = false;
  48. static bool LastSuperPressed = false;
  49. // internal only functions
  50. bool rlImGuiIsControlDown() { return IsKeyDown(KEY_RIGHT_CONTROL) || IsKeyDown(KEY_LEFT_CONTROL); }
  51. bool rlImGuiIsShiftDown() { return IsKeyDown(KEY_RIGHT_SHIFT) || IsKeyDown(KEY_LEFT_SHIFT); }
  52. bool rlImGuiIsAltDown() { return IsKeyDown(KEY_RIGHT_ALT) || IsKeyDown(KEY_LEFT_ALT); }
  53. bool rlImGuiIsSuperDown() { return IsKeyDown(KEY_RIGHT_SUPER) || IsKeyDown(KEY_LEFT_SUPER); }
  54. std::map<size_t, Texture2D*> FontTextures;
  55. void ReloadFonts(void)
  56. {
  57. ImGuiIO& io = ImGui::GetIO();
  58. unsigned char* pixels = nullptr;
  59. int width;
  60. int height;
  61. io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, nullptr);
  62. Image image = GenImageColor(width, height, BLANK);
  63. memcpy(image.data, pixels, width * height * 4);
  64. size_t textureId = reinterpret_cast<size_t>(io.Fonts->TexID);
  65. if (FontTextures.find(textureId) != FontTextures.end())
  66. {
  67. UnloadTexture(*FontTextures[textureId]);
  68. MemFree(FontTextures[textureId]);
  69. FontTextures.erase(FontTextures.find(textureId));
  70. }
  71. Texture2D* fontTexture = (Texture2D*)MemAlloc(sizeof(Texture2D));
  72. *fontTexture = LoadTextureFromImage(image);
  73. UnloadImage(image);
  74. textureId = size_t(fontTexture->id);
  75. FontTextures.insert_or_assign(textureId, fontTexture);
  76. io.Fonts->TexID = (ImTextureID)textureId;
  77. }
  78. static const char* GetClipTextCallback(void*)
  79. {
  80. return GetClipboardText();
  81. }
  82. static void SetClipTextCallback(void*, const char* text)
  83. {
  84. SetClipboardText(text);
  85. }
  86. static void ImGuiNewFrame(float deltaTime)
  87. {
  88. ImGuiIO& io = ImGui::GetIO();
  89. Vector2 resolutionScale = GetWindowScaleDPI();
  90. #ifndef PLATFORM_DRM
  91. if (IsWindowFullscreen())
  92. {
  93. int monitor = GetCurrentMonitor();
  94. io.DisplaySize.x = float(GetMonitorWidth(monitor));
  95. io.DisplaySize.y = float(GetMonitorHeight(monitor));
  96. }
  97. else
  98. {
  99. io.DisplaySize.x = float(GetScreenWidth());
  100. io.DisplaySize.y = float(GetScreenHeight());
  101. }
  102. #if !defined(__APPLE__)
  103. if (!IsWindowState(FLAG_WINDOW_HIGHDPI))
  104. resolutionScale = Vector2{ 1,1 };
  105. #endif
  106. #else
  107. io.DisplaySize.x = float(GetScreenWidth());
  108. io.DisplaySize.y = float(GetScreenHeight());
  109. #endif
  110. io.DisplayFramebufferScale = ImVec2(resolutionScale.x, resolutionScale.y);
  111. io.DeltaTime = deltaTime;
  112. if (io.WantSetMousePos)
  113. {
  114. SetMousePosition((int)io.MousePos.x, (int)io.MousePos.y);
  115. }
  116. else
  117. {
  118. io.AddMousePosEvent((float)GetMouseX(), (float)GetMouseY());
  119. }
  120. auto setMouseEvent = [&io](int rayMouse, int imGuiMouse)
  121. {
  122. if (IsMouseButtonPressed(rayMouse))
  123. io.AddMouseButtonEvent(imGuiMouse, true);
  124. else if (IsMouseButtonReleased(rayMouse))
  125. io.AddMouseButtonEvent(imGuiMouse, false);
  126. };
  127. setMouseEvent(MOUSE_BUTTON_LEFT, ImGuiMouseButton_Left);
  128. setMouseEvent(MOUSE_BUTTON_RIGHT, ImGuiMouseButton_Right);
  129. setMouseEvent(MOUSE_BUTTON_MIDDLE, ImGuiMouseButton_Middle);
  130. setMouseEvent(MOUSE_BUTTON_FORWARD, ImGuiMouseButton_Middle+1);
  131. setMouseEvent(MOUSE_BUTTON_BACK, ImGuiMouseButton_Middle+2);
  132. {
  133. Vector2 mouseWheel = GetMouseWheelMoveV();
  134. io.AddMouseWheelEvent(mouseWheel.x, mouseWheel.y);
  135. }
  136. if (ImGui::GetIO().BackendFlags & ImGuiBackendFlags_HasMouseCursors)
  137. {
  138. if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) == 0)
  139. {
  140. ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
  141. if (imgui_cursor != CurrentMouseCursor || io.MouseDrawCursor)
  142. {
  143. CurrentMouseCursor = imgui_cursor;
  144. if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
  145. {
  146. HideCursor();
  147. }
  148. else
  149. {
  150. ShowCursor();
  151. if (!(io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange))
  152. {
  153. SetMouseCursor((imgui_cursor > -1 && imgui_cursor < ImGuiMouseCursor_COUNT) ? MouseCursorMap[imgui_cursor] : MOUSE_CURSOR_DEFAULT);
  154. }
  155. }
  156. }
  157. }
  158. }
  159. }
  160. static void ImGuiTriangleVert(ImDrawVert& idx_vert)
  161. {
  162. Color* c;
  163. c = (Color*)&idx_vert.col;
  164. rlColor4ub(c->r, c->g, c->b, c->a);
  165. rlTexCoord2f(idx_vert.uv.x, idx_vert.uv.y);
  166. rlVertex2f(idx_vert.pos.x, idx_vert.pos.y);
  167. }
  168. static void ImGuiRenderTriangles(unsigned int count, int indexStart, const ImVector<ImDrawIdx>& indexBuffer, const ImVector<ImDrawVert>& vertBuffer, void* texturePtr)
  169. {
  170. if (count < 3)
  171. return;
  172. size_t textureId = reinterpret_cast<size_t>(texturePtr);
  173. rlBegin(RL_TRIANGLES);
  174. rlSetTexture(uint32_t(textureId));
  175. for (unsigned int i = 0; i <= (count - 3); i += 3)
  176. {
  177. ImDrawIdx indexA = indexBuffer[indexStart + i];
  178. ImDrawIdx indexB = indexBuffer[indexStart + i + 1];
  179. ImDrawIdx indexC = indexBuffer[indexStart + i + 2];
  180. ImDrawVert vertexA = vertBuffer[indexA];
  181. ImDrawVert vertexB = vertBuffer[indexB];
  182. ImDrawVert vertexC = vertBuffer[indexC];
  183. ImGuiTriangleVert(vertexA);
  184. ImGuiTriangleVert(vertexB);
  185. ImGuiTriangleVert(vertexC);
  186. }
  187. rlEnd();
  188. }
  189. static void EnableScissor(float x, float y, float width, float height)
  190. {
  191. rlEnableScissorTest();
  192. ImGuiIO& io = ImGui::GetIO();
  193. ImVec2 scale = io.DisplayFramebufferScale;
  194. #if !defined(__APPLE__)
  195. if (!IsWindowState(FLAG_WINDOW_HIGHDPI))
  196. {
  197. scale.x = 1;
  198. scale.y = 1;
  199. }
  200. #endif
  201. rlScissor((int)(x * scale.x),
  202. int((io.DisplaySize.y - (int)(y + height)) * scale.y),
  203. (int)(width * scale.x),
  204. (int)(height * scale.y));
  205. }
  206. static void SetupMouseCursors(void)
  207. {
  208. MouseCursorMap[ImGuiMouseCursor_Arrow] = MOUSE_CURSOR_ARROW;
  209. MouseCursorMap[ImGuiMouseCursor_TextInput] = MOUSE_CURSOR_IBEAM;
  210. MouseCursorMap[ImGuiMouseCursor_Hand] = MOUSE_CURSOR_POINTING_HAND;
  211. MouseCursorMap[ImGuiMouseCursor_ResizeAll] = MOUSE_CURSOR_RESIZE_ALL;
  212. MouseCursorMap[ImGuiMouseCursor_ResizeEW] = MOUSE_CURSOR_RESIZE_EW;
  213. MouseCursorMap[ImGuiMouseCursor_ResizeNESW] = MOUSE_CURSOR_RESIZE_NESW;
  214. MouseCursorMap[ImGuiMouseCursor_ResizeNS] = MOUSE_CURSOR_RESIZE_NS;
  215. MouseCursorMap[ImGuiMouseCursor_ResizeNWSE] = MOUSE_CURSOR_RESIZE_NWSE;
  216. MouseCursorMap[ImGuiMouseCursor_NotAllowed] = MOUSE_CURSOR_NOT_ALLOWED;
  217. }
  218. void SetupFontAwesome(void)
  219. {
  220. #ifndef NO_FONT_AWESOME
  221. static const ImWchar icons_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
  222. ImFontConfig icons_config;
  223. icons_config.MergeMode = true;
  224. icons_config.PixelSnapH = true;
  225. icons_config.FontDataOwnedByAtlas = false;
  226. icons_config.GlyphMaxAdvanceX = std::numeric_limits<float>::max();
  227. icons_config.RasterizerMultiply = 1.0f;
  228. icons_config.OversampleH = 2;
  229. icons_config.OversampleV = 1;
  230. icons_config.GlyphRanges = icons_ranges;
  231. ImGuiIO& io = ImGui::GetIO();
  232. io.Fonts->AddFontFromMemoryCompressedTTF((void*)fa_solid_900_compressed_data, fa_solid_900_compressed_size, FONT_AWESOME_ICON_SIZE, &icons_config, icons_ranges);
  233. #endif
  234. }
  235. void SetupBackend(void)
  236. {
  237. ImGuiIO& io = ImGui::GetIO();
  238. io.BackendPlatformName = "imgui_impl_raylib";
  239. io.BackendFlags |= ImGuiBackendFlags_HasGamepad | ImGuiBackendFlags_HasSetMousePos;
  240. #ifndef PLATFORM_DRM
  241. io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
  242. #endif
  243. io.MousePos = ImVec2(0, 0);
  244. io.SetClipboardTextFn = SetClipTextCallback;
  245. io.GetClipboardTextFn = GetClipTextCallback;
  246. io.ClipboardUserData = nullptr;
  247. }
  248. void rlImGuiEndInitImGui(void)
  249. {
  250. ImGui::SetCurrentContext(GlobalContext);
  251. SetupFontAwesome();
  252. SetupMouseCursors();
  253. SetupBackend();
  254. ReloadFonts();
  255. }
  256. static void SetupKeymap(void)
  257. {
  258. if (!RaylibKeyMap.empty())
  259. return;
  260. // build up a map of raylib keys to ImGuiKeys
  261. RaylibKeyMap[KEY_APOSTROPHE] = ImGuiKey_Apostrophe;
  262. RaylibKeyMap[KEY_COMMA] = ImGuiKey_Comma;
  263. RaylibKeyMap[KEY_MINUS] = ImGuiKey_Minus;
  264. RaylibKeyMap[KEY_PERIOD] = ImGuiKey_Period;
  265. RaylibKeyMap[KEY_SLASH] = ImGuiKey_Slash;
  266. RaylibKeyMap[KEY_ZERO] = ImGuiKey_0;
  267. RaylibKeyMap[KEY_ONE] = ImGuiKey_1;
  268. RaylibKeyMap[KEY_TWO] = ImGuiKey_2;
  269. RaylibKeyMap[KEY_THREE] = ImGuiKey_3;
  270. RaylibKeyMap[KEY_FOUR] = ImGuiKey_4;
  271. RaylibKeyMap[KEY_FIVE] = ImGuiKey_5;
  272. RaylibKeyMap[KEY_SIX] = ImGuiKey_6;
  273. RaylibKeyMap[KEY_SEVEN] = ImGuiKey_7;
  274. RaylibKeyMap[KEY_EIGHT] = ImGuiKey_8;
  275. RaylibKeyMap[KEY_NINE] = ImGuiKey_9;
  276. RaylibKeyMap[KEY_SEMICOLON] = ImGuiKey_Semicolon;
  277. RaylibKeyMap[KEY_EQUAL] = ImGuiKey_Equal;
  278. RaylibKeyMap[KEY_A] = ImGuiKey_A;
  279. RaylibKeyMap[KEY_B] = ImGuiKey_B;
  280. RaylibKeyMap[KEY_C] = ImGuiKey_C;
  281. RaylibKeyMap[KEY_D] = ImGuiKey_D;
  282. RaylibKeyMap[KEY_E] = ImGuiKey_E;
  283. RaylibKeyMap[KEY_F] = ImGuiKey_F;
  284. RaylibKeyMap[KEY_G] = ImGuiKey_G;
  285. RaylibKeyMap[KEY_H] = ImGuiKey_H;
  286. RaylibKeyMap[KEY_I] = ImGuiKey_I;
  287. RaylibKeyMap[KEY_J] = ImGuiKey_J;
  288. RaylibKeyMap[KEY_K] = ImGuiKey_K;
  289. RaylibKeyMap[KEY_L] = ImGuiKey_L;
  290. RaylibKeyMap[KEY_M] = ImGuiKey_M;
  291. RaylibKeyMap[KEY_N] = ImGuiKey_N;
  292. RaylibKeyMap[KEY_O] = ImGuiKey_O;
  293. RaylibKeyMap[KEY_P] = ImGuiKey_P;
  294. RaylibKeyMap[KEY_Q] = ImGuiKey_Q;
  295. RaylibKeyMap[KEY_R] = ImGuiKey_R;
  296. RaylibKeyMap[KEY_S] = ImGuiKey_S;
  297. RaylibKeyMap[KEY_T] = ImGuiKey_T;
  298. RaylibKeyMap[KEY_U] = ImGuiKey_U;
  299. RaylibKeyMap[KEY_V] = ImGuiKey_V;
  300. RaylibKeyMap[KEY_W] = ImGuiKey_W;
  301. RaylibKeyMap[KEY_X] = ImGuiKey_X;
  302. RaylibKeyMap[KEY_Y] = ImGuiKey_Y;
  303. RaylibKeyMap[KEY_Z] = ImGuiKey_Z;
  304. RaylibKeyMap[KEY_SPACE] = ImGuiKey_Space;
  305. RaylibKeyMap[KEY_ESCAPE] = ImGuiKey_Escape;
  306. RaylibKeyMap[KEY_ENTER] = ImGuiKey_Enter;
  307. RaylibKeyMap[KEY_TAB] = ImGuiKey_Tab;
  308. RaylibKeyMap[KEY_BACKSPACE] = ImGuiKey_Backspace;
  309. RaylibKeyMap[KEY_INSERT] = ImGuiKey_Insert;
  310. RaylibKeyMap[KEY_DELETE] = ImGuiKey_Delete;
  311. RaylibKeyMap[KEY_RIGHT] = ImGuiKey_RightArrow;
  312. RaylibKeyMap[KEY_LEFT] = ImGuiKey_LeftArrow;
  313. RaylibKeyMap[KEY_DOWN] = ImGuiKey_DownArrow;
  314. RaylibKeyMap[KEY_UP] = ImGuiKey_UpArrow;
  315. RaylibKeyMap[KEY_PAGE_UP] = ImGuiKey_PageUp;
  316. RaylibKeyMap[KEY_PAGE_DOWN] = ImGuiKey_PageDown;
  317. RaylibKeyMap[KEY_HOME] = ImGuiKey_Home;
  318. RaylibKeyMap[KEY_END] = ImGuiKey_End;
  319. RaylibKeyMap[KEY_CAPS_LOCK] = ImGuiKey_CapsLock;
  320. RaylibKeyMap[KEY_SCROLL_LOCK] = ImGuiKey_ScrollLock;
  321. RaylibKeyMap[KEY_NUM_LOCK] = ImGuiKey_NumLock;
  322. RaylibKeyMap[KEY_PRINT_SCREEN] = ImGuiKey_PrintScreen;
  323. RaylibKeyMap[KEY_PAUSE] = ImGuiKey_Pause;
  324. RaylibKeyMap[KEY_F1] = ImGuiKey_F1;
  325. RaylibKeyMap[KEY_F2] = ImGuiKey_F2;
  326. RaylibKeyMap[KEY_F3] = ImGuiKey_F3;
  327. RaylibKeyMap[KEY_F4] = ImGuiKey_F4;
  328. RaylibKeyMap[KEY_F5] = ImGuiKey_F5;
  329. RaylibKeyMap[KEY_F6] = ImGuiKey_F6;
  330. RaylibKeyMap[KEY_F7] = ImGuiKey_F7;
  331. RaylibKeyMap[KEY_F8] = ImGuiKey_F8;
  332. RaylibKeyMap[KEY_F9] = ImGuiKey_F9;
  333. RaylibKeyMap[KEY_F10] = ImGuiKey_F10;
  334. RaylibKeyMap[KEY_F11] = ImGuiKey_F11;
  335. RaylibKeyMap[KEY_F12] = ImGuiKey_F12;
  336. RaylibKeyMap[KEY_LEFT_SHIFT] = ImGuiKey_LeftShift;
  337. RaylibKeyMap[KEY_LEFT_CONTROL] = ImGuiKey_LeftCtrl;
  338. RaylibKeyMap[KEY_LEFT_ALT] = ImGuiKey_LeftAlt;
  339. RaylibKeyMap[KEY_LEFT_SUPER] = ImGuiKey_LeftSuper;
  340. RaylibKeyMap[KEY_RIGHT_SHIFT] = ImGuiKey_RightShift;
  341. RaylibKeyMap[KEY_RIGHT_CONTROL] = ImGuiKey_RightCtrl;
  342. RaylibKeyMap[KEY_RIGHT_ALT] = ImGuiKey_RightAlt;
  343. RaylibKeyMap[KEY_RIGHT_SUPER] = ImGuiKey_RightSuper;
  344. RaylibKeyMap[KEY_KB_MENU] = ImGuiKey_Menu;
  345. RaylibKeyMap[KEY_LEFT_BRACKET] = ImGuiKey_LeftBracket;
  346. RaylibKeyMap[KEY_BACKSLASH] = ImGuiKey_Backslash;
  347. RaylibKeyMap[KEY_RIGHT_BRACKET] = ImGuiKey_RightBracket;
  348. RaylibKeyMap[KEY_GRAVE] = ImGuiKey_GraveAccent;
  349. RaylibKeyMap[KEY_KP_0] = ImGuiKey_Keypad0;
  350. RaylibKeyMap[KEY_KP_1] = ImGuiKey_Keypad1;
  351. RaylibKeyMap[KEY_KP_2] = ImGuiKey_Keypad2;
  352. RaylibKeyMap[KEY_KP_3] = ImGuiKey_Keypad3;
  353. RaylibKeyMap[KEY_KP_4] = ImGuiKey_Keypad4;
  354. RaylibKeyMap[KEY_KP_5] = ImGuiKey_Keypad5;
  355. RaylibKeyMap[KEY_KP_6] = ImGuiKey_Keypad6;
  356. RaylibKeyMap[KEY_KP_7] = ImGuiKey_Keypad7;
  357. RaylibKeyMap[KEY_KP_8] = ImGuiKey_Keypad8;
  358. RaylibKeyMap[KEY_KP_9] = ImGuiKey_Keypad9;
  359. RaylibKeyMap[KEY_KP_DECIMAL] = ImGuiKey_KeypadDecimal;
  360. RaylibKeyMap[KEY_KP_DIVIDE] = ImGuiKey_KeypadDivide;
  361. RaylibKeyMap[KEY_KP_MULTIPLY] = ImGuiKey_KeypadMultiply;
  362. RaylibKeyMap[KEY_KP_SUBTRACT] = ImGuiKey_KeypadSubtract;
  363. RaylibKeyMap[KEY_KP_ADD] = ImGuiKey_KeypadAdd;
  364. RaylibKeyMap[KEY_KP_ENTER] = ImGuiKey_KeypadEnter;
  365. RaylibKeyMap[KEY_KP_EQUAL] = ImGuiKey_KeypadEqual;
  366. }
  367. static void SetupGlobals(void)
  368. {
  369. LastFrameFocused = IsWindowFocused();
  370. LastControlPressed = false;
  371. LastShiftPressed = false;
  372. LastAltPressed = false;
  373. LastSuperPressed = false;
  374. }
  375. void rlImGuiBeginInitImGui(void)
  376. {
  377. SetupGlobals();
  378. if (GlobalContext == nullptr)
  379. GlobalContext = ImGui::CreateContext(nullptr);
  380. SetupKeymap();
  381. ImGuiIO& io = ImGui::GetIO();
  382. io.Fonts->AddFontDefault();
  383. }
  384. void rlImGuiSetup(bool dark)
  385. {
  386. rlImGuiBeginInitImGui();
  387. if (dark)
  388. ImGui::StyleColorsDark();
  389. else
  390. ImGui::StyleColorsLight();
  391. rlImGuiEndInitImGui();
  392. }
  393. void rlImGuiReloadFonts(void)
  394. {
  395. ImGui::SetCurrentContext(GlobalContext);
  396. ReloadFonts();
  397. }
  398. void rlImGuiBegin(void)
  399. {
  400. ImGui::SetCurrentContext(GlobalContext);
  401. rlImGuiBeginDelta(GetFrameTime());
  402. }
  403. void rlImGuiBeginDelta(float deltaTime)
  404. {
  405. ImGui::SetCurrentContext(GlobalContext);
  406. ImGuiNewFrame(deltaTime);
  407. ImGui_ImplRaylib_ProcessEvents();
  408. ImGui::NewFrame();
  409. }
  410. void rlImGuiEnd(void)
  411. {
  412. ImGui::SetCurrentContext(GlobalContext);
  413. ImGui::Render();
  414. ImGui_ImplRaylib_RenderDrawData(ImGui::GetDrawData());
  415. }
  416. void rlImGuiShutdown(void)
  417. {
  418. if (GlobalContext == nullptr)
  419. return;
  420. ImGui::SetCurrentContext(GlobalContext);
  421. ImGui_ImplRaylib_Shutdown();
  422. ImGui::DestroyContext(GlobalContext);
  423. GlobalContext = nullptr;
  424. }
  425. void rlImGuiImage(const Texture* image)
  426. {
  427. if (!image)
  428. return;
  429. if (GlobalContext)
  430. ImGui::SetCurrentContext(GlobalContext);
  431. size_t id = image->id;
  432. ImGui::Image((ImTextureID)id, ImVec2(float(image->width), float(image->height)));
  433. }
  434. bool rlImGuiImageButton(const char* name, const Texture* image)
  435. {
  436. if (!image)
  437. return false;
  438. if (GlobalContext)
  439. ImGui::SetCurrentContext(GlobalContext);
  440. size_t id = image->id;
  441. return ImGui::ImageButton(name, (ImTextureID)id, ImVec2(float(image->width), float(image->height)));
  442. }
  443. bool rlImGuiImageButtonSize(const char* name, const Texture* image, ImVec2 size)
  444. {
  445. if (!image)
  446. return false;
  447. if (GlobalContext)
  448. ImGui::SetCurrentContext(GlobalContext);
  449. size_t id = image->id;
  450. return ImGui::ImageButton(name, (ImTextureID)id, size);
  451. }
  452. void rlImGuiImageSize(const Texture* image, int width, int height)
  453. {
  454. if (!image)
  455. return;
  456. if (GlobalContext)
  457. ImGui::SetCurrentContext(GlobalContext);
  458. size_t id = image->id;
  459. ImGui::Image((ImTextureID)id, ImVec2(float(width), float(height)));
  460. }
  461. void rlImGuiImageSizeV(const Texture* image, Vector2 size)
  462. {
  463. if (!image)
  464. return;
  465. if (GlobalContext)
  466. ImGui::SetCurrentContext(GlobalContext);
  467. size_t id = image->id;
  468. ImGui::Image((ImTextureID)id, ImVec2(size.x, size.y));
  469. }
  470. void rlImGuiImageRect(const Texture* image, int destWidth, int destHeight, Rectangle sourceRect)
  471. {
  472. if (!image)
  473. return;
  474. if (GlobalContext)
  475. ImGui::SetCurrentContext(GlobalContext);
  476. ImVec2 uv0;
  477. ImVec2 uv1;
  478. if (sourceRect.width < 0)
  479. {
  480. uv0.x = -((float)sourceRect.x / image->width);
  481. uv1.x = (uv0.x - (float)(fabs(sourceRect.width) / image->width));
  482. }
  483. else
  484. {
  485. uv0.x = (float)sourceRect.x / image->width;
  486. uv1.x = uv0.x + (float)(sourceRect.width / image->width);
  487. }
  488. if (sourceRect.height < 0)
  489. {
  490. uv0.y = -((float)sourceRect.y / image->height);
  491. uv1.y = (uv0.y - (float)(fabs(sourceRect.height) / image->height));
  492. }
  493. else
  494. {
  495. uv0.y = (float)sourceRect.y / image->height;
  496. uv1.y = uv0.y + (float)(sourceRect.height / image->height);
  497. }
  498. size_t id = image->id;
  499. ImGui::Image((ImTextureID)id, ImVec2(float(destWidth), float(destHeight)), uv0, uv1);
  500. }
  501. void rlImGuiImageRenderTexture(const RenderTexture* image)
  502. {
  503. if (!image)
  504. return;
  505. if (GlobalContext)
  506. ImGui::SetCurrentContext(GlobalContext);
  507. rlImGuiImageRect(&image->texture, image->texture.width, image->texture.height, Rectangle{ 0,0, float(image->texture.width), -float(image->texture.height) });
  508. }
  509. void rlImGuiImageRenderTextureFit(const RenderTexture* image, bool center)
  510. {
  511. if (!image)
  512. return;
  513. if (GlobalContext)
  514. ImGui::SetCurrentContext(GlobalContext);
  515. ImVec2 area = ImGui::GetContentRegionAvail();
  516. float scale = area.x / image->texture.width;
  517. float y = image->texture.height * scale;
  518. if (y > area.y)
  519. {
  520. scale = area.y / image->texture.height;
  521. }
  522. int sizeX = int(image->texture.width * scale);
  523. int sizeY = int(image->texture.height * scale);
  524. if (center)
  525. {
  526. ImGui::SetCursorPosX(0);
  527. ImGui::SetCursorPosX(area.x/2 - sizeX/2);
  528. ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (area.y / 2 - sizeY / 2));
  529. }
  530. rlImGuiImageRect(&image->texture, sizeX, sizeY, Rectangle{ 0,0, float(image->texture.width), -float(image->texture.height) });
  531. }
  532. // raw ImGui backend API
  533. bool ImGui_ImplRaylib_Init(void)
  534. {
  535. SetupGlobals();
  536. SetupKeymap();
  537. SetupMouseCursors();
  538. SetupBackend();
  539. return true;
  540. }
  541. void Imgui_ImplRaylib_BuildFontAtlas(void)
  542. {
  543. ReloadFonts();
  544. }
  545. void ImGui_ImplRaylib_Shutdown()
  546. {
  547. ImGuiIO& io =ImGui::GetIO();
  548. size_t fontTextureId = reinterpret_cast<size_t>(io.Fonts->TexID);
  549. if (FontTextures.find(fontTextureId) != FontTextures.end())
  550. {
  551. UnloadTexture(*FontTextures[fontTextureId]);
  552. MemFree(FontTextures[fontTextureId]);
  553. FontTextures.erase(FontTextures.find(fontTextureId));
  554. }
  555. io.Fonts->TexID = 0;
  556. }
  557. void ImGui_ImplRaylib_NewFrame(void)
  558. {
  559. ImGuiNewFrame(GetFrameTime());
  560. }
  561. void ImGui_ImplRaylib_RenderDrawData(ImDrawData* draw_data)
  562. {
  563. rlDrawRenderBatchActive();
  564. rlDisableBackfaceCulling();
  565. for (int l = 0; l < draw_data->CmdListsCount; ++l)
  566. {
  567. const ImDrawList* commandList = draw_data->CmdLists[l];
  568. for (const auto& cmd : commandList->CmdBuffer)
  569. {
  570. EnableScissor(cmd.ClipRect.x - draw_data->DisplayPos.x, cmd.ClipRect.y - draw_data->DisplayPos.y, cmd.ClipRect.z - (cmd.ClipRect.x - draw_data->DisplayPos.x), cmd.ClipRect.w - (cmd.ClipRect.y - draw_data->DisplayPos.y));
  571. if (cmd.UserCallback != nullptr)
  572. {
  573. cmd.UserCallback(commandList, &cmd);
  574. continue;
  575. }
  576. ImGuiRenderTriangles(cmd.ElemCount, cmd.IdxOffset, commandList->IdxBuffer, commandList->VtxBuffer, cmd.TextureId);
  577. rlDrawRenderBatchActive();
  578. }
  579. }
  580. rlSetTexture(0);
  581. rlDisableScissorTest();
  582. rlEnableBackfaceCulling();
  583. }
  584. void HandleGamepadButtonEvent(ImGuiIO& io, GamepadButton button, ImGuiKey key)
  585. {
  586. if (IsGamepadButtonPressed(0, button))
  587. io.AddKeyEvent(key, true);
  588. else if (IsGamepadButtonReleased(0, button))
  589. io.AddKeyEvent(key, false);
  590. }
  591. void HandleGamepadStickEvent(ImGuiIO& io, GamepadAxis axis, ImGuiKey negKey, ImGuiKey posKey)
  592. {
  593. constexpr float deadZone = 0.20f;
  594. float axisValue = GetGamepadAxisMovement(0, axis);
  595. io.AddKeyAnalogEvent(negKey, axisValue < -deadZone, axisValue < -deadZone ? -axisValue : 0);
  596. io.AddKeyAnalogEvent(posKey, axisValue > deadZone, axisValue > deadZone ? axisValue : 0);
  597. }
  598. bool ImGui_ImplRaylib_ProcessEvents(void)
  599. {
  600. ImGuiIO& io = ImGui::GetIO();
  601. bool focused = IsWindowFocused();
  602. if (focused != LastFrameFocused)
  603. io.AddFocusEvent(focused);
  604. LastFrameFocused = focused;
  605. // handle the modifyer key events so that shortcuts work
  606. bool ctrlDown = rlImGuiIsControlDown();
  607. if (ctrlDown != LastControlPressed)
  608. io.AddKeyEvent(ImGuiMod_Ctrl, ctrlDown);
  609. LastControlPressed = ctrlDown;
  610. bool shiftDown = rlImGuiIsShiftDown();
  611. if (shiftDown != LastShiftPressed)
  612. io.AddKeyEvent(ImGuiMod_Shift, shiftDown);
  613. LastShiftPressed = shiftDown;
  614. bool altDown = rlImGuiIsAltDown();
  615. if (altDown != LastAltPressed)
  616. io.AddKeyEvent(ImGuiMod_Alt, altDown);
  617. LastAltPressed = altDown;
  618. bool superDown = rlImGuiIsSuperDown();
  619. if (superDown != LastSuperPressed)
  620. io.AddKeyEvent(ImGuiMod_Super, superDown);
  621. LastSuperPressed = superDown;
  622. // get the pressed keys, just walk the keys so we don
  623. for (int keyId = KEY_NULL; keyId < KeyboardKey::KEY_KP_EQUAL; keyId++)
  624. {
  625. if (!IsKeyPressed(keyId))
  626. continue;
  627. auto keyItr = RaylibKeyMap.find(KeyboardKey(keyId));
  628. if (keyItr != RaylibKeyMap.end())
  629. io.AddKeyEvent(keyItr->second, true);
  630. }
  631. // look for any keys that were down last frame and see if they were down and are released
  632. for (const auto keyItr : RaylibKeyMap)
  633. {
  634. if (IsKeyReleased(keyItr.first))
  635. io.AddKeyEvent(keyItr.second, false);
  636. }
  637. if (io.WantCaptureKeyboard)
  638. {
  639. // add the text input in order
  640. unsigned int pressed = GetCharPressed();
  641. while (pressed != 0)
  642. {
  643. io.AddInputCharacter(pressed);
  644. pressed = GetCharPressed();
  645. }
  646. }
  647. if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad && IsGamepadAvailable(0))
  648. {
  649. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_FACE_UP, ImGuiKey_GamepadDpadUp);
  650. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_FACE_RIGHT, ImGuiKey_GamepadDpadRight);
  651. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_FACE_DOWN, ImGuiKey_GamepadDpadDown);
  652. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_FACE_LEFT, ImGuiKey_GamepadDpadLeft);
  653. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_FACE_UP, ImGuiKey_GamepadFaceUp);
  654. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, ImGuiKey_GamepadFaceLeft);
  655. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_FACE_DOWN, ImGuiKey_GamepadFaceDown);
  656. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_FACE_LEFT, ImGuiKey_GamepadFaceRight);
  657. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_TRIGGER_1, ImGuiKey_GamepadL1);
  658. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_TRIGGER_2, ImGuiKey_GamepadL2);
  659. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_TRIGGER_1, ImGuiKey_GamepadR1);
  660. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_TRIGGER_2, ImGuiKey_GamepadR2);
  661. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_LEFT_THUMB, ImGuiKey_GamepadL3);
  662. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_RIGHT_THUMB, ImGuiKey_GamepadR3);
  663. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_MIDDLE_LEFT, ImGuiKey_GamepadStart);
  664. HandleGamepadButtonEvent(io, GAMEPAD_BUTTON_MIDDLE_RIGHT, ImGuiKey_GamepadBack);
  665. // left stick
  666. HandleGamepadStickEvent(io, GAMEPAD_AXIS_LEFT_X, ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight);
  667. HandleGamepadStickEvent(io, GAMEPAD_AXIS_LEFT_Y, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
  668. // right stick
  669. HandleGamepadStickEvent(io, GAMEPAD_AXIS_RIGHT_X, ImGuiKey_GamepadRStickLeft, ImGuiKey_GamepadRStickRight);
  670. HandleGamepadStickEvent(io, GAMEPAD_AXIS_RIGHT_Y, ImGuiKey_GamepadRStickUp, ImGuiKey_GamepadRStickDown);
  671. }
  672. return true;
  673. }