• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Dear ImGui: standalone example application for GLFW + Metal, using programmable pipeline
2// (GLFW is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
3// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
4// Read online: https://github.com/ocornut/imgui/tree/master/docs
5
6#include "imgui.h"
7#include "imgui_impl_glfw.h"
8#include "imgui_impl_metal.h"
9#include <stdio.h>
10
11#define GLFW_INCLUDE_NONE
12#define GLFW_EXPOSE_NATIVE_COCOA
13#include <GLFW/glfw3.h>
14#include <GLFW/glfw3native.h>
15
16#import <Metal/Metal.h>
17#import <QuartzCore/QuartzCore.h>
18
19static void glfw_error_callback(int error, const char* description)
20{
21    fprintf(stderr, "Glfw Error %d: %s\n", error, description);
22}
23
24int main(int, char**)
25{
26    // Setup Dear ImGui context
27    IMGUI_CHECKVERSION();
28    ImGui::CreateContext();
29    ImGuiIO& io = ImGui::GetIO(); (void)io;
30    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;  // Enable Keyboard Controls
31    //io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;   // Enable Gamepad Controls
32
33    // Setup style
34    ImGui::StyleColorsDark();
35    //ImGui::StyleColorsClassic();
36
37    // Load Fonts
38    // - 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.
39    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
40    // - 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).
41    // - 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.
42    // - Read 'docs/FONTS.txt' for more instructions and details.
43    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
44    //io.Fonts->AddFontDefault();
45    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
46    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
47    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
48    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
49    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
50    //IM_ASSERT(font != NULL);
51
52    // Setup window
53    glfwSetErrorCallback(glfw_error_callback);
54    if (!glfwInit())
55        return 1;
56
57    // Create window with graphics context
58    glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
59    GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+Metal example", NULL, NULL);
60    if (window == NULL)
61        return 1;
62
63    id <MTLDevice> device = MTLCreateSystemDefaultDevice();
64    id <MTLCommandQueue> commandQueue = [device newCommandQueue];
65
66    // Setup Platform/Renderer backends
67    ImGui_ImplGlfw_InitForOpenGL(window, true);
68    ImGui_ImplMetal_Init(device);
69
70    NSWindow *nswin = glfwGetCocoaWindow(window);
71    CAMetalLayer *layer = [CAMetalLayer layer];
72    layer.device = device;
73    layer.pixelFormat = MTLPixelFormatBGRA8Unorm;
74    nswin.contentView.layer = layer;
75    nswin.contentView.wantsLayer = YES;
76
77    MTLRenderPassDescriptor *renderPassDescriptor = [MTLRenderPassDescriptor new];
78
79    // Our state
80    bool show_demo_window = true;
81    bool show_another_window = false;
82    float clear_color[4] = {0.45f, 0.55f, 0.60f, 1.00f};
83
84    // Main loop
85    while (!glfwWindowShouldClose(window))
86    {
87        @autoreleasepool
88        {
89            // Poll and handle events (inputs, window resize, etc.)
90            // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
91            // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
92            // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
93            // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
94            glfwPollEvents();
95
96            int width, height;
97            glfwGetFramebufferSize(window, &width, &height);
98            layer.drawableSize = CGSizeMake(width, height);
99            id<CAMetalDrawable> drawable = [layer nextDrawable];
100
101            id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
102            renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color[0] * clear_color[3], clear_color[1] * clear_color[3], clear_color[2] * clear_color[3], clear_color[3]);
103            renderPassDescriptor.colorAttachments[0].texture = drawable.texture;
104            renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionClear;
105            renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore;
106            id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
107            [renderEncoder pushDebugGroup:@"ImGui demo"];
108
109            // Start the Dear ImGui frame
110            ImGui_ImplMetal_NewFrame(renderPassDescriptor);
111            ImGui_ImplGlfw_NewFrame();
112            ImGui::NewFrame();
113
114            // 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!).
115            if (show_demo_window)
116                ImGui::ShowDemoWindow(&show_demo_window);
117
118            // 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
119            {
120                static float f = 0.0f;
121                static int counter = 0;
122
123                ImGui::Begin("Hello, world!");                          // Create a window called "Hello, world!" and append into it.
124
125                ImGui::Text("This is some useful text.");               // Display some text (you can use a format strings too)
126                ImGui::Checkbox("Demo Window", &show_demo_window);      // Edit bools storing our window open/close state
127                ImGui::Checkbox("Another Window", &show_another_window);
128
129                ImGui::SliderFloat("float", &f, 0.0f, 1.0f);            // Edit 1 float using a slider from 0.0f to 1.0f
130                ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
131
132                if (ImGui::Button("Button"))                            // Buttons return true when clicked (most widgets return true when edited/activated)
133                    counter++;
134                ImGui::SameLine();
135                ImGui::Text("counter = %d", counter);
136
137                ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
138                ImGui::End();
139            }
140
141            // 3. Show another simple window.
142            if (show_another_window)
143            {
144                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)
145                ImGui::Text("Hello from another window!");
146                if (ImGui::Button("Close Me"))
147                    show_another_window = false;
148                ImGui::End();
149            }
150
151            // Rendering
152            ImGui::Render();
153            ImGui_ImplMetal_RenderDrawData(ImGui::GetDrawData(), commandBuffer, renderEncoder);
154
155            [renderEncoder popDebugGroup];
156            [renderEncoder endEncoding];
157
158            [commandBuffer presentDrawable:drawable];
159            [commandBuffer commit];
160        }
161    }
162
163    // Cleanup
164    ImGui_ImplMetal_Shutdown();
165    ImGui_ImplGlfw_Shutdown();
166    ImGui::DestroyContext();
167
168    glfwDestroyWindow(window);
169    glfwTerminate();
170
171    return 0;
172}
173