2
0

main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. // dear imgui: standalone example application for Android + OpenGL ES 3
  2. // Learn about Dear ImGui:
  3. // - FAQ https://dearimgui.com/faq
  4. // - Getting Started https://dearimgui.com/getting-started
  5. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  6. // - Introduction, links and more at the top of imgui.cpp
  7. #include "imgui.h"
  8. #include "imgui_impl_android.h"
  9. #include "imgui_impl_opengl3.h"
  10. #include <android/log.h>
  11. #include <android_native_app_glue.h>
  12. #include <android/asset_manager.h>
  13. #include <EGL/egl.h>
  14. #include <GLES3/gl3.h>
  15. #include <string>
  16. // Data
  17. static EGLDisplay g_EglDisplay = EGL_NO_DISPLAY;
  18. static EGLSurface g_EglSurface = EGL_NO_SURFACE;
  19. static EGLContext g_EglContext = EGL_NO_CONTEXT;
  20. static struct android_app* g_App = nullptr;
  21. static bool g_Initialized = false;
  22. static char g_LogTag[] = "ImGuiExample";
  23. static std::string g_IniFilename = "";
  24. // Forward declarations of helper functions
  25. static void Init(struct android_app* app);
  26. static void Shutdown();
  27. static void MainLoopStep();
  28. static int ShowSoftKeyboardInput();
  29. static int PollUnicodeChars();
  30. static int GetAssetData(const char* filename, void** out_data);
  31. // Main code
  32. static void handleAppCmd(struct android_app* app, int32_t appCmd)
  33. {
  34. switch (appCmd)
  35. {
  36. case APP_CMD_SAVE_STATE:
  37. break;
  38. case APP_CMD_INIT_WINDOW:
  39. Init(app);
  40. break;
  41. case APP_CMD_TERM_WINDOW:
  42. Shutdown();
  43. break;
  44. case APP_CMD_GAINED_FOCUS:
  45. case APP_CMD_LOST_FOCUS:
  46. break;
  47. }
  48. }
  49. static int32_t handleInputEvent(struct android_app* app, AInputEvent* inputEvent)
  50. {
  51. return ImGui_ImplAndroid_HandleInputEvent(inputEvent);
  52. }
  53. void android_main(struct android_app* app)
  54. {
  55. app->onAppCmd = handleAppCmd;
  56. app->onInputEvent = handleInputEvent;
  57. while (true)
  58. {
  59. int out_events;
  60. struct android_poll_source* out_data;
  61. // Poll all events. If the app is not visible, this loop blocks until g_Initialized == true.
  62. while (ALooper_pollOnce(g_Initialized ? 0 : -1, nullptr, &out_events, (void**)&out_data) >= 0)
  63. {
  64. // Process one event
  65. if (out_data != nullptr)
  66. out_data->process(app, out_data);
  67. // Exit the app by returning from within the infinite loop
  68. if (app->destroyRequested != 0)
  69. {
  70. // shutdown() should have been called already while processing the
  71. // app command APP_CMD_TERM_WINDOW. But we play save here
  72. if (!g_Initialized)
  73. Shutdown();
  74. return;
  75. }
  76. }
  77. // Initiate a new frame
  78. MainLoopStep();
  79. }
  80. }
  81. void Init(struct android_app* app)
  82. {
  83. if (g_Initialized)
  84. return;
  85. g_App = app;
  86. ANativeWindow_acquire(g_App->window);
  87. // Initialize EGL
  88. // This is mostly boilerplate code for EGL...
  89. {
  90. g_EglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  91. if (g_EglDisplay == EGL_NO_DISPLAY)
  92. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglGetDisplay(EGL_DEFAULT_DISPLAY) returned EGL_NO_DISPLAY");
  93. if (eglInitialize(g_EglDisplay, 0, 0) != EGL_TRUE)
  94. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglInitialize() returned with an error");
  95. const EGLint egl_attributes[] = { EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
  96. EGLint num_configs = 0;
  97. if (eglChooseConfig(g_EglDisplay, egl_attributes, nullptr, 0, &num_configs) != EGL_TRUE)
  98. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned with an error");
  99. if (num_configs == 0)
  100. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned 0 matching config");
  101. // Get the first matching config
  102. EGLConfig egl_config;
  103. eglChooseConfig(g_EglDisplay, egl_attributes, &egl_config, 1, &num_configs);
  104. EGLint egl_format;
  105. eglGetConfigAttrib(g_EglDisplay, egl_config, EGL_NATIVE_VISUAL_ID, &egl_format);
  106. ANativeWindow_setBuffersGeometry(g_App->window, 0, 0, egl_format);
  107. const EGLint egl_context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
  108. g_EglContext = eglCreateContext(g_EglDisplay, egl_config, EGL_NO_CONTEXT, egl_context_attributes);
  109. if (g_EglContext == EGL_NO_CONTEXT)
  110. __android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglCreateContext() returned EGL_NO_CONTEXT");
  111. g_EglSurface = eglCreateWindowSurface(g_EglDisplay, egl_config, g_App->window, nullptr);
  112. eglMakeCurrent(g_EglDisplay, g_EglSurface, g_EglSurface, g_EglContext);
  113. }
  114. // Setup Dear ImGui context
  115. IMGUI_CHECKVERSION();
  116. ImGui::CreateContext();
  117. ImGuiIO& io = ImGui::GetIO();
  118. // Redirect loading/saving of .ini file to our location.
  119. // Make sure 'g_IniFilename' persists while we use Dear ImGui.
  120. g_IniFilename = std::string(app->activity->internalDataPath) + "/imgui.ini";
  121. io.IniFilename = g_IniFilename.c_str();;
  122. // Setup Dear ImGui style
  123. ImGui::StyleColorsDark();
  124. //ImGui::StyleColorsLight();
  125. // Setup Platform/Renderer backends
  126. ImGui_ImplAndroid_Init(g_App->window);
  127. ImGui_ImplOpenGL3_Init("#version 300 es");
  128. // Load Fonts
  129. // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
  130. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
  131. // - Read 'docs/FONTS.md' for more instructions and details.
  132. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  133. // - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them.
  134. // We load the default font with increased size to improve readability on many devices with "high" DPI.
  135. // FIXME: Put some effort into DPI awareness.
  136. // Important: when calling AddFontFromMemoryTTF(), ownership of font_data is transferred by Dear ImGui by default (deleted is handled by Dear ImGui), unless we set FontDataOwnedByAtlas=false in ImFontConfig
  137. ImFontConfig font_cfg;
  138. font_cfg.SizePixels = 22.0f;
  139. io.Fonts->AddFontDefault(&font_cfg);
  140. //void* font_data;
  141. //int font_data_size;
  142. //ImFont* font;
  143. //font_data_size = GetAssetData("segoeui.ttf", &font_data);
  144. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f);
  145. //IM_ASSERT(font != nullptr);
  146. //font_data_size = GetAssetData("DroidSans.ttf", &font_data);
  147. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f);
  148. //IM_ASSERT(font != nullptr);
  149. //font_data_size = GetAssetData("Roboto-Medium.ttf", &font_data);
  150. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f);
  151. //IM_ASSERT(font != nullptr);
  152. //font_data_size = GetAssetData("Cousine-Regular.ttf", &font_data);
  153. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 15.0f);
  154. //IM_ASSERT(font != nullptr);
  155. //font_data_size = GetAssetData("ArialUni.ttf", &font_data);
  156. //font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 18.0f);
  157. //IM_ASSERT(font != nullptr);
  158. // Arbitrary scale-up
  159. // FIXME: Put some effort into DPI awareness
  160. ImGui::GetStyle().ScaleAllSizes(3.0f);
  161. g_Initialized = true;
  162. }
  163. void MainLoopStep()
  164. {
  165. ImGuiIO& io = ImGui::GetIO();
  166. if (g_EglDisplay == EGL_NO_DISPLAY)
  167. return;
  168. // Our state
  169. // (we use static, which essentially makes the variable globals, as a convenience to keep the example code easy to follow)
  170. static bool show_demo_window = true;
  171. static bool show_another_window = false;
  172. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  173. // Poll Unicode characters via JNI
  174. // FIXME: do not call this every frame because of JNI overhead
  175. PollUnicodeChars();
  176. // Open on-screen (soft) input if requested by Dear ImGui
  177. static bool WantTextInputLast = false;
  178. if (io.WantTextInput && !WantTextInputLast)
  179. ShowSoftKeyboardInput();
  180. WantTextInputLast = io.WantTextInput;
  181. // Start the Dear ImGui frame
  182. ImGui_ImplOpenGL3_NewFrame();
  183. ImGui_ImplAndroid_NewFrame();
  184. ImGui::NewFrame();
  185. // 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
  186. if (show_demo_window)
  187. ImGui::ShowDemoWindow(&show_demo_window);
  188. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  189. {
  190. static float f = 0.0f;
  191. static int counter = 0;
  192. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  193. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  194. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  195. ImGui::Checkbox("Another Window", &show_another_window);
  196. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  197. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  198. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  199. counter++;
  200. ImGui::SameLine();
  201. ImGui::Text("counter = %d", counter);
  202. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  203. ImGui::End();
  204. }
  205. // 3. Show another simple window.
  206. if (show_another_window)
  207. {
  208. ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
  209. ImGui::Text("Hello from another window!");
  210. if (ImGui::Button("Close Me"))
  211. show_another_window = false;
  212. ImGui::End();
  213. }
  214. // Rendering
  215. ImGui::Render();
  216. glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
  217. glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
  218. glClear(GL_COLOR_BUFFER_BIT);
  219. ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
  220. eglSwapBuffers(g_EglDisplay, g_EglSurface);
  221. }
  222. void Shutdown()
  223. {
  224. if (!g_Initialized)
  225. return;
  226. // Cleanup
  227. ImGui_ImplOpenGL3_Shutdown();
  228. ImGui_ImplAndroid_Shutdown();
  229. ImGui::DestroyContext();
  230. if (g_EglDisplay != EGL_NO_DISPLAY)
  231. {
  232. eglMakeCurrent(g_EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  233. if (g_EglContext != EGL_NO_CONTEXT)
  234. eglDestroyContext(g_EglDisplay, g_EglContext);
  235. if (g_EglSurface != EGL_NO_SURFACE)
  236. eglDestroySurface(g_EglDisplay, g_EglSurface);
  237. eglTerminate(g_EglDisplay);
  238. }
  239. g_EglDisplay = EGL_NO_DISPLAY;
  240. g_EglContext = EGL_NO_CONTEXT;
  241. g_EglSurface = EGL_NO_SURFACE;
  242. ANativeWindow_release(g_App->window);
  243. g_Initialized = false;
  244. }
  245. // Helper functions
  246. // Unfortunately, there is no way to show the on-screen input from native code.
  247. // Therefore, we call ShowSoftKeyboardInput() of the main activity implemented in MainActivity.kt via JNI.
  248. static int ShowSoftKeyboardInput()
  249. {
  250. JavaVM* java_vm = g_App->activity->vm;
  251. JNIEnv* java_env = nullptr;
  252. jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6);
  253. if (jni_return == JNI_ERR)
  254. return -1;
  255. jni_return = java_vm->AttachCurrentThread(&java_env, nullptr);
  256. if (jni_return != JNI_OK)
  257. return -2;
  258. jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz);
  259. if (native_activity_clazz == nullptr)
  260. return -3;
  261. jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "showSoftInput", "()V");
  262. if (method_id == nullptr)
  263. return -4;
  264. java_env->CallVoidMethod(g_App->activity->clazz, method_id);
  265. jni_return = java_vm->DetachCurrentThread();
  266. if (jni_return != JNI_OK)
  267. return -5;
  268. return 0;
  269. }
  270. // Unfortunately, the native KeyEvent implementation has no getUnicodeChar() function.
  271. // Therefore, we implement the processing of KeyEvents in MainActivity.kt and poll
  272. // the resulting Unicode characters here via JNI and send them to Dear ImGui.
  273. static int PollUnicodeChars()
  274. {
  275. JavaVM* java_vm = g_App->activity->vm;
  276. JNIEnv* java_env = nullptr;
  277. jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6);
  278. if (jni_return == JNI_ERR)
  279. return -1;
  280. jni_return = java_vm->AttachCurrentThread(&java_env, nullptr);
  281. if (jni_return != JNI_OK)
  282. return -2;
  283. jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz);
  284. if (native_activity_clazz == nullptr)
  285. return -3;
  286. jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "pollUnicodeChar", "()I");
  287. if (method_id == nullptr)
  288. return -4;
  289. // Send the actual characters to Dear ImGui
  290. ImGuiIO& io = ImGui::GetIO();
  291. jint unicode_character;
  292. while ((unicode_character = java_env->CallIntMethod(g_App->activity->clazz, method_id)) != 0)
  293. io.AddInputCharacter(unicode_character);
  294. jni_return = java_vm->DetachCurrentThread();
  295. if (jni_return != JNI_OK)
  296. return -5;
  297. return 0;
  298. }
  299. // Helper to retrieve data placed into the assets/ directory (android/app/src/main/assets)
  300. static int GetAssetData(const char* filename, void** outData)
  301. {
  302. int num_bytes = 0;
  303. AAsset* asset_descriptor = AAssetManager_open(g_App->activity->assetManager, filename, AASSET_MODE_BUFFER);
  304. if (asset_descriptor)
  305. {
  306. num_bytes = AAsset_getLength(asset_descriptor);
  307. *outData = IM_ALLOC(num_bytes);
  308. int64_t num_bytes_read = AAsset_read(asset_descriptor, *outData, num_bytes);
  309. AAsset_close(asset_descriptor);
  310. IM_ASSERT(num_bytes_read == num_bytes);
  311. }
  312. return num_bytes;
  313. }