imgui.cpp 14 KB

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