22.5 KB、526行 生 Blame 履歴
1// Dear ImGui: standalone example application for using SDL2 + WebGPU
2// - Emscripten is supported for publishing on web. See https://emscripten.org.
3// - Dawn is used as a WebGPU implementation on desktop.
4
5// Learn about Dear ImGui:
6// - FAQ https://dearimgui.com/faq
7// - Getting Started https://dearimgui.com/getting-started
8// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
9// - Introduction, links and more at the top of imgui.cpp
10
11#include "imgui.h"
12#include "imgui_impl_sdl2.h"
13#include "imgui_impl_wgpu.h"
14#include <stdio.h>
15#include <SDL.h>
16
17// This example can also compile and run with Emscripten! See 'Makefile.emscripten' for details.
18#ifdef __EMSCRIPTEN__
19#include <emscripten.h>
20#include <emscripten/html5.h>
21#include "../libs/emscripten/emscripten_mainloop_stub.h"
22#endif
23
24#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
25#include <webgpu/webgpu_cpp.h>
26#endif
27
28// Data
29static WGPUInstance wgpu_instance = nullptr;
30static WGPUDevice wgpu_device = nullptr;
31static WGPUSurface wgpu_surface = nullptr;
32static WGPUQueue wgpu_queue = nullptr;
33static WGPUSurfaceConfiguration wgpu_surface_configuration = {};
34static int wgpu_surface_width = 1280;
35static int wgpu_surface_height = 800;
36
37// Forward declarations
38static bool InitWGPU(SDL_Window* window);
39WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window);
40
41static void ResizeSurface(int width, int height)
42{
43 wgpu_surface_configuration.width = wgpu_surface_width = width;
44 wgpu_surface_configuration.height = wgpu_surface_height = height;
45 wgpuSurfaceConfigure(wgpu_surface, (WGPUSurfaceConfiguration*)&wgpu_surface_configuration);
46}
47
48// Main code
49int main(int, char**)
50{
51 // Setup SDL
52 SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMECONTROLLER);
53
54 // Create window with graphics context
55 float main_scale = ImGui_ImplSDL2_GetContentScaleForDisplay(0);
56 wgpu_surface_width = (int)(wgpu_surface_width * main_scale);
57 wgpu_surface_height = (int)(wgpu_surface_height * main_scale);
58 SDL_WindowFlags window_flags = (SDL_WindowFlags)(SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
59 SDL_Window* window = SDL_CreateWindow("Dear ImGui SDL2+WebGPU example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, wgpu_surface_width, wgpu_surface_height, window_flags);
60 if (window == nullptr)
61 {
62 printf("Error: SDL_CreateWindow(): %s\n", SDL_GetError());
63 return 1;
64 }
65
66 // Initialize WGPU
67 InitWGPU(window);
68
69 // Setup Dear ImGui context
70 IMGUI_CHECKVERSION();
71 ImGui::CreateContext();
72 ImGuiIO& io = ImGui::GetIO(); (void)io;
73 io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
74 io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
75
76 // Setup Dear ImGui style
77 ImGui::StyleColorsDark();
78 //ImGui::StyleColorsLight();
79
80 // Setup scaling
81 ImGuiStyle& style = ImGui::GetStyle();
82 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)
83 style.FontScaleDpi = main_scale; // Set initial font scale. (in docking branch: using io.ConfigDpiScaleFonts=true automatically overrides this for every window depending on the current monitor)
84
85 // Setup Platform/Renderer backends
86 ImGui_ImplSDL2_InitForOther(window);
87 ImGui_ImplWGPU_InitInfo init_info;
88 init_info.Device = wgpu_device;
89 init_info.NumFramesInFlight = 3;
90 init_info.RenderTargetFormat = wgpu_surface_configuration.format;
91 init_info.DepthStencilFormat = WGPUTextureFormat_Undefined;
92 ImGui_ImplWGPU_Init(&init_info);
93
94 // Load Fonts
95 // - If fonts are not explicitly loaded, Dear ImGui will select an embedded font: either AddFontDefaultVector() or AddFontDefaultBitmap().
96 // This selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold.
97 // - You can load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
98 // - If a file cannot be loaded, AddFont functions will return a nullptr. Please handle those errors in your code (e.g. use an assertion, display an error and quit).
99 // - Read 'docs/FONTS.md' for more instructions and details.
100 // - Use '#define IMGUI_ENABLE_FREETYPE' in your imconfig file to use FreeType for higher quality font rendering.
101 // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
102 // - Our Emscripten build process allows embedding fonts to be accessible at runtime from the "fonts/" folder. See Makefile.emscripten for details.
103 //style.FontSizeBase = 20.0f;
104 //io.Fonts->AddFontDefaultVector();
105 //io.Fonts->AddFontDefaultBitmap();
106#ifndef IMGUI_DISABLE_FILE_FUNCTIONS
107 //io.Fonts->AddFontFromFileTTF("fonts/segoeui.ttf");
108 //io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf");
109 //io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf");
110 //io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf");
111 //ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf");
112 //IM_ASSERT(font != nullptr);
113#endif
114
115 // Our state
116 bool show_demo_window = true;
117 bool show_another_window = false;
118 ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
119
120 // Main loop
121 bool done = false;
122#ifdef __EMSCRIPTEN__
123 // For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
124 // You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
125 io.IniFilename = nullptr;
126 EMSCRIPTEN_MAINLOOP_BEGIN
127#else
128 while (!done)
129#endif
130 {
131 // Poll and handle events (inputs, window resize, etc.)
132 // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
133 // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
134 // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
135 // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
136 SDL_Event event;
137 while (SDL_PollEvent(&event))
138 {
139 ImGui_ImplSDL2_ProcessEvent(&event);
140 if (event.type == SDL_QUIT)
141 done = true;
142 if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_CLOSE && event.window.windowID == SDL_GetWindowID(window))
143 done = true;
144 }
145
146 // React to changes in screen size
147 int width, height;
148 SDL_GetWindowSizeInPixels(window, &width, &height);
149 if (width != wgpu_surface_width || height != wgpu_surface_height)
150 ResizeSurface(width, height);
151
152 // Check surface status for error. If texture is not optimal, try to reconfigure the surface.
153 WGPUSurfaceTexture surface_texture;
154 wgpuSurfaceGetCurrentTexture(wgpu_surface, &surface_texture);
155 if (ImGui_ImplWGPU_IsSurfaceStatusError(surface_texture.status))
156 {
157 fprintf(stderr, "Unrecoverable Surface Texture status=%#.8x\n", surface_texture.status);
158 abort();
159 }
160 if (ImGui_ImplWGPU_IsSurfaceStatusSubOptimal(surface_texture.status))
161 {
162 if (surface_texture.texture)
163 wgpuTextureRelease(surface_texture.texture);
164 if (width > 0 && height > 0)
165 ResizeSurface(width, height);
166 continue;
167 }
168
169 // Start the Dear ImGui frame
170 ImGui_ImplWGPU_NewFrame();
171 ImGui_ImplSDL2_NewFrame();
172 ImGui::NewFrame();
173
174 // 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!).
175 if (show_demo_window)
176 ImGui::ShowDemoWindow(&show_demo_window);
177
178 // 2. Show a simple window that we create ourselves. We use a Begin/End pair to create a named window.
179 {
180 static float f = 0.0f;
181 static int counter = 0;
182
183 ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
184
185 ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
186 ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
187 ImGui::Checkbox("Another Window", &show_another_window);
188
189 ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
190 ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
191
192 if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
193 counter++;
194 ImGui::SameLine();
195 ImGui::Text("counter = %d", counter);
196
197 ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
198 ImGui::End();
199 }
200
201 // 3. Show another simple window.
202 if (show_another_window)
203 {
204 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)
205 ImGui::Text("Hello from another window!");
206 if (ImGui::Button("Close Me"))
207 show_another_window = false;
208 ImGui::End();
209 }
210
211 // Rendering
212 ImGui::Render();
213
214 WGPUTextureViewDescriptor view_desc = {};
215 view_desc.format = wgpu_surface_configuration.format;
216 view_desc.dimension = WGPUTextureViewDimension_2D;
217 view_desc.mipLevelCount = WGPU_MIP_LEVEL_COUNT_UNDEFINED;
218 view_desc.arrayLayerCount = WGPU_ARRAY_LAYER_COUNT_UNDEFINED;
219 view_desc.aspect = WGPUTextureAspect_All;
220
221 WGPUTextureView texture_view = wgpuTextureCreateView(surface_texture.texture, &view_desc);
222
223 WGPURenderPassColorAttachment color_attachments = {};
224 color_attachments.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
225 color_attachments.loadOp = WGPULoadOp_Clear;
226 color_attachments.storeOp = WGPUStoreOp_Store;
227 color_attachments.clearValue = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
228 color_attachments.view = texture_view;
229
230 WGPURenderPassDescriptor render_pass_desc = {};
231 render_pass_desc.colorAttachmentCount = 1;
232 render_pass_desc.colorAttachments = &color_attachments;
233 render_pass_desc.depthStencilAttachment = nullptr;
234
235 WGPUCommandEncoderDescriptor enc_desc = {};
236 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc);
237
238 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
239 ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass);
240 wgpuRenderPassEncoderEnd(pass);
241
242 WGPUCommandBufferDescriptor cmd_buffer_desc = {};
243 WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc);
244 wgpuQueueSubmit(wgpu_queue, 1, &cmd_buffer);
245
246#ifndef __EMSCRIPTEN__
247 wgpuSurfacePresent(wgpu_surface);
248 // Tick needs to be called in Dawn to display validation errors
249#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
250 wgpuDeviceTick(wgpu_device);
251#endif
252#endif
253 wgpuTextureViewRelease(texture_view);
254 wgpuRenderPassEncoderRelease(pass);
255 wgpuCommandEncoderRelease(encoder);
256 wgpuCommandBufferRelease(cmd_buffer);
257 }
258#ifdef __EMSCRIPTEN__
259 EMSCRIPTEN_MAINLOOP_END;
260#endif
261
262 // Cleanup
263 ImGui_ImplWGPU_Shutdown();
264 ImGui_ImplSDL2_Shutdown();
265 ImGui::DestroyContext();
266
267 wgpuSurfaceUnconfigure(wgpu_surface);
268 wgpuSurfaceRelease(wgpu_surface);
269 wgpuQueueRelease(wgpu_queue);
270 wgpuDeviceRelease(wgpu_device);
271 wgpuInstanceRelease(wgpu_instance);
272
273 SDL_DestroyWindow(window);
274 SDL_Quit();
275
276 return 0;
277}
278
279#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
280static WGPUAdapter RequestAdapter(wgpu::Instance& instance)
281{
282 wgpu::Adapter acquired_adapter;
283 wgpu::RequestAdapterOptions adapter_options;
284 auto onRequestAdapter = [&](wgpu::RequestAdapterStatus status, wgpu::Adapter adapter, wgpu::StringView message)
285 {
286 if (status != wgpu::RequestAdapterStatus::Success)
287 {
288 printf("Failed to get an adapter: %s\n", message.data);
289 return;
290 }
291 acquired_adapter = std::move(adapter);
292 };
293
294 // Synchronously (wait until) acquire Adapter
295 wgpu::Future waitAdapterFunc { instance.RequestAdapter(&adapter_options, wgpu::CallbackMode::WaitAnyOnly, onRequestAdapter) };
296 wgpu::WaitStatus waitStatusAdapter = instance.WaitAny(waitAdapterFunc, UINT64_MAX);
297 IM_ASSERT(acquired_adapter != nullptr && waitStatusAdapter == wgpu::WaitStatus::Success && "Error on Adapter request");
298 return acquired_adapter.MoveToCHandle();
299}
300
301static WGPUDevice RequestDevice(wgpu::Instance& instance, wgpu::Adapter& adapter)
302{
303 // Set device callback functions
304 wgpu::DeviceDescriptor device_desc;
305 device_desc.SetDeviceLostCallback(wgpu::CallbackMode::AllowSpontaneous,
306 [](const wgpu::Device&, wgpu::DeviceLostReason type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetDeviceLostReasonName((WGPUDeviceLostReason)type), msg.data); }
307 );
308 device_desc.SetUncapturedErrorCallback(
309 [](const wgpu::Device&, wgpu::ErrorType type, wgpu::StringView msg) { fprintf(stderr, "%s error: %s\n", ImGui_ImplWGPU_GetErrorTypeName((WGPUErrorType)type), msg.data); }
310 );
311
312 wgpu::Device acquired_device;
313 auto onRequestDevice = [&](wgpu::RequestDeviceStatus status, wgpu::Device local_device, wgpu::StringView message)
314 {
315 if (status != wgpu::RequestDeviceStatus::Success)
316 {
317 printf("Failed to get an device: %s\n", message.data);
318 return;
319 }
320 acquired_device = std::move(local_device);
321 };
322
323 // Synchronously (wait until) get Device
324 wgpu::Future waitDeviceFunc { adapter.RequestDevice(&device_desc, wgpu::CallbackMode::WaitAnyOnly, onRequestDevice) };
325 wgpu::WaitStatus waitStatusDevice = instance.WaitAny(waitDeviceFunc, UINT64_MAX);
326 IM_ASSERT(acquired_device != nullptr && waitStatusDevice == wgpu::WaitStatus::Success && "Error on Device request");
327 return acquired_device.MoveToCHandle();
328}
329#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK)
330static void handle_request_adapter(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView message, void* userdata1, void* userdata2)
331{
332 IM_UNUSED(userdata2);
333 if (status == WGPURequestAdapterStatus_Success)
334 {
335 WGPUAdapter* extAdapter = (WGPUAdapter*)userdata1;
336 *extAdapter = adapter;
337 }
338 else
339 {
340 printf("Request_adapter status=%#.8x message=%.*s\n", status, (int)message.length, message.data);
341 }
342}
343
344static void handle_request_device(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView message, void* userdata1, void* userdata2)
345{
346 IM_UNUSED(userdata2);
347 if (status == WGPURequestDeviceStatus_Success)
348 {
349 WGPUDevice* extDevice = (WGPUDevice*)userdata1;
350 *extDevice = device;
351 }
352 else
353 {
354 printf("Request_device status=%#.8x message=%.*s\n", status, (int)message.length, message.data);
355 }
356}
357
358static WGPUAdapter RequestAdapter(WGPUInstance& instance)
359{
360 WGPURequestAdapterOptions adapter_options = {};
361
362 WGPUAdapter local_adapter = nullptr;
363 WGPURequestAdapterCallbackInfo adapterCallbackInfo = {};
364 adapterCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly;
365 adapterCallbackInfo.callback = handle_request_adapter;
366 adapterCallbackInfo.userdata1 = &local_adapter;
367
368 WGPUFuture future = wgpuInstanceRequestAdapter(instance, &adapter_options, adapterCallbackInfo);
369 WGPUFutureWaitInfo waitInfo = { future, false };
370 wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull);
371 IM_ASSERT(local_adapter && "Error on Adapter request");
372 return local_adapter;
373}
374
375static WGPUDevice RequestDevice(WGPUInstance& instance, WGPUAdapter& adapter)
376{
377 WGPUDevice local_device = nullptr;
378 WGPURequestDeviceCallbackInfo deviceCallbackInfo = {};
379 deviceCallbackInfo.mode = WGPUCallbackMode_WaitAnyOnly;
380 deviceCallbackInfo.callback = handle_request_device;
381 deviceCallbackInfo.userdata1 = &local_device;
382 WGPUFuture future = wgpuAdapterRequestDevice(adapter, nullptr, deviceCallbackInfo);
383 WGPUFutureWaitInfo waitInfo = { future, false };
384 wgpuInstanceWaitAny(instance, 1, &waitInfo, ~0ull);
385 IM_ASSERT(local_device && "Error on Device request");
386 return local_device;
387}
388#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU
389
390static bool InitWGPU(SDL_Window* window)
391{
392 WGPUTextureFormat preferred_fmt = WGPUTextureFormat_Undefined; // acquired from SurfaceCapabilities
393
394 // Google DAWN backend: Adapter and Device acquisition, Surface creation
395#if defined(IMGUI_IMPL_WEBGPU_BACKEND_DAWN)
396 wgpu::InstanceDescriptor instance_desc = {};
397 static constexpr wgpu::InstanceFeatureName timedWaitAny = wgpu::InstanceFeatureName::TimedWaitAny;
398 instance_desc.requiredFeatureCount = 1;
399 instance_desc.requiredFeatures = &timedWaitAny;
400 wgpu::Instance instance = wgpu::CreateInstance(&instance_desc);
401
402 wgpu::Adapter adapter = RequestAdapter(instance);
403 ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter.Get());
404
405 wgpu_device = RequestDevice(instance, adapter);
406
407 // Create the surface.
408#ifdef __EMSCRIPTEN__
409 wgpu::EmscriptenSurfaceSourceCanvasHTMLSelector canvas_desc = {};
410 canvas_desc.selector = "#canvas";
411
412 wgpu::SurfaceDescriptor surface_desc = {};
413 surface_desc.nextInChain = &canvas_desc;
414 wgpu::Surface surface = instance.CreateSurface(&surface_desc);
415#else
416 wgpu::Surface surface = CreateWGPUSurface(instance.Get(), window);
417#endif
418 if (!surface)
419 return false;
420
421 // Moving Dawn objects into WGPU handles
422 wgpu_instance = instance.MoveToCHandle();
423 wgpu_surface = surface.MoveToCHandle();
424
425 WGPUSurfaceCapabilities surface_capabilities = {};
426 wgpuSurfaceGetCapabilities(wgpu_surface, adapter.Get(), &surface_capabilities);
427
428 preferred_fmt = surface_capabilities.formats[0];
429
430 // WGPU backend: Adapter and Device acquisition, Surface creation
431#elif defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU) || defined(IMGUI_IMPL_WEBGPU_BACKEND_WGVK)
432 WGPUInstanceDescriptor instanceDesc = {};
433 WGPUInstanceFeatureName timedWaitAny = WGPUInstanceFeatureName_TimedWaitAny;
434 instanceDesc.requiredFeatureCount = 1;
435 instanceDesc.requiredFeatures = &timedWaitAny;
436 wgpu_instance = wgpuCreateInstance(&instanceDesc);
437
438#if defined(IMGUI_IMPL_WEBGPU_BACKEND_WGPU)
439 wgpuSetLogCallback(
440 [](WGPULogLevel level, WGPUStringView msg, void* userdata) { fprintf(stderr, "%s: %.*s\n", ImGui_ImplWGPU_GetLogLevelName(level), (int)msg.length, msg.data); }, nullptr
441 );
442 wgpuSetLogLevel(WGPULogLevel_Warn);
443#endif
444
445 WGPUAdapter adapter = RequestAdapter(wgpu_instance);
446 ImGui_ImplWGPU_DebugPrintAdapterInfo(adapter);
447
448 wgpu_device = RequestDevice(wgpu_instance, adapter);
449
450 // Create the surface.
451 wgpu_surface = CreateWGPUSurface(wgpu_instance, window);
452 if (!wgpu_surface)
453 return false;
454
455 WGPUSurfaceCapabilities surface_capabilities = {};
456 wgpuSurfaceGetCapabilities(wgpu_surface, adapter, &surface_capabilities);
457
458 preferred_fmt = surface_capabilities.formats[0];
459#endif // IMGUI_IMPL_WEBGPU_BACKEND_WGPU
460
461 wgpu_surface_configuration.presentMode = WGPUPresentMode_Fifo;
462 wgpu_surface_configuration.alphaMode = WGPUCompositeAlphaMode_Auto;
463 wgpu_surface_configuration.usage = WGPUTextureUsage_RenderAttachment;
464 wgpu_surface_configuration.width = wgpu_surface_width;
465 wgpu_surface_configuration.height = wgpu_surface_height;
466 wgpu_surface_configuration.device = wgpu_device;
467 wgpu_surface_configuration.format = preferred_fmt;
468
469 wgpuSurfaceConfigure(wgpu_surface, &wgpu_surface_configuration);
470 wgpu_queue = wgpuDeviceGetQueue(wgpu_device);
471
472 return true;
473}
474
475// SDL2 helper to create a WebGPU surface (exclusively!) for Native/Desktop applications: available only together with WebGPU/WGPU backend
476// As of today (2025/10/31) there is no "official" support in SDL2 to create a surface for WebGPU backend.
477// This stub uses "low level" SDL2 calls to acquire information from a specific Window Manager.
478// Currently supported platforms: Windows / Linux (X11 and Wayland) / MacOS. Not necessary nor available with EMSCRIPTEN.
479#ifndef __EMSCRIPTEN__
480
481#include <SDL_syswm.h>
482#undef Status // X11 headers are leaking this and also 'Success', 'Always', 'None', all used in DAWN api. Add #undef if necessary.
483
484WGPUSurface CreateWGPUSurface(const WGPUInstance& instance, SDL_Window* window)
485{
486 SDL_SysWMinfo sysWMInfo;
487 SDL_VERSION(&sysWMInfo.version);
488 SDL_GetWindowWMInfo(window, &sysWMInfo);
489
490 ImGui_ImplWGPU_CreateSurfaceInfo create_info = {};
491 create_info.Instance = instance;
492#if defined(SDL_VIDEO_DRIVER_COCOA)
493 {
494 create_info.System = "cocoa";
495 create_info.RawWindow = (void*)sysWMInfo.info.cocoa.window;
496 return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info);
497 }
498#elif defined(SDL_VIDEO_DRIVER_WAYLAND) || defined(SDL_VIDEO_DRIVER_X11)
499 const char* sdl_driver = SDL_GetCurrentVideoDriver();
500 if (sdl_driver && strcmp(sdl_driver, "wayland") == 0)
501 {
502 create_info.System = "wayland";
503 create_info.RawDisplay = (void*)sysWMInfo.info.wl.display;
504 create_info.RawSurface = (void*)sysWMInfo.info.wl.surface;
505 return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info);
506 }
507 else
508 {
509 create_info.System = "x11";
510 create_info.RawWindow = (void*)sysWMInfo.info.x11.window;
511 create_info.RawDisplay = (void*)sysWMInfo.info.x11.display;
512 return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info);
513 }
514#elif defined(SDL_VIDEO_DRIVER_WINDOWS)
515 {
516 create_info.System = "win32";
517 create_info.RawWindow = (void*)sysWMInfo.info.win.window;
518 create_info.RawInstance = (void*)sysWMInfo.info.win.hinstance;
519 return ImGui_ImplWGPU_CreateWGPUSurfaceHelper(&create_info);
520 }
521#else
522#error "Unsupported WebGPU native platform!"
523 return nullptr;
524#endif
525}
526#endif // #ifndef __EMSCRIPTEN__