main.mm 12 KB

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