main.mm 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // Dear ImGui: standalone example application for SDL3 + Metal
  2. // (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
  3. // Learn about Dear ImGui:
  4. // - FAQ https://dearimgui.com/faq
  5. // - Getting Started https://dearimgui.com/getting-started
  6. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  7. // - Introduction, links and more at the top of imgui.cpp
  8. #include "imgui.h"
  9. #include "imgui_impl_sdl3.h"
  10. #include "imgui_impl_metal.h"
  11. #include <stdio.h> // printf, fprintf
  12. #include <SDL3/SDL.h>
  13. #import <Metal/Metal.h>
  14. #import <QuartzCore/QuartzCore.h>
  15. // Main code
  16. int main(int, char**)
  17. {
  18. // Setup SDL
  19. // [If using SDL_MAIN_USE_CALLBACKS: all code below until the main loop starts would likely be your SDL_AppInit() function]
  20. if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD))
  21. {
  22. printf("Error: SDL_Init(): %s\n", SDL_GetError());
  23. return 1;
  24. }
  25. // Create SDL window graphics context
  26. float main_scale = SDL_GetDisplayContentScale(SDL_GetPrimaryDisplay());
  27. SDL_WindowFlags window_flags = SDL_WINDOW_METAL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY;
  28. SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL3+Metal example", (int)(1280 * main_scale), (int)(800 * main_scale), window_flags);
  29. if (window == nullptr)
  30. {
  31. printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
  32. return 1;
  33. }
  34. SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
  35. SDL_ShowWindow(window);
  36. // Create Metal device _before_ creating the view/layer
  37. id<MTLDevice> metalDevice = MTLCreateSystemDefaultDevice();
  38. if (!metalDevice)
  39. {
  40. printf("Error: failed to create Metal device.\n");
  41. SDL_DestroyWindow(window);
  42. SDL_Quit();
  43. return 1;
  44. }
  45. SDL_MetalView view = SDL_Metal_CreateView(window);
  46. CAMetalLayer* layer = (__bridge CAMetalLayer*)SDL_Metal_GetLayer(view);
  47. layer.device = metalDevice;
  48. layer.pixelFormat = MTLPixelFormatBGRA8Unorm;
  49. id<MTLCommandQueue> commandQueue = [layer.device newCommandQueue];
  50. MTLRenderPassDescriptor* renderPassDescriptor = [MTLRenderPassDescriptor new];
  51. // Setup Dear ImGui context
  52. IMGUI_CHECKVERSION();
  53. ImGui::CreateContext();
  54. ImGuiIO& io = ImGui::GetIO(); (void)io;
  55. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  56. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  57. // Setup Dear ImGui style
  58. ImGui::StyleColorsDark();
  59. //ImGui::StyleColorsLight();
  60. // Setup scaling
  61. ImGuiStyle& style = ImGui::GetStyle();
  62. style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
  63. style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor)
  64. // Setup Platform/Renderer backends
  65. ImGui_ImplMetal_Init(layer.device);
  66. ImGui_ImplSDL3_InitForMetal(window);
  67. // Load Fonts
  68. // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
  69. // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
  70. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
  71. // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
  72. // - Read 'docs/FONTS.md' for more instructions and details.
  73. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
  74. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  75. //style.FontSizeBase = 20.0f;
  76. //io.Fonts->AddFontDefaultVector();
  77. //io.Fonts->AddFontDefaultBitmap();
  78. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
  79. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
  80. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
  81. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
  82. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
  83. //IM_ASSERT(font != nullptr);
  84. // Our state
  85. bool show_demo_window = true;
  86. bool show_another_window = false;
  87. float clear_color[4] = { 0.45f, 0.55f, 0.60f, 1.00f };
  88. // Main loop
  89. bool done = false;
  90. while (!done)
  91. {
  92. @autoreleasepool
  93. {
  94. // Poll and handle events (inputs, window resize, etc.)
  95. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  96. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  97. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  98. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  99. // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function]
  100. SDL_Event event;
  101. while (SDL_PollEvent(&event))
  102. {
  103. ImGui_ImplSDL3_ProcessEvent(&event);
  104. if (event.type == SDL_EVENT_QUIT)
  105. done = true;
  106. if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window))
  107. done = true;
  108. }
  109. // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function]
  110. if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
  111. {
  112. SDL_Delay(10);
  113. continue;
  114. }
  115. int width, height;
  116. SDL_GetWindowSizeInPixels(window, &width, &height);
  117. layer.drawableSize = CGSizeMake(width, height);
  118. id<CAMetalDrawable> drawable = [layer nextDrawable];
  119. id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
  120. renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color[0] * clear_color[3], clear_color[1] * clear_color[3], clear_color[2] * clear_color[3], clear_color[3]);
  121. renderPassDescriptor.colorAttachments[0].texture = drawable.texture;
  122. renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear;
  123. renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore;
  124. id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
  125. [renderEncoder pushDebugGroup:@"ImGui demo"];
  126. // Start the Dear ImGui frame
  127. ImGui_ImplMetal_NewFrame(renderPassDescriptor);
  128. ImGui_ImplSDL3_NewFrame();
  129. ImGui::NewFrame();
  130. // 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!).
  131. if (show_demo_window)
  132. ImGui::ShowDemoWindow(&show_demo_window);
  133. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  134. {
  135. static float f = 0.0f;
  136. static int counter = 0;
  137. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  138. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  139. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  140. ImGui::Checkbox("Another Window", &show_another_window);
  141. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  142. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  143. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  144. counter++;
  145. ImGui::SameLine();
  146. ImGui::Text("counter = %d", counter);
  147. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  148. ImGui::End();
  149. }
  150. // 3. Show another simple window.
  151. if (show_another_window)
  152. {
  153. 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)
  154. ImGui::Text("Hello from another window!");
  155. if (ImGui::Button("Close Me"))
  156. show_another_window = false;
  157. ImGui::End();
  158. }
  159. // Rendering
  160. ImGui::Render();
  161. ImDrawData* draw_data = ImGui::GetDrawData();
  162. ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder);
  163. [renderEncoder popDebugGroup];
  164. [renderEncoder endEncoding];
  165. [commandBuffer presentDrawable:drawable];
  166. [commandBuffer commit];
  167. }
  168. }
  169. // Cleanup
  170. // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function]
  171. ImGui_ImplMetal_Shutdown();
  172. ImGui_ImplSDL3_Shutdown();
  173. ImGui::DestroyContext();
  174. SDL_DestroyWindow(window);
  175. SDL_Quit();
  176. return 0;
  177. }