main.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // Dear ImGui: standalone example application for OSX + Metal.
  2. // If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
  3. // Read online: https://github.com/ocornut/imgui/tree/master/docs
  4. #import <Foundation/Foundation.h>
  5. #if TARGET_OS_OSX
  6. #import <Cocoa/Cocoa.h>
  7. #else
  8. #import <UIKit/UIKit.h>
  9. #endif
  10. #import <Metal/Metal.h>
  11. #import <MetalKit/MetalKit.h>
  12. #include "imgui.h"
  13. #include "imgui_impl_metal.h"
  14. #if TARGET_OS_OSX
  15. #include "imgui_impl_osx.h"
  16. @interface AppViewController : NSViewController
  17. @end
  18. #else
  19. @interface AppViewController : UIViewController
  20. @end
  21. #endif
  22. @interface AppViewController () <MTKViewDelegate>
  23. @property (nonatomic, readonly) MTKView *mtkView;
  24. @property (nonatomic, strong) id <MTLDevice> device;
  25. @property (nonatomic, strong) id <MTLCommandQueue> commandQueue;
  26. @end
  27. //-----------------------------------------------------------------------------------
  28. // AppViewController
  29. //-----------------------------------------------------------------------------------
  30. @implementation AppViewController
  31. -(instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil
  32. {
  33. self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
  34. _device = MTLCreateSystemDefaultDevice();
  35. _commandQueue = [_device newCommandQueue];
  36. if (!self.device)
  37. {
  38. NSLog(@"Metal is not supported");
  39. abort();
  40. }
  41. // Setup Dear ImGui context
  42. // FIXME: This example doesn't have proper cleanup...
  43. IMGUI_CHECKVERSION();
  44. ImGui::CreateContext();
  45. ImGuiIO& io = ImGui::GetIO(); (void)io;
  46. //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  47. //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  48. // Setup Dear ImGui style
  49. ImGui::StyleColorsDark();
  50. //ImGui::StyleColorsClassic();
  51. // Setup Renderer backend
  52. ImGui_ImplMetal_Init(_device);
  53. // Load Fonts
  54. // - 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.
  55. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  56. // - 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).
  57. // - 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.
  58. // - Read 'docs/FONTS.txt' for more instructions and details.
  59. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  60. //io.Fonts->AddFontDefault();
  61. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
  62. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
  63. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
  64. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
  65. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
  66. //IM_ASSERT(font != NULL);
  67. return self;
  68. }
  69. -(MTKView *)mtkView
  70. {
  71. return (MTKView *)self.view;
  72. }
  73. -(void)loadView
  74. {
  75. self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 720)];
  76. }
  77. -(void)viewDidLoad
  78. {
  79. [super viewDidLoad];
  80. self.mtkView.device = self.device;
  81. self.mtkView.delegate = self;
  82. #if TARGET_OS_OSX
  83. // Add a tracking area in order to receive mouse events whenever the mouse is within the bounds of our view
  84. NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect
  85. options:NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingActiveAlways
  86. owner:self
  87. userInfo:nil];
  88. [self.view addTrackingArea:trackingArea];
  89. // If we want to receive key events, we either need to be in the responder chain of the key view,
  90. // or else we can install a local monitor. The consequence of this heavy-handed approach is that
  91. // we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our
  92. // window, we'd want to be much more careful than just ingesting the complete event stream.
  93. // To match the behavior of other backends, we pass every event down to the OS.
  94. NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged;
  95. [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event)
  96. {
  97. ImGui_ImplOSX_HandleEvent(event, self.view);
  98. return event;
  99. }];
  100. ImGui_ImplOSX_Init();
  101. #endif
  102. }
  103. -(void)drawInMTKView:(MTKView*)view
  104. {
  105. ImGuiIO& io = ImGui::GetIO();
  106. io.DisplaySize.x = view.bounds.size.width;
  107. io.DisplaySize.y = view.bounds.size.height;
  108. #if TARGET_OS_OSX
  109. CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor;
  110. #else
  111. CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale;
  112. #endif
  113. io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale);
  114. io.DeltaTime = 1 / float(view.preferredFramesPerSecond ?: 60);
  115. id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
  116. MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor;
  117. if (renderPassDescriptor == nil)
  118. {
  119. [commandBuffer commit];
  120. return;
  121. }
  122. // Start the Dear ImGui frame
  123. ImGui_ImplMetal_NewFrame(renderPassDescriptor);
  124. #if TARGET_OS_OSX
  125. ImGui_ImplOSX_NewFrame(view);
  126. #endif
  127. ImGui::NewFrame();
  128. // Our state (make them static = more or less global) as a convenience to keep the example terse.
  129. static bool show_demo_window = true;
  130. static bool show_another_window = false;
  131. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  132. // 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!).
  133. if (show_demo_window)
  134. ImGui::ShowDemoWindow(&show_demo_window);
  135. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
  136. {
  137. static float f = 0.0f;
  138. static int counter = 0;
  139. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  140. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  141. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  142. ImGui::Checkbox("Another Window", &show_another_window);
  143. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  144. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  145. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  146. counter++;
  147. ImGui::SameLine();
  148. ImGui::Text("counter = %d", counter);
  149. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  150. ImGui::End();
  151. }
  152. // 3. Show another simple window.
  153. if (show_another_window)
  154. {
  155. 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)
  156. ImGui::Text("Hello from another window!");
  157. if (ImGui::Button("Close Me"))
  158. show_another_window = false;
  159. ImGui::End();
  160. }
  161. // Rendering
  162. ImGui::Render();
  163. ImDrawData* draw_data = ImGui::GetDrawData();
  164. 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);
  165. id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
  166. [renderEncoder pushDebugGroup:@"Dear ImGui rendering"];
  167. ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder);
  168. [renderEncoder popDebugGroup];
  169. [renderEncoder endEncoding];
  170. // Present
  171. [commandBuffer presentDrawable:view.currentDrawable];
  172. [commandBuffer commit];
  173. }
  174. -(void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size
  175. {
  176. }
  177. //-----------------------------------------------------------------------------------
  178. // Input processing
  179. //-----------------------------------------------------------------------------------
  180. #if TARGET_OS_OSX
  181. // Forward Mouse/Keyboard events to Dear ImGui OSX backend.
  182. // Other events are registered via addLocalMonitorForEventsMatchingMask()
  183. -(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  184. -(void)rightMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  185. -(void)otherMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  186. -(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  187. -(void)rightMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  188. -(void)otherMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  189. -(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  190. -(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  191. -(void)rightMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  192. -(void)rightMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  193. -(void)otherMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  194. -(void)otherMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  195. -(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
  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.MousePos = ImVec2(touchLocation.x, touchLocation.y);
  208. BOOL hasActiveTouch = NO;
  209. for (UITouch *touch in event.allTouches)
  210. {
  211. if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled)
  212. {
  213. hasActiveTouch = YES;
  214. break;
  215. }
  216. }
  217. io.MouseDown[0] = hasActiveTouch;
  218. }
  219. -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  220. -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  221. -(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  222. -(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
  223. #endif
  224. @end
  225. //-----------------------------------------------------------------------------------
  226. // AppDelegate
  227. //-----------------------------------------------------------------------------------
  228. #if TARGET_OS_OSX
  229. @interface AppDelegate : NSObject <NSApplicationDelegate>
  230. @property (nonatomic, strong) NSWindow *window;
  231. @end
  232. @implementation AppDelegate
  233. -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
  234. {
  235. return YES;
  236. }
  237. -(instancetype)init
  238. {
  239. if (self = [super init])
  240. {
  241. NSViewController *rootViewController = [[AppViewController alloc] initWithNibName:nil bundle:nil];
  242. self.window = [[NSWindow alloc] initWithContentRect:NSZeroRect
  243. styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable
  244. backing:NSBackingStoreBuffered
  245. defer:NO];
  246. self.window.contentViewController = rootViewController;
  247. [self.window orderFront:self];
  248. [self.window center];
  249. [self.window becomeKeyWindow];
  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 argc, const char * argv[])
  275. {
  276. return NSApplicationMain(argc, argv);
  277. }
  278. #else
  279. int main(int argc, char * argv[])
  280. {
  281. @autoreleasepool
  282. {
  283. return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
  284. }
  285. }
  286. #endif