main.mm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. // Setup Dear ImGui style
  52. ImGui::StyleColorsDark();
  53. //ImGui::StyleColorsLight();
  54. // Setup Renderer backend
  55. ImGui_ImplMetal_Init(_device);
  56. // Load Fonts
  57. // - 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.
  58. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  59. // - 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).
  60. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  61. // - Read 'docs/FONTS.md' for more instructions and details.
  62. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  63. //style.FontSizeBase = 20.0f;
  64. //io.Fonts->AddFontDefault();
  65. //io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\segoeui.ttf");
  66. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf");
  67. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf");
  68. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf");
  69. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf");
  70. //IM_ASSERT(font != nullptr);
  71. return self;
  72. }
  73. -(MTKView *)mtkView
  74. {
  75. return (MTKView *)self.view;
  76. }
  77. -(void)loadView
  78. {
  79. self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 720)];
  80. }
  81. -(void)viewDidLoad
  82. {
  83. [super viewDidLoad];
  84. self.mtkView.device = self.device;
  85. self.mtkView.delegate = self;
  86. #if TARGET_OS_OSX
  87. ImGui_ImplOSX_Init(self.view);
  88. [NSApp activateIgnoringOtherApps:YES];
  89. #endif
  90. }
  91. -(void)drawInMTKView:(MTKView*)view
  92. {
  93. ImGuiIO& io = ImGui::GetIO();
  94. io.DisplaySize.x = view.bounds.size.width;
  95. io.DisplaySize.y = view.bounds.size.height;
  96. #if TARGET_OS_OSX
  97. CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor;
  98. #else
  99. CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale;
  100. #endif
  101. io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale);
  102. id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
  103. MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor;
  104. if (renderPassDescriptor == nil)
  105. {
  106. [commandBuffer commit];
  107. return;
  108. }
  109. // Start the Dear ImGui frame
  110. ImGui_ImplMetal_NewFrame(renderPassDescriptor);
  111. #if TARGET_OS_OSX
  112. ImGui_ImplOSX_NewFrame(view);
  113. #endif
  114. ImGui::NewFrame();
  115. // Our state (make them static = more or less global) as a convenience to keep the example terse.
  116. static bool show_demo_window = true;
  117. static bool show_another_window = false;
  118. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  119. // 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!).
  120. if (show_demo_window)
  121. ImGui::ShowDemoWindow(&show_demo_window);
  122. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  123. {
  124. static float f = 0.0f;
  125. static int counter = 0;
  126. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  127. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  128. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  129. ImGui::Checkbox("Another Window", &show_another_window);
  130. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  131. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  132. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  133. counter++;
  134. ImGui::SameLine();
  135. ImGui::Text("counter = %d", counter);
  136. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  137. ImGui::End();
  138. }
  139. // 3. Show another simple window.
  140. if (show_another_window)
  141. {
  142. 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)
  143. ImGui::Text("Hello from another window!");
  144. if (ImGui::Button("Close Me"))
  145. show_another_window = false;
  146. ImGui::End();
  147. }
  148. // Rendering
  149. ImGui::Render();
  150. ImDrawData* draw_data = ImGui::GetDrawData();
  151. 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);
  152. id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
  153. [renderEncoder pushDebugGroup:@"Dear ImGui rendering"];
  154. ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder);
  155. [renderEncoder popDebugGroup];
  156. [renderEncoder endEncoding];
  157. // Present
  158. [commandBuffer presentDrawable:view.currentDrawable];
  159. [commandBuffer commit];
  160. }
  161. -(void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size
  162. {
  163. }
  164. //-----------------------------------------------------------------------------------
  165. // Input processing
  166. //-----------------------------------------------------------------------------------
  167. #if TARGET_OS_OSX
  168. - (void)viewWillAppear
  169. {
  170. [super viewWillAppear];
  171. self.view.window.delegate = self;
  172. }
  173. - (void)windowWillClose:(NSNotification *)notification
  174. {
  175. ImGui_ImplMetal_Shutdown();
  176. ImGui_ImplOSX_Shutdown();
  177. ImGui::DestroyContext();
  178. }
  179. #else
  180. // This touch mapping is super cheesy/hacky. We treat any touch on the screen
  181. // as if it were a depressed left mouse button, and we don't bother handling
  182. // multitouch correctly at all. This causes the "cursor" to behave very erratically
  183. // when there are multiple active touches. But for demo purposes, single-touch
  184. // interaction actually works surprisingly well.
  185. -(void)updateIOWithTouchEvent:(UIEvent *)event
  186. {
  187. UITouch *anyTouch = event.allTouches.anyObject;
  188. CGPoint touchLocation = [anyTouch locationInView:self.view];
  189. ImGuiIO &io = ImGui::GetIO();
  190. io.AddMouseSourceEvent(ImGuiMouseSource_TouchScreen);
  191. io.AddMousePosEvent(touchLocation.x, touchLocation.y);
  192. BOOL hasActiveTouch = NO;
  193. for (UITouch *touch in event.allTouches)
  194. {
  195. if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled)
  196. {
  197. hasActiveTouch = YES;
  198. break;
  199. }
  200. }
  201. io.AddMouseButtonEvent(0, hasActiveTouch);
  202. }
  203. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  204. -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  205. -(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  206. -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  207. #endif
  208. @end
  209. //-----------------------------------------------------------------------------------
  210. // AppDelegate
  211. //-----------------------------------------------------------------------------------
  212. #if TARGET_OS_OSX
  213. @interface AppDelegate : NSObject <NSApplicationDelegate>
  214. @property (nonatomic, strong) NSWindow *window;
  215. @end
  216. @implementation AppDelegate
  217. -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
  218. {
  219. return YES;
  220. }
  221. -(instancetype)init
  222. {
  223. if (self = [super init])
  224. {
  225. NSViewController *rootViewController = [[AppViewController alloc] initWithNibName:nil bundle:nil];
  226. self.window = [[NSWindow alloc] initWithContentRect:NSZeroRect
  227. styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable
  228. backing:NSBackingStoreBuffered
  229. defer:NO];
  230. self.window.contentViewController = rootViewController;
  231. [self.window center];
  232. [self.window makeKeyAndOrderFront:self];
  233. }
  234. return self;
  235. }
  236. @end
  237. #else
  238. @interface AppDelegate : UIResponder <UIApplicationDelegate>
  239. @property (strong, nonatomic) UIWindow *window;
  240. @end
  241. @implementation AppDelegate
  242. -(BOOL)application:(UIApplication *)application
  243. didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions
  244. {
  245. UIViewController *rootViewController = [[AppViewController alloc] init];
  246. self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
  247. self.window.rootViewController = rootViewController;
  248. [self.window makeKeyAndVisible];
  249. return YES;
  250. }
  251. @end
  252. #endif
  253. //-----------------------------------------------------------------------------------
  254. // Application main() function
  255. //-----------------------------------------------------------------------------------
  256. #if TARGET_OS_OSX
  257. int main(int, const char**)
  258. {
  259. @autoreleasepool
  260. {
  261. [NSApplication sharedApplication];
  262. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  263. AppDelegate *appDelegate = [[AppDelegate alloc] init]; // creates window
  264. [NSApp setDelegate:appDelegate];
  265. [NSApp activateIgnoringOtherApps:YES];
  266. [NSApp run];
  267. }
  268. return 0;
  269. }
  270. #else
  271. int main(int argc, char * argv[])
  272. {
  273. @autoreleasepool
  274. {
  275. return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
  276. }
  277. }
  278. #endif