imgui_context.cpp 11 KB

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