main.cpp 14 KB

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