main.mm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. // Setup Dear ImGui context
  32. // FIXME: This example doesn't have proper cleanup...
  33. IMGUI_CHECKVERSION();
  34. ImGui::CreateContext();
  35. ImGuiIO& io = ImGui::GetIO(); (void)io;
  36. //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  37. //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  38. io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
  39. io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; // Enable Multi-Viewport / Platform Windows
  40. // Setup Dear ImGui style
  41. ImGui::StyleColorsDark();
  42. //ImGui::StyleColorsLight();
  43. // When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
  44. ImGuiStyle& style = ImGui::GetStyle();
  45. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  46. {
  47. style.WindowRounding = 0.0f;
  48. style.Colors[ImGuiCol_WindowBg].w = 1.0f;
  49. }
  50. // Setup Platform/Renderer backends
  51. ImGui_ImplOSX_Init(self);
  52. ImGui_ImplOpenGL2_Init();
  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. }
  68. -(void)updateAndDrawDemoView
  69. {
  70. // Start the Dear ImGui frame
  71. ImGuiIO& io = ImGui::GetIO();
  72. ImGui_ImplOpenGL2_NewFrame();
  73. ImGui_ImplOSX_NewFrame(self);
  74. ImGui::NewFrame();
  75. // Our state (make them static = more or less global) as a convenience to keep the example terse.
  76. static bool show_demo_window = true;
  77. static bool show_another_window = false;
  78. static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  79. // 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!).
  80. if (show_demo_window)
  81. ImGui::ShowDemoWindow(&show_demo_window);
  82. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
  83. {
  84. static float f = 0.0f;
  85. static int counter = 0;
  86. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  87. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  88. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  89. ImGui::Checkbox("Another Window", &show_another_window);
  90. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  91. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  92. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  93. counter++;
  94. ImGui::SameLine();
  95. ImGui::Text("counter = %d", counter);
  96. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
  97. ImGui::End();
  98. }
  99. // 3. Show another simple window.
  100. if (show_another_window)
  101. {
  102. 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)
  103. ImGui::Text("Hello from another window!");
  104. if (ImGui::Button("Close Me"))
  105. show_another_window = false;
  106. ImGui::End();
  107. }
  108. // Rendering
  109. ImGui::Render();
  110. ImDrawData* draw_data = ImGui::GetDrawData();
  111. [[self openGLContext] makeCurrentContext];
  112. GLsizei width = (GLsizei)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
  113. GLsizei height = (GLsizei)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
  114. glViewport(0, 0, width, height);
  115. glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
  116. glClear(GL_COLOR_BUFFER_BIT);
  117. ImGui_ImplOpenGL2_RenderDrawData(draw_data);
  118. // Update and Render additional Platform Windows
  119. if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
  120. {
  121. ImGui::UpdatePlatformWindows();
  122. ImGui::RenderPlatformWindowsDefault();
  123. }
  124. // Present
  125. [[self openGLContext] flushBuffer];
  126. if (!animationTimer)
  127. animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.017 target:self selector:@selector(animationTimerFired:) userInfo:nil repeats:YES];
  128. }
  129. -(void)reshape { [super reshape]; [[self openGLContext] update]; [self updateAndDrawDemoView]; }
  130. -(void)drawRect:(NSRect)bounds { [self updateAndDrawDemoView]; }
  131. -(void)animationTimerFired:(NSTimer*)timer { [self setNeedsDisplay:YES]; }
  132. -(void)dealloc { animationTimer = nil; }
  133. @end
  134. //-----------------------------------------------------------------------------------
  135. // AppDelegate
  136. //-----------------------------------------------------------------------------------
  137. @interface AppDelegate : NSObject <NSApplicationDelegate>
  138. @property (nonatomic, readonly) NSWindow* window;
  139. @end
  140. @implementation AppDelegate
  141. @synthesize window = _window;
  142. -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
  143. {
  144. return YES;
  145. }
  146. -(NSWindow*)window
  147. {
  148. if (_window != nil)
  149. return (_window);
  150. NSRect viewRect = NSMakeRect(100.0, 100.0, 100.0 + 1280.0, 100 + 720.0);
  151. _window = [[NSWindow alloc] initWithContentRect:viewRect styleMask:NSWindowStyleMaskTitled|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskResizable|NSWindowStyleMaskClosable backing:NSBackingStoreBuffered defer:YES];
  152. [_window setTitle:@"Dear ImGui OSX+OpenGL2 Example"];
  153. [_window setAcceptsMouseMovedEvents:YES];
  154. [_window setOpaque:YES];
  155. [_window makeKeyAndOrderFront:NSApp];
  156. return (_window);
  157. }
  158. -(void)setupMenu
  159. {
  160. NSMenu* mainMenuBar = [[NSMenu alloc] init];
  161. NSMenu* appMenu;
  162. NSMenuItem* menuItem;
  163. appMenu = [[NSMenu alloc] initWithTitle:@"Dear ImGui OSX+OpenGL2 Example"];
  164. menuItem = [appMenu addItemWithTitle:@"Quit Dear ImGui OSX+OpenGL2 Example" action:@selector(terminate:) keyEquivalent:@"q"];
  165. [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagCommand];
  166. menuItem = [[NSMenuItem alloc] init];
  167. [menuItem setSubmenu:appMenu];
  168. [mainMenuBar addItem:menuItem];
  169. appMenu = nil;
  170. [NSApp setMainMenu:mainMenuBar];
  171. }
  172. -(void)dealloc
  173. {
  174. _window = nil;
  175. }
  176. -(void)applicationDidFinishLaunching:(NSNotification *)aNotification
  177. {
  178. // Make the application a foreground application (else it won't receive keyboard events)
  179. ProcessSerialNumber psn = {0, kCurrentProcess};
  180. TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  181. // Menu
  182. [self setupMenu];
  183. NSOpenGLPixelFormatAttribute attrs[] =
  184. {
  185. NSOpenGLPFADoubleBuffer,
  186. NSOpenGLPFADepthSize, 32,
  187. 0
  188. };
  189. NSOpenGLPixelFormat* format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
  190. AppView* view = [[AppView alloc] initWithFrame:self.window.frame pixelFormat:format];
  191. format = nil;
  192. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  193. if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
  194. [view setWantsBestResolutionOpenGLSurface:YES];
  195. #endif // MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  196. [self.window setContentView:view];
  197. if ([view openGLContext] == nil)
  198. NSLog(@"No OpenGL Context!");
  199. [view initialize];
  200. }
  201. @end
  202. //-----------------------------------------------------------------------------------
  203. // Application main() function
  204. //-----------------------------------------------------------------------------------
  205. int main(int argc, const char* argv[])
  206. {
  207. @autoreleasepool
  208. {
  209. NSApp = [NSApplication sharedApplication];
  210. AppDelegate* delegate = [[AppDelegate alloc] init];
  211. [[NSApplication sharedApplication] setDelegate:delegate];
  212. [NSApp run];
  213. }
  214. return NSApplicationMain(argc, argv);
  215. }