main.cpp 14 KB

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