main.cpp 14 KB

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