main.mm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. // Dear ImGui: standalone example application for OSX + Metal.
  2. // Learn about Dear ImGui:
  3. // - FAQ https://dearimgui.com/faq
  4. // - Getting Started https://dearimgui.com/getting-started
  5. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  6. // - Introduction, links and more at the top of imgui.cpp
  7. #import <Foundation/Foundation.h>
  8. #if TARGET_OS_OSX
  9. #import <Cocoa/Cocoa.h>
  10. #else
  11. #import <UIKit/UIKit.h>
  12. #endif
  13. #import <Metal/Metal.h>
  14. #import <MetalKit/MetalKit.h>
  15. #include "imgui.h"
  16. #include "imgui_impl_metal.h"
  17. #if TARGET_OS_OSX
  18. #include "imgui_impl_osx.h"
  19. @interface AppViewController : NSViewController<NSWindowDelegate>
  20. @end
  21. #else
  22. @interface AppViewController : UIViewController
  23. @end
  24. #endif
  25. @interface AppViewController () <MTKViewDelegate>
  26. @property (nonatomic, readonly) MTKView *mtkView;
  27. @property (nonatomic, strong) id <MTLDevice> device;
  28. @property (nonatomic, strong) id <MTLCommandQueue> commandQueue;
  29. @end
  30. //-----------------------------------------------------------------------------------
  31. // AppViewController
  32. //-----------------------------------------------------------------------------------
  33. @implementation AppViewController
  34. -(instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil
  35. {
  36. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  37. _device = MTLCreateSystemDefaultDevice();
  38. _commandQueue = [_device newCommandQueue];
  39. if (!self.device)
  40. {
  41. NSLog(@"Metal is not supported");
  42. abort();
  43. }
  44. // Setup Dear ImGui context
  45. // FIXME: This example doesn't have proper cleanup...
  46. IMGUI_CHECKVERSION();
  47. ImGui::CreateContext();
  48. ImGuiIO& io = ImGui::GetIO(); (void)io;
  49. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  50. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  51. io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
  52. io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
  53. // Setup Dear ImGui style
  54. ImGui::StyleColorsDark();
  55. //ImGui::StyleColorsLight();
  56. // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
  57. ImGuiStyle& style = ImGui::GetStyle();
  58. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  59. {
  60. style.WindowRounding = 0.0f;
  61. style.Colors[ImGuiCol_WindowBg].w = 1.0f;
  62. }
  63. // Setup Renderer backend
  64. ImGui_ImplMetal_Init(_device);
  65. // Load Fonts
  66. // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
  67. // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
  68. // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
  69. // - 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).
  70. // - Read 'docs/FONTS.md' for more instructions and details.
  71. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
  72. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  73. //style.FontSizeBase = 20.0f;
  74. //io.Fonts->AddFontDefaultVector();
  75. //io.Fonts->AddFontDefaultBitmap();
  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. return self;
  83. }
  84. -(MTKView *)mtkView
  85. {
  86. return (MTKView *)self.view;
  87. }
  88. -(void)loadView
  89. {
  90. self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 800)];
  91. }
  92. -(void)viewDidLoad
  93. {
  94. [super viewDidLoad];
  95. self.mtkView.device = self.device;
  96. self.mtkView.delegate = self;
  97. #if TARGET_OS_OSX
  98. ImGui_ImplOSX_Init(self.view);
  99. [NSApp activateIgnoringOtherApps:YES];
  100. #endif
  101. }
  102. -(void)drawInMTKView:(MTKView*)view
  103. {
  104. ImGuiIO& io = ImGui::GetIO();
  105. io.DisplaySize.x = view.bounds.size.width;
  106. io.DisplaySize.y = view.bounds.size.height;
  107. #if TARGET_OS_OSX
  108. CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor;
  109. #else
  110. CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale;
  111. #endif
  112. io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale);
  113. id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
  114. MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor;
  115. if (renderPassDescriptor == nil)
  116. {
  117. [commandBuffer commit];
  118. return;
  119. }
  120. // Start the Dear ImGui frame
  121. ImGui_ImplMetal_NewFrame(renderPassDescriptor);
  122. #if TARGET_OS_OSX
  123. ImGui_ImplOSX_NewFrame(view);
  124. #endif
  125. ImGui::NewFrame();
  126. // Our state (make them static = more or less global) as a convenience to keep the example terse.
  127. static bool show_demo_window = true;
  128. static bool show_another_window = false;
  129. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  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. renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
  163. id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
  164. [renderEncoder pushDebugGroup:@"Dear ImGui rendering"];
  165. ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder);
  166. [renderEncoder popDebugGroup];
  167. [renderEncoder endEncoding];
  168. // Present
  169. [commandBuffer presentDrawable:view.currentDrawable];
  170. [commandBuffer commit];
  171. // Update and Render additional Platform Windows
  172. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  173. {
  174. ImGui::UpdatePlatformWindows();
  175. ImGui::RenderPlatformWindowsDefault();
  176. }
  177. }
  178. -(void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size
  179. {
  180. }
  181. //-----------------------------------------------------------------------------------
  182. // Input processing
  183. //-----------------------------------------------------------------------------------
  184. #if TARGET_OS_OSX
  185. - (void)viewWillAppear
  186. {
  187. [super viewWillAppear];
  188. self.view.window.delegate = self;
  189. }
  190. - (void)windowWillClose:(NSNotification *)notification
  191. {
  192. ImGui_ImplMetal_Shutdown();
  193. ImGui_ImplOSX_Shutdown();
  194. ImGui::DestroyContext();
  195. }
  196. #else
  197. // This touch mapping is super cheesy/hacky. We treat any touch on the screen
  198. // as if it were a depressed left mouse button, and we don't bother handling
  199. // multitouch correctly at all. This causes the "cursor" to behave very erratically
  200. // when there are multiple active touches. But for demo purposes, single-touch
  201. // interaction actually works surprisingly well.
  202. -(void)updateIOWithTouchEvent:(UIEvent *)event
  203. {
  204. UITouch *anyTouch = event.allTouches.anyObject;
  205. CGPoint touchLocation = [anyTouch locationInView:self.view];
  206. ImGuiIO &io = ImGui::GetIO();
  207. io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen);
  208. io.AddMousePosEvent(touchLocation.x, touchLocation.y);
  209. BOOL hasActiveTouch = NO;
  210. for (UITouch *touch in event.allTouches)
  211. {
  212. if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled)
  213. {
  214. hasActiveTouch = YES;
  215. break;
  216. }
  217. }
  218. io.AddMouseButtonEvent(0, hasActiveTouch);
  219. }
  220. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  221. -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  222. -(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  223. -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  224. #endif
  225. @end
  226. //-----------------------------------------------------------------------------------
  227. // AppDelegate
  228. //-----------------------------------------------------------------------------------
  229. #if TARGET_OS_OSX
  230. @interface AppDelegate : NSObject <NSApplicationDelegate>
  231. @property (nonatomic, strong) NSWindow *window;
  232. @end
  233. @implementation AppDelegate
  234. -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
  235. {
  236. return YES;
  237. }
  238. -(instancetype)init
  239. {
  240. if (self = [super init])
  241. {
  242. NSViewController *rootViewController = [[AppViewController alloc] initWithNibName:nil bundle:nil];
  243. self.window = [[NSWindow alloc] initWithContentRect:NSZeroRect
  244. styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable
  245. backing:NSBackingStoreBuffered
  246. defer:NO];
  247. self.window.contentViewController = rootViewController;
  248. [self.window center];
  249. [self.window makeKeyAndOrderFront:self];
  250. }
  251. return self;
  252. }
  253. @end
  254. #else
  255. @interface AppDelegate : UIResponder <UIApplicationDelegate>
  256. @property (strong, nonatomic) UIWindow *window;
  257. @end
  258. @implementation AppDelegate
  259. -(BOOL)application:(UIApplication *)application
  260. didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions
  261. {
  262. UIViewController *rootViewController = [[AppViewController alloc] init];
  263. self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
  264. self.window.rootViewController = rootViewController;
  265. [self.window makeKeyAndVisible];
  266. return YES;
  267. }
  268. @end
  269. #endif
  270. //-----------------------------------------------------------------------------------
  271. // Application main() function
  272. //-----------------------------------------------------------------------------------
  273. #if TARGET_OS_OSX
  274. int main(int, const char**)
  275. {
  276. @autoreleasepool
  277. {
  278. [NSApplication sharedApplication];
  279. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  280. AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window
  281. [NSApp setDelegate:appDelegate];
  282. [NSApp activateIgnoringOtherApps:YES];
  283. [NSApp run];
  284. }
  285. return 0;
  286. }
  287. #else
  288. int main(int argc, char * argv[])
  289. {
  290. @autoreleasepool
  291. {
  292. return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
  293. }
  294. }
  295. #endif