imgui.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 <dear-imgui/imgui.h>
  11. #include <dear-imgui/imgui_internal.h>
  12. #include "imgui.h"
  13. #include "../bgfx_utils.h"
  14. //#define USE_ENTRY 1
  15. #ifndef USE_ENTRY
  16. # define USE_ENTRY 0
  17. #endif // USE_ENTRY
  18. #if USE_ENTRY
  19. # include "../entry/entry.h"
  20. # include "../entry/input.h"
  21. #endif // USE_ENTRY
  22. #include "vs_ocornut_imgui.bin.h"
  23. #include "fs_ocornut_imgui.bin.h"
  24. #include "vs_imgui_image.bin.h"
  25. #include "fs_imgui_image.bin.h"
  26. #include "roboto_regular.ttf.h"
  27. #include "robotomono_regular.ttf.h"
  28. #include "icons_kenney.ttf.h"
  29. #include "icons_font_awesome.ttf.h"
  30. static const bgfx::EmbeddedShader s_embeddedShaders[] =
  31. {
  32. BGFX_EMBEDDED_SHADER(vs_ocornut_imgui),
  33. BGFX_EMBEDDED_SHADER(fs_ocornut_imgui),
  34. BGFX_EMBEDDED_SHADER(vs_imgui_image),
  35. BGFX_EMBEDDED_SHADER(fs_imgui_image),
  36. BGFX_EMBEDDED_SHADER_END()
  37. };
  38. struct FontRangeMerge
  39. {
  40. const void* data;
  41. size_t size;
  42. ImWchar ranges[3];
  43. };
  44. static FontRangeMerge s_fontRangeMerge[] =
  45. {
  46. { s_iconsKenneyTtf, sizeof(s_iconsKenneyTtf), { ICON_MIN_KI, ICON_MAX_KI, 0 } },
  47. { s_iconsFontAwesomeTtf, sizeof(s_iconsFontAwesomeTtf), { ICON_MIN_FA, ICON_MAX_FA, 0 } },
  48. };
  49. static void* memAlloc(size_t _size, void* _userData);
  50. static void memFree(void* _ptr, void* _userData);
  51. struct OcornutImguiContext
  52. {
  53. void render(ImDrawData* _drawData)
  54. {
  55. // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
  56. int fb_width = (int)(_drawData->DisplaySize.x * _drawData->FramebufferScale.x);
  57. int fb_height = (int)(_drawData->DisplaySize.y * _drawData->FramebufferScale.y);
  58. if (fb_width <= 0 || fb_height <= 0)
  59. return;
  60. bgfx::setViewName(m_viewId, "ImGui");
  61. bgfx::setViewMode(m_viewId, bgfx::ViewMode::Sequential);
  62. const bgfx::Caps* caps = bgfx::getCaps();
  63. {
  64. float ortho[16];
  65. float x = _drawData->DisplayPos.x;
  66. float y = _drawData->DisplayPos.y;
  67. float width = _drawData->DisplaySize.x;
  68. float height = _drawData->DisplaySize.y;
  69. bx::mtxOrtho(ortho, x, x + width, y + height, y, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
  70. bgfx::setViewTransform(m_viewId, NULL, ortho);
  71. bgfx::setViewRect(m_viewId, 0, 0, uint16_t(width), uint16_t(height) );
  72. }
  73. const ImVec2 clipPos = _drawData->DisplayPos; // (0,0) unless using multi-viewports
  74. const ImVec2 clipScale = _drawData->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
  75. // Render command lists
  76. for (int32_t ii = 0, num = _drawData->CmdListsCount; ii < num; ++ii)
  77. {
  78. bgfx::TransientVertexBuffer tvb;
  79. bgfx::TransientIndexBuffer tib;
  80. const ImDrawList* drawList = _drawData->CmdLists[ii];
  81. uint32_t numVertices = (uint32_t)drawList->VtxBuffer.size();
  82. uint32_t numIndices = (uint32_t)drawList->IdxBuffer.size();
  83. if (!checkAvailTransientBuffers(numVertices, m_layout, numIndices) )
  84. {
  85. // not enough space in transient buffer just quit drawing the rest...
  86. break;
  87. }
  88. bgfx::allocTransientVertexBuffer(&tvb, numVertices, m_layout);
  89. bgfx::allocTransientIndexBuffer(&tib, numIndices, sizeof(ImDrawIdx) == 4);
  90. ImDrawVert* verts = (ImDrawVert*)tvb.data;
  91. bx::memCopy(verts, drawList->VtxBuffer.begin(), numVertices * sizeof(ImDrawVert) );
  92. ImDrawIdx* indices = (ImDrawIdx*)tib.data;
  93. bx::memCopy(indices, drawList->IdxBuffer.begin(), numIndices * sizeof(ImDrawIdx) );
  94. uint32_t offset = 0;
  95. for (const ImDrawCmd* cmd = drawList->CmdBuffer.begin(), *cmdEnd = drawList->CmdBuffer.end(); cmd != cmdEnd; ++cmd)
  96. {
  97. if (cmd->UserCallback)
  98. {
  99. cmd->UserCallback(drawList, cmd);
  100. }
  101. else if (0 != cmd->ElemCount)
  102. {
  103. uint64_t state = 0
  104. | BGFX_STATE_WRITE_RGB
  105. | BGFX_STATE_WRITE_A
  106. | BGFX_STATE_MSAA
  107. ;
  108. bgfx::TextureHandle th = m_texture;
  109. bgfx::ProgramHandle program = m_program;
  110. if (NULL != cmd->TextureId)
  111. {
  112. union { ImTextureID ptr; struct { bgfx::TextureHandle handle; uint8_t flags; uint8_t mip; } s; } texture = { cmd->TextureId };
  113. state |= 0 != (IMGUI_FLAGS_ALPHA_BLEND & texture.s.flags)
  114. ? BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)
  115. : BGFX_STATE_NONE
  116. ;
  117. th = texture.s.handle;
  118. if (0 != texture.s.mip)
  119. {
  120. const float lodEnabled[4] = { float(texture.s.mip), 1.0f, 0.0f, 0.0f };
  121. bgfx::setUniform(u_imageLodEnabled, lodEnabled);
  122. program = m_imageProgram;
  123. }
  124. }
  125. else
  126. {
  127. state |= BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA);
  128. }
  129. // Project scissor/clipping rectangles into framebuffer space
  130. ImVec4 clipRect;
  131. clipRect.x = (cmd->ClipRect.x - clipPos.x) * clipScale.x;
  132. clipRect.y = (cmd->ClipRect.y - clipPos.y) * clipScale.y;
  133. clipRect.z = (cmd->ClipRect.z - clipPos.x) * clipScale.x;
  134. clipRect.w = (cmd->ClipRect.w - clipPos.y) * clipScale.y;
  135. if (clipRect.x < fb_width
  136. && clipRect.y < fb_height
  137. && clipRect.z >= 0.0f
  138. && clipRect.w >= 0.0f)
  139. {
  140. const uint16_t xx = uint16_t(bx::max(clipRect.x, 0.0f) );
  141. const uint16_t yy = uint16_t(bx::max(clipRect.y, 0.0f) );
  142. bgfx::setScissor(xx, yy
  143. , uint16_t(bx::min(clipRect.z, 65535.0f)-xx)
  144. , uint16_t(bx::min(clipRect.w, 65535.0f)-yy)
  145. );
  146. bgfx::setState(state);
  147. bgfx::setTexture(0, s_tex, th);
  148. bgfx::setVertexBuffer(0, &tvb, 0, numVertices);
  149. bgfx::setIndexBuffer(&tib, offset, cmd->ElemCount);
  150. bgfx::submit(m_viewId, program);
  151. }
  152. }
  153. offset += cmd->ElemCount;
  154. }
  155. }
  156. }
  157. void create(float _fontSize, bx::AllocatorI* _allocator)
  158. {
  159. m_allocator = _allocator;
  160. if (NULL == _allocator)
  161. {
  162. static bx::DefaultAllocator allocator;
  163. m_allocator = &allocator;
  164. }
  165. m_viewId = 255;
  166. m_lastScroll = 0;
  167. m_last = bx::getHPCounter();
  168. ImGui::SetAllocatorFunctions(memAlloc, memFree, NULL);
  169. m_imgui = ImGui::CreateContext();
  170. ImGuiIO& io = ImGui::GetIO();
  171. io.DisplaySize = ImVec2(1280.0f, 720.0f);
  172. io.DeltaTime = 1.0f / 60.0f;
  173. io.IniFilename = NULL;
  174. setupStyle(true);
  175. #if USE_ENTRY
  176. io.KeyMap[ImGuiKey_Tab] = (int)entry::Key::Tab;
  177. io.KeyMap[ImGuiKey_LeftArrow] = (int)entry::Key::Left;
  178. io.KeyMap[ImGuiKey_RightArrow] = (int)entry::Key::Right;
  179. io.KeyMap[ImGuiKey_UpArrow] = (int)entry::Key::Up;
  180. io.KeyMap[ImGuiKey_DownArrow] = (int)entry::Key::Down;
  181. io.KeyMap[ImGuiKey_PageUp] = (int)entry::Key::PageUp;
  182. io.KeyMap[ImGuiKey_PageDown] = (int)entry::Key::PageDown;
  183. io.KeyMap[ImGuiKey_Home] = (int)entry::Key::Home;
  184. io.KeyMap[ImGuiKey_End] = (int)entry::Key::End;
  185. io.KeyMap[ImGuiKey_Insert] = (int)entry::Key::Insert;
  186. io.KeyMap[ImGuiKey_Delete] = (int)entry::Key::Delete;
  187. io.KeyMap[ImGuiKey_Backspace] = (int)entry::Key::Backspace;
  188. io.KeyMap[ImGuiKey_Space] = (int)entry::Key::Space;
  189. io.KeyMap[ImGuiKey_Enter] = (int)entry::Key::Return;
  190. io.KeyMap[ImGuiKey_Escape] = (int)entry::Key::Esc;
  191. io.KeyMap[ImGuiKey_A] = (int)entry::Key::KeyA;
  192. io.KeyMap[ImGuiKey_C] = (int)entry::Key::KeyC;
  193. io.KeyMap[ImGuiKey_V] = (int)entry::Key::KeyV;
  194. io.KeyMap[ImGuiKey_X] = (int)entry::Key::KeyX;
  195. io.KeyMap[ImGuiKey_Y] = (int)entry::Key::KeyY;
  196. io.KeyMap[ImGuiKey_Z] = (int)entry::Key::KeyZ;
  197. io.ConfigFlags |= 0
  198. | ImGuiConfigFlags_NavEnableGamepad
  199. | ImGuiConfigFlags_NavEnableKeyboard
  200. ;
  201. io.NavInputs[ImGuiNavInput_Activate] = (int)entry::Key::GamepadA;
  202. io.NavInputs[ImGuiNavInput_Cancel] = (int)entry::Key::GamepadB;
  203. // io.NavInputs[ImGuiNavInput_Input] = (int)entry::Key::;
  204. // io.NavInputs[ImGuiNavInput_Menu] = (int)entry::Key::;
  205. io.NavInputs[ImGuiNavInput_DpadLeft] = (int)entry::Key::GamepadLeft;
  206. io.NavInputs[ImGuiNavInput_DpadRight] = (int)entry::Key::GamepadRight;
  207. io.NavInputs[ImGuiNavInput_DpadUp] = (int)entry::Key::GamepadUp;
  208. io.NavInputs[ImGuiNavInput_DpadDown] = (int)entry::Key::GamepadDown;
  209. // io.NavInputs[ImGuiNavInput_LStickLeft] = (int)entry::Key::;
  210. // io.NavInputs[ImGuiNavInput_LStickRight] = (int)entry::Key::;
  211. // io.NavInputs[ImGuiNavInput_LStickUp] = (int)entry::Key::;
  212. // io.NavInputs[ImGuiNavInput_LStickDown] = (int)entry::Key::;
  213. // io.NavInputs[ImGuiNavInput_FocusPrev] = (int)entry::Key::;
  214. // io.NavInputs[ImGuiNavInput_FocusNext] = (int)entry::Key::;
  215. // io.NavInputs[ImGuiNavInput_TweakSlow] = (int)entry::Key::;
  216. // io.NavInputs[ImGuiNavInput_TweakFast] = (int)entry::Key::;
  217. #endif // USE_ENTRY
  218. bgfx::RendererType::Enum type = bgfx::getRendererType();
  219. m_program = bgfx::createProgram(
  220. bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_ocornut_imgui")
  221. , bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_ocornut_imgui")
  222. , true
  223. );
  224. u_imageLodEnabled = bgfx::createUniform("u_imageLodEnabled", bgfx::UniformType::Vec4);
  225. m_imageProgram = bgfx::createProgram(
  226. bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_imgui_image")
  227. , bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_imgui_image")
  228. , true
  229. );
  230. m_layout
  231. .begin()
  232. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  233. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  234. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  235. .end();
  236. s_tex = bgfx::createUniform("s_tex", bgfx::UniformType::Sampler);
  237. uint8_t* data;
  238. int32_t width;
  239. int32_t height;
  240. {
  241. ImFontConfig config;
  242. config.FontDataOwnedByAtlas = false;
  243. config.MergeMode = false;
  244. // config.MergeGlyphCenterV = true;
  245. const ImWchar* ranges = io.Fonts->GetGlyphRangesCyrillic();
  246. m_font[ImGui::Font::Regular] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoRegularTtf, sizeof(s_robotoRegularTtf), _fontSize, &config, ranges);
  247. m_font[ImGui::Font::Mono ] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoMonoRegularTtf, sizeof(s_robotoMonoRegularTtf), _fontSize-3.0f, &config, ranges);
  248. config.MergeMode = true;
  249. config.DstFont = m_font[ImGui::Font::Regular];
  250. for (uint32_t ii = 0; ii < BX_COUNTOF(s_fontRangeMerge); ++ii)
  251. {
  252. const FontRangeMerge& frm = s_fontRangeMerge[ii];
  253. io.Fonts->AddFontFromMemoryTTF( (void*)frm.data
  254. , (int)frm.size
  255. , _fontSize-3.0f
  256. , &config
  257. , frm.ranges
  258. );
  259. }
  260. }
  261. io.Fonts->GetTexDataAsRGBA32(&data, &width, &height);
  262. m_texture = bgfx::createTexture2D(
  263. (uint16_t)width
  264. , (uint16_t)height
  265. , false
  266. , 1
  267. , bgfx::TextureFormat::BGRA8
  268. , 0
  269. , bgfx::copy(data, width*height*4)
  270. );
  271. ImGui::InitDockContext();
  272. }
  273. void destroy()
  274. {
  275. ImGui::ShutdownDockContext();
  276. ImGui::DestroyContext(m_imgui);
  277. bgfx::destroy(s_tex);
  278. bgfx::destroy(m_texture);
  279. bgfx::destroy(u_imageLodEnabled);
  280. bgfx::destroy(m_imageProgram);
  281. bgfx::destroy(m_program);
  282. m_allocator = NULL;
  283. }
  284. void setupStyle(bool _dark)
  285. {
  286. // Doug Binks' darl color scheme
  287. // https://gist.github.com/dougbinks/8089b4bbaccaaf6fa204236978d165a9
  288. ImGuiStyle& style = ImGui::GetStyle();
  289. if (_dark)
  290. {
  291. ImGui::StyleColorsDark(&style);
  292. }
  293. else
  294. {
  295. ImGui::StyleColorsLight(&style);
  296. }
  297. style.FrameRounding = 4.0f;
  298. style.WindowBorderSize = 0.0f;
  299. }
  300. void beginFrame(
  301. int32_t _mx
  302. , int32_t _my
  303. , uint8_t _button
  304. , int32_t _scroll
  305. , int _width
  306. , int _height
  307. , int _inputChar
  308. , bgfx::ViewId _viewId
  309. )
  310. {
  311. m_viewId = _viewId;
  312. ImGuiIO& io = ImGui::GetIO();
  313. if (_inputChar >= 0)
  314. {
  315. io.AddInputCharacter(_inputChar);
  316. }
  317. io.DisplaySize = ImVec2( (float)_width, (float)_height);
  318. const int64_t now = bx::getHPCounter();
  319. const int64_t frameTime = now - m_last;
  320. m_last = now;
  321. const double freq = double(bx::getHPFrequency() );
  322. io.DeltaTime = float(frameTime/freq);
  323. io.MousePos = ImVec2( (float)_mx, (float)_my);
  324. io.MouseDown[0] = 0 != (_button & IMGUI_MBUT_LEFT);
  325. io.MouseDown[1] = 0 != (_button & IMGUI_MBUT_RIGHT);
  326. io.MouseDown[2] = 0 != (_button & IMGUI_MBUT_MIDDLE);
  327. io.MouseWheel = (float)(_scroll - m_lastScroll);
  328. m_lastScroll = _scroll;
  329. #if USE_ENTRY
  330. uint8_t modifiers = inputGetModifiersState();
  331. io.KeyShift = 0 != (modifiers & (entry::Modifier::LeftShift | entry::Modifier::RightShift) );
  332. io.KeyCtrl = 0 != (modifiers & (entry::Modifier::LeftCtrl | entry::Modifier::RightCtrl ) );
  333. io.KeyAlt = 0 != (modifiers & (entry::Modifier::LeftAlt | entry::Modifier::RightAlt ) );
  334. for (int32_t ii = 0; ii < (int32_t)entry::Key::Count; ++ii)
  335. {
  336. io.KeysDown[ii] = inputGetKeyState(entry::Key::Enum(ii) );
  337. }
  338. #endif // USE_ENTRY
  339. ImGui::NewFrame();
  340. ImGuizmo::BeginFrame();
  341. }
  342. void endFrame()
  343. {
  344. ImGui::Render();
  345. render(ImGui::GetDrawData() );
  346. }
  347. ImGuiContext* m_imgui;
  348. bx::AllocatorI* m_allocator;
  349. bgfx::VertexLayout m_layout;
  350. bgfx::ProgramHandle m_program;
  351. bgfx::ProgramHandle m_imageProgram;
  352. bgfx::TextureHandle m_texture;
  353. bgfx::UniformHandle s_tex;
  354. bgfx::UniformHandle u_imageLodEnabled;
  355. ImFont* m_font[ImGui::Font::Count];
  356. int64_t m_last;
  357. int32_t m_lastScroll;
  358. bgfx::ViewId m_viewId;
  359. };
  360. static OcornutImguiContext s_ctx;
  361. static void* memAlloc(size_t _size, void* _userData)
  362. {
  363. BX_UNUSED(_userData);
  364. return BX_ALLOC(s_ctx.m_allocator, _size);
  365. }
  366. static void memFree(void* _ptr, void* _userData)
  367. {
  368. BX_UNUSED(_userData);
  369. BX_FREE(s_ctx.m_allocator, _ptr);
  370. }
  371. void imguiCreate(float _fontSize, bx::AllocatorI* _allocator)
  372. {
  373. s_ctx.create(_fontSize, _allocator);
  374. }
  375. void imguiDestroy()
  376. {
  377. s_ctx.destroy();
  378. }
  379. void imguiBeginFrame(int32_t _mx, int32_t _my, uint8_t _button, int32_t _scroll, uint16_t _width, uint16_t _height, int _inputChar, bgfx::ViewId _viewId)
  380. {
  381. s_ctx.beginFrame(_mx, _my, _button, _scroll, _width, _height, _inputChar, _viewId);
  382. }
  383. void imguiEndFrame()
  384. {
  385. s_ctx.endFrame();
  386. }
  387. namespace ImGui
  388. {
  389. void PushFont(Font::Enum _font)
  390. {
  391. PushFont(s_ctx.m_font[_font]);
  392. }
  393. void PushEnabled(bool _enabled)
  394. {
  395. extern void PushItemFlag(int option, bool enabled);
  396. PushItemFlag(ImGuiItemFlags_Disabled, !_enabled);
  397. PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * (_enabled ? 1.0f : 0.5f) );
  398. }
  399. void PopEnabled()
  400. {
  401. extern void PopItemFlag();
  402. PopItemFlag();
  403. PopStyleVar();
  404. }
  405. } // namespace ImGui
  406. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4505); // error C4505: '' : unreferenced local function has been removed
  407. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wunused-function"); // warning: 'int rect_width_compare(const void*, const void*)' defined but not used
  408. BX_PRAGMA_DIAGNOSTIC_PUSH();
  409. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG("-Wunknown-pragmas")
  410. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits"); // warning: comparison is always true due to limited range of data type
  411. #define STBTT_malloc(_size, _userData) memAlloc(_size, _userData)
  412. #define STBTT_free(_ptr, _userData) memFree(_ptr, _userData)
  413. #define STB_RECT_PACK_IMPLEMENTATION
  414. #include <stb/stb_rect_pack.h>
  415. #define STB_TRUETYPE_IMPLEMENTATION
  416. #include <stb/stb_truetype.h>
  417. BX_PRAGMA_DIAGNOSTIC_POP();