main.cpp 14 KB

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