main.mm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // Dear ImGui: standalone example application for OSX + OpenGL2, using legacy fixed pipeline
  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 <Cocoa/Cocoa.h>
  5. #import <OpenGL/gl.h>
  6. #import <OpenGL/glu.h>
  7. #include "imgui.h"
  8. #include "imgui_impl_opengl2.h"
  9. #include "imgui_impl_osx.h"
  10. //-----------------------------------------------------------------------------------
  11. // AppView
  12. //-----------------------------------------------------------------------------------
  13. @interface AppView : NSOpenGLView
  14. {
  15. NSTimer* animationTimer;
  16. }
  17. @end
  18. @implementation AppView
  19. -(void)prepareOpenGL
  20. {
  21. [super prepareOpenGL];
  22. #ifndef DEBUG
  23. GLint swapInterval = 1;
  24. [[self openGLContext] setValues:&swapInterval forParameter:NSOpenGLCPSwapInterval];
  25. if (swapInterval == 0)
  26. NSLog(@"Error: Cannot set swap interval.");
  27. #endif
  28. }
  29. -(void)initialize
  30. {
  31. // Some events do not raise callbacks of AppView in some circumstances (for example when CMD key is held down).
  32. // This monitor taps into global event stream and captures these events.
  33. NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged;
  34. [NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event)
  35. {
  36. ImGui_ImplOSX_HandleEvent(event, self);
  37. return event;
  38. }];
  39. // Setup Dear ImGui context
  40. // FIXME: This example doesn't have proper cleanup...
  41. IMGUI_CHECKVERSION();
  42. ImGui::CreateContext();
  43. ImGuiIO& io = ImGui::GetIO(); (void)io;
  44. //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  45. //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  46. // Setup Dear ImGui style
  47. ImGui::StyleColorsDark();
  48. //ImGui::StyleColorsClassic();
  49. // Setup Platform/Renderer backends
  50. ImGui_ImplOSX_Init();
  51. ImGui_ImplOpenGL2_Init();
  52. // Load Fonts
  53. // - 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.
  54. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  55. // - 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).
  56. // - 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.
  57. // - Read 'docs/FONTS.txt' for more instructions and details.
  58. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  59. //io.Fonts->AddFontDefault();
  60. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
  61. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
  62. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
  63. //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
  64. //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
  65. //IM_ASSERT(font != NULL);
  66. }
  67. -(void)updateAndDrawDemoView
  68. {
  69. // Start the Dear ImGui frame
  70. ImGui_ImplOpenGL2_NewFrame();
  71. ImGui_ImplOSX_NewFrame(self);
  72. ImGui::NewFrame();
  73. // Our state (make them static = more or less global) as a convenience to keep the example terse.
  74. static bool show_demo_window = true;
  75. static bool show_another_window = false;
  76. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  77. // 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!).
  78. if (show_demo_window)
  79. ImGui::ShowDemoWindow(&show_demo_window);
  80. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
  81. {
  82. static float f = 0.0f;
  83. static int counter = 0;
  84. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  85. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  86. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  87. ImGui::Checkbox("Another Window", &show_another_window);
  88. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  89. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  90. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  91. counter++;
  92. ImGui::SameLine();
  93. ImGui::Text("counter = %d", counter);
  94. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  95. ImGui::End();
  96. }
  97. // 3. Show another simple window.
  98. if (show_another_window)
  99. {
  100. 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)
  101. ImGui::Text("Hello from another window!");
  102. if (ImGui::Button("Close Me"))
  103. show_another_window = false;
  104. ImGui::End();
  105. }
  106. // Rendering
  107. ImGui::Render();
  108. ImDrawData* draw_data = ImGui::GetDrawData();
  109. [[self openGLContext] makeCurrentContext];
  110. GLsizei width = (GLsizei)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  111. GLsizei height = (GLsizei)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  112. glViewport(0, 0, width, height);
  113. glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
  114. glClear(GL_COLOR_BUFFER_BIT);
  115. ImGui_ImplOpenGL2_RenderDrawData(draw_data);
  116. // Present
  117. [[self openGLContext] flushBuffer];
  118. if (!animationTimer)
  119. animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.017 target:self selector:@selector(animationTimerFired:) userInfo:nil repeats:YES];
  120. }
  121. -(void)reshape { [[self openGLContext] update]; [self updateAndDrawDemoView]; }
  122. -(void)drawRect:(NSRect)bounds { [self updateAndDrawDemoView]; }
  123. -(void)animationTimerFired:(NSTimer*)timer { [self setNeedsDisplay:YES]; }
  124. -(BOOL)acceptsFirstResponder { return (YES); }
  125. -(BOOL)becomeFirstResponder { return (YES); }
  126. -(BOOL)resignFirstResponder { return (YES); }
  127. -(void)dealloc { animationTimer = nil; }
  128. //-----------------------------------------------------------------------------------
  129. // Input processing
  130. //-----------------------------------------------------------------------------------
  131. // Forward Mouse/Keyboard events to Dear ImGui OSX backend.
  132. // Other events are registered via addLocalMonitorForEventsMatchingMask()
  133. -(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  134. -(void)rightMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  135. -(void)otherMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  136. -(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  137. -(void)rightMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  138. -(void)otherMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  139. -(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  140. -(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  141. -(void)rightMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  142. -(void)rightMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  143. -(void)otherMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  144. -(void)otherMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  145. -(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self); }
  146. @end
  147. //-----------------------------------------------------------------------------------
  148. // AppDelegate
  149. //-----------------------------------------------------------------------------------
  150. @interface AppDelegate : NSObject <NSApplicationDelegate>
  151. @property (nonatomic, readonly) NSWindow* window;
  152. @end
  153. @implementation AppDelegate
  154. @synthesize window = _window;
  155. -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
  156. {
  157. return YES;
  158. }
  159. -(NSWindow*)window
  160. {
  161. if (_window != nil)
  162. return (_window);
  163. NSRect viewRect = NSMakeRect(100.0, 100.0, 100.0 + 1280.0, 100 + 720.0);
  164. _window = [[NSWindow alloc] initWithContentRect:viewRect styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable|NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:YES];
  165. [_window setTitle:@"Dear ImGui OSX+OpenGL2 Example"];
  166. [_window setAcceptsMouseMovedEvents:YES];
  167. [_window setOpaque:YES];
  168. [_window makeKeyAndOrderFront:NSApp];
  169. return (_window);
  170. }
  171. -(void)setupMenu
  172. {
  173. NSMenu* mainMenuBar = [[NSMenu alloc] init];
  174. NSMenu* appMenu;
  175. NSMenuItem* menuItem;
  176. appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"];
  177. menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL2 Example" action:@selector(terminate:) keyEquivalent:@"q"];
  178. [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand];
  179. menuItem = [[NSMenuItem alloc] init];
  180. [menuItem setSubmenu:appMenu];
  181. [mainMenuBar addItem:menuItem];
  182. appMenu = nil;
  183. [NSApp setMainMenu:mainMenuBar];
  184. }
  185. -(void)dealloc
  186. {
  187. _window = nil;
  188. }
  189. -(void)applicationDidFinishLaunching:(NSNotification *)aNotification
  190. {
  191. // Make the application a foreground application (else it won't receive keyboard events)
  192. ProcessSerialNumber psn = {0, kCurrentProcess};
  193. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  194. // Menu
  195. [self setupMenu];
  196. NSOpenGLPixelFormatAttribute attrs[] =
  197. {
  198. NSOpenGLPFADoubleBuffer,
  199. NSOpenGLPFADepthSize, 32,
  200. 0
  201. };
  202. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
  203. AppView* view = [[AppView alloc] initWithFrame:self.window.frame pixelFormat:format];
  204. format = nil;
  205. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  206. if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
  207. [view setWantsBestResolutionOpenGLSurface:YES];
  208. #endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  209. [self.window setContentView:view];
  210. if ([view openGLContext] == nil)
  211. NSLog(@"No OpenGL Context!");
  212. [view initialize];
  213. }
  214. @end
  215. //-----------------------------------------------------------------------------------
  216. // Application main() function
  217. //-----------------------------------------------------------------------------------
  218. int main(int argc, const char* argv[])
  219. {
  220. @autoreleasepool
  221. {
  222. NSApp = [NSApplication sharedApplication];
  223. AppDelegate* delegate = [[AppDelegate alloc] init];
  224. [[NSApplication sharedApplication] setDelegate:delegate];
  225. [NSApp run];
  226. }
  227. return NSApplicationMain(argc, argv);
  228. }