main_impl.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. #include "main_impl.h"
  2. #include "core/object_manager.h"
  3. #include "apps/app_selector/app_selector.h"
  4. #include "core_v2/memory_manager.h"
  5. #include "core_v2/utility.hpp"
  6. // from sophiar
  7. #include "core/local_connection.h"
  8. #include <boost/asio/io_context.hpp>
  9. #include <boost/asio/post.hpp>
  10. #include <boost/asio/steady_timer.hpp>
  11. #include <glad/gl.h>
  12. #include <GLFW/glfw3.h>
  13. #include <imgui.h>
  14. #include <imgui_impl_glfw.h>
  15. #include <imgui_impl_opengl3.h>
  16. // make glad happy
  17. #include "core/imgui_utility.hpp"
  18. using boost::asio::io_context;
  19. using boost::asio::post;
  20. using boost::asio::steady_timer;
  21. using boost::system::error_code;
  22. GLFWwindow *window = nullptr;
  23. smart_cuda_stream *default_cuda_stream = nullptr;
  24. io_context *main_ctx;
  25. BS::thread_pool *g_thread_pool;
  26. std::jthread *sophiar_thread = nullptr;
  27. sophiar::local_connection *g_sophiar_conn = nullptr;
  28. using cleanup_list_type =
  29. std::vector<cleanup_func_type>;
  30. cleanup_list_type cleanup_list;
  31. //event_timer perf_timer; // performance timer
  32. std::unique_ptr<steady_timer> ui_timer;
  33. std::chrono::milliseconds ui_interval;
  34. std::unique_ptr<app_base> app;
  35. bool hide_app_ui = false;
  36. bool hide_debug_ui = true;
  37. bool show_demo = false;
  38. // display config
  39. bool full_screen = false;
  40. int chose_monitor = 0;
  41. struct {
  42. int x_pos, y_pos;
  43. int width, height;
  44. } win_info; // windowed mode info
  45. void init_cuda() {
  46. CUDA_API_CHECK(cuInit(0));
  47. auto cuda_dev = CUdevice();
  48. CUDA_API_CHECK(cuDeviceGet(&cuda_dev, 0)); // TODO: select device
  49. CUDA_API_CHECK(cuCtxCreate(&cuda_ctx, CU_CTX_SCHED_AUTO, cuda_dev));
  50. default_cuda_stream = new smart_cuda_stream();
  51. g_cuda_event_pool = new cuda_event_pool();
  52. std::atexit([] {
  53. // elegant cleanup
  54. cuCtxDestroy(cuda_ctx);
  55. });
  56. }
  57. void init_window() {
  58. // set GLFW error handler
  59. glfwSetErrorCallback([](int error, const char *desc) {
  60. SPDLOG_ERROR("GLFW error: code = {}, description = {}", error, desc);
  61. });
  62. // create main window
  63. auto ret = glfwInit();
  64. assert(ret == GLFW_TRUE);
  65. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  66. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
  67. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
  68. // TODO: select width and height
  69. window = glfwCreateWindow(800, 600, "An not simple platform for visual navigation", nullptr, nullptr);
  70. assert(window != nullptr);
  71. glfwMakeContextCurrent(window);
  72. glfwSwapInterval(0);
  73. // load opengl functions
  74. auto version = gladLoadGL(glfwGetProcAddress);
  75. assert(version > 0);
  76. SPDLOG_INFO("Loaded OpenGL {}.{}", GLAD_VERSION_MAJOR(version), GLAD_VERSION_MINOR(version));
  77. // enable color blending
  78. glEnable(GL_BLEND);
  79. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  80. #ifndef NDEBUG
  81. // log opengl error
  82. glEnable(GL_DEBUG_OUTPUT);
  83. glDebugMessageCallback([](GLenum source, GLenum type, GLuint id, GLenum severity,
  84. GLsizei length, const GLchar *message, const void *user_data) {
  85. if (type == GL_DEBUG_TYPE_ERROR) {
  86. SPDLOG_ERROR("OpenGL error: type = {}, severity = {}, message = {}", type, severity, message);
  87. assert(false);
  88. }
  89. }, nullptr);
  90. #endif
  91. // setup imgui context
  92. IMGUI_CHECKVERSION();
  93. ImGui::CreateContext();
  94. auto io = ImGui::GetIO();
  95. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
  96. ImGui::StyleColorsDark();
  97. ImGui_ImplGlfw_InitForOpenGL(window, true);
  98. ImGui_ImplOpenGL3_Init();
  99. // elegant cleanup
  100. std::atexit([] {
  101. ImGui_ImplOpenGL3_Shutdown();
  102. ImGui_ImplGlfw_Shutdown();
  103. ImGui::DestroyContext();
  104. glfwDestroyWindow(window);
  105. glfwTerminate();
  106. });
  107. }
  108. void ui_timer_func(error_code ec) {
  109. if (ec == boost::asio::error::operation_aborted) return;
  110. assert(ec == error_code());
  111. show_ui();
  112. ui_timer->expires_after(ui_interval);
  113. ui_timer->async_wait(ui_timer_func);
  114. }
  115. void init_all() {
  116. init_cuda();
  117. init_window();
  118. main_ctx = new io_context();
  119. main_ob = new object_manager_v2({.ctx = main_ctx});
  120. g_memory_manager = new memory_manager();
  121. constexpr auto background_thread_count = 1; // TODO: load this in config file
  122. g_thread_pool = new BS::thread_pool(background_thread_count);
  123. auto app_conf = app_selector::create_config();
  124. app_conf.asio_ctx = main_ctx;
  125. app_conf.cuda_ctx = &cuda_ctx;
  126. app_conf.app_ptr = &app;
  127. app = std::make_unique<app_selector>(app_conf);
  128. glfwSetWindowTitle(window, app->window_name());
  129. ui_interval = std::chrono::milliseconds(33); // TODO: select refresh rate
  130. ui_timer = std::make_unique<steady_timer>(*main_ctx, ui_interval);
  131. ui_timer->async_wait(ui_timer_func);
  132. }
  133. void process_keys() {
  134. auto &io = ImGui::GetIO();
  135. if (io.WantCaptureKeyboard) return;
  136. if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_H)) {
  137. // Ctrl+H
  138. hide_app_ui ^= true;
  139. }
  140. if (io.KeyCtrl && ImGui::IsKeyPressed(ImGuiKey_D)) {
  141. // Ctrl+D
  142. hide_debug_ui ^= true;
  143. }
  144. }
  145. void update_display() {
  146. auto win = glfwGetCurrentContext();
  147. if (!full_screen) {
  148. glfwSetWindowMonitor(win, nullptr, win_info.x_pos, win_info.y_pos,
  149. win_info.width, win_info.height, GLFW_DONT_CARE);
  150. } else {
  151. assert(full_screen);
  152. int monitor_num = 0;
  153. auto monitors = glfwGetMonitors(&monitor_num);
  154. assert(chose_monitor < monitor_num);
  155. auto monitor = monitors[chose_monitor];
  156. auto mode = glfwGetVideoMode(monitor);
  157. glfwSetWindowMonitor(win, monitor, 0, 0, mode->width, mode->height, mode->refreshRate);
  158. }
  159. }
  160. void recorde_window_info() {
  161. auto win = glfwGetCurrentContext();
  162. glfwGetWindowPos(win, &win_info.x_pos, &win_info.y_pos);
  163. glfwGetWindowSize(win, &win_info.width, &win_info.height);
  164. }
  165. void show_display_config() {
  166. // display mode
  167. if (ImGui::RadioButton("Windowed", !full_screen)) {
  168. if (full_screen) {
  169. full_screen = false;
  170. update_display();
  171. }
  172. }
  173. ImGui::SameLine();
  174. if (ImGui::RadioButton("Full Screen", full_screen)) {
  175. if (!full_screen) {
  176. recorde_window_info();
  177. full_screen = true;
  178. update_display();
  179. }
  180. }
  181. if (full_screen) {
  182. int monitor_count;
  183. auto monitors = glfwGetMonitors(&monitor_count);
  184. if (chose_monitor >= monitor_count) {
  185. chose_monitor = 0;
  186. }
  187. auto monitor_name_preview = glfwGetMonitorName(monitors[chose_monitor]);
  188. if (ImGui::BeginCombo("Monitor", monitor_name_preview)) {
  189. // let user select monitors
  190. for (int k = 0; k < monitor_count; ++k) {
  191. auto is_selected = (chose_monitor == k);
  192. auto monitor_name = fmt::format("{} - {}", k, glfwGetMonitorName(monitors[k]));
  193. if (ImGui::Selectable(monitor_name.c_str(), is_selected)) {
  194. if (chose_monitor != k) {
  195. chose_monitor = k;
  196. update_display();
  197. }
  198. }
  199. if (is_selected) {
  200. ImGui::SetItemDefaultFocus();
  201. }
  202. }
  203. ImGui::EndCombo();
  204. }
  205. }
  206. }
  207. void show_memory_usage() {
  208. auto status = g_memory_manager->status();
  209. constexpr float kb_to_mb = 1.0 / 1e6f;
  210. ImGui::Text("Host: %.2f MB (%.2f MB)",
  211. status.host_allocated * kb_to_mb, status.host_cached * kb_to_mb);
  212. ImGui::Text("CUDA: %.2f MB (%.2f MB)",
  213. status.cuda_allocated * kb_to_mb, status.cuda_cached * kb_to_mb);
  214. }
  215. void show_thread_pool_usage() {
  216. ImGui::Text("Running: %ld", g_thread_pool->get_tasks_running());
  217. ImGui::Text("Queued: %ld", g_thread_pool->get_tasks_queued());
  218. }
  219. void show_debug_ui() {
  220. if (ImGui::Begin("Debug")) {
  221. ImGui::SeparatorText("Display Config");
  222. show_display_config();
  223. ImGui::SeparatorText("Memory Usage");
  224. show_memory_usage();
  225. ImGui::SeparatorText("Thread Pool Usage");
  226. show_thread_pool_usage();
  227. ImGui::SeparatorText("Miscellaneous");
  228. ImGui::Checkbox("Show Demo", &show_demo);
  229. }
  230. ImGui::End();
  231. }
  232. void show_ui() {
  233. glfwPollEvents();
  234. ImGui_ImplOpenGL3_NewFrame();
  235. ImGui_ImplGlfw_NewFrame();
  236. ImGui::NewFrame();
  237. if (glfwWindowShouldClose(window)) {
  238. ui_timer->cancel();
  239. main_ctx->stop();
  240. return;
  241. }
  242. process_keys();
  243. assert(app != nullptr);
  244. if (!hide_app_ui) {
  245. app->show_ui();
  246. }
  247. if (!hide_debug_ui) {
  248. show_debug_ui();
  249. }
  250. if (show_demo) {
  251. ImGui::ShowDemoWindow();
  252. }
  253. cv::Size frame_size;
  254. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  255. glfwGetFramebufferSize(window, &frame_size.width, &frame_size.height);
  256. glViewport(0, 0, frame_size.width, frame_size.height);
  257. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  258. app->render_background();
  259. ImGui::Render();
  260. ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
  261. glfwSwapBuffers(window);
  262. }
  263. void register_cleanup_func(cleanup_func_type func) {
  264. cleanup_list.push_back(func);
  265. }
  266. void cleanup() {
  267. app = nullptr;
  268. ui_timer = nullptr;
  269. // custom cleanup funcs
  270. for (auto func: cleanup_list) {
  271. func();
  272. }
  273. delete main_ob;
  274. delete main_ctx;
  275. delete g_memory_manager;
  276. if (sophiar_thread != nullptr) {
  277. sophiar::stop_sophiar();
  278. delete g_sophiar_conn;
  279. delete sophiar_thread;
  280. }
  281. }