imgui_context.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * Copyright 2014-2015 Daniel Collin. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <bgfx/bgfx.h>
  6. #include <bgfx/embedded_shader.h>
  7. #include <bx/allocator.h>
  8. #include <bx/math.h>
  9. #include <bx/timer.h>
  10. #include <imgui.h>
  11. #include "data/roboto_regular.ttf.h"
  12. #include "data/robotomono_regular.ttf.h"
  13. #include "data/icons_kenney.ttf.h"
  14. #include "data/icons_font_awesome.ttf.h"
  15. #include "core/strings/string_id.h"
  16. #include "core/strings/string_id.inl"
  17. #include "device/device.h"
  18. #include "device/input_device.h"
  19. #include "device/input_types.h"
  20. #include "device/pipeline.h"
  21. #include "device/window.h"
  22. #include "imgui_context.h"
  23. #include "world/shader_manager.h"
  24. using namespace crown;
  25. // From bgfx_utils.h
  26. inline bool checkAvailTransientBuffers(uint32_t _numVertices, const bgfx::VertexLayout& _layout, uint32_t _numIndices)
  27. {
  28. return _numVertices == bgfx::getAvailTransientVertexBuffer(_numVertices, _layout)
  29. && _numIndices == bgfx::getAvailTransientIndexBuffer(_numIndices)
  30. ;
  31. }
  32. struct FontRangeMerge
  33. {
  34. const void* data;
  35. size_t size;
  36. ImWchar ranges[3];
  37. };
  38. static FontRangeMerge s_fontRangeMerge[] =
  39. {
  40. { s_iconsKenneyTtf, sizeof(s_iconsKenneyTtf), { ICON_MIN_KI, ICON_MAX_KI, 0 } },
  41. { s_iconsFontAwesomeTtf, sizeof(s_iconsFontAwesomeTtf), { ICON_MIN_FA, ICON_MAX_FA, 0 } },
  42. };
  43. static int g_MouseCursors[ImGuiMouseCursor_COUNT] = { MouseCursor::ARROW /* Which is == 0 */ };
  44. static void* memAlloc(size_t _size, void* _userData);
  45. static void memFree(void* _ptr, void* _userData);
  46. struct ImGuiContext
  47. {
  48. void render(ImDrawData* _drawData)
  49. {
  50. const ImGuiIO& io = ImGui::GetIO();
  51. const float width = io.DisplaySize.x;
  52. const float height = io.DisplaySize.y;
  53. bgfx::setViewName(m_viewId, "ImGui");
  54. bgfx::setViewMode(m_viewId, bgfx::ViewMode::Sequential);
  55. const bgfx::Caps* caps = bgfx::getCaps();
  56. float ortho[16];
  57. bx::mtxOrtho(ortho, 0.0f, width, height, 0.0f, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
  58. bgfx::setViewTransform(m_viewId, NULL, ortho);
  59. bgfx::setViewRect(m_viewId, 0, 0, uint16_t(width), uint16_t(height) );
  60. // Render command lists
  61. for (int32_t ii = 0, num = _drawData->CmdListsCount; ii < num; ++ii)
  62. {
  63. bgfx::TransientVertexBuffer tvb;
  64. bgfx::TransientIndexBuffer tib;
  65. const ImDrawList* drawList = _drawData->CmdLists[ii];
  66. uint32_t numVertices = (uint32_t)drawList->VtxBuffer.size();
  67. uint32_t numIndices = (uint32_t)drawList->IdxBuffer.size();
  68. if (!checkAvailTransientBuffers(numVertices, m_layout, numIndices) )
  69. {
  70. // not enough space in transient buffer just quit drawing the rest...
  71. break;
  72. }
  73. bgfx::allocTransientVertexBuffer(&tvb, numVertices, m_layout);
  74. bgfx::allocTransientIndexBuffer(&tib, numIndices);
  75. ImDrawVert* verts = (ImDrawVert*)tvb.data;
  76. bx::memCopy(verts, drawList->VtxBuffer.begin(), numVertices * sizeof(ImDrawVert) );
  77. ImDrawIdx* indices = (ImDrawIdx*)tib.data;
  78. bx::memCopy(indices, drawList->IdxBuffer.begin(), numIndices * sizeof(ImDrawIdx) );
  79. uint32_t offset = 0;
  80. for (const ImDrawCmd* cmd = drawList->CmdBuffer.begin(), *cmdEnd = drawList->CmdBuffer.end(); cmd != cmdEnd; ++cmd)
  81. {
  82. if (cmd->UserCallback)
  83. {
  84. cmd->UserCallback(drawList, cmd);
  85. }
  86. else if (0 != cmd->ElemCount)
  87. {
  88. uint64_t state = 0
  89. | BGFX_STATE_WRITE_RGB
  90. | BGFX_STATE_WRITE_A
  91. | BGFX_STATE_MSAA
  92. ;
  93. bgfx::TextureHandle th = m_texture;
  94. StringId32 program = STRING_ID_32("ocornut_imgui", 0xde1bd0ed);
  95. if (NULL != cmd->TextureId)
  96. {
  97. union { ImTextureID ptr; struct { bgfx::TextureHandle handle; uint8_t flags; uint8_t mip; } s; } texture = { cmd->TextureId };
  98. state |= 0 != (IMGUI_FLAGS_ALPHA_BLEND & texture.s.flags)
  99. ? BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)
  100. : BGFX_STATE_NONE
  101. ;
  102. th = texture.s.handle;
  103. if (0 != texture.s.mip)
  104. {
  105. const float lodEnabled[4] = { float(texture.s.mip), 1.0f, 0.0f, 0.0f };
  106. bgfx::setUniform(u_imageLodEnabled, lodEnabled);
  107. program = STRING_ID_32("imgui_image", 0xe2ec5960);
  108. }
  109. }
  110. else
  111. {
  112. state |= BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA);
  113. }
  114. const uint16_t xx = uint16_t(bx::max(cmd->ClipRect.x, 0.0f) );
  115. const uint16_t yy = uint16_t(bx::max(cmd->ClipRect.y, 0.0f) );
  116. bgfx::setScissor(xx, yy
  117. , uint16_t(bx::min(cmd->ClipRect.z, 65535.0f)-xx)
  118. , uint16_t(bx::min(cmd->ClipRect.w, 65535.0f)-yy)
  119. );
  120. bgfx::setState(state);
  121. bgfx::setTexture(0, s_tex, th);
  122. bgfx::setVertexBuffer(0, &tvb, 0, numVertices);
  123. bgfx::setIndexBuffer(&tib, offset, cmd->ElemCount);
  124. device()->_shader_manager->submit(program, VIEW_IMGUI, 0, state);
  125. }
  126. offset += cmd->ElemCount;
  127. }
  128. }
  129. }
  130. void create(float _fontSize, bx::AllocatorI* _allocator)
  131. {
  132. m_allocator = _allocator;
  133. if (NULL == _allocator)
  134. {
  135. static bx::DefaultAllocator allocator;
  136. m_allocator = &allocator;
  137. }
  138. m_viewId = VIEW_IMGUI;
  139. ImGui::SetAllocatorFunctions(memAlloc, memFree, NULL);
  140. m_imgui = ImGui::CreateContext();
  141. ImGuiIO& io = ImGui::GetIO();
  142. io.DisplaySize = ImVec2(1280.0f, 720.0f);
  143. io.DeltaTime = 1.0f / 60.0f;
  144. io.IniFilename = NULL;
  145. setupStyle(true);
  146. // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array.
  147. io.KeyMap[ImGuiKey_Tab] = KeyboardButton::TAB;
  148. io.KeyMap[ImGuiKey_LeftArrow] = KeyboardButton::LEFT;
  149. io.KeyMap[ImGuiKey_RightArrow] = KeyboardButton::RIGHT;
  150. io.KeyMap[ImGuiKey_UpArrow] = KeyboardButton::UP;
  151. io.KeyMap[ImGuiKey_DownArrow] = KeyboardButton::DOWN;
  152. io.KeyMap[ImGuiKey_PageUp] = KeyboardButton::PAGE_UP;
  153. io.KeyMap[ImGuiKey_PageDown] = KeyboardButton::PAGE_DOWN;
  154. io.KeyMap[ImGuiKey_Home] = KeyboardButton::HOME;
  155. io.KeyMap[ImGuiKey_End] = KeyboardButton::END;
  156. io.KeyMap[ImGuiKey_Insert] = KeyboardButton::INS;
  157. io.KeyMap[ImGuiKey_Delete] = KeyboardButton::DEL;
  158. io.KeyMap[ImGuiKey_Backspace] = KeyboardButton::BACKSPACE;
  159. io.KeyMap[ImGuiKey_Space] = KeyboardButton::SPACE;
  160. io.KeyMap[ImGuiKey_Enter] = KeyboardButton::ENTER;
  161. io.KeyMap[ImGuiKey_Escape] = KeyboardButton::ESCAPE;
  162. io.KeyMap[ImGuiKey_A] = KeyboardButton::A;
  163. io.KeyMap[ImGuiKey_C] = KeyboardButton::C;
  164. io.KeyMap[ImGuiKey_V] = KeyboardButton::V;
  165. io.KeyMap[ImGuiKey_X] = KeyboardButton::X;
  166. io.KeyMap[ImGuiKey_Y] = KeyboardButton::Y;
  167. io.KeyMap[ImGuiKey_Z] = KeyboardButton::Z;
  168. io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
  169. io.IniFilename = "imgui.ini";
  170. u_imageLodEnabled = bgfx::createUniform("u_imageLodEnabled", bgfx::UniformType::Vec4);
  171. m_layout
  172. .begin()
  173. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  174. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  175. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  176. .end();
  177. s_tex = bgfx::createUniform("s_tex", bgfx::UniformType::Sampler);
  178. uint8_t* data;
  179. int32_t width;
  180. int32_t height;
  181. {
  182. ImFontConfig config;
  183. config.FontDataOwnedByAtlas = false;
  184. config.MergeMode = false;
  185. // config.MergeGlyphCenterV = true;
  186. const ImWchar* ranges = io.Fonts->GetGlyphRangesCyrillic();
  187. m_font[ImGui::Font::Regular] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoRegularTtf, sizeof(s_robotoRegularTtf), _fontSize, &config, ranges);
  188. m_font[ImGui::Font::Mono ] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoMonoRegularTtf, sizeof(s_robotoMonoRegularTtf), _fontSize-3.0f, &config, ranges);
  189. config.MergeMode = true;
  190. config.DstFont = m_font[ImGui::Font::Regular];
  191. for (uint32_t ii = 0; ii < BX_COUNTOF(s_fontRangeMerge); ++ii)
  192. {
  193. const FontRangeMerge& frm = s_fontRangeMerge[ii];
  194. io.Fonts->AddFontFromMemoryTTF( (void*)frm.data
  195. , (int)frm.size
  196. , _fontSize-3.0f
  197. , &config
  198. , frm.ranges
  199. );
  200. }
  201. }
  202. io.Fonts->GetTexDataAsRGBA32(&data, &width, &height);
  203. m_texture = bgfx::createTexture2D(
  204. (uint16_t)width
  205. , (uint16_t)height
  206. , false
  207. , 1
  208. , bgfx::TextureFormat::BGRA8
  209. , 0
  210. , bgfx::copy(data, width*height*4)
  211. );
  212. }
  213. void destroy()
  214. {
  215. ImGui::DestroyContext(m_imgui);
  216. bgfx::destroy(s_tex);
  217. bgfx::destroy(m_texture);
  218. bgfx::destroy(u_imageLodEnabled);
  219. m_allocator = NULL;
  220. }
  221. void setupStyle(bool _dark)
  222. {
  223. // Doug Binks' darl color scheme
  224. // https://gist.github.com/dougbinks/8089b4bbaccaaf6fa204236978d165a9
  225. ImGuiStyle& style = ImGui::GetStyle();
  226. if (_dark)
  227. {
  228. ImGui::StyleColorsDark(&style);
  229. }
  230. else
  231. {
  232. ImGui::StyleColorsLight(&style);
  233. }
  234. style.FrameRounding = 2.0f;
  235. style.ScrollbarRounding = 2.0f;
  236. style.ScrollbarSize = 13.0f;
  237. style.WindowBorderSize = 0.0f;
  238. style.WindowPadding = ImVec2(4.0f, 4.0f);
  239. style.WindowRounding = 2.0f;
  240. style.WindowTitleAlign = ImVec2(0.5f, 0.5f);
  241. g_MouseCursors[ImGuiMouseCursor_Arrow] = MouseCursor::ARROW;
  242. g_MouseCursors[ImGuiMouseCursor_TextInput] = MouseCursor::TEXT_INPUT;
  243. g_MouseCursors[ImGuiMouseCursor_ResizeAll] = MouseCursor::ARROW;
  244. g_MouseCursors[ImGuiMouseCursor_ResizeNS] = MouseCursor::SIZE_VERTICAL;
  245. g_MouseCursors[ImGuiMouseCursor_ResizeEW] = MouseCursor::SIZE_HORIZONTAL;
  246. g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = MouseCursor::CORNER_TOP_RIGHT;
  247. g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = MouseCursor::CORNER_TOP_LEFT;
  248. g_MouseCursors[ImGuiMouseCursor_Hand] = MouseCursor::HAND;
  249. }
  250. void updateMouseCursor()
  251. {
  252. ImGuiIO& io = ImGui::GetIO();
  253. if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
  254. return;
  255. ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
  256. ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
  257. for (int n = 0; n < platform_io.Viewports.Size; n++)
  258. {
  259. if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor)
  260. {
  261. // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
  262. device()->_window->show_cursor(false);
  263. }
  264. else
  265. {
  266. // Show OS mouse cursor
  267. device()->_window->set_cursor((MouseCursor::Enum)g_MouseCursors[imgui_cursor]);
  268. }
  269. }
  270. }
  271. void beginFrame(uint8_t view_id, uint16_t width, uint16_t height)
  272. {
  273. m_viewId = view_id;
  274. ImGuiIO& io = ImGui::GetIO();
  275. io.DisplaySize = ImVec2(width, height);
  276. io.DeltaTime = 1.0f / 60.0f;
  277. updateMouseCursor();
  278. ImGui::NewFrame();
  279. }
  280. void endFrame()
  281. {
  282. ImGui::Render();
  283. render(ImGui::GetDrawData());
  284. }
  285. ImGuiContext* m_imgui;
  286. bx::AllocatorI* m_allocator;
  287. bgfx::VertexLayout m_layout;
  288. bgfx::TextureHandle m_texture;
  289. bgfx::UniformHandle s_tex;
  290. bgfx::UniformHandle u_imageLodEnabled;
  291. ImFont* m_font[ImGui::Font::Count];
  292. bgfx::ViewId m_viewId;
  293. };
  294. static ImGuiContext s_ctx;
  295. static void* memAlloc(size_t _size, void* _userData)
  296. {
  297. BX_UNUSED(_userData);
  298. return BX_ALLOC(s_ctx.m_allocator, _size);
  299. }
  300. static void memFree(void* _ptr, void* _userData)
  301. {
  302. BX_UNUSED(_userData);
  303. BX_FREE(s_ctx.m_allocator, _ptr);
  304. }
  305. namespace ImGui
  306. {
  307. void PushFont(Font::Enum _font)
  308. {
  309. PushFont(s_ctx.m_font[_font]);
  310. }
  311. } // namespace ImGui
  312. namespace crown
  313. {
  314. void imgui_create(f32 _fontSize, bx::AllocatorI* _allocator)
  315. {
  316. s_ctx.create(_fontSize, _allocator);
  317. }
  318. void imgui_destroy()
  319. {
  320. s_ctx.destroy();
  321. }
  322. void imgui_begin_frame(uint8_t view_id, u16 width, u16 height)
  323. {
  324. s_ctx.beginFrame(view_id, width, height);
  325. }
  326. void imgui_end_frame()
  327. {
  328. s_ctx.endFrame();
  329. }
  330. } // namespace crown
  331. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4505); // error C4505: '' : unreferenced local function has been removed
  332. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-function"); // warning: ‘int rect_width_compare(const void*, const void*)’ defined but not used
  333. BX_PRAGMA_DIAGNOSTIC_PUSH();
  334. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG("-Wunknown-pragmas")
  335. //BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-but-set-variable"); // warning: variable ‘L1’ set but not used
  336. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits"); // warning: comparison is always true due to limited range of data type
  337. #define STBTT_malloc(_size, _userData) memAlloc(_size, _userData)
  338. #define STBTT_free(_ptr, _userData) memFree(_ptr, _userData)
  339. #define STB_RECT_PACK_IMPLEMENTATION
  340. #include <stb/stb_rect_pack.h>
  341. #define STB_TRUETYPE_IMPLEMENTATION
  342. #include <stb/stb_truetype.h>
  343. BX_PRAGMA_DIAGNOSTIC_POP();