main.cpp 11 KB

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