main.mm 9.5 KB

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