main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. // Dear ImGui: standalone example application for GLFW + WebGPU
  2. // - Emscripten is supported for publishing on web. See https://emscripten.org.
  3. // - Dawn is used as a WebGPU implementation on desktop.
  4. // Learn about Dear ImGui:
  5. // - FAQ https://dearimgui.com/faq
  6. // - Getting Started https://dearimgui.com/getting-started
  7. // - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
  8. // - Introduction, links and more at the top of imgui.cpp
  9. #include "imgui.h"
  10. #include "imgui_impl_glfw.h"
  11. #include "imgui_impl_wgpu.h"
  12. #include <stdio.h>
  13. #include <GLFW/glfw3.h>
  14. // This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details.
  15. #ifdef __EMSCRIPTEN__
  16. #include <emscripten.h>
  17. #include <emscripten/html5.h>
  18. #include <emscripten/html5_webgpu.h>
  19. #include "../libs/emscripten/emscripten_mainloop_stub.h"
  20. #else
  21. #include <webgpu/webgpu_glfw.h>
  22. #endif
  23. #include <webgpu/webgpu.h>
  24. #include <webgpu/webgpu_cpp.h>
  25. // Data
  26. static WGPUInstance wgpu_instance = nullptr;
  27. static WGPUDevice wgpu_device = nullptr;
  28. static WGPUSurface wgpu_surface = nullptr;
  29. static WGPUTextureFormat wgpu_preferred_fmt = WGPUTextureFormat_RGBA8Unorm;
  30. static WGPUSwapChain wgpu_swap_chain = nullptr;
  31. static int wgpu_surface_width = 1280;
  32. static int wgpu_surface_height = 800;
  33. // Forward declarations
  34. static bool InitWGPU(GLFWwindow* window);
  35. static void ResizeSurface(int width, int height);
  36. static void glfw_error_callback(int error, const char* description)
  37. {
  38. printf("GLFW Error %d: %s\n", error, description);
  39. }
  40. static void wgpu_error_callback(WGPUErrorType error_type, const char* message, void*)
  41. {
  42. const char* error_type_lbl = "";
  43. switch (error_type)
  44. {
  45. case WGPUErrorType_Validation: error_type_lbl = "Validation"; break;
  46. case WGPUErrorType_OutOfMemory: error_type_lbl = "Out of memory"; break;
  47. case WGPUErrorType_Unknown: error_type_lbl = "Unknown"; break;
  48. case WGPUErrorType_DeviceLost: error_type_lbl = "Device lost"; break;
  49. default: error_type_lbl = "Unknown";
  50. }
  51. printf("%s error: %s\n", error_type_lbl, message);
  52. }
  53. // Main code
  54. int main(int, char**)
  55. {
  56. glfwSetErrorCallback(glfw_error_callback);
  57. if (!glfwInit())
  58. return 1;
  59. // Make sure GLFW does not initialize any graphics context.
  60. // This needs to be done explicitly later.
  61. glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
  62. // Create window
  63. float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor()); // Valid on GLFW 3.3+ only
  64. wgpu_surface_width *= main_scale;
  65. wgpu_surface_height *= main_scale;
  66. GLFWwindow* window = glfwCreateWindow(wgpu_surface_width, wgpu_surface_height, "Dear ImGui GLFW+WebGPU example", nullptr, nullptr);
  67. if (window == nullptr)
  68. return 1;
  69. // Initialize the WebGPU environment
  70. if (!InitWGPU(window))
  71. {
  72. glfwDestroyWindow(window);
  73. glfwTerminate();
  74. return 1;
  75. }
  76. ResizeSurface(wgpu_surface_width, wgpu_surface_height);
  77. glfwShowWindow(window);
  78. // Setup Dear ImGui context
  79. IMGUI_CHECKVERSION();
  80. ImGui::CreateContext();
  81. ImGuiIO& io = ImGui::GetIO(); (void)io;
  82. io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
  83. io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
  84. io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
  85. // Setup Dear ImGui style
  86. ImGui::StyleColorsDark();
  87. //ImGui::StyleColorsLight();
  88. // Setup scaling
  89. ImGuiStyle& style = ImGui::GetStyle();
  90. style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
  91. style.FontScaleDpi = main_scale; // Set initial font scale. (using io.ConfigDpiScaleFonts=true makes this unnecessary. We leave both here for documentation purpose)
  92. // Setup Platform/Renderer backends
  93. ImGui_ImplGlfw_InitForOther(window, true);
  94. #ifdef __EMSCRIPTEN__
  95. ImGui_ImplGlfw_InstallEmscriptenCallbacks(window, "#canvas");
  96. #endif
  97. ImGui_ImplWGPU_InitInfo init_info;
  98. init_info.Device = wgpu_device;
  99. init_info.NumFramesInFlight = 3;
  100. init_info.RenderTargetFormat = wgpu_preferred_fmt;
  101. init_info.DepthStencilFormat = WGPUTextureFormat_Undefined;
  102. ImGui_ImplWGPU_Init(&init_info);
  103. // Load Fonts
  104. // - 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.
  105. // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
  106. // - If the file cannot be loaded, the function will return a nullptr. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
  107. // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use Freetype for higher quality font rendering.
  108. // - Read 'docs/FONTS.md' for more instructions and details. If you like the default font but want it to scale better, consider using the 'ProggyVector' from the same author!
  109. // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
  110. // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details.
  111. //style.FontSizeBase = 20.0f;
  112. //io.Fonts->AddFontDefault();
  113. #ifndef IMGUI_DISABLE_FILE_FUNCTIONS
  114. //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf");
  115. //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf");
  116. //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf");
  117. //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf");
  118. //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf");
  119. //IM_ASSERT(font != nullptr);
  120. #endif
  121. // Our state
  122. bool show_demo_window = true;
  123. bool show_another_window = false;
  124. ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
  125. // Main loop
  126. #ifdef __EMSCRIPTEN__
  127. // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
  128. // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
  129. io.IniFilename = nullptr;
  130. EMSCRIPTEN_MAINLOOP_BEGIN
  131. #else
  132. while (!glfwWindowShouldClose(window))
  133. #endif
  134. {
  135. // Poll and handle events (inputs, window resize, etc.)
  136. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
  137. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
  138. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
  139. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
  140. glfwPollEvents();
  141. if (glfwGetWindowAttrib(window, GLFW_ICONIFIED) != 0)
  142. {
  143. ImGui_ImplGlfw_Sleep(10);
  144. continue;
  145. }
  146. // React to changes in screen size
  147. int width, height;
  148. glfwGetFramebufferSize((GLFWwindow*)window, &width, &height);
  149. if (width != wgpu_surface_width || height != wgpu_surface_height)
  150. {
  151. ImGui_ImplWGPU_InvalidateDeviceObjects();
  152. ResizeSurface(width, height);
  153. ImGui_ImplWGPU_CreateDeviceObjects();
  154. }
  155. // Start the Dear ImGui frame
  156. ImGui_ImplWGPU_NewFrame();
  157. ImGui_ImplGlfw_NewFrame();
  158. ImGui::NewFrame();
  159. // 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!).
  160. if (show_demo_window)
  161. ImGui::ShowDemoWindow(&show_demo_window);
  162. // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
  163. {
  164. static float f = 0.0f;
  165. static int counter = 0;
  166. ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
  167. ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
  168. ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
  169. ImGui::Checkbox("Another Window", &show_another_window);
  170. ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
  171. ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
  172. if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
  173. counter++;
  174. ImGui::SameLine();
  175. ImGui::Text("counter = %d", counter);
  176. ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
  177. ImGui::End();
  178. }
  179. // 3. Show another simple window.
  180. if (show_another_window)
  181. {
  182. 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)
  183. ImGui::Text("Hello from another window!");
  184. if (ImGui::Button("Close Me"))
  185. show_another_window = false;
  186. ImGui::End();
  187. }
  188. // Rendering
  189. ImGui::Render();
  190. #ifndef __EMSCRIPTEN__
  191. // Tick needs to be called in Dawn to display validation errors
  192. wgpuDeviceTick(wgpu_device);
  193. #endif
  194. WGPURenderPassColorAttachment color_attachments = {};
  195. color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
  196. color_attachments.loadOp = WGPULoadOp_Clear;
  197. color_attachments.storeOp = WGPUStoreOp_Store;
  198. color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
  199. color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain);
  200. WGPURenderPassDescriptor render_pass_desc = {};
  201. render_pass_desc.colorAttachmentCount = 1;
  202. render_pass_desc.colorAttachments = &color_attachments;
  203. render_pass_desc.depthStencilAttachment = nullptr;
  204. WGPUCommandEncoderDescriptor enc_desc = {};
  205. WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc);
  206. WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
  207. ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass);
  208. wgpuRenderPassEncoderEnd(pass);
  209. WGPUCommandBufferDescriptor cmd_buffer_desc = {};
  210. WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc);
  211. WGPUQueue wgpu_queue = wgpuDeviceGetQueue(wgpu_device);
  212. wgpuQueueSubmit(wgpu_queue, 1, &cmd_buffer);
  213. #ifndef __EMSCRIPTEN__
  214. wgpuSwapChainPresent(wgpu_swap_chain);
  215. #endif
  216. wgpuTextureViewRelease(color_attachments.view);
  217. wgpuRenderPassEncoderRelease(pass);
  218. wgpuCommandEncoderRelease(encoder);
  219. wgpuCommandBufferRelease(cmd_buffer);
  220. }
  221. #ifdef __EMSCRIPTEN__
  222. EMSCRIPTEN_MAINLOOP_END;
  223. #endif
  224. // Cleanup
  225. ImGui_ImplWGPU_Shutdown();
  226. ImGui_ImplGlfw_Shutdown();
  227. ImGui::DestroyContext();
  228. glfwDestroyWindow(window);
  229. glfwTerminate();
  230. return 0;
  231. }
  232. #ifndef __EMSCRIPTEN__
  233. static WGPUAdapter RequestAdapter(WGPUInstance instance)
  234. {
  235. auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* message, void* pUserData)
  236. {
  237. if (status == WGPURequestAdapterStatus_Success)
  238. *(WGPUAdapter*)(pUserData) = adapter;
  239. else
  240. printf("Could not get WebGPU adapter: %s\n", message);
  241. };
  242. WGPUAdapter adapter;
  243. wgpuInstanceRequestAdapter(instance, nullptr, onAdapterRequestEnded, (void*)&adapter);
  244. return adapter;
  245. }
  246. static WGPUDevice RequestDevice(WGPUAdapter& adapter)
  247. {
  248. auto onDeviceRequestEnded = [](WGPURequestDeviceStatus status, WGPUDevice device, const char* message, void* pUserData)
  249. {
  250. if (status == WGPURequestDeviceStatus_Success)
  251. *(WGPUDevice*)(pUserData) = device;
  252. else
  253. printf("Could not get WebGPU device: %s\n", message);
  254. };
  255. WGPUDevice device;
  256. wgpuAdapterRequestDevice(adapter, nullptr, onDeviceRequestEnded, (void*)&device);
  257. return device;
  258. }
  259. #endif
  260. static bool InitWGPU(GLFWwindow* window)
  261. {
  262. wgpu::Instance instance = wgpuCreateInstance(nullptr);
  263. #ifdef __EMSCRIPTEN__
  264. wgpu_device = emscripten_webgpu_get_device();
  265. if (!wgpu_device)
  266. return false;
  267. #else
  268. WGPUAdapter adapter = RequestAdapter(instance.Get());
  269. if (!adapter)
  270. return false;
  271. wgpu_device = RequestDevice(adapter);
  272. #endif
  273. #ifdef __EMSCRIPTEN__
  274. wgpu::SurfaceDescriptorFromCanvasHTMLSelector canvas_desc = {};
  275. canvas_desc.selector = "#canvas";
  276. wgpu::SurfaceDescriptor surface_desc = {};
  277. surface_desc.nextInChain = &canvas_desc;
  278. wgpu::Surface surface = instance.CreateSurface(&surface_desc);
  279. wgpu::Adapter adapter = {};
  280. wgpu_preferred_fmt = (WGPUTextureFormat)surface.GetPreferredFormat(adapter);
  281. #else
  282. wgpu::Surface surface = wgpu::glfw::CreateSurfaceForWindow(instance, window);
  283. if (!surface)
  284. return false;
  285. wgpu_preferred_fmt = WGPUTextureFormat_BGRA8Unorm;
  286. #endif
  287. // Moving Dawn objects into WGPU handles
  288. wgpu_instance = instance.MoveToCHandle();
  289. wgpu_surface = surface.MoveToCHandle();
  290. wgpuDeviceSetUncapturedErrorCallback(wgpu_device, wgpu_error_callback, nullptr);
  291. return true;
  292. }
  293. static void ResizeSurface(int width, int height)
  294. {
  295. if (wgpu_swap_chain)
  296. wgpuSwapChainRelease(wgpu_swap_chain);
  297. wgpu_surface_width = width;
  298. wgpu_surface_height = height;
  299. WGPUSwapChainDescriptor swap_chain_desc = {};
  300. swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment;
  301. swap_chain_desc.format = wgpu_preferred_fmt;
  302. swap_chain_desc.width = width;
  303. swap_chain_desc.height = height;
  304. swap_chain_desc.presentMode = WGPUPresentMode_Fifo;
  305. wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc);
  306. }