main.cpp 10 KB

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