main.cpp 12 KB

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