imgui.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 "imgui.h"
  12. #include "../bgfx_utils.h"
  13. //#define USE_ENTRY 1
  14. #ifndef USE_ENTRY
  15. # if defined(SCI_NAMESPACE)
  16. # define USE_ENTRY 1
  17. # else
  18. # define USE_ENTRY 0
  19. # endif // defined(SCI_NAMESPACE)
  20. #endif // USE_ENTRY
  21. #if USE_ENTRY
  22. # include "../entry/entry.h"
  23. # include "../entry/input.h"
  24. #endif // USE_ENTRY
  25. #if defined(SCI_NAMESPACE)
  26. # include "scintilla.h"
  27. #endif // defined(SCI_NAMESPACE)
  28. #include "vs_ocornut_imgui.bin.h"
  29. #include "fs_ocornut_imgui.bin.h"
  30. #include "vs_imgui_image.bin.h"
  31. #include "fs_imgui_image.bin.h"
  32. #include "roboto_regular.ttf.h"
  33. #include "robotomono_regular.ttf.h"
  34. #include "icons_kenney.ttf.h"
  35. #include "icons_font_awesome.ttf.h"
  36. static const bgfx::EmbeddedShader s_embeddedShaders[] =
  37. {
  38. BGFX_EMBEDDED_SHADER(vs_ocornut_imgui),
  39. BGFX_EMBEDDED_SHADER(fs_ocornut_imgui),
  40. BGFX_EMBEDDED_SHADER(vs_imgui_image),
  41. BGFX_EMBEDDED_SHADER(fs_imgui_image),
  42. BGFX_EMBEDDED_SHADER_END()
  43. };
  44. struct FontRangeMerge
  45. {
  46. const void* data;
  47. size_t size;
  48. ImWchar ranges[3];
  49. };
  50. static FontRangeMerge s_fontRangeMerge[] =
  51. {
  52. { s_iconsKenneyTtf, sizeof(s_iconsKenneyTtf), { ICON_MIN_KI, ICON_MAX_KI, 0 } },
  53. { s_iconsFontAwesomeTtf, sizeof(s_iconsFontAwesomeTtf), { ICON_MIN_FA, ICON_MAX_FA, 0 } },
  54. };
  55. static void* memAlloc(size_t _size, void* _userData);
  56. static void memFree(void* _ptr, void* _userData);
  57. struct OcornutImguiContext
  58. {
  59. void render(ImDrawData* _drawData)
  60. {
  61. const ImGuiIO& io = ImGui::GetIO();
  62. const float width = io.DisplaySize.x;
  63. const float height = io.DisplaySize.y;
  64. bgfx::setViewName(m_viewId, "ImGui");
  65. bgfx::setViewMode(m_viewId, bgfx::ViewMode::Sequential);
  66. const bgfx::Caps* caps = bgfx::getCaps();
  67. {
  68. float ortho[16];
  69. bx::mtxOrtho(ortho, 0.0f, width, height, 0.0f, 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. // Render command lists
  74. for (int32_t ii = 0, num = _drawData->CmdListsCount; ii < num; ++ii)
  75. {
  76. bgfx::TransientVertexBuffer tvb;
  77. bgfx::TransientIndexBuffer tib;
  78. const ImDrawList* drawList = _drawData->CmdLists[ii];
  79. uint32_t numVertices = (uint32_t)drawList->VtxBuffer.size();
  80. uint32_t numIndices = (uint32_t)drawList->IdxBuffer.size();
  81. if (!checkAvailTransientBuffers(numVertices, m_decl, numIndices) )
  82. {
  83. // not enough space in transient buffer just quit drawing the rest...
  84. break;
  85. }
  86. bgfx::allocTransientVertexBuffer(&tvb, numVertices, m_decl);
  87. bgfx::allocTransientIndexBuffer(&tib, numIndices);
  88. ImDrawVert* verts = (ImDrawVert*)tvb.data;
  89. bx::memCopy(verts, drawList->VtxBuffer.begin(), numVertices * sizeof(ImDrawVert) );
  90. ImDrawIdx* indices = (ImDrawIdx*)tib.data;
  91. bx::memCopy(indices, drawList->IdxBuffer.begin(), numIndices * sizeof(ImDrawIdx) );
  92. uint32_t offset = 0;
  93. for (const ImDrawCmd* cmd = drawList->CmdBuffer.begin(), *cmdEnd = drawList->CmdBuffer.end(); cmd != cmdEnd; ++cmd)
  94. {
  95. if (cmd->UserCallback)
  96. {
  97. cmd->UserCallback(drawList, cmd);
  98. }
  99. else if (0 != cmd->ElemCount)
  100. {
  101. uint64_t state = 0
  102. | BGFX_STATE_WRITE_RGB
  103. | BGFX_STATE_WRITE_A
  104. | BGFX_STATE_MSAA
  105. ;
  106. bgfx::TextureHandle th = m_texture;
  107. bgfx::ProgramHandle program = m_program;
  108. if (NULL != cmd->TextureId)
  109. {
  110. union { ImTextureID ptr; struct { bgfx::TextureHandle handle; uint8_t flags; uint8_t mip; } s; } texture = { cmd->TextureId };
  111. state |= 0 != (IMGUI_FLAGS_ALPHA_BLEND & texture.s.flags)
  112. ? BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA)
  113. : BGFX_STATE_NONE
  114. ;
  115. th = texture.s.handle;
  116. if (0 != texture.s.mip)
  117. {
  118. const float lodEnabled[4] = { float(texture.s.mip), 1.0f, 0.0f, 0.0f };
  119. bgfx::setUniform(u_imageLodEnabled, lodEnabled);
  120. program = m_imageProgram;
  121. }
  122. }
  123. else
  124. {
  125. state |= BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA);
  126. }
  127. const uint16_t xx = uint16_t(bx::max(cmd->ClipRect.x, 0.0f) );
  128. const uint16_t yy = uint16_t(bx::max(cmd->ClipRect.y, 0.0f) );
  129. bgfx::setScissor(xx, yy
  130. , uint16_t(bx::min(cmd->ClipRect.z, 65535.0f)-xx)
  131. , uint16_t(bx::min(cmd->ClipRect.w, 65535.0f)-yy)
  132. );
  133. bgfx::setState(state);
  134. bgfx::setTexture(0, s_tex, th);
  135. bgfx::setVertexBuffer(0, &tvb, 0, numVertices);
  136. bgfx::setIndexBuffer(&tib, offset, cmd->ElemCount);
  137. bgfx::submit(m_viewId, program);
  138. }
  139. offset += cmd->ElemCount;
  140. }
  141. }
  142. }
  143. void create(float _fontSize, bx::AllocatorI* _allocator)
  144. {
  145. m_allocator = _allocator;
  146. if (NULL == _allocator)
  147. {
  148. static bx::DefaultAllocator allocator;
  149. m_allocator = &allocator;
  150. }
  151. m_viewId = 255;
  152. m_lastScroll = 0;
  153. m_last = bx::getHPCounter();
  154. ImGui::SetAllocatorFunctions(memAlloc, memFree, NULL);
  155. m_imgui = ImGui::CreateContext();
  156. ImGuiIO& io = ImGui::GetIO();
  157. io.DisplaySize = ImVec2(1280.0f, 720.0f);
  158. io.DeltaTime = 1.0f / 60.0f;
  159. io.IniFilename = NULL;
  160. setupStyle(true);
  161. #if USE_ENTRY
  162. io.KeyMap[ImGuiKey_Tab] = (int)entry::Key::Tab;
  163. io.KeyMap[ImGuiKey_LeftArrow] = (int)entry::Key::Left;
  164. io.KeyMap[ImGuiKey_RightArrow] = (int)entry::Key::Right;
  165. io.KeyMap[ImGuiKey_UpArrow] = (int)entry::Key::Up;
  166. io.KeyMap[ImGuiKey_DownArrow] = (int)entry::Key::Down;
  167. io.KeyMap[ImGuiKey_PageUp] = (int)entry::Key::PageUp;
  168. io.KeyMap[ImGuiKey_PageDown] = (int)entry::Key::PageDown;
  169. io.KeyMap[ImGuiKey_Home] = (int)entry::Key::Home;
  170. io.KeyMap[ImGuiKey_End] = (int)entry::Key::End;
  171. io.KeyMap[ImGuiKey_Insert] = (int)entry::Key::Insert;
  172. io.KeyMap[ImGuiKey_Delete] = (int)entry::Key::Delete;
  173. io.KeyMap[ImGuiKey_Backspace] = (int)entry::Key::Backspace;
  174. io.KeyMap[ImGuiKey_Space] = (int)entry::Key::Space;
  175. io.KeyMap[ImGuiKey_Enter] = (int)entry::Key::Return;
  176. io.KeyMap[ImGuiKey_Escape] = (int)entry::Key::Esc;
  177. io.KeyMap[ImGuiKey_A] = (int)entry::Key::KeyA;
  178. io.KeyMap[ImGuiKey_C] = (int)entry::Key::KeyC;
  179. io.KeyMap[ImGuiKey_V] = (int)entry::Key::KeyV;
  180. io.KeyMap[ImGuiKey_X] = (int)entry::Key::KeyX;
  181. io.KeyMap[ImGuiKey_Y] = (int)entry::Key::KeyY;
  182. io.KeyMap[ImGuiKey_Z] = (int)entry::Key::KeyZ;
  183. io.ConfigFlags |= 0
  184. | ImGuiConfigFlags_NavEnableGamepad
  185. | ImGuiConfigFlags_NavEnableKeyboard
  186. ;
  187. io.NavInputs[ImGuiNavInput_Activate] = (int)entry::Key::GamepadA;
  188. io.NavInputs[ImGuiNavInput_Cancel] = (int)entry::Key::GamepadB;
  189. // io.NavInputs[ImGuiNavInput_Input] = (int)entry::Key::;
  190. // io.NavInputs[ImGuiNavInput_Menu] = (int)entry::Key::;
  191. io.NavInputs[ImGuiNavInput_DpadLeft] = (int)entry::Key::GamepadLeft;
  192. io.NavInputs[ImGuiNavInput_DpadRight] = (int)entry::Key::GamepadRight;
  193. io.NavInputs[ImGuiNavInput_DpadUp] = (int)entry::Key::GamepadUp;
  194. io.NavInputs[ImGuiNavInput_DpadDown] = (int)entry::Key::GamepadDown;
  195. // io.NavInputs[ImGuiNavInput_LStickLeft] = (int)entry::Key::;
  196. // io.NavInputs[ImGuiNavInput_LStickRight] = (int)entry::Key::;
  197. // io.NavInputs[ImGuiNavInput_LStickUp] = (int)entry::Key::;
  198. // io.NavInputs[ImGuiNavInput_LStickDown] = (int)entry::Key::;
  199. // io.NavInputs[ImGuiNavInput_FocusPrev] = (int)entry::Key::;
  200. // io.NavInputs[ImGuiNavInput_FocusNext] = (int)entry::Key::;
  201. // io.NavInputs[ImGuiNavInput_TweakSlow] = (int)entry::Key::;
  202. // io.NavInputs[ImGuiNavInput_TweakFast] = (int)entry::Key::;
  203. #endif // USE_ENTRY
  204. bgfx::RendererType::Enum type = bgfx::getRendererType();
  205. m_program = bgfx::createProgram(
  206. bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_ocornut_imgui")
  207. , bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_ocornut_imgui")
  208. , true
  209. );
  210. u_imageLodEnabled = bgfx::createUniform("u_imageLodEnabled", bgfx::UniformType::Vec4);
  211. m_imageProgram = bgfx::createProgram(
  212. bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_imgui_image")
  213. , bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_imgui_image")
  214. , true
  215. );
  216. m_decl
  217. .begin()
  218. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  219. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  220. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  221. .end();
  222. s_tex = bgfx::createUniform("s_tex", bgfx::UniformType::Int1);
  223. uint8_t* data;
  224. int32_t width;
  225. int32_t height;
  226. {
  227. ImFontConfig config;
  228. config.FontDataOwnedByAtlas = false;
  229. config.MergeMode = false;
  230. // config.MergeGlyphCenterV = true;
  231. const ImWchar* ranges = io.Fonts->GetGlyphRangesCyrillic();
  232. m_font[ImGui::Font::Regular] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoRegularTtf, sizeof(s_robotoRegularTtf), _fontSize, &config, ranges);
  233. m_font[ImGui::Font::Mono ] = io.Fonts->AddFontFromMemoryTTF( (void*)s_robotoMonoRegularTtf, sizeof(s_robotoMonoRegularTtf), _fontSize-3.0f, &config, ranges);
  234. config.MergeMode = true;
  235. config.DstFont = m_font[ImGui::Font::Regular];
  236. for (uint32_t ii = 0; ii < BX_COUNTOF(s_fontRangeMerge); ++ii)
  237. {
  238. const FontRangeMerge& frm = s_fontRangeMerge[ii];
  239. io.Fonts->AddFontFromMemoryTTF( (void*)frm.data
  240. , (int)frm.size
  241. , _fontSize-3.0f
  242. , &config
  243. , frm.ranges
  244. );
  245. }
  246. }
  247. io.Fonts->GetTexDataAsRGBA32(&data, &width, &height);
  248. m_texture = bgfx::createTexture2D(
  249. (uint16_t)width
  250. , (uint16_t)height
  251. , false
  252. , 1
  253. , bgfx::TextureFormat::BGRA8
  254. , 0
  255. , bgfx::copy(data, width*height*4)
  256. );
  257. ImGui::InitDockContext();
  258. }
  259. void destroy()
  260. {
  261. ImGui::ShutdownDockContext();
  262. ImGui::DestroyContext(m_imgui);
  263. bgfx::destroy(s_tex);
  264. bgfx::destroy(m_texture);
  265. bgfx::destroy(u_imageLodEnabled);
  266. bgfx::destroy(m_imageProgram);
  267. bgfx::destroy(m_program);
  268. m_allocator = NULL;
  269. }
  270. void setupStyle(bool _dark)
  271. {
  272. // Doug Binks' darl color scheme
  273. // https://gist.github.com/dougbinks/8089b4bbaccaaf6fa204236978d165a9
  274. ImGuiStyle& style = ImGui::GetStyle();
  275. if (_dark)
  276. {
  277. ImGui::StyleColorsDark(&style);
  278. }
  279. else
  280. {
  281. ImGui::StyleColorsLight(&style);
  282. }
  283. style.FrameRounding = 4.0f;
  284. style.WindowBorderSize = 0.0f;
  285. }
  286. void beginFrame(
  287. int32_t _mx
  288. , int32_t _my
  289. , uint8_t _button
  290. , int32_t _scroll
  291. , int _width
  292. , int _height
  293. , char _inputChar
  294. , bgfx::ViewId _viewId
  295. )
  296. {
  297. m_viewId = _viewId;
  298. ImGuiIO& io = ImGui::GetIO();
  299. if (_inputChar < 0x7f)
  300. {
  301. io.AddInputCharacter(_inputChar); // ASCII or GTFO! :(
  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, char _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();