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