main.cpp 14 KB

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