main.mm 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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)(720 * 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. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose)
  64. // Setup Platform/Renderer backends
  65. ImGui_ImplMetal_Init(layer.device);
  66. ImGui_ImplSDL3_InitForMetal(window);
  67. // Load Fonts
  68. // - 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.
  69. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  70. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
  71. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  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. //style.FontSizeBase = 20.0f;
  75. //io.Fonts->AddFontDefault();
  76. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
  77. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
  78. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
  79. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
  80. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
  81. //IM_ASSERT(font != nullptr);
  82. // Our state
  83. bool show_demo_window = true;
  84. bool show_another_window = false;
  85. float clear_color[4] = { 0.45f, 0.55f, 0.60f, 1.00f };
  86. // Main loop
  87. bool done = false;
  88. while (!done)
  89. {
  90. @autoreleasepool
  91. {
  92. // Poll and handle events (inputs, window resize, etc.)
  93. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  94. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  95. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  96. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  97. // [If using SDL_MAIN_USE_CALLBACKS: call ImGui_ImplSDL3_ProcessEvent() from your SDL_AppEvent() function]
  98. SDL_Event event;
  99. while (SDL_PollEvent(&event))
  100. {
  101. ImGui_ImplSDL3_ProcessEvent(&event);
  102. if (event.type == SDL_EVENT_QUIT)
  103. done = true;
  104. if (event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED && event.window.windowID == SDL_GetWindowID(window))
  105. done = true;
  106. }
  107. // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppIterate() function]
  108. if (SDL_GetWindowFlags(window) & SDL_WINDOW_MINIMIZED)
  109. {
  110. SDL_Delay(10);
  111. continue;
  112. }
  113. int width, height;
  114. SDL_GetWindowSizeInPixels(window, &width, &height);
  115. layer.drawableSize = CGSizeMake(width, height);
  116. id<CAMetalDrawable> drawable = [layer nextDrawable];
  117. id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
  118. 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]);
  119. renderPassDescriptor.colorAttachments[0].texture = drawable.texture;
  120. renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear;
  121. renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore;
  122. id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
  123. [renderEncoder pushDebugGroup:@"ImGui demo"];
  124. // Start the Dear ImGui frame
  125. ImGui_ImplMetal_NewFrame(renderPassDescriptor);
  126. ImGui_ImplSDL3_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 / io.Framerate, io.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. ImDrawData* draw_data = ImGui::GetDrawData();
  160. ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder);
  161. [renderEncoder popDebugGroup];
  162. [renderEncoder endEncoding];
  163. [commandBuffer presentDrawable:drawable];
  164. [commandBuffer commit];
  165. }
  166. }
  167. // Cleanup
  168. // [If using SDL_MAIN_USE_CALLBACKS: all code below would likely be your SDL_AppQuit() function]
  169. ImGui_ImplMetal_Shutdown();
  170. ImGui_ImplSDL3_Shutdown();
  171. ImGui::DestroyContext();
  172. SDL_DestroyWindow(window);
  173. SDL_Quit();
  174. return 0;
  175. }