Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
WebGPUDevice.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
10#include "WebGPUDevice.hpp"
11#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
12#include "MetalComputeQueue.hpp"
13#endif
14#include "WebGPUMappings.hpp"
16#include "../../core/Log.hpp"
17#include "../../core/Hash.hpp"
18
19#include <algorithm>
20#include <cstring>
21#include <string>
22#include <vector>
23
24namespace esengine {
25
26using namespace webgpu;
27
28namespace {
29WGPUStringView sv(const char* text) {
30 WGPUStringView view{};
31 view.data = text;
32 view.length = text ? std::strlen(text) : 0;
33 return view;
34}
35
36std::string fromSv(const WGPUStringView& view) {
37 if (!view.data) return {};
38 return std::string(view.data,
39 view.length == WGPU_STRLEN ? std::strlen(view.data) : view.length);
40}
41
42bool isDepthFormat(WGPUTextureFormat format) {
43 return format == WGPUTextureFormat_Depth24Plus ||
44 format == WGPUTextureFormat_Depth24PlusStencil8;
45}
46
47u32 dsVariantOf(WGPUTextureFormat format) {
48 if (format == WGPUTextureFormat_Undefined) return WebGPUDevice::kDsNone;
50}
51
52
53
54u8 packSamplerKey(TextureFilter minFilter, TextureFilter magFilter,
55 TextureWrap wrapS, TextureWrap wrapT) {
56 return static_cast<u8>((minFilter == TextureFilter::Nearest ? 1u : 0u) |
57 (magFilter == TextureFilter::Nearest ? 2u : 0u) |
58 (static_cast<u32>(wrapS) << 2) |
59 (static_cast<u32>(wrapT) << 4));
60}
61} // namespace
62
63WebGPUDevice::WebGPUDevice(WGPUDevice device, WGPUInstance instance, WGPUAdapter adapter)
64 : device_(device), adapter_(adapter) {
65 if (device_) {
66 queue_ = wgpuDeviceGetQueue(device_);
67 if (instance) {
68 instance_ = instance; // native shell shares its instance (surface must match it)
69 owns_instance_ = false;
70 } else {
71 instance_ = wgpuCreateInstance(nullptr); // web/standalone: own one (emscripten singleton)
72 owns_instance_ = true;
73 }
74 }
75}
76
80
81// One and four: what WebGPU guarantees for every renderable format. A target
82// asking for more gets four, and its pipelines are built to match the pass they
83// draw into — which WebGPU validates, unlike GL.
85
88#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
90#endif
91}
92
94 // Ask the adapter who this GPU is. getString() below answers with constants
95 // true of every WebGPU build, and so useless in a loss report; the adapter
96 // knows the vendor, the chip and the driver build.
97 std::string vendor = "WebGPU";
98 std::string renderer = getString(GfxStringName::Renderer);
99 std::string version = getString(GfxStringName::Version);
100 if (adapter_) {
101 WGPUAdapterInfo info = {};
102 if (wgpuAdapterGetInfo(adapter_, &info) == WGPUStatus_Success) {
103 vendor = fromSv(info.vendor);
104 renderer = fromSv(info.device) + " (" + fromSv(info.architecture) + ")";
105 version = fromSv(info.description);
106 wgpuAdapterInfoFreeMembers(info);
107 }
108 }
109 setDeviceIdentity("WebGPU", std::move(vendor), std::move(renderer), std::move(version));
110}
111
113 switch (static_cast<WGPUDeviceLostReason>(wgpuReason)) {
114 // Not a failure: this is the device we destroyed reporting that it is gone.
115 case WGPUDeviceLostReason_Destroyed: return GfxDeviceLostReason::Destroyed;
116 case WGPUDeviceLostReason_FailedCreation: return GfxDeviceLostReason::Internal;
117 default: return GfxDeviceLostReason::Unknown;
118 }
119}
120
122 // The device-lost callback is registered AllowSpontaneous and so fires on
123 // its own, but pumping here gives it a guaranteed point in the frame — and
124 // keeps the loss detectable if the mode ever tightens to ProcessEvents.
125 if (instance_) wgpuInstanceProcessEvents(instance_);
126 drainCompletions();
127 return false;
128}
129
130void WebGPUDevice::reportUncapturedError(u32 wgpuErrorType, const char* message) {
131 // Only errors that mean the device is finished become losses. A validation
132 // error is a bug in the frame we just built — WebGPU drops the call and keeps
133 // the device — so promoting it would end the game over one bad draw.
134 const auto type = static_cast<WGPUErrorType>(wgpuErrorType);
135 if (type == WGPUErrorType_OutOfMemory) {
136 markDeviceLost(GfxDeviceLostReason::OutOfMemory, message ? message : "",
137 "uncaptured error");
138 } else if (type == WGPUErrorType_Internal) {
139 markDeviceLost(GfxDeviceLostReason::Internal, message ? message : "",
140 "uncaptured error");
141 } else if (type == WGPUErrorType_Validation && validation_errors_logged_ < 8) {
142 // Said, the first few: otherwise all that reaches the console is the queue refusing an invalid command buffer, which names
143 // nothing that made it invalid.
145 ES_LOG_WARN("WebGPU validation error: {}", message ? message : "(no message)");
146 }
147}
148
149bool WebGPUDevice::adoptDevice(WGPUDevice device) {
150 if (!device) return false;
151
152 // Everything below the device goes: a WebGPU object belongs to the device
153 // that made it, so none of these caches can be carried over. The instance
154 // stays — it outlives devices, and on native the surface must match it.
155 releaseDeviceObjects();
156
157 mailbox_ = std::make_shared<Mailbox>();
158 device_ = device;
159 queue_ = wgpuDeviceGetQueue(device_);
160 init();
161
162#if defined(__EMSCRIPTEN__)
163 if (surface_selector_.empty()) return true;
164 return configureSurface(surface_selector_.c_str(), surface_width_, surface_height_);
165#else
166 if (!surface_window_) return true;
167 NativeSurface window{};
168 window.handle = surface_window_;
169 return configureSurface(window, surface_width_, surface_height_);
170#endif
171}
172
174 // "Not yet", not "never": only whoever created the device can replace it, so
175 // this waits for a host to hand one over rather than claiming a recovery it
176 // cannot perform. The GL path waits on the browser the same way.
177 if (!pending_device_) return false;
178 WGPUDevice next = pending_device_;
179 pending_device_ = nullptr;
180 return adoptDevice(next);
181}
182
184 releaseDeviceObjects();
185 if (owns_device_ && pending_device_) wgpuDeviceRelease(pending_device_);
186 pending_device_ = nullptr;
187 if (instance_ && owns_instance_) { wgpuInstanceRelease(instance_); }
188 instance_ = nullptr;
189}
190
191void WebGPUDevice::releaseDeviceObjects() {
192 mailbox_.reset();
193 frames_done_ = frames_ended_;
194#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
196 metal_compute_.reset();
197 metal_compute_attempted_ = false;
198#endif
199 if (pass_) { wgpuRenderPassEncoderRelease(pass_); pass_ = nullptr; }
200 pass_pipeline_ = nullptr;
201 if (encoder_) { wgpuCommandEncoderRelease(encoder_); encoder_ = nullptr; }
202 if (frame_view_) { wgpuTextureViewRelease(frame_view_); frame_view_ = nullptr; }
203 if (frame_texture_) { wgpuTextureRelease(frame_texture_); frame_texture_ = nullptr; }
204 capture_id_ = 0;
205 capture_copied_ = false;
206 pass_is_surface_ = false;
207 pass_timed_ = false;
208 span_open_ = false;
209 span_closing_ = false;
210 span_slot_ = kGpuTimeRing;
211 span_passes_ = 0;
212
213 // bind_group_/texture_group_ point INTO the cache — release the cache, not them.
214 for (auto& bucket : bind_group_cache_) for (auto& e : bucket.second) if (e.bg) wgpuBindGroupRelease(e.bg);
215 bind_group_cache_.clear();
216 bind_group_count_ = 0;
217 bind_group_ = nullptr;
218 texture_group_ = nullptr;
219 bind_group_dirty_ = true;
220 bound_pipeline_ = 0;
221
222 for (auto& [id, rec] : buffers_) {
223 if (rec.buffer) wgpuBufferRelease(rec.buffer);
224 }
225 buffers_.clear();
226 for (auto& [id, rec] : textures_) releaseTexture(rec);
227 textures_.clear();
228 for (auto& [id, rec] : programs_) {
229 if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);
230 if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);
231 }
232 programs_.clear();
233 for (auto& [id, rec] : computes_) {
234 for (auto& [key, pipeline] : rec.pipelines) {
235 if (pipeline) wgpuComputePipelineRelease(pipeline);
236 }
237 if (rec.module) wgpuShaderModuleRelease(rec.module);
238 }
239 computes_.clear();
240 for (auto& [key, layout] : compute_pipeline_layouts_) {
241 if (layout) wgpuPipelineLayoutRelease(layout);
242 }
243 compute_pipeline_layouts_.clear();
244 for (auto& [key, layout] : compute_layouts_) {
245 if (layout) wgpuBindGroupLayoutRelease(layout);
246 }
247 compute_layouts_.clear();
248 for (auto& [id, rec] : pipelines_) {
249 for (WGPURenderPipeline variant : rec.variants) {
250 if (variant) wgpuRenderPipelineRelease(variant);
251 }
252 }
253 pipelines_.clear();
254
255 if (dummy_ubo_.buffer) wgpuBufferRelease(dummy_ubo_.buffer);
256 dummy_ubo_ = BufferRec{};
257 releaseTexture(dummy_texture_);
258 releaseTexture(dummy_depth_texture_);
259 releaseTexture(dummy_array_texture_);
260 releaseTexture(dummy_volume_texture_);
261
262 // GPU timing resources.
263 parallel_span_ = false;
264 if (clock_pipeline_) { wgpuComputePipelineRelease(clock_pipeline_); clock_pipeline_ = nullptr; }
265 if (timestamp_qset_) { wgpuQuerySetRelease(timestamp_qset_); timestamp_qset_ = nullptr; }
266 if (timestamp_resolve_) { wgpuBufferRelease(timestamp_resolve_); timestamp_resolve_ = nullptr; }
267 for (auto& s : gpu_time_ring_) { if (s.buf) wgpuBufferRelease(s.buf); s.buf = nullptr; s.pending = false; }
268 gpu_time_results_.clear();
269 for (auto& ps : pass_time_pool_) { if (ps.buf) wgpuBufferRelease(ps.buf); }
270 pass_time_pool_.clear();
271 pass_time_results_.clear();
272 pass_time_slot_ = kNoPassSlot;
273 armed_pass_tag_ = 0;
274 timestamp_supported_ = false;
275 timestamp_init_done_ = false;
276 if (clear_bind_group_) { wgpuBindGroupRelease(clear_bind_group_); clear_bind_group_ = nullptr; }
277 if (clear_color_buffer_) { wgpuBufferRelease(clear_color_buffer_); clear_color_buffer_ = nullptr; }
278 for (auto& [key, pipeline] : clear_pipelines_) {
279 if (pipeline) wgpuRenderPipelineRelease(pipeline);
280 }
281 clear_pipelines_.clear();
282 if (clear_layout_) { wgpuPipelineLayoutRelease(clear_layout_); clear_layout_ = nullptr; }
283 if (clear_bgl_) { wgpuBindGroupLayoutRelease(clear_bgl_); clear_bgl_ = nullptr; }
284 for (auto& [key, pipeline] : flip_pipelines_) {
285 if (pipeline) wgpuRenderPipelineRelease(pipeline);
286 }
287 flip_pipelines_.clear();
288 if (surface_copy_view_) { wgpuTextureViewRelease(surface_copy_view_); surface_copy_view_ = nullptr; }
289 if (surface_copy_) { wgpuTextureRelease(surface_copy_); surface_copy_ = nullptr; }
290 surface_copy_width_ = surface_copy_height_ = 0;
291 if (flip_layout_) { wgpuPipelineLayoutRelease(flip_layout_); flip_layout_ = nullptr; }
292 if (flip_bgl_) { wgpuBindGroupLayoutRelease(flip_bgl_); flip_bgl_ = nullptr; }
293 // The depth-resolve family, for the same reason: every one of these belongs to
294 // the device that made it, and Dawn refuses one from the generation before.
295 for (auto& [key, pipeline] : depth_resolve_pipelines_) {
296 if (pipeline) wgpuRenderPipelineRelease(pipeline);
297 }
298 depth_resolve_pipelines_.clear();
299 if (depth_resolve_layout_) { wgpuPipelineLayoutRelease(depth_resolve_layout_); depth_resolve_layout_ = nullptr; }
300 if (depth_resolve_bgl_) { wgpuBindGroupLayoutRelease(depth_resolve_bgl_); depth_resolve_bgl_ = nullptr; }
301 if (depth_resolve_vs_) { wgpuShaderModuleRelease(depth_resolve_vs_); depth_resolve_vs_ = nullptr; }
302 if (depth_resolve_fs_) { wgpuShaderModuleRelease(depth_resolve_fs_); depth_resolve_fs_ = nullptr; }
303 for (auto& [key, pipeline] : mip_pipelines_) {
304 if (pipeline) wgpuRenderPipelineRelease(pipeline);
305 }
306 mip_pipelines_.clear();
307 if (mip_layout_) { wgpuPipelineLayoutRelease(mip_layout_); mip_layout_ = nullptr; }
308 if (mip_bgl_) { wgpuBindGroupLayoutRelease(mip_bgl_); mip_bgl_ = nullptr; }
309 if (mip_module_) { wgpuShaderModuleRelease(mip_module_); mip_module_ = nullptr; }
310 if (mip_sampler_) { wgpuSamplerRelease(mip_sampler_); mip_sampler_ = nullptr; }
311 for (auto& [key, layout] : pipeline_layouts_) {
312 if (layout) wgpuPipelineLayoutRelease(layout);
313 }
314 pipeline_layouts_.clear();
315 for (auto& [key, layout] : group_layouts_) {
316 if (layout) wgpuBindGroupLayoutRelease(layout);
317 }
318 group_layouts_.clear();
319 // Erase before release: aborting a pending map fires the callback, which must
320 // miss the lookup rather than see a half-dead record.
321 while (!readbacks_.empty()) releaseReadback(readbacks_.begin()->first);
322 for (auto& [key, sampler] : samplers_) {
323 if (sampler) wgpuSamplerRelease(sampler);
324 }
325 samplers_.clear();
326 if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ = nullptr; }
327 if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ = nullptr; }
328 if (surface_msaa_view_) { wgpuTextureViewRelease(surface_msaa_view_); surface_msaa_view_ = nullptr; }
329 if (surface_msaa_texture_) { wgpuTextureRelease(surface_msaa_texture_); surface_msaa_texture_ = nullptr; }
330 surface_msaa_width_ = surface_msaa_height_ = 0;
331 surface_msaa_samples_ = 0;
332 releaseSurfaceProxy();
333 if (surface_) { wgpuSurfaceRelease(surface_); surface_ = nullptr; }
334 // Sizes are kept: a re-configured surface has to come back the same shape,
335 // and the depth companion is rebuilt against them.
336 surface_depth_width_ = 0;
337 surface_depth_height_ = 0;
338 if (queue_) { wgpuQueueRelease(queue_); queue_ = nullptr; }
339 if (owns_device_ && device_) { wgpuDeviceRelease(device_); device_ = nullptr; }
340}
341
342// =============================================================================
343// Surface (bring-up: a canvas is the Default framebuffer)
344// =============================================================================
345
346#if defined(__EMSCRIPTEN__)
347bool WebGPUDevice::configureSurface(const char* selector, u32 width, u32 height) {
348 if (!device_ || !instance_) {
349 ES_LOG_ERROR("WebGPUDevice::configureSurface: no device/instance");
350 return false;
351 }
352
353 WGPUEmscriptenSurfaceSourceCanvasHTMLSelector canvas{};
354 canvas.chain.sType = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector;
355 canvas.selector = sv(selector);
356
357 WGPUSurfaceDescriptor sd{};
358 sd.nextInChain = &canvas.chain;
359 // Kept so a replacement device can re-make the surface: the old one belonged
360 // to the device that died, and nothing else records which canvas it was.
361 surface_selector_ = selector;
362 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
363 if (!surface_) {
364 ES_LOG_ERROR("WebGPUDevice::configureSurface: surface creation failed for '{}'", selector);
365 return false;
366 }
367
368 return configureSwapchain(width, height);
369}
370#endif // __EMSCRIPTEN__
371
372#if !defined(__EMSCRIPTEN__)
373// The native (iOS/Android) surface source: the same instance + swapchain as the web
374// path, but the surface is created from a native window handle instead of a canvas
375// selector. Dawn's Metal/Android surface descriptors replace the emscripten one; the
376// host owns the CAMetalLayer / ANativeWindow lifetime. Compiled only in a native Dawn
377// build (emscripten's emdawnwebgpu has no native window source).
378bool WebGPUDevice::configureSurface(const NativeSurface& window, u32 width, u32 height) {
379 if (!device_ || !instance_) {
380 ES_LOG_ERROR("WebGPUDevice::configureSurface(native): no device/instance");
381 return false;
382 }
383 if (!window.handle) {
384 ES_LOG_ERROR("WebGPUDevice::configureSurface(native): null window handle");
385 return false;
386 }
387
388 // The SAME window, a new size — a rotation, insets changing, the system bars
389 // leaving — is a reconfigure, not a new surface. Creating a second surface for
390 // a window the first one still holds leaves every getCurrentTexture in error
391 // on Vulkan (the old swapchain owns it), which is a black screen with nothing
392 // else wrong.
393 if (surface_ && surface_window_ == window.handle) {
394 endFrame(); // a held texture belongs to the swapchain being replaced
395 return configureSwapchain(width, height);
396 }
397
398 // A genuinely new window (an Android screen-off/on destroys it and hands back
399 // another): let go of the old swapchain before building one on the new one.
400 if (surface_) {
401 endFrame();
402 wgpuSurfaceUnconfigure(surface_);
403 wgpuSurfaceRelease(surface_);
404 surface_ = nullptr;
405 }
406 if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ = nullptr; }
407 if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ = nullptr; }
408 surface_depth_width_ = surface_depth_height_ = 0;
409 if (surface_msaa_view_) { wgpuTextureViewRelease(surface_msaa_view_); surface_msaa_view_ = nullptr; }
410 if (surface_msaa_texture_) { wgpuTextureRelease(surface_msaa_texture_); surface_msaa_texture_ = nullptr; }
411 surface_msaa_width_ = surface_msaa_height_ = 0;
412 surface_msaa_samples_ = 0;
413
414
415 WGPUSurfaceDescriptor sd{};
416 switch (window.kind) {
418 WGPUSurfaceSourceMetalLayer metal{};
419 metal.chain.sType = WGPUSType_SurfaceSourceMetalLayer;
420 metal.layer = window.handle; // CAMetalLayer*
421 sd.nextInChain = &metal.chain;
422 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
423 break;
424 }
426 WGPUSurfaceSourceAndroidNativeWindow android{};
427 android.chain.sType = WGPUSType_SurfaceSourceAndroidNativeWindow;
428 android.window = window.handle; // ANativeWindow*
429 sd.nextInChain = &android.chain;
430 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
431 break;
432 }
434#if defined(_WIN32)
435 WGPUSurfaceSourceWindowsHWND win32{};
436 win32.chain.sType = WGPUSType_SurfaceSourceWindowsHWND;
437 win32.hinstance = window.instance;
438 win32.hwnd = window.handle;
439 sd.nextInChain = &win32.chain;
440 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
441#endif
442 break;
443 }
445#if defined(__linux__)
446 WGPUSurfaceSourceWaylandSurface wayland{};
447 wayland.chain.sType = WGPUSType_SurfaceSourceWaylandSurface;
448 wayland.display = window.instance; // wl_display*
449 wayland.surface = window.handle; // wl_surface*
450 sd.nextInChain = &wayland.chain;
451 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
452#endif
453 break;
454 }
456#if defined(__linux__)
457 WGPUSurfaceSourceXlibWindow xlib{};
458 xlib.chain.sType = WGPUSType_SurfaceSourceXlibWindow;
459 xlib.display = window.instance; // Display*
460 // The XID is an integer, not a pointer — it travels in `handle`
461 // because the seam carries one window field, and is read back as the
462 // integer it is rather than dereferenced.
463 xlib.window = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(window.handle));
464 sd.nextInChain = &xlib.chain;
465 surface_ = wgpuInstanceCreateSurface(instance_, &sd);
466#endif
467 break;
468 }
469 }
470 if (!surface_) {
471 ES_LOG_ERROR("WebGPUDevice::configureSurface(native): surface creation failed");
472 return false;
473 }
474 surface_window_ = window.handle;
475
476 return configureSwapchain(width, height);
477}
478
480static bool isSrgbFormat(WGPUTextureFormat f) {
481 return f == WGPUTextureFormat_BGRA8UnormSrgb || f == WGPUTextureFormat_RGBA8UnormSrgb;
482}
483
485 if (!surface_) return;
486 presentSurfaceProxy(); // a frame the renderer never ended still reaches the swapchain the right way up
487 wgpuSurfacePresent(surface_);
488 // Also the frame's end, for a frame the renderer never finished (the host's
489 // fallback frame, or a tick that drew nothing): a swapchain texture must
490 // never outlive the present it belongs to.
491 endFrame();
492}
493#endif // !__EMSCRIPTEN__
494
495// Not native-only: a web surface can be BGRA too, and a capture consumer has to
496// know which order the bytes came back in.
498 return surface_format_ == WGPUTextureFormat_BGRA8Unorm
499 || surface_format_ == WGPUTextureFormat_BGRA8UnormSrgb;
500}
501
510WGPUPresentMode WebGPUDevice::pickUncappedPresentMode() const {
511#if !defined(__EMSCRIPTEN__)
512 if (surface_ && adapter_) {
513 WGPUSurfaceCapabilities caps{};
514 if (wgpuSurfaceGetCapabilities(surface_, adapter_, &caps) == WGPUStatus_Success) {
515 WGPUPresentMode chosen = WGPUPresentMode_Fifo;
516 for (size_t i = 0; i < caps.presentModeCount; ++i) {
517 if (caps.presentModes[i] == WGPUPresentMode_Immediate) {
518 chosen = WGPUPresentMode_Immediate;
519 break;
520 }
521 if (caps.presentModes[i] == WGPUPresentMode_Mailbox) chosen = WGPUPresentMode_Mailbox;
522 }
523 wgpuSurfaceCapabilitiesFreeMembers(caps);
524 return chosen;
525 }
526 }
527#endif
528 return WGPUPresentMode_Fifo;
529}
530
531bool WebGPUDevice::configureSwapchain(u32 width, u32 height) {
532 // Anything but the canvas' preferred format costs a full-frame copy per
533 // present, and only the page can name it (setPreferredSurfaceBGRA). Readback
534 // asks frameCaptureIsBGRA which order it got.
535 surface_format_ = prefer_surface_bgra_ ? WGPUTextureFormat_BGRA8Unorm
536 : WGPUTextureFormat_RGBA8Unorm;
537#if !defined(__EMSCRIPTEN__)
538 // A native surface may accept nothing of the sort — a CAMetalLayer offers only
539 // BGRA8Unorm, while Vulkan happens to take RGBA8 — and configuring a format the
540 // surface does not advertise leaves every getCurrentTexture in error rather
541 // than failing here. So ask, and take the surface's preferred (first) format.
542 //
543 // Of the formats it advertises, take a NON-sRGB one: the engine hands the
544 // surface values that are already display-encoded (the shaders in gamma
545 // mode, the final blit in linear), so an *Srgb surface encodes them twice.
546 if (adapter_) {
547 WGPUSurfaceCapabilities caps{};
548 if (wgpuSurfaceGetCapabilities(surface_, adapter_, &caps) == WGPUStatus_Success
549 && caps.formatCount > 0) {
550 surface_format_ = caps.formats[0];
551 for (size_t i = 0; i < caps.formatCount; ++i) {
552 if (!isSrgbFormat(caps.formats[i])) {
553 surface_format_ = caps.formats[i];
554 break;
555 }
556 }
557 wgpuSurfaceCapabilitiesFreeMembers(caps);
558 }
559 }
560#endif
561 WGPUSurfaceConfiguration cfg{};
562 cfg.device = device_;
563 cfg.format = surface_format_;
564 cfg.usage = WGPUTextureUsage_RenderAttachment;
565 // Opt-in (setSurfaceReadback): lets captureNextFrame copy the presented frame.
566 if (surface_readback_) cfg.usage |= WGPUTextureUsage_CopySrc;
567 cfg.width = width;
568 cfg.height = height;
569 // Auto, not Opaque: let the backend pick a mode the surface advertises. A
570 // browser canvas supports Opaque, but a native Vulkan surface may not (e.g.
571 // Adreno on Android only offers Inherit/PreMultiplied) — Configure() rejects
572 // an unsupported mode outright.
573 cfg.alphaMode = WGPUCompositeAlphaMode_Auto;
574 // Fifo is the only mode every surface must support, and the only one a shipped
575 // game should want. setPresentUncapped asks for a measurable frame instead —
576 // see its comment for why a vsynced one cannot be measured.
577 cfg.presentMode = present_uncapped_ ? pickUncappedPresentMode() : WGPUPresentMode_Fifo;
578 // Said out loud, because a fallback here makes a measurement WRONG rather than
579 // absent: a frame that was throttled reads as the refresh interval, and the
580 // bench consuming it cannot tell that from a frame that cost that much.
581 if (present_uncapped_) {
582 ES_LOG_WARN("WebGPUDevice: uncapped present asked for, surface gave {}",
583 cfg.presentMode == WGPUPresentMode_Immediate ? "Immediate"
584 : cfg.presentMode == WGPUPresentMode_Mailbox ? "Mailbox — the compositor still shows one frame per vsync"
585 : "Fifo — the frame IS the refresh interval");
586 }
587 wgpuSurfaceConfigure(surface_, &cfg);
588 surface_width_ = width;
589 surface_height_ = height;
590
591 return ensureSurfaceDepth(width, height);
592}
593
601bool WebGPUDevice::ensureSurfaceDepth(u32 width, u32 height) {
602 if (surface_depth_view_ && width == surface_depth_width_ && height == surface_depth_height_
603 && surface_depth_samples_ == surface_samples_) {
604 return true;
605 }
606 if (surface_depth_view_) { wgpuTextureViewRelease(surface_depth_view_); surface_depth_view_ = nullptr; }
607 if (surface_depth_texture_) { wgpuTextureRelease(surface_depth_texture_); surface_depth_texture_ = nullptr; }
608 WGPUTextureDescriptor dd{};
609 dd.dimension = WGPUTextureDimension_2D;
610 dd.format = WGPUTextureFormat_Depth24PlusStencil8;
611 dd.size = WGPUExtent3D{width, height, 1};
612 dd.mipLevelCount = 1;
613 // Every attachment of a pass shares its sample count, so the backbuffer's
614 // depth follows the colour it is paired with.
615 dd.sampleCount = surface_samples_;
616 dd.usage = WGPUTextureUsage_RenderAttachment;
617 surface_depth_texture_ = wgpuDeviceCreateTexture(device_, &dd);
618 if (surface_depth_texture_) {
619 surface_depth_view_ = wgpuTextureCreateView(surface_depth_texture_, nullptr);
620 surface_depth_width_ = width;
621 surface_depth_height_ = height;
622 surface_depth_samples_ = surface_samples_;
623 }
624 return surface_depth_view_ != nullptr;
625}
626
633bool WebGPUDevice::ensureSurfaceMsaa(u32 width, u32 height) {
634 if (surface_samples_ <= 1) {
635 if (surface_msaa_view_) { wgpuTextureViewRelease(surface_msaa_view_); surface_msaa_view_ = nullptr; }
636 if (surface_msaa_texture_) { wgpuTextureRelease(surface_msaa_texture_); surface_msaa_texture_ = nullptr; }
637 surface_msaa_samples_ = 0;
638 return false;
639 }
640 if (surface_msaa_view_ && width == surface_msaa_width_ && height == surface_msaa_height_
641 && surface_samples_ == surface_msaa_samples_) {
642 return true;
643 }
644 if (surface_msaa_view_) { wgpuTextureViewRelease(surface_msaa_view_); surface_msaa_view_ = nullptr; }
645 if (surface_msaa_texture_) { wgpuTextureRelease(surface_msaa_texture_); surface_msaa_texture_ = nullptr; }
646 WGPUTextureDescriptor cd{};
647 cd.dimension = WGPUTextureDimension_2D;
648 cd.format = surface_format_;
649 cd.size = WGPUExtent3D{width, height, 1};
650 cd.mipLevelCount = 1;
651 cd.sampleCount = surface_samples_;
652 cd.usage = WGPUTextureUsage_RenderAttachment;
653 surface_msaa_texture_ = wgpuDeviceCreateTexture(device_, &cd);
654 if (surface_msaa_texture_) {
655 surface_msaa_view_ = wgpuTextureCreateView(surface_msaa_texture_, nullptr);
656 surface_msaa_width_ = width;
657 surface_msaa_height_ = height;
658 surface_msaa_samples_ = surface_samples_;
659 }
660 return surface_msaa_view_ != nullptr;
661}
662
663void WebGPUDevice::releaseSurfaceProxy() {
664 if (surface_proxy_view_) { wgpuTextureViewRelease(surface_proxy_view_); surface_proxy_view_ = nullptr; }
665 if (surface_proxy_) { wgpuTextureRelease(surface_proxy_); surface_proxy_ = nullptr; }
666 surface_proxy_width_ = surface_proxy_height_ = 0;
667 surface_proxy_format_ = WGPUTextureFormat_Undefined;
668 surface_proxy_drawn_ = false;
669}
670
671bool WebGPUDevice::ensureSurfaceProxy(u32 width, u32 height) {
672 if (surface_proxy_view_ && width == surface_proxy_width_ && height == surface_proxy_height_
673 && surface_format_ == surface_proxy_format_) {
674 return true;
675 }
676 releaseSurfaceProxy();
677 WGPUTextureDescriptor td{};
678 td.dimension = WGPUTextureDimension_2D;
679 td.format = surface_format_;
680 td.size = WGPUExtent3D{width, height, 1};
681 td.mipLevelCount = 1;
682 td.sampleCount = 1;
683 td.usage = WGPUTextureUsage_RenderAttachment | WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopySrc;
684 surface_proxy_ = wgpuDeviceCreateTexture(device_, &td);
685 if (!surface_proxy_) return false;
686 surface_proxy_view_ = wgpuTextureCreateView(surface_proxy_, nullptr);
687 surface_proxy_width_ = width;
688 surface_proxy_height_ = height;
689 surface_proxy_format_ = surface_format_;
690 return surface_proxy_view_ != nullptr;
691}
692
693bool WebGPUDevice::acquireFrameView() {
694 if (frame_view_) return true;
695 if (surface_reconfigure_) {
696 surface_reconfigure_ = false;
697 configureSwapchain(surface_width_, surface_height_);
698 }
699 WGPUSurfaceTexture st{};
700 wgpuSurfaceGetCurrentTexture(surface_, &st);
701 if (st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal &&
702 st.status != WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal) {
703 ES_LOG_ERROR("WebGPUDevice: surface texture unavailable ({})",
704 static_cast<u32>(st.status));
705 if (st.texture) wgpuTextureRelease(st.texture);
706 return false;
707 }
708 frame_texture_ = st.texture;
709 frame_view_ = wgpuTextureCreateView(frame_texture_, nullptr);
710 // The texture the surface hands back is the truth about its size: a
711 // native surface may ignore the configured extent (a window mid-
712 // rotation still reports the old one), and a depth companion built
713 // for the size we ASKED for is then the wrong shape, which invalidates
714 // the pass and takes the whole frame with it.
715 const u32 texW = wgpuTextureGetWidth(frame_texture_);
716 const u32 texH = wgpuTextureGetHeight(frame_texture_);
717 if (texW > 0 && texH > 0) {
718 surface_width_ = texW;
719 surface_height_ = texH;
720 ensureSurfaceDepth(texW, texH);
721 }
722 return frame_view_ != nullptr;
723}
724
725void WebGPUDevice::presentSurfaceProxy() {
726 if (!surface_proxy_drawn_) return;
727 surface_proxy_drawn_ = false;
728 if (!device_ || !surface_proxy_view_ || !isDeviceUsable() || !acquireFrameView()) return;
729 if (pass_) endRenderPass();
730 WGPURenderPipeline pipeline = ensureFlipPipeline(surface_format_, /*flip=*/true);
731 if (!pipeline) return;
732 WGPUBindGroupEntry entry{};
733 entry.binding = 0;
734 entry.textureView = surface_proxy_view_;
735 WGPUBindGroupDescriptor bgd{};
736 bgd.layout = flip_bgl_;
737 bgd.entryCount = 1;
738 bgd.entries = &entry;
739 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
740 WGPURenderPassColorAttachment color{};
741 color.view = frame_view_;
742 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
743 color.loadOp = WGPULoadOp_Clear;
744 color.storeOp = WGPUStoreOp_Store;
745 WGPURenderPassDescriptor rp{};
746 rp.colorAttachmentCount = 1;
747 rp.colorAttachments = &color;
748 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
749 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &rp);
750 wgpuRenderPassEncoderSetPipeline(pass, pipeline);
751 wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0, nullptr);
752 wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
753 wgpuRenderPassEncoderEnd(pass);
754 wgpuRenderPassEncoderRelease(pass);
755 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
756 wgpuQueueSubmit(queue_, 1, &commands);
757 wgpuCommandBufferRelease(commands);
758 wgpuCommandEncoderRelease(encoder);
759 wgpuBindGroupRelease(group);
760}
761
763 if (!surface_ || !device_ || width == 0 || height == 0) return;
764 if (width == surface_width_ && height == surface_height_) return;
765 if (pass_) {
766 ES_LOG_WARN("WebGPUDevice::resizeBackbuffer: ignored inside a render pass");
767 return;
768 }
769 configureSwapchain(width, height);
770}
771
772void WebGPUDevice::stubOnce(const char* what) {
773 for (const auto& logged : stub_logged_) {
774 if (logged == what) return;
775 }
776 stub_logged_.emplace_back(what);
777 ES_LOG_WARN("WebGPUDevice: {} not implemented yet (REARCH_WGSL Phase 2 slice 2)", what);
778}
779
780// =============================================================================
781// Dynamic state (recorded in slice 2's pass encoder)
782// =============================================================================
783
784// The RHI states a rectangle the way GL does: origin bottom-left, y up. A target
785// here holds its rows bottom-up as GL does (clip y is turned over on the way in),
786// so WebGPU's row 0 is the bottom row and the rect is used as it is given.
788 viewport_ = {x, y, w, h};
789 if (pass_) {
790 wgpuRenderPassEncoderSetViewport(pass_, static_cast<f32>(x), static_cast<f32>(y),
791 static_cast<f32>(w), static_cast<f32>(h), 0.0f, 1.0f);
792 }
793}
794
796 // Mid-pass stencil reset (mask rebuild) — the one clear that cannot restart
797 // the pass. Emulated with a stencil-write triangle under whatever scissor is
798 // currently active, matching GL's glClear-honors-scissor semantics.
799 if (!pass_) {
800 ES_LOG_WARN("WebGPUDevice::clearStencil: no active pass");
801 return;
802 }
803 if (!hasStencilPlanes(pass_ds_format_)) {
804 ES_LOG_WARN("WebGPUDevice::clearStencil: pass target has no stencil planes");
805 return;
806 }
807 drawInternalClear(false, false, true, nullptr, value, nullptr);
808}
809
811 // WebGPU's scissor is always on; "disabled" = the full target rectangle.
812 if (pass_ && !enabled) {
813 wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, pass_width_, pass_height_);
814 }
815}
816
818 if (!pass_ || w <= 0 || h <= 0) return;
819 // Clamped to the attachment: WebGPU rejects a rect that leaves it, where GL
820 // simply clips — and a mask scrolled half off screen is ordinary.
821 const i32 x0 = std::clamp(x, 0, static_cast<i32>(pass_width_));
822 const i32 y0 = std::clamp(y, 0, static_cast<i32>(pass_height_));
823 const i32 x1 = std::clamp(x + w, 0, static_cast<i32>(pass_width_));
824 const i32 y1 = std::clamp(y + h, 0, static_cast<i32>(pass_height_));
825 wgpuRenderPassEncoderSetScissorRect(pass_, static_cast<u32>(x0), static_cast<u32>(y0),
826 static_cast<u32>(std::max(0, x1 - x0)),
827 static_cast<u32>(std::max(0, y1 - y0)));
828}
829
830// =============================================================================
831// Buffers
832// =============================================================================
833
835 if (!device_ || !isDeviceUsable()) return 0;
836 u64 bytes = 0;
837 const auto bufferBytes = [](WGPUBuffer buffer) -> u64 { return buffer ? wgpuBufferGetSize(buffer) : 0; };
838 for (const auto& [id, buffer] : buffers_) bytes += bufferBytes(buffer.buffer);
839 bytes += bufferBytes(dummy_ubo_.buffer) + bufferBytes(clear_color_buffer_) + bufferBytes(timestamp_resolve_);
840 for (const auto& slot : gpu_time_ring_) bytes += bufferBytes(slot.buf);
841 for (const auto& [id, readback] : readbacks_) bytes += bufferBytes(readback.buffer);
842 const auto textureBytes = [](WGPUTexture texture) -> u64 {
843 if (!texture) return 0;
844 u32 width = wgpuTextureGetWidth(texture), height = wgpuTextureGetHeight(texture);
845 const auto format = wgpuTextureGetFormat(texture);
846 const u32 pixelBytes = format == WGPUTextureFormat_RGBA32Float ? 16 : format == WGPUTextureFormat_RGBA16Float ? 8 : 4;
847 GfxBlockInfo block{1, 1, pixelBytes};
852 if (format == toWGPUCompressedFormat(compressed)) { block = gfxCompressedBlockInfo(compressed); break; }
853 }
854 u64 size = 0;
855 for (u32 level = 0; level < wgpuTextureGetMipLevelCount(texture); ++level) {
856 size += ((static_cast<u64>(width) + block.blockWidth - 1) / block.blockWidth)
857 * ((static_cast<u64>(height) + block.blockHeight - 1) / block.blockHeight) * block.bytesPerBlock
858 * wgpuTextureGetSampleCount(texture);
859 width = std::max(1u, width / 2); height = std::max(1u, height / 2);
860 }
861 return size * wgpuTextureGetDepthOrArrayLayers(texture);
862 };
863 for (const auto& [id, texture] : textures_) bytes += textureBytes(texture.texture);
864 bytes += textureBytes(dummy_texture_.texture) + textureBytes(dummy_depth_texture_.texture)
865 + textureBytes(dummy_array_texture_.texture) + textureBytes(dummy_volume_texture_.texture);
866 bytes += textureBytes(surface_depth_texture_) + textureBytes(surface_msaa_texture_);
867 return bytes;
868}
869
870WGPUBuffer WebGPUDevice::makeBuffer(GfxBufferUsage usage, u32 size, const void* data) {
871 if (!device_) {
872 ES_LOG_ERROR("WebGPUDevice: no device to create a buffer on");
873 return nullptr;
874 }
875 WGPUBufferDescriptor bd{};
876 bd.usage = toWGPUBufferUsage(usage);
877 // Round the allocation, never the caller's data — see alignedWriteSize.
878 bd.size = webgpu::alignedWriteSize(size);
879 WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);
880 if (!buffer) {
881 ES_LOG_ERROR("WebGPUDevice: buffer creation failed ({} bytes)", size);
882 return nullptr;
883 }
884 if (data && size > 0) writeBufferPadded(buffer, 0, data, size);
885 return buffer;
886}
887
888bool WebGPUDevice::backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) {
889 WGPUBuffer buffer = makeBuffer(desc.usage, desc.size, data);
890 if (!buffer) return false;
891 buffers_[id] = BufferRec{buffer, desc.size, desc.usage};
892 return true;
893}
894
895void WebGPUDevice::writeBufferPadded(WGPUBuffer buffer, u32 offset, const void* data, u32 size) {
896 if (!webgpu::needsWriteStaging(size)) {
897 wgpuQueueWriteBuffer(queue_, buffer, offset, data, size);
898 return;
899 }
900 std::vector<u8> padded(webgpu::alignedWriteSize(size), 0);
901 std::memcpy(padded.data(), data, size);
902 wgpuQueueWriteBuffer(queue_, buffer, offset, padded.data(), padded.size());
903}
904
906#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
907 if (metal_compute_) metal_compute_->forgetBuffer(id);
908#endif
909 auto it = buffers_.find(id);
910 if (it == buffers_.end()) return;
911 if (it->second.buffer) {
912 evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(it->second.buffer)));
913 wgpuBufferRelease(it->second.buffer);
914 }
915 buffers_.erase(it);
916}
917
918void WebGPUDevice::evictBindGroups(u64 id) {
919 for (auto it = bind_group_cache_.begin(); it != bind_group_cache_.end();) {
920 auto& bucket = it->second;
921 for (usize i = bucket.size(); i-- > 0;) {
922 auto& e = bucket[i];
923 bool hit = false;
924 for (u64 v : e.ids) {
925 if (v == id) { hit = true; break; }
926 }
927 if (!hit) continue;
928 if (e.bg == bind_group_) bind_group_ = nullptr;
929 if (e.bg == texture_group_) texture_group_ = nullptr;
930 if (e.bg) wgpuBindGroupRelease(e.bg);
931 bucket.erase(bucket.begin() + static_cast<std::ptrdiff_t>(i));
932 --bind_group_count_;
933 bind_group_dirty_ = true;
934 }
935 it = bucket.empty() ? bind_group_cache_.erase(it) : std::next(it);
936 }
937}
938
939void WebGPUDevice::backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) {
940 auto it = buffers_.find(id);
941 if (it == buffers_.end() || !it->second.buffer || !data || sizeBytes == 0) return;
942 if (!webgpu::writeFitsInBuffer(offsetBytes, sizeBytes, it->second.size)) {
943 ES_LOG_ERROR("WebGPUDevice::updateBuffer: range {}+{} exceeds buffer size {}",
944 offsetBytes, sizeBytes, it->second.size);
945 return;
946 }
947 // GL takes any offset and size; WriteBuffer takes 4-byte multiples of both.
948 if ((offsetBytes & 3u) != 0) {
949 ES_LOG_ERROR("WebGPUDevice::updateBuffer: offset {} is not 4-byte aligned", offsetBytes);
950 return;
951 }
952 // Only a write ending at the logical end may pad, into the slack the rounded
953 // allocation has. One ending mid-buffer would clobber the next field.
954 if (webgpu::needsWriteStaging(sizeBytes) && offsetBytes + sizeBytes != it->second.size) {
955 ES_LOG_ERROR("WebGPUDevice::updateBuffer: unaligned partial write {}+{} of {}",
956 offsetBytes, sizeBytes, it->second.size);
957 return;
958 }
959 writeBufferPadded(it->second.buffer, offsetBytes, data, sizeBytes);
960}
961
962void WebGPUDevice::backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) {
963#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
964 if (metal_compute_) metal_compute_->forgetBuffer(id);
965#endif
966 auto it = buffers_.find(id);
967 if (it == buffers_.end()) return;
968
969 // WebGPU buffers are fixed-size, so the store is re-created behind the same id.
970 // A cached bind group names the old WGPUBuffer, not the id, and would keep
971 // drawing its bytes.
972 if (it->second.buffer) {
973 evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(it->second.buffer)));
974 wgpuBufferRelease(it->second.buffer);
975 }
976 bind_group_dirty_ = true;
977 it->second.buffer = makeBuffer(desc.usage, desc.size, data);
978 it->second.size = desc.size;
979}
980
981void WebGPUDevice::backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
982 if (slot >= kUniformSlots) return;
983 const u32 id = static_cast<u32>(buffer);
984 if (uniform_slots_[slot] != id || uniform_offsets_[slot] != offsetBytes ||
985 uniform_sizes_[slot] != sizeBytes) {
986 uniform_slots_[slot] = id;
987 uniform_offsets_[slot] = offsetBytes;
988 uniform_sizes_[slot] = sizeBytes;
989 bind_group_dirty_ = true;
990 }
991}
992
993// =============================================================================
994// Vertex layouts (descriptors retained; pipelines consume them at build time)
995// =============================================================================
996
998 // Every attribute needs a WebGPU spelling — a mismatch is an engine bug, not a
999 // runtime condition, so it is refused where the layout is declared.
1000 for (u32 i = 0; i < desc.attributeCount; ++i) {
1001 const auto& a = desc.attributes[i];
1002 if (toWGPUVertexFormat(a.components, a.type, a.normalized) == kInvalidVertexFormat) {
1003 ES_LOG_ERROR("WebGPUDevice::createVertexLayout: attribute {} ({} x type {}) has no WGPU format",
1004 i, a.components, static_cast<u32>(a.type));
1005 return false;
1006 }
1007 }
1008 return true;
1009}
1010
1011void WebGPUDevice::setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) {
1012 auto it = buffers_.find(static_cast<u32>(buffer));
1013 if (!pass_ || it == buffers_.end()) return;
1014 wgpuRenderPassEncoderSetVertexBuffer(pass_, slot, it->second.buffer, offsetBytes,
1015 it->second.size - offsetBytes);
1016}
1017
1019 // The RHI carries the index TYPE on the draw, not the bind - record the
1020 // buffer and bind it at draw time with the draw's format.
1021 bound_index_buffer_ = static_cast<u32>(buffer);
1022}
1023
1024// =============================================================================
1025// Textures
1026// =============================================================================
1027
1028u32 WebGPUDevice::colorVariantOf(WGPUTextureFormat format) {
1029 switch (format) {
1030 case WGPUTextureFormat_RGBA8UnormSrgb: return kColorSrgb8;
1031 case WGPUTextureFormat_RGBA16Float: return kColorRgba16f;
1032 case WGPUTextureFormat_RGBA32Float: return kColorRgba32f;
1033 case WGPUTextureFormat_BGRA8Unorm: return kColorBgra8;
1034 default: return kColorRgba8;
1035 }
1036}
1037
1038bool WebGPUDevice::makeTexture(const TextureDesc& desc, const void* pixels, TextureRec& out) {
1039 if (!device_) {
1040 ES_LOG_ERROR("WebGPUDevice: no device to create a texture on");
1041 return false;
1042 }
1043
1044 const u32 layers = desc.layers > 1 ? desc.layers : 1;
1045 WGPUTextureDescriptor td{};
1046 td.dimension = desc.volume ? WGPUTextureDimension_3D : WGPUTextureDimension_2D;
1047 td.format = toWGPUTextureFormat(desc.format);
1048 td.size = WGPUExtent3D{desc.width, desc.height, layers};
1049 td.sampleCount = desc.samples > 1 ? kMsaaSamples : 1;
1050 td.mipLevelCount = 1;
1051 if (desc.mipmaps && !desc.volume && td.sampleCount == 1 && !isDepthFormat(td.format)) {
1052 for (u32 side = std::max(desc.width, desc.height); side > 1; side >>= 1) ++td.mipLevelCount;
1053 }
1054 // Depth-stencil takes no upload and no readback (writeTexture cannot fill
1055 // it, CopySrc is refused on depth24plus) but IS sampled: an effect reads the
1056 // scene's depth. Colour carries CopySrc for the async readback seam.
1057 td.usage = isDepthFormat(td.format)
1058 ? (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_RenderAttachment)
1059 : desc.volume
1060 ? (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst)
1061 : (WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst |
1062 WGPUTextureUsage_CopySrc | WGPUTextureUsage_RenderAttachment);
1063 // A compute target is also written by shaders. Only these formats have the capability in core WebGPU,
1064 // and one that does not is created plain rather than refused: the record says what it got.
1065 const bool storage = desc.storage && !desc.volume && td.sampleCount == 1 &&
1066 (td.format == WGPUTextureFormat_RGBA8Unorm || td.format == WGPUTextureFormat_RGBA16Float ||
1067 td.format == WGPUTextureFormat_RGBA32Float);
1068 if (storage) td.usage |= WGPUTextureUsage_StorageBinding;
1069 // No copies: invalid on a multisampled texture. Depth keeps TextureBinding
1070 // because resolveDepthAttachment samples it; colour is read through the
1071 // single-sample twin the pass resolves into.
1072 if (td.sampleCount > 1) {
1073 td.usage = isDepthFormat(td.format)
1074 ? (WGPUTextureUsage_RenderAttachment | WGPUTextureUsage_TextureBinding)
1075 : WGPUTextureUsage_RenderAttachment;
1076 }
1077
1078 WGPUTexture texture = wgpuDeviceCreateTexture(device_, &td);
1079 if (!texture) {
1080 ES_LOG_ERROR("WebGPUDevice: texture creation failed ({}x{})", desc.width, desc.height);
1081 return false;
1082 }
1083
1084 WGPUTextureView view = nullptr;
1085 if (desc.volume) {
1086 // Never an attachment: the one view is the sampled one, every slice.
1087 WGPUTextureViewDescriptor vd{};
1088 vd.format = td.format;
1089 vd.dimension = WGPUTextureViewDimension_3D;
1090 vd.mipLevelCount = 1;
1091 vd.arrayLayerCount = 1;
1092 vd.aspect = WGPUTextureAspect_All;
1093 view = wgpuTextureCreateView(texture, &vd);
1094 } else if (layers > 1) {
1095 // Never an attachment, so the one view is the sampled one: every layer, every level.
1096 WGPUTextureViewDescriptor vd{};
1097 vd.format = td.format;
1098 vd.dimension = WGPUTextureViewDimension_2DArray;
1099 vd.mipLevelCount = td.mipLevelCount;
1100 vd.arrayLayerCount = layers;
1101 vd.aspect = WGPUTextureAspect_All;
1102 view = wgpuTextureCreateView(texture, &vd);
1103 } else if (td.mipLevelCount > 1) {
1104 WGPUTextureViewDescriptor vd{};
1105 vd.format = td.format;
1106 vd.dimension = WGPUTextureViewDimension_2D;
1107 vd.mipLevelCount = 1;
1108 vd.arrayLayerCount = 1;
1109 vd.aspect = WGPUTextureAspect_All;
1110 view = wgpuTextureCreateView(texture, &vd);
1111 } else {
1112 view = wgpuTextureCreateView(texture, nullptr);
1113 }
1114 // A depth-stencil texture has two aspects and a sample may name only one, so
1115 // the view a binding uses is depth-only. Every other format samples through
1116 // the view it already has — the two members alias, and cleanup knows it.
1117 WGPUTextureView sampleView = view;
1118 if (isDepthFormat(td.format)) {
1119 WGPUTextureViewDescriptor vd{};
1120 // The ASPECT's format, not the texture's: a depth-only view of a
1121 // depth24plus-stencil8 texture is a depth24plus view, and asking for it
1122 // under the combined format is rejected as incompatible.
1123 vd.format = td.format == WGPUTextureFormat_Depth24PlusStencil8
1124 ? WGPUTextureFormat_Depth24Plus
1125 : td.format;
1126 vd.dimension = WGPUTextureViewDimension_2D;
1127 vd.mipLevelCount = 1;
1128 vd.arrayLayerCount = 1;
1129 vd.aspect = WGPUTextureAspect_DepthOnly;
1130 sampleView = wgpuTextureCreateView(texture, &vd);
1131 } else if (td.mipLevelCount > 1 && layers == 1) {
1132 sampleView = wgpuTextureCreateView(texture, nullptr);
1133 }
1134
1135 out = TextureRec{texture, view, sampleView,
1136 desc.width, desc.height, td.format, desc.format,
1137 packSamplerKey(desc.minFilter, desc.magFilter, desc.wrapS, desc.wrapT),
1138 td.sampleCount, td.mipLevelCount};
1139 out.storage = storage;
1140 out.layers = layers;
1141 out.volume = desc.volume;
1142
1143 if (pixels && !isDepthFormat(td.format) && (layers > 1 || desc.volume)) {
1144 // An array takes its layers in the rows given, as GL does (which cannot flip a 3D upload); a volume its slices,
1145 // each written at its depth as a layer is at its index.
1146 const usize layerBytes = static_cast<usize>(desc.width) * desc.height * gfxBytesPerPixel(desc.format);
1147 for (u32 layer = 0; layer < layers; ++layer) {
1148 writeTexture(out, 0, 0, desc.width, desc.height,
1149 static_cast<const u8*>(pixels) + layerBytes * layer, false, layer);
1150 }
1151 if (out.mipLevels > 1) buildMipChain(out);
1152 } else if (pixels && !isDepthFormat(td.format)) {
1153 // desc.flipY, not false: the caller's orientation request has to reach the
1154 // upload, which is where the row reversal happens (see writeTexture).
1155 writeTexture(out, 0, 0, desc.width, desc.height, pixels, desc.flipY);
1156 if (out.mipLevels > 1) buildMipChain(out);
1157 }
1158 return true;
1159}
1160
1161bool WebGPUDevice::backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) {
1162 TextureRec rec;
1163 if (!makeTexture(desc, pixels, rec)) return false;
1164 textures_[id] = rec;
1165 return true;
1166}
1167
1169 const void* data, u32 byteLength, u32 mipLevels) {
1170 if (!device_ || !queue_) {
1171 ES_LOG_ERROR("WebGPUDevice::createCompressedTexture: no device");
1172 return false;
1173 }
1174 const WGPUTextureFormat wgpuFmt = toWGPUCompressedFormat(format);
1175 if (wgpuFmt == WGPUTextureFormat_Undefined) {
1176 ES_LOG_ERROR("WebGPUDevice::createCompressedTexture: unmapped format");
1177 return false;
1178 }
1179 const u32 levels = mipLevels ? mipLevels : 1;
1180
1181 WGPUTextureDescriptor td{};
1182 td.dimension = WGPUTextureDimension_2D;
1183 td.format = wgpuFmt;
1184 td.size = WGPUExtent3D{desc.width, desc.height, 1};
1185 td.mipLevelCount = levels;
1186 td.sampleCount = 1;
1187 td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst; // compressed = sampled, never a target
1188
1189 WGPUTexture texture = wgpuDeviceCreateTexture(device_, &td);
1190 if (!texture) {
1191 ES_LOG_ERROR("WebGPUDevice::createCompressedTexture: creation failed ({}x{})", desc.width, desc.height);
1192 return false;
1193 }
1194
1195 // Upload each mip level from the concatenated pyramid. writeTexture counts
1196 // BLOCKS, not pixels (a partial edge block still counts a whole block).
1197 const GfxBlockInfo bi = gfxCompressedBlockInfo(format);
1198 const u8* ptr = static_cast<const u8*>(data);
1199 const u8* end = ptr + byteLength;
1200 for (u32 level = 0; ptr && level < levels; ++level) {
1201 const u32 lw = (desc.width >> level) ? (desc.width >> level) : 1u;
1202 const u32 lh = (desc.height >> level) ? (desc.height >> level) : 1u;
1203 const u32 blocksX = (lw + bi.blockWidth - 1) / bi.blockWidth;
1204 const u32 blocksY = (lh + bi.blockHeight - 1) / bi.blockHeight;
1205 const u32 levelBytes = blocksX * blocksY * bi.bytesPerBlock;
1206 if (levelBytes > static_cast<usize>(end - ptr)) break; // truncated pyramid
1207 WGPUTexelCopyTextureInfo dst{};
1208 dst.texture = texture;
1209 dst.mipLevel = level;
1210 dst.origin = WGPUOrigin3D{0, 0, 0};
1211 WGPUTexelCopyBufferLayout layout{};
1212 layout.bytesPerRow = blocksX * bi.bytesPerBlock;
1213 layout.rowsPerImage = blocksY;
1214 // The level's physical size, whole blocks: a level 634 texels tall is stored as 636, and a copy must name whole blocks. Its last
1215 // block row holds texels past the edge, which the sampler never reads.
1216 WGPUExtent3D extent{blocksX * bi.blockWidth, blocksY * bi.blockHeight, 1};
1217 wgpuQueueWriteTexture(queue_, &dst, ptr, levelBytes, &layout, &extent);
1218 ptr += levelBytes;
1219 }
1220
1221 // A compressed texture is never a depth one, so it samples through the view
1222 // it already has — the two members alias, as they do for any colour format.
1223 WGPUTextureView view = wgpuTextureCreateView(texture, nullptr);
1224 textures_[id] = TextureRec{texture, view, view,
1225 desc.width, desc.height, wgpuFmt, desc.format,
1226 packSamplerKey(desc.minFilter, desc.magFilter,
1227 desc.wrapS, desc.wrapT)};
1228 return true;
1229}
1230
1231void WebGPUDevice::releaseTexture(TextureRec& rec) {
1232#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
1233 if (metal_compute_ && rec.texture) metal_compute_->forgetTexture(rec.texture);
1234#endif
1235 // The sample view first, and only when it is a view of its own: for a colour
1236 // texture it aliases `view`, and releasing that twice frees a live object.
1237 if (rec.sampleView && rec.sampleView != rec.view) {
1238 evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(rec.sampleView)));
1239 wgpuTextureViewRelease(rec.sampleView);
1240 }
1241 if (rec.view) {
1242 evictBindGroups(static_cast<u64>(reinterpret_cast<uintptr_t>(rec.view)));
1243 wgpuTextureViewRelease(rec.view);
1244 }
1245 if (rec.texture) wgpuTextureRelease(rec.texture);
1246 rec = TextureRec{};
1247}
1248
1250 auto it = textures_.find(id);
1251 if (it == textures_.end()) return;
1252 releaseTexture(it->second);
1253 textures_.erase(it);
1254}
1255
1257 auto it = textures_.find(from);
1258 if (it == textures_.end()) return;
1259 textures_[into] = it->second;
1260 textures_.erase(from);
1261 for (u32 slot = 0; slot < kTextureSlots; ++slot) {
1262 if (texture_slots_[slot] == into || texture_slots_[slot] == from) bind_group_dirty_ = true;
1263 }
1264}
1265
1267 const void* pixels, bool flipY) {
1268 auto it = textures_.find(id);
1269 if (it == textures_.end()) return;
1270 writeTexture(it->second, x, y, width, height, pixels, flipY);
1271}
1272
1273void WebGPUDevice::writeTexture(const TextureRec& rec, i32 x, i32 y, u32 width, u32 height,
1274 const void* pixels, bool flipY, u32 layer) {
1275 if (!pixels || !queue_ || !rec.texture) return;
1276 if (isDepthFormat(rec.format)) {
1277 ES_LOG_ERROR("WebGPUDevice::updateTexture: depth-stencil textures are attachment-only");
1278 return;
1279 }
1280 WGPUTexelCopyTextureInfo dst{};
1281 dst.texture = rec.texture;
1282 dst.origin = WGPUOrigin3D{static_cast<u32>(x), static_cast<u32>(y), layer};
1283
1284 // Source rows are what the caller allocated; destination rows are the texel
1285 // size WebGPU stores. They differ for RGB8, which has no WebGPU format and so
1286 // lands in an RGBA8 texture — reading dstRow from the source is the over-read.
1287 const u32 srcBpp = gfxBytesPerPixel(rec.srcFormat);
1288 const u32 dstBpp = wgpuBytesPerPixel(rec.srcFormat);
1289 const usize dstRow = static_cast<usize>(width) * dstBpp;
1290
1291 WGPUTexelCopyBufferLayout layout{};
1292 layout.bytesPerRow = static_cast<u32>(dstRow);
1293 layout.rowsPerImage = height;
1294
1295 // Decoded images arrive top-first while the engine samples v upward. GL flips
1296 // with UNPACK_FLIP_Y_WEBGL; WebGPU has no pixel-store parameter, so rows are
1297 // reversed here — the same bytes GL sends, which is what keeps the two equal.
1298 const bool reverseRows = flipY && height > 1;
1299 std::vector<u8> staged;
1300 const void* src = pixels;
1301 if (reverseRows || srcBpp != dstBpp) {
1302 staged.resize(dstRow * height);
1303 stageTextureRows(staged.data(), static_cast<const u8*>(pixels),
1304 width, height, srcBpp, dstBpp, reverseRows);
1305 src = staged.data();
1306 }
1307
1308 WGPUExtent3D extent{width, height, 1};
1309 wgpuQueueWriteTexture(queue_, &dst, src, dstRow * height, &layout, &extent);
1310}
1311
1313 // GL's texture-object sampler state, de-combined: the texture record carries
1314 // its params key and the bind group pairs it with a cached sampler object.
1315 auto it = textures_.find(id);
1316 if (it == textures_.end()) return;
1317 const u8 key = packSamplerKey(desc.minFilter, desc.magFilter, desc.wrapS, desc.wrapT);
1318 if (it->second.samplerKey == key) return;
1319 it->second.samplerKey = key;
1320 for (u32 slot = 0; slot < kTextureSlots; ++slot) {
1321 if (texture_slots_[slot] == id) {
1322 bind_group_dirty_ = true;
1323 break;
1324 }
1325 }
1326}
1327
1329 auto it = textures_.find(id);
1330 if (it != textures_.end() && it->second.mipLevels > 1) buildMipChain(it->second);
1331}
1332
1334 if (slot >= kTextureSlots) return;
1335 const u32 id = static_cast<u32>(texture);
1336 if (texture_slots_[slot] != id) {
1337 texture_slots_[slot] = id;
1338 bind_group_dirty_ = true;
1339 }
1340}
1341
1343 if (toWGPUCompressedFormat(format) == WGPUTextureFormat_Undefined) return false;
1344 if (!device_) return false;
1345 // The DEVICE, not the adapter: a format the adapter offers is unusable until
1346 // the device was created asking for its feature, and createTexture rejects it
1347 // — which arrives as a texture that never loaded rather than as this answer.
1348 return wgpuDeviceHasFeature(device_, compressionFeatureFor(format)) != 0;
1349}
1350
1351// =============================================================================
1352// Programs (WGSL shader modules)
1353// =============================================================================
1354
1356 const GfxAttribBinding*, u32,
1357 std::string* outLog, GfxShaderStage* outFailedStage) {
1358 if (source.language != GfxShaderLanguage::WGSL) {
1359 if (outLog) *outLog = "WebGPUDevice compiles WGSL only";
1360 if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;
1361 ES_LOG_ERROR("WebGPUDevice::createProgram: unsupported shader language");
1362 return false;
1363 }
1364 if (!device_) {
1365 if (outLog) *outLog = "no WGPUDevice";
1366 ES_LOG_ERROR("WebGPUDevice::createProgram: no device");
1367 return false;
1368 }
1369
1370 // A stage that names `tN`/`sN` without declaring it cannot compile, and WebGPU says
1371 // so as an invalid PIPELINE naming no shader — so the refusal is here, where the
1372 // source is still in hand. check-wgsl-twin holds the repo's own to the same rule.
1373 const auto undeclared = [&](const char* src, const char* stage) -> bool {
1374 u32 reachedTex = 0;
1375 u32 reachedSam = 0;
1376 scanWGSLReachedUnits(src, reachedTex, reachedSam);
1377 const u64 declared = scanWGSLBindingMask(src, 1);
1378 for (u32 unit = 0; unit < 16; ++unit) {
1379 const bool tex = (reachedTex & (1u << unit)) != 0
1380 && (declared & (u64{1} << textureBindingForUnit(unit))) == 0;
1381 const bool sam = (reachedSam & (1u << unit)) != 0
1382 && (declared & (u64{1} << samplerBindingForUnit(unit))) == 0;
1383 if (!tex && !sam) continue;
1384 if (outLog) {
1385 *outLog = std::string("the ") + stage + " stage reaches "
1386 + (tex ? "t" : "s") + std::to_string(unit) + " and declares no binding for it";
1387 }
1388 ES_LOG_ERROR("WebGPUDevice::createProgram: the {} stage reaches {}{} and declares "
1389 "no binding for it", stage, tex ? "t" : "s", unit);
1390 return true;
1391 }
1392 return false;
1393 };
1394 if (undeclared(source.vertexSrc, "vertex")) {
1395 if (outFailedStage) *outFailedStage = GfxShaderStage::Vertex;
1396 return false;
1397 }
1398 if (undeclared(source.fragmentSrc, "fragment")) {
1399 if (outFailedStage) *outFailedStage = GfxShaderStage::Fragment;
1400 return false;
1401 }
1402
1403 auto makeModule = [&](const char* code) -> WGPUShaderModule {
1404 WGPUShaderSourceWGSL wgsl{};
1405 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
1406 wgsl.code = sv(code);
1407 WGPUShaderModuleDescriptor md{};
1408 md.nextInChain = &wgsl.chain;
1409 return wgpuDeviceCreateShaderModule(device_, &md);
1410 };
1411
1412 ProgramRec rec{};
1413 rec.vertex = makeModule(source.vertexSrc);
1414 rec.fragment = makeModule(source.fragmentSrc);
1415 // Reflection-by-scan: bind groups must match the pipeline's auto layout
1416 // exactly, so record which group-0 UBO slots and group-1 texture/sampler
1417 // bindings the program declares (twin discipline: declare = use).
1418 rec.group0Mask = scanWGSLBindingMask(source.vertexSrc, 0) |
1420 rec.group1Mask = scanWGSLBindingMask(source.vertexSrc, 1) |
1422 rec.group1DepthMask = scanWGSLDepthTextureMask(source.vertexSrc, 1) |
1424 rec.group1ArrayMask = scanWGSLArrayTextureMask(source.vertexSrc, 1) |
1426 rec.group1VolumeMask = scanWGSLVolumeTextureMask(source.vertexSrc, 1) |
1428 // What the VERTEX stage declares, on its own: a sampled texture is visible
1429 // to the fragment stage alone unless the layout says otherwise, and reading
1430 // one it was not given is a pipeline WebGPU rejects with nothing named.
1431 rec.group1VertexMask = scanWGSLBindingMask(source.vertexSrc, 1);
1432 rec.group1FragmentMask = scanWGSLBindingMask(source.fragmentSrc, 1);
1433 if (!rec.vertex || !rec.fragment) {
1434 if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);
1435 if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);
1436 if (outLog) *outLog = "shader module creation failed";
1437 if (outFailedStage) *outFailedStage = rec.vertex ? GfxShaderStage::Fragment : GfxShaderStage::Vertex;
1438 return false;
1439 }
1440
1441 programs_[id] = rec;
1442 return true;
1443}
1444
1446 auto it = programs_.find(id);
1447 if (it == programs_.end()) return;
1448 if (it->second.vertex) wgpuShaderModuleRelease(it->second.vertex);
1449 if (it->second.fragment) wgpuShaderModuleRelease(it->second.fragment);
1450 programs_.erase(it);
1451}
1452
1453// =============================================================================
1454// Pipelines (descriptors retained; WGPURenderPipeline built lazily per pass
1455// depth-stencil shape — WebGPU validates that coupling, GL never had it)
1456// =============================================================================
1457
1458WGPURenderPipeline WebGPUDevice::ensurePipeline(u32 id) {
1459 const PipelineDesc* described = pipelineDesc(PipelineHandle{id});
1460 if (!described || !device_) return nullptr;
1461 PipelineRec& built = pipelines_[id];
1462 const u32 dsVariant = dsVariantOf(pass_ds_format_);
1463 const PipelineDesc& desc = *described;
1464 const bool writesAlbedo = pass_albedo_ && desc.gbuffer && desc.albedo;
1465 const u32 gbufferVariant = !pass_gbuffer_ ? kGBufferNone
1466 : writesAlbedo ? kGBufferWritesAlbedo
1467 : desc.gbuffer ? kGBufferWrites : kGBufferSkips;
1468 const u32 variant = ((dsVariant * kColorVariantCount + colorVariantOf(pass_color_format_))
1469 * kSampleVariantCount + (pass_samples_ > 1 ? kMultiSample : kSingleSample))
1470 * kGBufferVariantCount + gbufferVariant;
1471 if (built.variants[variant]) return built.variants[variant];
1472
1473 auto progIt = programs_.find(static_cast<u32>(desc.program));
1474 const VertexLayoutDesc* layout = vertexLayoutDesc(desc.vertexLayout);
1475 if (progIt == programs_.end() || !layout) {
1476 ES_LOG_ERROR("WebGPUDevice::ensurePipeline: missing program or layout");
1477 return nullptr;
1478 }
1479 const VertexLayoutDesc& vl = *layout;
1480
1481 // RHI layout (attributes across up to 2 slots) -> per-slot WGPU buffer layouts.
1482 WGPUVertexAttribute attrs[MAX_VERTEX_ATTRIBUTES] = {};
1483 WGPUVertexBufferLayout slots[MAX_VERTEX_BUFFER_SLOTS] = {};
1484 u32 attrCursor = 0;
1485 u32 slotCount = 0;
1486 for (u32 slot = 0; slot < MAX_VERTEX_BUFFER_SLOTS; ++slot) {
1487 const u32 first = attrCursor;
1488 for (u32 i = 0; i < vl.attributeCount; ++i) {
1489 const auto& a = vl.attributes[i];
1490 if (a.bufferSlot != slot) continue;
1491 attrs[attrCursor].format = toWGPUVertexFormat(a.components, a.type, a.normalized);
1492 attrs[attrCursor].offset = a.offset;
1493 attrs[attrCursor].shaderLocation = a.location;
1494 ++attrCursor;
1495 }
1496 if (attrCursor == first) continue;
1497 slots[slotCount].stepMode = vl.instanceStep[slot] ? WGPUVertexStepMode_Instance
1498 : WGPUVertexStepMode_Vertex;
1499 slots[slotCount].arrayStride = vl.strides[slot];
1500 slots[slotCount].attributeCount = attrCursor - first;
1501 slots[slotCount].attributes = &attrs[first];
1502 ++slotCount;
1503 }
1504
1505 const BlendStateWGPU blend = toWGPUBlend(desc.blend, desc.layerAlpha);
1506 WGPUBlendState blendState{};
1507 blendState.color = blend.color;
1508 blendState.alpha = blend.alpha;
1509
1510 WGPUColorTargetState targets[3]{};
1511 targets[0].format = pass_color_format_;
1512 targets[0].blend = desc.blendEnabled ? &blendState : nullptr;
1513 targets[0].writeMask = (writesStencil(desc.stencil) || !desc.colorWrite) ? WGPUColorWriteMask_None
1514 : WGPUColorWriteMask_All;
1515 // The second attachment, when the pass has one: written by a shader that has the output, and
1516 // declared with an empty write mask by every other — WebGPU asks the pipeline to account for
1517 // every attachment of the pass, and a shader with one output may not be given a mask that
1518 // would write the second. Never blended: a normal averaged with what was there is neither's.
1519 targets[1].format = WGPUTextureFormat_RGBA8Unorm;
1520 targets[1].writeMask = (desc.gbuffer && desc.colorWrite && !writesStencil(desc.stencil)) ? WGPUColorWriteMask_All
1521 : WGPUColorWriteMask_None;
1522 // The third, the albedo, the same way: written only by a shader that has a location-2 output.
1523 targets[2].format = WGPUTextureFormat_RGBA8Unorm;
1524 targets[2].writeMask = (writesAlbedo && desc.colorWrite && !writesStencil(desc.stencil)) ? WGPUColorWriteMask_All
1525 : WGPUColorWriteMask_None;
1526
1527 WGPUFragmentState fragment{};
1528 fragment.module = progIt->second.fragment;
1529 fragment.entryPoint = sv("fs_main");
1530 fragment.targetCount = !pass_gbuffer_ ? 1 : pass_albedo_ ? 3 : 2;
1531 fragment.targets = targets;
1532
1533 WGPURenderPipelineDescriptor pd{};
1534 // Explicit layout from the program's binding masks — the same cached
1535 // objects flushBindGroup builds bind groups against, so declared-but-
1536 // unbound bindings are legal (dummy backfill) and group compatibility
1537 // holds by identity.
1538 pd.layout = pipelineLayoutFor(progIt->second.group0Mask, progIt->second.group1Mask,
1539 progIt->second.group1DepthMask,
1540 progIt->second.group1VertexMask,
1541 progIt->second.group1ArrayMask,
1542 progIt->second.group1VolumeMask, progIt->second.group1FragmentMask);
1543 pd.vertex.module = progIt->second.vertex;
1544 pd.vertex.entryPoint = sv("vs_main");
1545 pd.vertex.bufferCount = slotCount;
1546 pd.vertex.buffers = slots;
1547 pd.primitive.topology = desc.topology == GfxTopology::Lines ? WGPUPrimitiveTopology_LineList
1548 : WGPUPrimitiveTopology_TriangleList;
1549 // Every vertex stage of this device turns clip y over, so a target's rows land bottom-up as GL lays them; that mirrors
1550 // each triangle on the way to the target, so the winding GL calls front (counter-clockwise) arrives clockwise.
1551 pd.primitive.frontFace = WGPUFrontFace_CW;
1552 pd.primitive.cullMode = toWGPUCullMode(desc.cullEnabled, desc.cullFront);
1553 // The pass's count, which WebGPU validates against the attachment: a pipeline
1554 // built for one sample cannot draw into a multisampled target at all.
1555 pd.multisample.count = pass_samples_;
1556 pd.multisample.mask = 0xFFFFFFFFu;
1557 // WebGPU refuses coverage from alpha on a single-sampled pipeline.
1558 pd.multisample.alphaToCoverageEnabled = desc.alphaToCoverage && pass_samples_ > 1;
1559 pd.fragment = &fragment;
1560 WGPUDepthStencilState ds{};
1561 if (dsVariant != kDsNone) {
1562 ds = toWGPUDepthStencil(desc, pass_ds_format_);
1563 pd.depthStencil = &ds;
1564 } else if (desc.depthTest || desc.stencil != GfxStencilMode::Off) {
1565 ES_LOG_WARN("WebGPUDevice::ensurePipeline: depth/stencil requested but the "
1566 "pass target has no depth-stencil attachment");
1567 }
1568
1569 built.variants[variant] = wgpuDeviceCreateRenderPipeline(device_, &pd);
1570 if (!built.variants[variant]) {
1571 ES_LOG_ERROR("WebGPUDevice::ensurePipeline: creation failed");
1572 }
1573 return built.variants[variant];
1574}
1575
1577 bound_pipeline_ = id;
1578 if (!pass_) return;
1579 if (WGPURenderPipeline p = ensurePipeline(id)) {
1580 if (p == pass_pipeline_) return;
1581 wgpuRenderPassEncoderSetPipeline(pass_, p);
1582 pass_pipeline_ = p;
1583 bind_group_dirty_ = true;
1584 }
1585}
1586
1588 stencil_ref_ = reference;
1589 if (pass_) wgpuRenderPassEncoderSetStencilReference(pass_, static_cast<u32>(reference));
1590}
1591
1592WGPUSampler WebGPUDevice::samplerFor(u8 key) {
1593 auto it = samplers_.find(key);
1594 if (it != samplers_.end()) return it->second;
1595 if (!device_) return nullptr;
1596
1597 WGPUSamplerDescriptor sd{};
1598 sd.minFilter = (key & 1u) ? WGPUFilterMode_Nearest : WGPUFilterMode_Linear;
1599 sd.magFilter = (key & 2u) ? WGPUFilterMode_Nearest : WGPUFilterMode_Linear;
1600 sd.addressModeU = toWGPUAddressMode(static_cast<TextureWrap>((key >> 2) & 3u));
1601 sd.addressModeV = toWGPUAddressMode(static_cast<TextureWrap>((key >> 4) & 3u));
1602 sd.addressModeW = WGPUAddressMode_ClampToEdge;
1603 // Trilinear across mips when a texture has them (compressed KTX2 pyramids);
1604 // with a single mip WebGPU samples level 0 unchanged, so this is harmless for
1605 // the still-common single-mip textures.
1606 sd.mipmapFilter = WGPUMipmapFilterMode_Linear;
1607 sd.lodMinClamp = 0.0f;
1608 sd.lodMaxClamp = 32.0f;
1609 // Sharpened at a slant (a floor, a hair card, a sleeve seen edge-on): the sampler takes extra samples along the footprint's long side.
1610 // WebGPU allows it only when every filter is linear, so a nearest-filtered sampler stays at one.
1611 sd.maxAnisotropy = (key & 3u) == 0u ? 16 : 1;
1612 WGPUSampler sampler = wgpuDeviceCreateSampler(device_, &sd);
1613 samplers_[key] = sampler;
1614 return sampler;
1615}
1616
1617// =============================================================================
1618// Depth resolve — the half WebGPU does not do: a depth attachment has no
1619// resolveTarget, so a fullscreen pass writes sample 0 into the single-sample
1620// twin. Stencil does not come along; a shader cannot write it.
1621// =============================================================================
1622
1623WGPURenderPipeline WebGPUDevice::ensureDepthResolvePipeline(WGPUTextureFormat format) {
1624 const u32 key = static_cast<u32>(format);
1625 auto it = depth_resolve_pipelines_.find(key);
1626 if (it != depth_resolve_pipelines_.end()) return it->second;
1627 if (!device_) return nullptr;
1628
1629 static const char* kVS = R"(
1630@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4f {
1631 var p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(3.0, 1.0), vec2f(-1.0, 1.0));
1632 return vec4f(p[i], 0.0, 1.0);
1633}
1634)";
1635 static const char* kFS = R"(
1636@group(0) @binding(0) var src : texture_depth_multisampled_2d;
1637@fragment fn fs_main(@builtin(position) pos : vec4f) -> @builtin(frag_depth) f32 {
1638 return textureLoad(src, vec2i(i32(pos.x), i32(pos.y)), 0);
1639}
1640)";
1641 auto makeModule = [&](const char* code) {
1642 WGPUShaderSourceWGSL wgsl{};
1643 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
1644 wgsl.code = sv(code);
1645 WGPUShaderModuleDescriptor md{};
1646 md.nextInChain = &wgsl.chain;
1647 return wgpuDeviceCreateShaderModule(device_, &md);
1648 };
1649 if (!depth_resolve_vs_) depth_resolve_vs_ = makeModule(kVS);
1650 if (!depth_resolve_fs_) depth_resolve_fs_ = makeModule(kFS);
1651 if (!depth_resolve_bgl_) {
1652 WGPUBindGroupLayoutEntry ble{};
1653 ble.binding = 0;
1654 ble.visibility = WGPUShaderStage_Fragment;
1655 ble.texture.sampleType = WGPUTextureSampleType_Depth;
1656 ble.texture.viewDimension = WGPUTextureViewDimension_2D;
1657 ble.texture.multisampled = true;
1658 WGPUBindGroupLayoutDescriptor bld{};
1659 bld.entryCount = 1;
1660 bld.entries = &ble;
1661 depth_resolve_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
1662 WGPUPipelineLayoutDescriptor pld{};
1663 pld.bindGroupLayoutCount = 1;
1664 pld.bindGroupLayouts = &depth_resolve_bgl_;
1665 depth_resolve_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
1666 }
1667
1668 WGPURenderPipelineDescriptor pd{};
1669 pd.layout = depth_resolve_layout_;
1670 pd.vertex.module = depth_resolve_vs_;
1671 pd.vertex.entryPoint = sv("vs_main");
1672 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
1673 pd.primitive.frontFace = WGPUFrontFace_CCW;
1674 pd.primitive.cullMode = WGPUCullMode_None;
1675 pd.multisample.count = 1;
1676 pd.multisample.mask = 0xFFFFFFFFu;
1677 // No colour target: the pass writes depth and nothing else.
1678 WGPUFragmentState fragment{};
1679 fragment.module = depth_resolve_fs_;
1680 fragment.entryPoint = sv("fs_main");
1681 fragment.targetCount = 0;
1682 pd.fragment = &fragment;
1683 WGPUDepthStencilState ds{};
1684 ds.format = format;
1685 ds.depthWriteEnabled = WGPUOptionalBool_True;
1686 ds.depthCompare = WGPUCompareFunction_Always;
1687 WGPUStencilFaceState face{};
1688 face.compare = WGPUCompareFunction_Always;
1689 face.failOp = WGPUStencilOperation_Keep;
1690 face.depthFailOp = WGPUStencilOperation_Keep;
1691 face.passOp = WGPUStencilOperation_Keep;
1692 ds.stencilFront = face;
1693 ds.stencilBack = face;
1694 ds.stencilReadMask = 0xFFFFFFFFu;
1695 ds.stencilWriteMask = 0u;
1696 pd.depthStencil = &ds;
1697
1698 WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
1699 if (!pipeline) ES_LOG_ERROR("WebGPUDevice: depth resolve pipeline creation failed");
1700 depth_resolve_pipelines_[key] = pipeline;
1701 return pipeline;
1702}
1703
1704WGPURenderPipeline WebGPUDevice::ensureMipPipeline(WGPUTextureFormat format) {
1705 const u32 key = static_cast<u32>(format);
1706 auto it = mip_pipelines_.find(key);
1707 if (it != mip_pipelines_.end()) return it->second;
1708 if (!device_) return nullptr;
1709
1710 // The triangle's uv runs down the target as its rows do, so a level keeps the
1711 // orientation of the one it is made from.
1712 static const char* kWGSL = R"(
1713struct VSOut { @builtin(position) pos : vec4f, @location(0) uv : vec2f };
1714@vertex fn vs_main(@builtin(vertex_index) i : u32) -> VSOut {
1715 var p = array<vec2f, 3>(vec2f(-1.0, 1.0), vec2f(3.0, 1.0), vec2f(-1.0, -3.0));
1716 var out : VSOut;
1717 out.pos = vec4f(p[i], 0.0, 1.0);
1718 out.uv = vec2f(p[i].x * 0.5 + 0.5, 0.5 - p[i].y * 0.5);
1719 return out;
1720}
1721@group(0) @binding(0) var src : texture_2d<f32>;
1722@group(0) @binding(1) var smp : sampler;
1723@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
1724 return textureSampleLevel(src, smp, v.uv, 0.0);
1725}
1726)";
1727 if (!mip_module_) {
1728 WGPUShaderSourceWGSL wgsl{};
1729 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
1730 wgsl.code = sv(kWGSL);
1731 WGPUShaderModuleDescriptor md{};
1732 md.nextInChain = &wgsl.chain;
1733 mip_module_ = wgpuDeviceCreateShaderModule(device_, &md);
1734 }
1735 if (!mip_bgl_) {
1736 WGPUBindGroupLayoutEntry entries[2]{};
1737 entries[0].binding = 0;
1738 entries[0].visibility = WGPUShaderStage_Fragment;
1739 entries[0].texture.sampleType = WGPUTextureSampleType_Float;
1740 entries[0].texture.viewDimension = WGPUTextureViewDimension_2D;
1741 entries[1].binding = 1;
1742 entries[1].visibility = WGPUShaderStage_Fragment;
1743 entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
1744 WGPUBindGroupLayoutDescriptor bld{};
1745 bld.entryCount = 2;
1746 bld.entries = entries;
1747 mip_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
1748 WGPUPipelineLayoutDescriptor pld{};
1749 pld.bindGroupLayoutCount = 1;
1750 pld.bindGroupLayouts = &mip_bgl_;
1751 mip_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
1752 WGPUSamplerDescriptor sd{};
1753 sd.minFilter = WGPUFilterMode_Linear;
1754 sd.magFilter = WGPUFilterMode_Linear;
1755 sd.mipmapFilter = WGPUMipmapFilterMode_Nearest;
1756 sd.addressModeU = WGPUAddressMode_ClampToEdge;
1757 sd.addressModeV = WGPUAddressMode_ClampToEdge;
1758 sd.addressModeW = WGPUAddressMode_ClampToEdge;
1759 sd.lodMaxClamp = 32.0f;
1760 sd.maxAnisotropy = 1;
1761 mip_sampler_ = wgpuDeviceCreateSampler(device_, &sd);
1762 }
1763
1764 WGPURenderPipelineDescriptor pd{};
1765 pd.layout = mip_layout_;
1766 pd.vertex.module = mip_module_;
1767 pd.vertex.entryPoint = sv("vs_main");
1768 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
1769 pd.primitive.frontFace = WGPUFrontFace_CCW;
1770 pd.primitive.cullMode = WGPUCullMode_None;
1771 pd.multisample.count = 1;
1772 pd.multisample.mask = 0xFFFFFFFFu;
1773 WGPUColorTargetState target{};
1774 target.format = format;
1775 target.writeMask = WGPUColorWriteMask_All;
1776 WGPUFragmentState fragment{};
1777 fragment.module = mip_module_;
1778 fragment.entryPoint = sv("fs_main");
1779 fragment.targetCount = 1;
1780 fragment.targets = &target;
1781 pd.fragment = &fragment;
1782
1783 WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
1784 if (!pipeline) ES_LOG_ERROR("WebGPUDevice: mip pipeline creation failed");
1785 mip_pipelines_[key] = pipeline;
1786 return pipeline;
1787}
1788
1789void WebGPUDevice::buildMipChain(const TextureRec& rec) {
1790 if (!device_ || !queue_ || rec.mipLevels < 2) return;
1791 WGPURenderPipeline pipeline = ensureMipPipeline(rec.format);
1792 if (!pipeline) return;
1793
1794 // Its own encoder, submitted at once: an upload can land in the middle of a
1795 // frame, and the frame's encoder may have a pass open.
1796 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
1797 if (!encoder) return;
1798 // Each layer of an array is its own chain: views[layer * mipLevels + level] is one level of one layer.
1799 std::vector<WGPUTextureView> views;
1800 std::vector<WGPUBindGroup> groups;
1801 for (u32 layer = 0; layer < rec.layers; ++layer) {
1802 for (u32 level = 0; level < rec.mipLevels; ++level) {
1803 WGPUTextureViewDescriptor vd{};
1804 vd.format = rec.format;
1805 vd.dimension = WGPUTextureViewDimension_2D;
1806 vd.baseMipLevel = level;
1807 vd.mipLevelCount = 1;
1808 vd.baseArrayLayer = layer;
1809 vd.arrayLayerCount = 1;
1810 vd.aspect = WGPUTextureAspect_All;
1811 views.push_back(wgpuTextureCreateView(rec.texture, &vd));
1812 }
1813 }
1814 for (u32 step = 0; step < rec.layers * rec.mipLevels; ++step) {
1815 const u32 level = step % rec.mipLevels;
1816 if (level == 0) continue;
1817 WGPUBindGroupEntry entries[2]{};
1818 entries[0].binding = 0;
1819 entries[0].textureView = views[step - 1];
1820 entries[1].binding = 1;
1821 entries[1].sampler = mip_sampler_;
1822 WGPUBindGroupDescriptor bgd{};
1823 bgd.layout = mip_bgl_;
1824 bgd.entryCount = 2;
1825 bgd.entries = entries;
1826 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
1827 if (!group) break;
1828 groups.push_back(group);
1829
1830 WGPURenderPassColorAttachment color{};
1831 color.view = views[step];
1832 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
1833 color.loadOp = WGPULoadOp_Clear;
1834 color.storeOp = WGPUStoreOp_Store;
1835 WGPURenderPassDescriptor rp{};
1836 rp.colorAttachmentCount = 1;
1837 rp.colorAttachments = &color;
1838 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &rp);
1839 if (!pass) break;
1840 wgpuRenderPassEncoderSetPipeline(pass, pipeline);
1841 wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0, nullptr);
1842 wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
1843 wgpuRenderPassEncoderEnd(pass);
1844 wgpuRenderPassEncoderRelease(pass);
1845 }
1846 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
1847 if (commands) {
1848 wgpuQueueSubmit(queue_, 1, &commands);
1849 wgpuCommandBufferRelease(commands);
1850 }
1851 wgpuCommandEncoderRelease(encoder);
1852 for (WGPUBindGroup group : groups) wgpuBindGroupRelease(group);
1853 for (WGPUTextureView view : views) wgpuTextureViewRelease(view);
1854}
1855
1856void WebGPUDevice::resolveDepthAttachment(u32 msaaDepth, u32 resolveDepth) {
1857 if (!device_ || !encoder_) return;
1858 auto srcIt = textures_.find(msaaDepth);
1859 auto dstIt = textures_.find(resolveDepth);
1860 if (srcIt == textures_.end() || dstIt == textures_.end()) return;
1861 WGPURenderPipeline pipeline = ensureDepthResolvePipeline(dstIt->second.format);
1862 if (!pipeline) return;
1863
1864 // The MULTISAMPLED view, not the depth-only sample view: a multisampled depth
1865 // texture is read through `texture_depth_multisampled_2d`, whose view carries
1866 // every aspect the texture has.
1867 WGPUBindGroupEntry entry{};
1868 entry.binding = 0;
1869 entry.textureView = srcIt->second.sampleView;
1870 WGPUBindGroupDescriptor bgd{};
1871 bgd.layout = depth_resolve_bgl_;
1872 bgd.entryCount = 1;
1873 bgd.entries = &entry;
1874 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
1875 if (!group) return;
1876
1877 WGPURenderPassDepthStencilAttachment ds{};
1878 ds.view = dstIt->second.view;
1879 ds.depthLoadOp = WGPULoadOp_Clear;
1880 ds.depthStoreOp = WGPUStoreOp_Store;
1881 ds.depthClearValue = 1.0f;
1882 if (hasStencilPlanes(dstIt->second.format)) {
1883 ds.stencilLoadOp = WGPULoadOp_Clear;
1884 ds.stencilStoreOp = WGPUStoreOp_Store;
1885 }
1886 WGPURenderPassDescriptor rp{};
1887 rp.colorAttachmentCount = 0;
1888 rp.depthStencilAttachment = &ds;
1889
1890 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder_, &rp);
1891 if (pass) {
1892 wgpuRenderPassEncoderSetPipeline(pass, pipeline);
1893 wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0, nullptr);
1894 wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
1895 wgpuRenderPassEncoderEnd(pass);
1896 wgpuRenderPassEncoderRelease(pass);
1897 }
1898 wgpuBindGroupRelease(group);
1899}
1900
1901// =============================================================================
1902// Internal clear family — the two clears WebGPU load-ops cannot spell: a
1903// region-scoped pass clear and a mid-pass stencil reset. A fullscreen triangle
1904// at z=1 (GL's clear depth) writes exactly the attachments requested: color via
1905// the write mask, depth via depthWriteEnabled + Always, stencil via
1906// Replace + the encoder's stencil reference.
1907// =============================================================================
1908
1909WGPURenderPipeline WebGPUDevice::ensureClearPipeline(bool color, bool depth, bool stencil) {
1910 // The sample count is part of the key for the same reason the formats are:
1911 // a clear pipeline is validated against the pass it runs in.
1912 const u32 key = (pass_gbuffer_ ? 1u << 12 : 0u) | (pass_albedo_ ? 1u << 13 : 0u) |
1913 colorVariantOf(pass_color_format_) << 6 |
1914 dsVariantOf(pass_ds_format_) << 4 |
1915 (pass_samples_ > 1 ? 8u : 0u) |
1916 (color ? 1u : 0u) | (depth ? 2u : 0u) | (stencil ? 4u : 0u);
1917 auto it = clear_pipelines_.find(key);
1918 if (it != clear_pipelines_.end()) return it->second;
1919
1920 static const char* kClearVS = R"(
1921@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4f {
1922 var p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(3.0, 1.0), vec2f(-1.0, 1.0));
1923 return vec4f(p[i], 1.0, 1.0);
1924}
1925)";
1926 static const char* kClearFS = R"(
1927struct ClearColor { value : vec4f };
1928@group(0) @binding(0) var<uniform> clearColor : ClearColor;
1929@fragment fn fs_main() -> @location(0) vec4f { return clearColor.value; }
1930)";
1931 auto makeModule = [&](const char* code) {
1932 WGPUShaderSourceWGSL wgsl{};
1933 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
1934 wgsl.code = sv(code);
1935 WGPUShaderModuleDescriptor md{};
1936 md.nextInChain = &wgsl.chain;
1937 return wgpuDeviceCreateShaderModule(device_, &md);
1938 };
1939
1940 // One explicit layout for the whole family, so the single bind group is
1941 // valid with every write-mask variant (auto layouts are per-pipeline).
1942 if (!clear_bgl_) {
1943 WGPUBindGroupLayoutEntry ble{};
1944 ble.binding = 0;
1945 ble.visibility = WGPUShaderStage_Fragment;
1946 ble.buffer.type = WGPUBufferBindingType_Uniform;
1947 ble.buffer.minBindingSize = 16;
1948 WGPUBindGroupLayoutDescriptor bld{};
1949 bld.entryCount = 1;
1950 bld.entries = &ble;
1951 clear_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
1952
1953 WGPUPipelineLayoutDescriptor pld{};
1954 pld.bindGroupLayoutCount = 1;
1955 pld.bindGroupLayouts = &clear_bgl_;
1956 clear_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
1957
1958 clear_color_buffer_ = makeBuffer(GfxBufferUsage::Uniform, 16, nullptr);
1959 WGPUBindGroupEntry entry{};
1960 entry.binding = 0;
1961 entry.buffer = clear_color_buffer_;
1962 entry.offset = 0;
1963 entry.size = 16;
1964 WGPUBindGroupDescriptor bgd{};
1965 bgd.layout = clear_bgl_;
1966 bgd.entryCount = 1;
1967 bgd.entries = &entry;
1968 clear_bind_group_ = wgpuDeviceCreateBindGroup(device_, &bgd);
1969 }
1970
1971 WGPUShaderModule vs = makeModule(kClearVS);
1972 WGPUShaderModule fs = makeModule(kClearFS);
1973
1974 WGPUColorTargetState clearTargets[3]{};
1975 clearTargets[0].format = pass_color_format_;
1976 clearTargets[0].writeMask = color ? WGPUColorWriteMask_All : WGPUColorWriteMask_None;
1977 // A scoped clear is the camera's background, which a surface record has no part in.
1978 clearTargets[1].format = WGPUTextureFormat_RGBA8Unorm;
1979 clearTargets[1].writeMask = WGPUColorWriteMask_None;
1980 clearTargets[2].format = WGPUTextureFormat_RGBA8Unorm;
1981 clearTargets[2].writeMask = WGPUColorWriteMask_None;
1982
1983 WGPUFragmentState fragment{};
1984 fragment.module = fs;
1985 fragment.entryPoint = sv("fs_main");
1986 fragment.targetCount = !pass_gbuffer_ ? 1 : pass_albedo_ ? 3 : 2;
1987 fragment.targets = clearTargets;
1988
1989 WGPURenderPipelineDescriptor pd{};
1990 pd.layout = clear_layout_;
1991 pd.vertex.module = vs;
1992 pd.vertex.entryPoint = sv("vs_main");
1993 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
1994 pd.primitive.frontFace = WGPUFrontFace_CCW;
1995 pd.primitive.cullMode = WGPUCullMode_None;
1996 pd.multisample.count = pass_samples_;
1997 pd.multisample.mask = 0xFFFFFFFFu;
1998 pd.fragment = &fragment;
1999
2000 WGPUDepthStencilState ds{};
2001 if (pass_ds_format_ != WGPUTextureFormat_Undefined) {
2002 ds.format = pass_ds_format_;
2003 ds.depthCompare = WGPUCompareFunction_Always;
2004 ds.depthWriteEnabled = depth ? WGPUOptionalBool_True : WGPUOptionalBool_False;
2005 WGPUStencilFaceState face{};
2006 face.compare = WGPUCompareFunction_Always;
2007 face.failOp = stencil ? WGPUStencilOperation_Replace : WGPUStencilOperation_Keep;
2008 face.depthFailOp = face.failOp;
2009 face.passOp = face.failOp;
2010 ds.stencilFront = face;
2011 ds.stencilBack = face;
2012 ds.stencilReadMask = 0xFFu;
2013 ds.stencilWriteMask = stencil ? 0xFFu : 0x00u;
2014 pd.depthStencil = &ds;
2015 }
2016
2017 WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
2018 wgpuShaderModuleRelease(vs);
2019 wgpuShaderModuleRelease(fs);
2020 clear_pipelines_[key] = pipeline;
2021 return pipeline;
2022}
2023
2024void WebGPUDevice::drawInternalClear(bool color, bool depth, bool stencil,
2025 const f32 rgba[4], i32 stencilValue,
2026 const RenderPassDesc* region) {
2027 if (!pass_ || !device_) return;
2028 WGPURenderPipeline pipeline = ensureClearPipeline(color, depth, stencil);
2029 if (!pipeline || !clear_bind_group_) return;
2030
2031 const f32 black[4] = {0.0f, 0.0f, 0.0f, 0.0f};
2032 writeBufferPadded(clear_color_buffer_, 0, rgba ? rgba : black, 16);
2033
2034 // A region rides its own scissor and restores the full target; without one
2035 // (mid-pass stencil reset) the currently active scissor applies — the same
2036 // rectangle glClear would have honored.
2037 if (region) {
2038 setScissor(region->clearX, region->clearY,
2039 static_cast<i32>(region->clearW), static_cast<i32>(region->clearH));
2040 }
2041 wgpuRenderPassEncoderSetPipeline(pass_, pipeline);
2042 wgpuRenderPassEncoderSetBindGroup(pass_, 0, clear_bind_group_, 0, nullptr);
2043 if (stencil) {
2044 wgpuRenderPassEncoderSetStencilReference(pass_, static_cast<u32>(stencilValue));
2045 }
2046 wgpuRenderPassEncoderDraw(pass_, 3, 1, 0, 0);
2047 if (region) {
2048 wgpuRenderPassEncoderSetScissorRect(pass_, 0, 0, pass_width_, pass_height_);
2049 }
2050 if (stencil) {
2051 wgpuRenderPassEncoderSetStencilReference(pass_, static_cast<u32>(stencil_ref_));
2052 }
2053
2054 bound_pipeline_ = 0;
2055 pass_pipeline_ = nullptr;
2056 bind_group_dirty_ = true;
2057}
2058
2059WGPURenderPipeline WebGPUDevice::ensureFlipPipeline(WGPUTextureFormat format, bool flip) {
2060 const u32 key = static_cast<u32>(format) | (flip ? 0u : 0x80000000u);
2061 if (auto it = flip_pipelines_.find(key); it != flip_pipelines_.end()) return it->second;
2062 static const char* kFlipVS = R"(
2063@vertex fn vs_main(@builtin(vertex_index) i : u32) -> @builtin(position) vec4f {
2064 var p = array<vec2f, 3>(vec2f(-1.0, -3.0), vec2f(3.0, 1.0), vec2f(-1.0, 1.0));
2065 return vec4f(p[i], 0.0, 1.0);
2066}
2067)";
2068 static const char* kFlipFS = R"(
2069@group(0) @binding(0) var source : texture_2d<f32>;
2070@fragment fn fs_main(@builtin(position) at : vec4f) -> @location(0) vec4f {
2071 let size = vec2i(textureDimensions(source));
2072 return textureLoad(source, vec2i(i32(at.x), size.y - 1 - i32(at.y)), 0);
2073}
2074)";
2075 static const char* kCopyFS = R"(
2076@group(0) @binding(0) var source : texture_2d<f32>;
2077@fragment fn fs_main(@builtin(position) at : vec4f) -> @location(0) vec4f {
2078 return textureLoad(source, vec2i(i32(at.x), i32(at.y)), 0);
2079}
2080)";
2081 auto makeModule = [&](const char* code) {
2082 WGPUShaderSourceWGSL wgsl{};
2083 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
2084 wgsl.code = sv(code);
2085 WGPUShaderModuleDescriptor md{};
2086 md.nextInChain = &wgsl.chain;
2087 return wgpuDeviceCreateShaderModule(device_, &md);
2088 };
2089 if (!flip_bgl_) {
2090 WGPUBindGroupLayoutEntry entry{};
2091 entry.binding = 0;
2092 entry.visibility = WGPUShaderStage_Fragment;
2093 entry.texture.sampleType = WGPUTextureSampleType_UnfilterableFloat;
2094 entry.texture.viewDimension = WGPUTextureViewDimension_2D;
2095 WGPUBindGroupLayoutDescriptor bld{};
2096 bld.entryCount = 1;
2097 bld.entries = &entry;
2098 flip_bgl_ = wgpuDeviceCreateBindGroupLayout(device_, &bld);
2099 WGPUPipelineLayoutDescriptor pld{};
2100 pld.bindGroupLayoutCount = 1;
2101 pld.bindGroupLayouts = &flip_bgl_;
2102 flip_layout_ = wgpuDeviceCreatePipelineLayout(device_, &pld);
2103 }
2104 WGPUShaderModule vs = makeModule(kFlipVS);
2105 WGPUShaderModule fs = makeModule(flip ? kFlipFS : kCopyFS);
2106 WGPUColorTargetState target{};
2107 target.format = format;
2108 target.writeMask = WGPUColorWriteMask_All;
2109 WGPUFragmentState fragment{};
2110 fragment.module = fs;
2111 fragment.entryPoint = sv("fs_main");
2112 fragment.targetCount = 1;
2113 fragment.targets = &target;
2114 WGPURenderPipelineDescriptor pd{};
2115 pd.layout = flip_layout_;
2116 pd.vertex.module = vs;
2117 pd.vertex.entryPoint = sv("vs_main");
2118 pd.primitive.topology = WGPUPrimitiveTopology_TriangleList;
2119 pd.primitive.frontFace = WGPUFrontFace_CCW;
2120 pd.primitive.cullMode = WGPUCullMode_None;
2121 pd.multisample.count = 1;
2122 pd.multisample.mask = 0xFFFFFFFFu;
2123 pd.fragment = &fragment;
2124 WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device_, &pd);
2125 wgpuShaderModuleRelease(vs);
2126 wgpuShaderModuleRelease(fs);
2127 flip_pipelines_[key] = pipeline;
2128 return pipeline;
2129}
2130
2131bool WebGPUDevice::surfaceAllowsCopy() const {
2132#if !defined(__EMSCRIPTEN__)
2133 if (surface_ && adapter_) {
2134 WGPUSurfaceCapabilities caps{};
2135 if (wgpuSurfaceGetCapabilities(surface_, adapter_, &caps) == WGPUStatus_Success) {
2136 const bool allowed = (caps.usages & WGPUTextureUsage_CopySrc) != 0;
2137 wgpuSurfaceCapabilitiesFreeMembers(caps);
2138 return allowed;
2139 }
2140 }
2141#endif
2142 return true;
2143}
2144
2145bool WebGPUDevice::copyFramebufferColor(FramebufferHandle source, TextureHandle dst) {
2146 if (!device_ || !isDeviceUsable()) return false;
2147 const auto to = textures_.find(static_cast<u32>(dst));
2148 if (to == textures_.end() || to->second.samples > 1 || to->second.layers > 1 || to->second.volume) return false;
2149 if (pass_) endRenderPass();
2150
2151 WGPUTexture from = nullptr;
2152 WGPUTextureFormat fromFormat = WGPUTextureFormat_Undefined;
2153 u32 width = 0;
2154 u32 height = 0;
2155 if (source == FramebufferHandle::Default) {
2156 if (!surface_readback_) {
2157 if (!surfaceAllowsCopy()) return false;
2158 surface_readback_ = true;
2159 surface_reconfigure_ = true;
2160 return false;
2161 }
2162 if (surface_reconfigure_ || (!frame_texture_ && !surface_proxy_drawn_) || !surface_proxy_) return false;
2163 from = surface_proxy_;
2164 fromFormat = surface_format_;
2165 width = surface_width_;
2166 height = surface_height_;
2167 } else {
2168 const FramebufferDesc* fb = framebufferDesc(source);
2169 if (!fb) return false;
2170 auto color = textures_.find(static_cast<u32>(fb->color0));
2171 if (color != textures_.end() && color->second.samples > 1) color = textures_.find(static_cast<u32>(fb->resolveColor0));
2172 if (color == textures_.end() || color->second.samples > 1) return false;
2173 from = color->second.texture;
2174 fromFormat = color->second.format;
2175 width = color->second.width;
2176 height = color->second.height;
2177 }
2178 if (!from || width != to->second.width || height != to->second.height) return false;
2179
2180 const bool direct = fromFormat == to->second.format;
2181 WGPUTexture target = to->second.texture;
2182 if (!direct) {
2183 if (!surface_copy_ || surface_copy_format_ != fromFormat || surface_copy_width_ != width || surface_copy_height_ != height) {
2184 if (surface_copy_view_) { wgpuTextureViewRelease(surface_copy_view_); surface_copy_view_ = nullptr; }
2185 if (surface_copy_) { wgpuTextureRelease(surface_copy_); surface_copy_ = nullptr; }
2186 WGPUTextureDescriptor td{};
2187 td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst;
2188 td.dimension = WGPUTextureDimension_2D;
2189 td.size = {width, height, 1};
2190 td.format = fromFormat;
2191 td.mipLevelCount = 1;
2192 td.sampleCount = 1;
2193 surface_copy_ = wgpuDeviceCreateTexture(device_, &td);
2194 if (!surface_copy_) return false;
2195 surface_copy_view_ = wgpuTextureCreateView(surface_copy_, nullptr);
2196 surface_copy_format_ = fromFormat;
2197 surface_copy_width_ = width;
2198 surface_copy_height_ = height;
2199 }
2200 target = surface_copy_;
2201 }
2202
2203 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
2204 WGPUTexelCopyTextureInfo src{};
2205 src.texture = from;
2206 src.aspect = WGPUTextureAspect_All;
2207 WGPUTexelCopyTextureInfo dest{};
2208 dest.texture = target;
2209 dest.aspect = WGPUTextureAspect_All;
2210 const WGPUExtent3D extent{width, height, 1};
2211 wgpuCommandEncoderCopyTextureToTexture(encoder, &src, &dest, &extent);
2212 if (!direct) {
2213 WGPURenderPipeline pipeline = ensureFlipPipeline(to->second.format, /*flip=*/false);
2214 if (!pipeline) {
2215 wgpuCommandEncoderRelease(encoder);
2216 return false;
2217 }
2218 WGPUBindGroupEntry entry{};
2219 entry.binding = 0;
2220 entry.textureView = surface_copy_view_;
2221 WGPUBindGroupDescriptor bgd{};
2222 bgd.layout = flip_bgl_;
2223 bgd.entryCount = 1;
2224 bgd.entries = &entry;
2225 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
2226 WGPURenderPassColorAttachment color{};
2227 color.view = to->second.view;
2228 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
2229 color.loadOp = WGPULoadOp_Clear;
2230 color.storeOp = WGPUStoreOp_Store;
2231 WGPURenderPassDescriptor rp{};
2232 rp.colorAttachmentCount = 1;
2233 rp.colorAttachments = &color;
2234 WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &rp);
2235 wgpuRenderPassEncoderSetPipeline(pass, pipeline);
2236 wgpuRenderPassEncoderSetBindGroup(pass, 0, group, 0, nullptr);
2237 wgpuRenderPassEncoderDraw(pass, 3, 1, 0, 0);
2238 wgpuRenderPassEncoderEnd(pass);
2239 wgpuRenderPassEncoderRelease(pass);
2240 wgpuBindGroupRelease(group);
2241 }
2242 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
2243 wgpuQueueSubmit(queue_, 1, &commands);
2244 wgpuCommandBufferRelease(commands);
2245 wgpuCommandEncoderRelease(encoder);
2246 return true;
2247}
2248
2249WGPUBindGroupLayout WebGPUDevice::groupLayoutFor(u32 group, u64 mask, u64 depthMask,
2250 u64 vertexMask, u64 arrayMask, u64 volumeMask, u64 fragmentMask) {
2251 // Every mask is part of the key: the same bindings sampled as depth or as an
2252 // array are a DIFFERENT layout, and visibility is part of an entry too.
2253 const std::array<u64, 7> key{group, mask, depthMask, vertexMask, arrayMask, volumeMask, fragmentMask};
2254 auto cached = group_layouts_.find(key);
2255 if (cached != group_layouts_.end()) return cached->second;
2256 if (!device_) return nullptr;
2257
2258 WGPUBindGroupLayoutEntry entries[kTextureSlots * 2];
2259 u32 count = 0;
2260 if (group == 0) {
2261 // Engine UBO slots. minBindingSize stays 0: the shader's own struct
2262 // size is validated per draw, and dummy backfill covers unbound slots.
2263 for (u32 slot = 0; slot < kUniformSlots; ++slot) {
2264 if ((mask & (1u << slot)) == 0) continue;
2265 WGPUBindGroupLayoutEntry e{};
2266 e.binding = slot;
2267 e.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment;
2268 e.buffer.type = WGPUBufferBindingType_Uniform;
2269 entries[count++] = e;
2270 }
2271 } else {
2272 // Track vertex and fragment visibility separately so vertex records never consume a fragment slot.
2273 static_assert(kTextureSlots == kGroup1TextureUnits,
2274 "device texture slots mirror the group-1 convention");
2275 for (u32 unit = 0; unit < kTextureSlots; ++unit) {
2276 const u32 tb = textureBindingForUnit(unit);
2277 const u32 sb = samplerBindingForUnit(unit);
2278 const auto stages = [&](u32 binding) {
2279 const u64 bit = u64{1} << binding;
2280 return ((vertexMask & bit) ? WGPUShaderStage_Vertex : 0) |
2281 ((fragmentMask & bit) ? WGPUShaderStage_Fragment : 0);
2282 };
2283 if (mask & (u64{1} << tb)) {
2284 WGPUBindGroupLayoutEntry e{};
2285 e.binding = tb;
2286 e.visibility = stages(tb);
2287 // A unit with no sampler cannot be textureSample'd, so it is
2288 // unfilterable by construction — which is what lets rgba32float
2289 // bind here. Filterable formats satisfy it too.
2290 e.texture.sampleType =
2291 (depthMask & (u64{1} << tb)) ? WGPUTextureSampleType_Depth
2292 : (mask & (u64{1} << sb)) ? WGPUTextureSampleType_Float
2293 : WGPUTextureSampleType_UnfilterableFloat;
2294 e.texture.viewDimension = (arrayMask & (u64{1} << tb)) ? WGPUTextureViewDimension_2DArray
2295 : (volumeMask & (u64{1} << tb)) ? WGPUTextureViewDimension_3D
2296 : WGPUTextureViewDimension_2D;
2297 entries[count++] = e;
2298 }
2299 if (mask & (u64{1} << sb)) {
2300 WGPUBindGroupLayoutEntry e{};
2301 e.binding = sb;
2302 e.visibility = stages(sb);
2303 e.sampler.type = WGPUSamplerBindingType_Filtering;
2304 entries[count++] = e;
2305 }
2306 }
2307 }
2308
2309 WGPUBindGroupLayoutDescriptor bld{};
2310 bld.entryCount = count;
2311 bld.entries = entries;
2312 WGPUBindGroupLayout layout = wgpuDeviceCreateBindGroupLayout(device_, &bld);
2313 group_layouts_[key] = layout;
2314 return layout;
2315}
2316
2317WGPUPipelineLayout WebGPUDevice::pipelineLayoutFor(u32 group0Mask, u64 group1Mask,
2318 u64 group1DepthMask, u64 group1VertexMask,
2319 u64 group1ArrayMask, u64 group1VolumeMask, u64 group1FragmentMask) {
2320 // The depth, visibility and array masks change the group-1 layout under this
2321 // pipeline, so they have to reach the key here too — see groupLayoutFor.
2322 const std::array<u64, 7> key{group0Mask, group1Mask, group1DepthMask, group1VertexMask, group1ArrayMask,
2323 group1VolumeMask, group1FragmentMask};
2324 auto cached = pipeline_layouts_.find(key);
2325 if (cached != pipeline_layouts_.end()) return cached->second;
2326 if (!device_) return nullptr;
2327
2328 // Group indices are positional: a program with group-1 bindings always
2329 // carries a group-0 layout too (zero entries when the mask is empty).
2330 WGPUBindGroupLayout bgls[2];
2331 u32 count = 0;
2332 if (group0Mask != 0 || group1Mask != 0) bgls[count++] = groupLayoutFor(0, group0Mask);
2333 if (group1Mask != 0) {
2334 bgls[count++] = groupLayoutFor(1, group1Mask, group1DepthMask, group1VertexMask, group1ArrayMask,
2335 group1VolumeMask, group1FragmentMask);
2336 }
2337
2338 WGPUPipelineLayoutDescriptor pld{};
2339 pld.bindGroupLayoutCount = count;
2340 pld.bindGroupLayouts = bgls;
2341 WGPUPipelineLayout layout = wgpuDeviceCreatePipelineLayout(device_, &pld);
2342 pipeline_layouts_[key] = layout;
2343 return layout;
2344}
2345
2346void WebGPUDevice::ensureDummies() {
2347 if (!dummy_ubo_.buffer) {
2348 // Sized past the largest engine block (LightConstants, just under 16 KB with the tiled lights) so a
2349 // declared-but-unbound block always satisfies draw-time size validation.
2350 const std::vector<u8> zeros(16384, 0);
2351 dummy_ubo_ = BufferRec{makeBuffer(GfxBufferUsage::Uniform, 16384, zeros.data()), 16384,
2352 GfxBufferUsage::Uniform};
2353 }
2354 if (!dummy_texture_.texture) {
2355 const u8 white[4] = {255, 255, 255, 255};
2356 makeTexture(TextureDesc{}, white, dummy_texture_);
2357 }
2358 if (!dummy_depth_texture_.texture) {
2359 // Never written, only bound: a depth format takes no upload, and the
2360 // point is a texture of the right KIND under a declared depth binding.
2361 TextureDesc td{};
2362 td.format = GfxPixelFormat::Depth24Stencil8;
2363 makeTexture(td, nullptr, dummy_depth_texture_);
2364 }
2365 if (!dummy_array_texture_.texture) {
2366 const u8 white[8] = {255, 255, 255, 255, 255, 255, 255, 255};
2367 TextureDesc td{};
2368 td.layers = 2;
2369 makeTexture(td, white, dummy_array_texture_);
2370 }
2371 if (!dummy_volume_texture_.texture) {
2372 const u8 white[4] = {255, 255, 255, 255};
2373 TextureDesc td{};
2374 td.volume = true;
2375 makeTexture(td, white, dummy_volume_texture_);
2376 }
2377}
2378
2379WGPUBindGroup WebGPUDevice::cachedBindGroup(const u64* ids, u32 idCount,
2380 const WGPUBindGroupDescriptor& desc) {
2381 u64 hash = esengine::hash::kFnv64Offset ^ reinterpret_cast<uintptr_t>(desc.layout);
2382 for (u32 i = 0; i < idCount; ++i) hash = esengine::hash::fnv1aWord(hash, ids[i]);
2383 auto found = bind_group_cache_.find(hash);
2384 if (found != bind_group_cache_.end()) {
2385 for (auto& e : found->second) {
2386 if (e.layout != desc.layout || e.ids.size() != idCount) continue;
2387 bool same = true;
2388 for (u32 i = 0; i < idCount; ++i) {
2389 if (e.ids[i] != ids[i]) { same = false; break; }
2390 }
2391 if (same) { e.used = bind_group_frame_; return e.bg; } // hit — reuse, no wgpuDeviceCreateBindGroup
2392 }
2393 }
2394 // Miss. When full, only what neither this frame nor the last bound goes: emptying the cache made a view of more groups than
2395 // it holds create every one of them again each frame, and the device ran out of descriptors within some hundreds of frames.
2396 if (bind_group_count_ >= kBindGroupCacheCap) {
2397 for (auto it = bind_group_cache_.begin(); it != bind_group_cache_.end();) {
2398 auto& bucket = it->second;
2399 for (usize i = bucket.size(); i-- > 0;) {
2400 if (bucket[i].used + 1 >= bind_group_frame_) continue;
2401 if (bucket[i].bg) wgpuBindGroupRelease(bucket[i].bg);
2402 bucket.erase(bucket.begin() + static_cast<std::ptrdiff_t>(i));
2403 --bind_group_count_;
2404 }
2405 it = bucket.empty() ? bind_group_cache_.erase(it) : std::next(it);
2406 }
2407 }
2408 WGPUBindGroup bg = wgpuDeviceCreateBindGroup(device_, &desc);
2409 if (bg) {
2410 bind_group_cache_[hash].push_back({desc.layout, std::vector<u64>(ids, ids + idCount), bg, bind_group_frame_});
2411 ++bind_group_count_;
2412 }
2413 return bg;
2414}
2415
2416void WebGPUDevice::flushBindGroup() {
2417 if (!bind_group_dirty_ || !pass_ || !device_) return;
2418
2419 WGPURenderPipeline p = ensurePipeline(bound_pipeline_);
2420 if (!p) return;
2421
2422 const ProgramRec* prog = nullptr;
2423 if (const PipelineDesc* desc = pipelineDesc(PipelineHandle{bound_pipeline_})) {
2424 auto progIt = programs_.find(static_cast<u32>(desc->program));
2425 if (progIt != programs_.end()) prog = &progIt->second;
2426 }
2427 if (!prog) return;
2428 if (prog->group0Mask == 0 && prog->group1Mask == 0) {
2429 bind_group_dirty_ = false;
2430 return;
2431 }
2432
2433 ensureDummies();
2434
2435 // Group 0 = the engine's UBO bindings (0..4). Every mask bit gets an entry
2436 // against the explicit layout: the armed slot's buffer (the engine keeps
2437 // Frame/Time/DrawParams on 0/3/4, Material/Light arrive per draw/frame), or
2438 // the zeroed dummy for a declared-but-unbound slot. A group-1-only program
2439 // still sets a (zero-entry) group 0, keeping indices positional.
2440 {
2441 WGPUBindGroupEntry entries[kUniformSlots];
2442 u32 count = 0;
2443 for (u32 slot = 0; slot < kUniformSlots; ++slot) {
2444 if ((prog->group0Mask & (1u << slot)) == 0) continue;
2445 auto it = buffers_.find(uniform_slots_[slot]);
2446 const bool armed = it != buffers_.end() && it->second.buffer;
2447 const BufferRec& bound = armed ? it->second : dummy_ubo_;
2448 if (!bound.buffer) continue;
2449 WGPUBindGroupEntry e{};
2450 e.binding = slot;
2451 e.buffer = bound.buffer;
2452 e.offset = armed ? uniform_offsets_[slot] : 0;
2453 e.size = armed && uniform_sizes_[slot] ? uniform_sizes_[slot] : bound.size;
2454 entries[count++] = e;
2455 }
2456
2457 WGPUBindGroupDescriptor bgd{};
2458 bgd.layout = groupLayoutFor(0, prog->group0Mask);
2459 bgd.entryCount = count;
2460 bgd.entries = entries;
2461 // An offset is keyed with its top bit set, so it never equals the buffer
2462 // pointer evictBindGroups looks for.
2463 u64 ids[kUniformSlots * 2];
2464 for (u32 i = 0; i < count; ++i) {
2465 ids[i * 2] = static_cast<u64>(reinterpret_cast<uintptr_t>(entries[i].buffer));
2466 ids[i * 2 + 1] = (u64{1} << 63) | (entries[i].offset << 20) | entries[i].size;
2467 }
2468 bind_group_ = cachedBindGroup(ids, count * 2, bgd);
2469 if (bind_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 0, bind_group_, 0, nullptr);
2470 }
2471
2472 // Group 1: the texture units through the unit→binding convention (engine
2473 // units 0..7 at texture bindings 0..7 / samplers 8..15, material units
2474 // 8..15 at 16..23 / 24..31; sampler i carries texture i's filter/wrap
2475 // params via the sampler cache). Every declared binding gets an entry —
2476 // the bound unit's view/sampler or the 1x1 white dummy — so the group
2477 // always matches the explicit layout, textures bound or not.
2478 if (prog->group1Mask != 0) {
2479 const TextureRec* dummy = dummy_texture_.texture ? &dummy_texture_ : nullptr;
2480 const TextureRec* depthDummy = dummy_depth_texture_.texture ? &dummy_depth_texture_ : nullptr;
2481 const TextureRec* arrayDummy = dummy_array_texture_.texture ? &dummy_array_texture_ : nullptr;
2482 const TextureRec* volumeDummy = dummy_volume_texture_.texture ? &dummy_volume_texture_ : nullptr;
2483
2484 WGPUBindGroupEntry texEntries[kTextureSlots * 2];
2485 u32 texCount = 0;
2486 for (u32 unit = 0; unit < kTextureSlots; ++unit) {
2487 // A pass may not sample what it draws into: WebGPU rejects the whole
2488 // COMMAND BUFFER for it, not the draw. The dummy stands in — reading
2489 // one's own attachment is undefined under every backend anyway.
2490 const u32 bound = texture_slots_[unit];
2491 const bool feedback = bound != 0 && (bound == pass_color_texture_ ||
2492 bound == pass_depth_texture_);
2493 auto it = feedback ? textures_.end() : textures_.find(bound);
2494 const TextureRec* rec = (it != textures_.end()) ? &it->second : dummy;
2495 if (!rec) continue;
2496 const u32 tb = textureBindingForUnit(unit);
2497 const u32 sb = samplerBindingForUnit(unit);
2498 if (prog->group1Mask & (u64{1} << tb)) {
2499 // A depth declaration must be fed a depth texture even when the
2500 // unit is unbound: the white dummy under `sampleType = Depth` is
2501 // a validation error, not a blank sample.
2502 const bool wantsDepth = (prog->group1DepthMask & (u64{1} << tb)) != 0;
2503 // The view's dimension must be the declaration's: an array where a
2504 // 2D texture is declared, or the reverse, is the dummy of the right kind.
2505 const bool wantsArray = (prog->group1ArrayMask & (u64{1} << tb)) != 0;
2506 const bool wantsVolume = (prog->group1VolumeMask & (u64{1} << tb)) != 0;
2507 const bool isArray = !rec->volume && rec->layers > 1;
2508 const TextureRec* src = rec;
2509 if (wantsDepth && !isDepthFormat(src->format)) src = depthDummy;
2510 // And the other way: a colour declaration handed a depth texture. The scene's depth stays bound on its unit
2511 // after the post chain reads it, and the next program that declares that unit as a colour texture (the
2512 // sprite batch, a mesh, the sky) would take it, which WebGPU refuses with the frame's whole command buffer.
2513 // GL samples it as a number and nothing reads it; here it is the dummy, as an unbound unit is.
2514 else if (!wantsDepth && isDepthFormat(src->format)) src = dummy;
2515 else if (wantsVolume) src = rec->volume ? rec : volumeDummy;
2516 else if (wantsArray && !isArray) src = arrayDummy;
2517 else if (!wantsArray && (isArray || rec->volume)) src = dummy;
2518 if (!src) continue;
2519 WGPUBindGroupEntry e{};
2520 e.binding = tb;
2521 e.textureView = src->sampleView;
2522 texEntries[texCount++] = e;
2523 }
2524 if (prog->group1Mask & (u64{1} << sb)) {
2525 WGPUBindGroupEntry e{};
2526 e.binding = sb;
2527 e.sampler = samplerFor(rec->samplerKey);
2528 texEntries[texCount++] = e;
2529 }
2530 }
2531
2532 WGPUBindGroupDescriptor tgd{};
2533 tgd.layout = groupLayoutFor(1, prog->group1Mask, prog->group1DepthMask,
2534 prog->group1VertexMask, prog->group1ArrayMask, prog->group1VolumeMask, prog->group1FragmentMask);
2535 tgd.entryCount = texCount;
2536 tgd.entries = texEntries;
2537 u64 tids[kTextureSlots * 2];
2538 for (u32 i = 0; i < texCount; ++i) {
2539 const uintptr_t p = texEntries[i].textureView
2540 ? reinterpret_cast<uintptr_t>(texEntries[i].textureView)
2541 : reinterpret_cast<uintptr_t>(texEntries[i].sampler);
2542 tids[i] = static_cast<u64>(p);
2543 }
2544 texture_group_ = cachedBindGroup(tids, texCount, tgd);
2545 if (texture_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 1, texture_group_, 0, nullptr);
2546 }
2547 bind_group_dirty_ = false;
2548}
2549
2550// =============================================================================
2551// Draws / passes — slice 2 (per-frame command encoder + surface plumbing)
2552// =============================================================================
2553
2554void WebGPUDevice::drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) {
2555 if (!isDeviceUsable() || !pass_) return;
2556 auto it = buffers_.find(bound_index_buffer_);
2557 if (it == buffers_.end()) return;
2558 flushBindGroup();
2559 wgpuRenderPassEncoderSetIndexBuffer(pass_, it->second.buffer, toWGPUIndexFormat(indexType),
2560 0, it->second.size);
2561 const u32 indexSize = (indexType == GfxDataType::UnsignedShort) ? 2 : 4;
2562 countDraw();
2563 wgpuRenderPassEncoderDrawIndexed(pass_, indexCount, 1, indexByteOffset / indexSize, 0, 0);
2564}
2565
2566void WebGPUDevice::drawArrays(u32 firstVertex, u32 vertexCount) {
2567 if (!isDeviceUsable() || !pass_) return;
2568 flushBindGroup();
2569 countDraw();
2570 wgpuRenderPassEncoderDraw(pass_, vertexCount, 1, firstVertex, 0);
2571}
2572
2573void WebGPUDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset,
2574 u32 instanceCount) {
2575 if (!isDeviceUsable() || !pass_) return;
2576 auto it = buffers_.find(bound_index_buffer_);
2577 if (it == buffers_.end()) return;
2578 flushBindGroup();
2579 wgpuRenderPassEncoderSetIndexBuffer(pass_, it->second.buffer, toWGPUIndexFormat(indexType),
2580 0, it->second.size);
2581 const u32 indexSize = (indexType == GfxDataType::UnsignedShort) ? 2 : 4;
2582 countDraw();
2583 wgpuRenderPassEncoderDrawIndexed(pass_, indexCount, instanceCount,
2584 indexByteOffset / indexSize, 0, 0);
2585}
2586
2587bool WebGPUDevice::backendCreateFramebuffer(u32, const FramebufferDesc& desc) {
2588 const u32 depthStencil = static_cast<u32>(desc.depthStencil);
2589 if (depthStencil != 0 && !textures_.count(depthStencil)) {
2590 ES_LOG_ERROR("WebGPUDevice::createFramebuffer: unknown depth-stencil texture");
2591 return false;
2592 }
2593 return true;
2594}
2595
2596void WebGPUDevice::beginRenderPass(const RenderPassDesc& desc) {
2597 if (computeJobOpen()) {
2598 ES_LOG_ERROR("WebGPUDevice::beginRenderPass: a compute job is open");
2599 return;
2600 }
2601 if (!isDeviceUsable()) return;
2602 if (!device_) return;
2603 if (pass_) endRenderPass(); // defensive: a dangling pass would deadlock the queue
2604
2605 WGPUTextureView targetView = nullptr;
2606 WGPUTextureView resolveView = nullptr;
2607 WGPUTextureView dsView = nullptr;
2608 pass_ds_format_ = WGPUTextureFormat_Undefined;
2609 pass_color_format_ = surface_format_;
2610 pass_color_texture_ = 0;
2611 pass_depth_texture_ = 0;
2612 pass_is_surface_ = desc.target == FramebufferHandle::Default;
2613 pass_samples_ = 1;
2614 pass_gbuffer_ = false;
2615 pass_albedo_ = false;
2616 WGPUTextureView gbufferView = nullptr;
2617 WGPUTextureView gbufferResolveView = nullptr;
2618 WGPUTextureView albedoView = nullptr;
2619 WGPUTextureView albedoResolveView = nullptr;
2620 pass_depth_msaa_ = 0;
2621 pass_depth_resolve_ = 0;
2622 if (desc.target != FramebufferHandle::Default) {
2623 const FramebufferDesc* fb = framebufferDesc(desc.target);
2624 if (!fb) {
2625 ES_LOG_ERROR("WebGPUDevice::beginRenderPass: unknown framebuffer");
2626 return;
2627 }
2628 const u32 color0 = static_cast<u32>(fb->color0);
2629 const u32 depthStencil = static_cast<u32>(fb->depthStencil);
2630 auto texIt = textures_.find(color0);
2631 if (texIt == textures_.end()) {
2632 ES_LOG_ERROR("WebGPUDevice::beginRenderPass: framebuffer color texture missing");
2633 return;
2634 }
2635 targetView = texIt->second.view;
2636 pass_color_format_ = texIt->second.format;
2637 pass_color_texture_ = color0;
2638 pass_samples_ = texIt->second.samples;
2639 pass_width_ = texIt->second.width;
2640 pass_height_ = texIt->second.height;
2641 // A multisampled attachment is written, never read: the frame's readback
2642 // and everything that samples the scene take the single-sample twin the
2643 // pass resolves into, so that is the texture this pass ANSWERS with.
2644 if (pass_samples_ > 1) {
2645 const u32 resolve = static_cast<u32>(fb->resolveColor0);
2646 auto resolveIt = textures_.find(resolve);
2647 if (resolveIt == textures_.end()) {
2648 ES_LOG_ERROR("WebGPUDevice::beginRenderPass: a multisampled target with no resolve twin");
2649 return;
2650 }
2651 resolveView = resolveIt->second.view;
2652 pass_color_texture_ = resolve;
2653 }
2654 if (fb->color1 != TextureHandle::Invalid) {
2655 auto gIt = textures_.find(static_cast<u32>(fb->color1));
2656 if (gIt != textures_.end()) {
2657 gbufferView = gIt->second.view;
2658 pass_gbuffer_ = true;
2659 if (gIt->second.samples > 1) {
2660 auto gResolve = textures_.find(static_cast<u32>(fb->resolveColor1));
2661 if (gResolve == textures_.end()) {
2662 ES_LOG_ERROR("WebGPUDevice::beginRenderPass: a multisampled surface record with no resolve twin");
2663 return;
2664 }
2665 gbufferResolveView = gResolve->second.view;
2666 }
2667 }
2668 }
2669 if (pass_gbuffer_ && fb->color2 != TextureHandle::Invalid) {
2670 auto aIt = textures_.find(static_cast<u32>(fb->color2));
2671 if (aIt != textures_.end()) {
2672 albedoView = aIt->second.view;
2673 pass_albedo_ = true;
2674 if (aIt->second.samples > 1) {
2675 auto aResolve = textures_.find(static_cast<u32>(fb->resolveColor2));
2676 if (aResolve == textures_.end()) {
2677 ES_LOG_ERROR("WebGPUDevice::beginRenderPass: a multisampled albedo with no resolve twin");
2678 return;
2679 }
2680 albedoResolveView = aResolve->second.view;
2681 }
2682 }
2683 }
2684 if (depthStencil != 0) {
2685 auto dsIt = textures_.find(depthStencil);
2686 if (dsIt != textures_.end()) {
2687 dsView = dsIt->second.view;
2688 pass_ds_format_ = dsIt->second.format;
2689 pass_depth_texture_ = depthStencil;
2690 // A multisampled depth attachment owes its contents to the twin
2691 // whatever samples scene depth will read; the resolve runs once
2692 // the pass is closed, on the same encoder.
2693 const u32 resolveDepth = static_cast<u32>(fb->resolveDepthStencil);
2694 if (dsIt->second.samples > 1 && resolveDepth != 0) {
2695 pass_depth_msaa_ = depthStencil;
2696 pass_depth_resolve_ = resolveDepth;
2697 pass_depth_texture_ = resolveDepth;
2698 }
2699 }
2700 }
2701 } else {
2702 if (!surface_) {
2703 ES_LOG_ERROR("WebGPUDevice::beginRenderPass: no surface configured");
2704 return;
2705 }
2706 // A browser worker may yield to its event loop between passes. Its
2707 // canvas texture expires at that boundary, while our surface proxy persists.
2708 if (!late_surface_acquire_ && !acquireFrameView()) return;
2709 pass_width_ = surface_width_;
2710 pass_height_ = surface_height_;
2711 // Drawn into the proxy, whose rows are bottom-up like every target's here; the swapchain texture receives the
2712 // frame at its end. Multisampled: draw into the companion and resolve into the proxy.
2713 if (!ensureSurfaceProxy(surface_width_, surface_height_)) {
2714 ES_LOG_ERROR("WebGPUDevice::beginRenderPass: no backbuffer texture");
2715 return;
2716 }
2717 if (!ensureSurfaceDepth(surface_width_, surface_height_)) return;
2718 const bool multisampled = ensureSurfaceMsaa(surface_width_, surface_height_);
2719 if (surface_samples_ > 1 && !multisampled) return;
2720 surface_proxy_drawn_ = true;
2721 if (multisampled) {
2722 targetView = surface_msaa_view_;
2723 resolveView = surface_proxy_view_;
2724 pass_samples_ = surface_msaa_samples_;
2725 } else {
2726 targetView = surface_proxy_view_;
2727 }
2728 dsView = surface_depth_view_;
2729 pass_ds_format_ = WGPUTextureFormat_Depth24PlusStencil8;
2730 }
2731
2732 encoder_ = wgpuDeviceCreateCommandEncoder(device_, nullptr);
2733
2734 // GPU timing. A pass the graph armed is timed under its own name; any other pass that opens inside a timer span
2735 // adds its time to the span, whatever it draws to — the span is the frame's, not the surface pass's.
2736 pass_time_slot_ = takePassTimeSlot();
2737 pass_timed_ = pass_time_slot_ == kNoPassSlot && spanTakesPass();
2738
2739 const bool scoped = desc.clearW != 0;
2740 WGPURenderPassColorAttachment color{};
2741 color.view = targetView;
2742 color.resolveTarget = resolveView;
2743 color.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
2744 color.loadOp = toWGPULoadOp(desc.clearColor, scoped);
2745 // Resolved into its single-sample twin by the pass itself; when nothing continues on this target the samples need not be kept.
2746 color.storeOp = (desc.discardMultisampled && resolveView) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
2747 color.clearValue = toWGPUClearColor(desc);
2748
2749 // The surface record clears to zero — "nothing wrote here" — whatever the background is.
2750 WGPURenderPassColorAttachment colors[3]{};
2751 colors[0] = color;
2752 if (pass_gbuffer_) {
2753 colors[1].view = gbufferView;
2754 colors[1].resolveTarget = gbufferResolveView;
2755 colors[1].depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
2756 colors[1].loadOp = toWGPULoadOp(desc.clearColor, scoped);
2757 colors[1].storeOp = (desc.discardMultisampled && gbufferResolveView) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
2758 colors[1].clearValue = {0.0, 0.0, 0.0, 0.0};
2760 if (pass_albedo_) {
2761 colors[2].view = albedoView;
2762 colors[2].resolveTarget = albedoResolveView;
2763 colors[2].depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
2764 colors[2].loadOp = toWGPULoadOp(desc.clearColor, scoped);
2765 colors[2].storeOp = (desc.discardMultisampled && albedoResolveView) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
2766 colors[2].clearValue = {0.0, 0.0, 0.0, 0.0};
2767 }
2768
2769 WGPURenderPassDescriptor rp{};
2770 rp.colorAttachmentCount = !pass_gbuffer_ ? 1 : pass_albedo_ ? 3 : 2;
2771 rp.colorAttachments = colors;
2772
2773 WGPURenderPassDepthStencilAttachment ds{};
2774 if (dsView) {
2775 ds.view = dsView;
2776 ds.depthLoadOp = toWGPULoadOp(desc.clearDepth, scoped);
2777 // Kept unless the pass said it is only for testing, and unless a multisampled one is resolved by hand after the pass.
2778 ds.depthStoreOp = (desc.discardDepth && pass_depth_msaa_ == 0) ? WGPUStoreOp_Discard : WGPUStoreOp_Store;
2779 ds.depthClearValue = 1.0f; // GL's default clear depth; no RHI override exists
2780 if (hasStencilPlanes(pass_ds_format_)) {
2781 ds.stencilLoadOp = toWGPULoadOp(desc.clearStencil, scoped);
2782 ds.stencilStoreOp = WGPUStoreOp_Store;
2783 ds.stencilClearValue = static_cast<u32>(desc.clearStencilValue);
2784 }
2785 rp.depthStencilAttachment = &ds;
2786 }
2787 WGPUPassTimestampWrites tw{};
2788 if (pass_timed_ || pass_time_slot_ != kNoPassSlot) {
2789 tw.querySet = timestamp_qset_;
2790 tw.beginningOfPassWriteIndex = 0;
2791 tw.endOfPassWriteIndex = 1;
2792 rp.timestampWrites = &tw; // outlives the call below (same scope)
2793 }
2794 pass_ = wgpuCommandEncoderBeginRenderPass(encoder_, &rp);
2795 pass_pipeline_ = nullptr;
2796 bind_group_dirty_ = true;
2797 stencil_ref_ = 0; // a fresh pass encoder resets its stencil reference
2798
2799 // Region-scoped clear = load + scissored clear-triangle, per the RHI
2800 // contract — for every attachment the desc asks to clear.
2801 if (scoped && (desc.clearColor || desc.clearDepth || desc.clearStencil)) {
2802 drawInternalClear(desc.clearColor, desc.clearDepth && dsView,
2803 desc.clearStencil && hasStencilPlanes(pass_ds_format_),
2804 desc.clearColorValue, desc.clearStencilValue, &desc);
2805 }
2806}
2809 if (!pass_) return;
2810 wgpuRenderPassEncoderEnd(pass_);
2811 wgpuRenderPassEncoderRelease(pass_);
2812 pass_ = nullptr;
2813 pass_pipeline_ = nullptr;
2815 // Depth, on the same encoder and after the pass that wrote it: colour was
2816 // resolved by the pass itself, and this is the half WebGPU leaves to us.
2817 if (pass_depth_msaa_ && pass_depth_resolve_) {
2818 resolveDepthAttachment(pass_depth_msaa_, pass_depth_resolve_);
2819 pass_depth_msaa_ = 0;
2820 pass_depth_resolve_ = 0;
2821 }
2822
2823 // GPU timing: resolve this pass's begin/end timestamps into the reserved ring
2824 // slot (recorded on the same encoder, so it runs after the pass on the GPU).
2825 const u32 passSlot = encoder_ ? pass_time_slot_ : kNoPassSlot;
2826 pass_time_slot_ = kNoPassSlot;
2827 if (passSlot != kNoPassSlot) resolvePassTime(encoder_, passSlot);
2828 if (pass_timed_ && encoder_) resolveSpanPass(encoder_);
2829 pass_timed_ = false;
2830
2831 // A booked capture rides the pass's OWN encoder: the browser presents the
2832 // swapchain image with this submit, so a copy encoded afterwards copies a
2833 // destroyed texture. Several surface passes overwrite; the last one wins.
2834 if (capture_id_ && pass_is_surface_ && surface_proxy_ && encoder_) {
2835 encodeReadbackCopy(encoder_, capture_id_, surface_proxy_);
2836 capture_copied_ = true;
2837 }
2838 pass_is_surface_ = false;
2839
2840 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder_, nullptr);
2841 wgpuCommandEncoderRelease(encoder_);
2842 encoder_ = nullptr;
2843 wgpuQueueSubmit(queue_, 1, &commands);
2844 wgpuCommandBufferRelease(commands);
2845
2846 if (passSlot != kNoPassSlot) mapPassTime(passSlot);
2847 // The span was closed while this pass was still open: it was the last one in it.
2848 if (span_closing_) {
2849 span_closing_ = false;
2850 finishSpan();
2852}
2853
2856bool WebGPUDevice::framePending() {
2857 if (frames_done_ >= frames_ended_) return false;
2858 if (instance_) wgpuInstanceProcessEvents(instance_);
2859 drainCompletions();
2860 return frames_done_ < frames_ended_;
2861}
2862
2863void WebGPUDevice::endFrame() {
2864 drainCompletions();
2865 ++bind_group_frame_;
2866 presentSurfaceProxy();
2867 // Told when the queue has finished everything submitted so far: this frame and all before it.
2868 if (queue_) {
2869 const u64 frame = ++frames_ended_;
2870 WGPUQueueWorkDoneCallbackInfo done = WGPU_QUEUE_WORK_DONE_CALLBACK_INFO_INIT;
2871 done.mode = WGPUCallbackMode_AllowSpontaneous;
2872 done.callback = [](WGPUQueueWorkDoneStatus, WGPUStringView, void* ticket, void*) {
2873 publishCompletion(ticket);
2874 };
2875 done.userdata1 = new Ticket{mailbox_, {CompletionKind::Frame, frame}};
2876 wgpuQueueOnSubmittedWorkDone(queue_, done);
2877 }
2878 // A capture is served HERE and nowhere else: this is the last instant at which
2879 // the frame is both finished and still ours. Asking from outside cannot work —
2880 // whoever could ask runs after the renderer has already given the image back.
2881 if (capture_id_) {
2882 const u32 id = capture_id_;
2883 capture_id_ = 0;
2884 if (capture_copied_) {
2885 capture_copied_ = false;
2886 mapReadback(id);
2887 } else if (frame_texture_ && surface_proxy_) {
2888 submitReadbackCopy(id, surface_proxy_);
2889 } else {
2890 // Nothing drew, so there is no image to copy. Leaving the record
2891 // Pending would hang whoever is polling it.
2892 auto it = readbacks_.find(id);
2893 if (it != readbacks_.end()) it->second.status = GfxReadbackStatus::Failed;
2894 }
2895 }
2896 if (frame_view_) { wgpuTextureViewRelease(frame_view_); frame_view_ = nullptr; }
2897 if (frame_texture_) { wgpuTextureRelease(frame_texture_); frame_texture_ = nullptr; }
2898}
2899
2900ReadbackHandle WebGPUDevice::captureNextFrame(u32 w, u32 h) {
2901 if (!isDeviceUsable() || !device_ || w == 0 || h == 0) return ReadbackHandle::Invalid;
2902 if (!surface_readback_) {
2903 ES_LOG_ERROR("WebGPUDevice::captureNextFrame: the surface was configured without CopySrc "
2904 "(setSurfaceReadback must be on before configureSurface)");
2905 return ReadbackHandle::Invalid;
2906 }
2907 if (capture_id_) return ReadbackHandle::Invalid; // one in flight is enough
2908 capture_id_ = allocReadback(w, h);
2909 return static_cast<ReadbackHandle>(capture_id_);
2910}
2911
2912// =============================================================================
2913// Readback (async seam: texture → staging copy, resolved when the map lands)
2914// =============================================================================
2915
2916void WebGPUDevice::publishCompletion(void* userdata, WGPUMapAsyncStatus status) {
2917 std::unique_ptr<Ticket> ticket(static_cast<Ticket*>(userdata));
2918 ticket->result.status = status;
2919 std::lock_guard lock(ticket->mailbox->mutex);
2920 ticket->mailbox->ready.push_back(ticket->result);
2921}
2922
2923WGPUBufferMapCallbackInfo WebGPUDevice::mapCallback(CompletionKind kind, u32 id) {
2924 WGPUBufferMapCallbackInfo cb = WGPU_BUFFER_MAP_CALLBACK_INFO_INIT;
2925 cb.mode = WGPUCallbackMode_AllowSpontaneous;
2926 cb.callback = [](WGPUMapAsyncStatus status, WGPUStringView, void* data, void*) {
2927 publishCompletion(data, status);
2928 };
2929 cb.userdata1 = new Ticket{mailbox_, {kind, id}};
2930 return cb;
2931}
2932
2933void WebGPUDevice::drainCompletions() {
2934 if (!mailbox_) return;
2935 std::vector<Completion> ready;
2936 {
2937 std::lock_guard lock(mailbox_->mutex);
2938 ready.swap(mailbox_->ready);
2939 }
2940 for (const auto& result : ready) {
2941 const u32 id = static_cast<u32>(result.id);
2942 switch (result.kind) {
2943 case CompletionKind::Frame: frames_done_ = std::max(frames_done_, result.id); break;
2944 case CompletionKind::Readback: onReadbackMapped(result.status, id); break;
2945 case CompletionKind::PassTime: onPassTimeMapped(result.status, id); break;
2946 case CompletionKind::GpuTime: onGpuTimeMapped(result.status, id); break;
2947 }
2948 }
2949}
2950
2951void WebGPUDevice::onReadbackMapped(WGPUMapAsyncStatus status, u32 id) {
2952 auto it = readbacks_.find(id);
2953 if (it == readbacks_.end()) return; // taken or discarded while in flight
2954 it->second.status = (status == WGPUMapAsyncStatus_Success) ? GfxReadbackStatus::Ready
2956}
2957
2958void WebGPUDevice::releaseReadback(u32 id) {
2959 auto it = readbacks_.find(id);
2960 if (it == readbacks_.end()) return;
2961 WGPUBuffer buffer = it->second.buffer;
2962 // Erase first: releasing a buffer with a pending map fires the callback with
2963 // an abort status, which must miss the lookup.
2964 readbacks_.erase(it);
2965 if (buffer) wgpuBufferRelease(buffer);
2966}
2967
2968ReadbackHandle WebGPUDevice::requestReadback(FramebufferHandle target, u32 w, u32 h) {
2969 if (!isDeviceUsable()) return ReadbackHandle::Invalid;
2970 if (!device_ || w == 0 || h == 0) return ReadbackHandle::Invalid;
2971 if (inPass()) {
2972 ES_LOG_ERROR("WebGPUDevice::requestReadback: must be called outside a render pass");
2973 return ReadbackHandle::Invalid;
2974 }
2975 if (target == FramebufferHandle::Default) {
2976 // Not addressable from out here: the renderer gives the swapchain image
2977 // back at the end of its own frame, so any caller is already too late.
2978 // captureNextFrame reads the presented frame instead.
2979 stubOnce("requestReadback(default framebuffer) — use captureNextFrame");
2980 return ReadbackHandle::Invalid;
2981 }
2982 const FramebufferDesc* fb = framebufferDesc(target);
2983 if (!fb) return ReadbackHandle::Invalid;
2984 auto tit = textures_.find(static_cast<u32>(fb->color0));
2985 if (tit == textures_.end() || !tit->second.texture) return ReadbackHandle::Invalid;
2986
2987 const u32 id = allocReadback(w, h);
2988 if (!id) return ReadbackHandle::Invalid;
2989 submitReadbackCopy(id, tit->second.texture);
2990 return static_cast<ReadbackHandle>(id);
2991}
2992
2996u32 WebGPUDevice::allocReadback(u32 w, u32 h) {
2997 // copyTextureToBuffer requires a 256-byte row alignment; rows are compacted
2998 // (and flipped to the bottom-up contract) in takeReadback.
2999 const u32 padded = (w * 4u + 255u) & ~255u;
3000 WGPUBufferDescriptor bd{};
3001 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
3002 bd.size = static_cast<u64>(padded) * h;
3003 WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);
3004 if (!buffer) return 0;
3005 const u32 id = next_readback_id_++;
3006 readbacks_[id] = ReadbackRec{buffer, w, h, padded, GfxReadbackStatus::Pending};
3007 return id;
3008}
3009
3010void WebGPUDevice::encodeReadbackCopy(WGPUCommandEncoder encoder, u32 id, WGPUTexture source) {
3011 auto it = readbacks_.find(id);
3012 if (it == readbacks_.end() || !source || !encoder) return;
3013 ReadbackRec& rec = it->second;
3014
3015 WGPUTexelCopyTextureInfo src = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT;
3016 src.texture = source;
3017 WGPUTexelCopyBufferInfo dst = WGPU_TEXEL_COPY_BUFFER_INFO_INIT;
3018 dst.buffer = rec.buffer;
3019 dst.layout.offset = 0;
3020 dst.layout.bytesPerRow = rec.paddedBytesPerRow;
3021 dst.layout.rowsPerImage = rec.height;
3022 WGPUExtent3D size{rec.width, rec.height, 1};
3023 wgpuCommandEncoderCopyTextureToBuffer(encoder, &src, &dst, &size);
3024}
3025
3026void WebGPUDevice::mapReadback(u32 id) {
3027 auto it = readbacks_.find(id);
3028 if (it == readbacks_.end()) return;
3029 ReadbackRec& rec = it->second;
3030 auto cb = mapCallback(CompletionKind::Readback, id);
3031 wgpuBufferMapAsync(rec.buffer, WGPUMapMode_Read, 0,
3032 static_cast<u64>(rec.paddedBytesPerRow) * rec.height, cb);
3033}
3034
3035void WebGPUDevice::submitReadbackCopy(u32 id, WGPUTexture source) {
3036 if (readbacks_.find(id) == readbacks_.end() || !source) return;
3037 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
3038 encodeReadbackCopy(encoder, id, source);
3039 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
3040 wgpuCommandEncoderRelease(encoder);
3041 wgpuQueueSubmit(queue_, 1, &commands);
3042 wgpuCommandBufferRelease(commands);
3043 mapReadback(id);
3044}
3045
3046GfxReadbackStatus WebGPUDevice::pollReadback(ReadbackHandle handle) {
3047 // AllowSpontaneous callbacks fire from the browser's event loop on their own;
3048 // the pump is defensive (and required if the callback mode ever tightens).
3049 if (instance_) wgpuInstanceProcessEvents(instance_);
3050 drainCompletions();
3051 auto it = readbacks_.find(static_cast<u32>(handle));
3052 if (it == readbacks_.end()) return GfxReadbackStatus::Failed;
3053 if (it->second.status == GfxReadbackStatus::Failed) {
3054 releaseReadback(static_cast<u32>(handle));
3056 }
3057 return it->second.status;
3058}
3059
3060bool WebGPUDevice::takeReadback(ReadbackHandle handle, void* dest, usize destSize) {
3061 drainCompletions();
3062 auto it = readbacks_.find(static_cast<u32>(handle));
3063 if (it == readbacks_.end() || it->second.status != GfxReadbackStatus::Ready) return false;
3064 ReadbackRec& rec = it->second;
3065 if (rec.raw) {
3066 // A compute readback: the source's own bytes, rows top-down with the padding taken out.
3067 if (destSize < rec.tightBytes) return false;
3068 const auto* mapped = static_cast<const u8*>(
3069 wgpuBufferGetConstMappedRange(rec.buffer, 0, static_cast<u64>(rec.paddedBytesPerRow) * rec.height));
3070 if (!mapped) {
3071 releaseReadback(static_cast<u32>(handle));
3072 return false;
3073 }
3074 auto* out = static_cast<u8*>(dest);
3075 const u32 rowBytes = rec.width * rec.bytesPerTexel;
3076 for (u32 row = 0; row < rec.height; ++row) {
3077 std::memcpy(out + static_cast<usize>(row) * rowBytes, mapped + static_cast<usize>(row) * rec.paddedBytesPerRow, rowBytes);
3078 }
3079 wgpuBufferUnmap(rec.buffer);
3080 releaseReadback(static_cast<u32>(handle));
3081 return true;
3082 }
3083 const usize tight = static_cast<usize>(rec.width) * rec.height * 4;
3084 if (destSize < tight) return false;
3085 const auto* mapped = static_cast<const u8*>(
3086 wgpuBufferGetConstMappedRange(rec.buffer, 0, static_cast<u64>(rec.paddedBytesPerRow) * rec.height));
3087 if (!mapped) {
3088 releaseReadback(static_cast<u32>(handle));
3089 return false;
3090 }
3091 // A target's rows are bottom-up here, as the contract (GL readPixels) has them.
3092 auto* out = static_cast<u8*>(dest);
3093 const u32 rowBytes = rec.width * 4u;
3094 for (u32 row = 0; row < rec.height; ++row) {
3095 std::memcpy(out + static_cast<usize>(row) * rowBytes,
3096 mapped + static_cast<usize>(row) * rec.paddedBytesPerRow, rowBytes);
3097 }
3098 wgpuBufferUnmap(rec.buffer);
3099 releaseReadback(static_cast<u32>(handle));
3100 return true;
3101}
3102
3103void WebGPUDevice::discardReadback(ReadbackHandle handle) {
3104 releaseReadback(static_cast<u32>(handle));
3105}
3106
3107// =============================================================================
3108// Timing / queries / debug
3109// =============================================================================
3110
3111void WebGPUDevice::ensureTimestamps() {
3112 if (timestamp_init_done_) return;
3113 timestamp_init_done_ = true;
3114 if (!device_ || !wgpuDeviceHasFeature(device_, WGPUFeatureName_TimestampQuery)) return;
3115
3116 WGPUQuerySetDescriptor qd{};
3117 qd.type = WGPUQueryType_Timestamp;
3118 qd.count = 2; // begin + end of the pass being timed; resolved out before the next pass reuses them
3119 timestamp_qset_ = wgpuDeviceCreateQuerySet(device_, &qd);
3120 if (!timestamp_qset_) return;
3121
3122 WGPUBufferDescriptor rd{};
3123 rd.usage = WGPUBufferUsage_QueryResolve | WGPUBufferUsage_CopySrc;
3124 rd.size = 16; // 2 × u64 nanosecond timestamps
3125 timestamp_resolve_ = wgpuDeviceCreateBuffer(device_, &rd);
3126 for (u32 i = 0; i < kGpuTimeRing; ++i) {
3127 WGPUBufferDescriptor bd{};
3128 bd.usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst;
3129 bd.size = 16 * kSpanPasses;
3130 gpu_time_ring_[i].buf = wgpuDeviceCreateBuffer(device_, &bd);
3131 }
3132 timestamp_supported_ = timestamp_resolve_ && gpu_time_ring_[0].buf;
3133}
3134
3135// One query set serves every timer: timing rides the passes, so a query id
3136// only has to exist for the engine's GpuTimer to turn on.
3137bool WebGPUDevice::backendCreateTimerQuery(u32) {
3138 ensureTimestamps();
3139 return timestamp_supported_;
3140}
3141
3142// A span is what GL's GL_TIME_ELAPSED gives between the same two calls: the GPU's time for everything issued inside
3143// it. Single-queue spans sum timed passes. Parallel spans measure the interval between two GPU timestamps.
3144void WebGPUDevice::beginTimerQuery(u32) {
3145 if (!timestamp_supported_) return;
3146 span_closing_ = false;
3147 span_slot_ = kGpuTimeRing;
3148 span_passes_ = 0;
3149 for (u32 i = 0; i < kGpuTimeRing; ++i) {
3150 const u32 s = (gpu_time_next_ + i) % kGpuTimeRing;
3151 if (!gpu_time_ring_[s].pending) {
3152 span_slot_ = s;
3153 gpu_time_next_ = (s + 1) % kGpuTimeRing;
3154 break;
3155 }
3156 }
3157 // With every readback still in flight the span goes untimed, and says so with a zero rather than no answer:
3158 // the caller keeps one query in flight per span and would otherwise wait on this one for good.
3159 span_open_ = true;
3160 parallel_span_ = asyncComputeEnabled() && supportsAsyncCompute();
3161 if (parallel_span_ && span_slot_ < kGpuTimeRing) stampParallelSpan(false);
3162}
3163
3164void WebGPUDevice::stampParallelSpan(bool end) {
3165 if (!clock_pipeline_) {
3166 WGPUShaderSourceWGSL code{};
3167 code.chain.sType = WGPUSType_ShaderSourceWGSL;
3168 code.code = sv("@compute @workgroup_size(1) fn main() {}");
3169 WGPUShaderModuleDescriptor md{};
3170 md.nextInChain = &code.chain;
3171 auto module = wgpuDeviceCreateShaderModule(device_, &md);
3172 WGPUComputePipelineDescriptor pd = WGPU_COMPUTE_PIPELINE_DESCRIPTOR_INIT;
3173 pd.compute.module = module;
3174 pd.compute.entryPoint = sv("main");
3175 clock_pipeline_ = wgpuDeviceCreateComputePipeline(device_, &pd);
3176 wgpuShaderModuleRelease(module);
3177 }
3178 if (!clock_pipeline_) return;
3179 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
3180 WGPUPassTimestampWrites time{};
3181 time.querySet = timestamp_qset_;
3182 time.beginningOfPassWriteIndex = 0;
3183 time.endOfPassWriteIndex = 1;
3184 WGPUComputePassDescriptor pd{};
3185 pd.timestampWrites = &time;
3186 auto pass = wgpuCommandEncoderBeginComputePass(encoder, &pd);
3187 wgpuComputePassEncoderSetPipeline(pass, clock_pipeline_);
3188 wgpuComputePassEncoderDispatchWorkgroups(pass, 1, 1, 1);
3189 wgpuComputePassEncoderEnd(pass);
3190 wgpuComputePassEncoderRelease(pass);
3191 wgpuCommandEncoderResolveQuerySet(encoder, timestamp_qset_, 0, 2, timestamp_resolve_, 0);
3192 const u64 offset = end ? sizeof(u64) : 0;
3193 wgpuCommandEncoderCopyBufferToBuffer(encoder, timestamp_resolve_, offset, gpu_time_ring_[span_slot_].buf, offset, sizeof(u64));
3194 if (end) span_passes_ = 1; // The existing readback consumes one pair of timestamps.
3195 auto commands = wgpuCommandEncoderFinish(encoder, nullptr);
3196 wgpuCommandEncoderRelease(encoder);
3197 wgpuQueueSubmit(queue_, 1, &commands);
3198 wgpuCommandBufferRelease(commands);
3199}
3200
3202 if (!span_open_) return;
3203 span_open_ = false;
3204 // A pass still open belongs to the span and has not been stamped yet; its end finishes the span.
3205 if (pass_) span_closing_ = true;
3206 else finishSpan();
3207}
3208
3209bool WebGPUDevice::spanTakesPass() const {
3210 return timestamp_supported_ && span_open_ && !parallel_span_ && span_slot_ < kGpuTimeRing && span_passes_ < kSpanPasses;
3211}
3212
3213void WebGPUDevice::resolveSpanPass(WGPUCommandEncoder encoder) {
3214 wgpuCommandEncoderResolveQuerySet(encoder, timestamp_qset_, 0, 2, timestamp_resolve_, 0);
3215 wgpuCommandEncoderCopyBufferToBuffer(encoder, timestamp_resolve_, 0,
3216 gpu_time_ring_[span_slot_].buf, 16ull * span_passes_, 16);
3217 ++span_passes_;
3218}
3219
3220void WebGPUDevice::finishSpan() {
3221 // A sum of pass durations double-counts overlap. The closing timestamp follows the GPU join.
3222 if (parallel_span_) {
3223 parallel_span_ = false;
3224 manualComputeBarrier();
3225 if (span_slot_ < kGpuTimeRing && isDeviceUsable()) stampParallelSpan(true);
3226 }
3227 const u32 slot = span_slot_;
3228 const u32 passes = span_passes_;
3229 span_slot_ = kGpuTimeRing;
3230 span_passes_ = 0;
3231 if (!timestamp_supported_) return;
3232 if (slot >= kGpuTimeRing || passes == 0) {
3233 if (gpu_time_results_.size() < 16) gpu_time_results_.push_back(0);
3234 return;
3235 }
3236 // Map async — drained by getTimerQueryNs a few frames later (the GpuTimer ring tolerates the latency).
3237 gpu_time_ring_[slot].pending = true;
3238 gpu_time_ring_[slot].passes = passes;
3239 auto cb = mapCallback(CompletionKind::GpuTime, slot);
3240 wgpuBufferMapAsync(gpu_time_ring_[slot].buf, WGPUMapMode_Read, 0, 16ull * passes, cb);
3241}
3242bool WebGPUDevice::timerDisjoint() { return false; }
3243
3244bool WebGPUDevice::getTimerQueryNs(u32 query, u64* outNs) {
3245 drainCompletions();
3246 if (pass_time_tags_.count(query)) {
3247 const auto it = pass_time_results_.find(query);
3248 if (it == pass_time_results_.end()) return false;
3249 if (outNs) *outNs = it->second;
3250 pass_time_results_.erase(it);
3251 return true;
3252 }
3253 if (gpu_time_results_.empty()) return false;
3254 if (outNs) *outNs = gpu_time_results_.front();
3255 gpu_time_results_.erase(gpu_time_results_.begin());
3256 return true;
3257}
3258
3259void WebGPUDevice::armPassTimer(u32 query) {
3260 armed_pass_tag_ = timestamp_supported_ ? query : 0;
3261 if (armed_pass_tag_) pass_time_tags_.insert(armed_pass_tag_);
3262}
3263
3264u32 WebGPUDevice::takePassTimeSlot() {
3265 const u32 tag = armed_pass_tag_;
3266 armed_pass_tag_ = 0;
3267 if (!tag || !timestamp_supported_) return kNoPassSlot;
3268 u32 slot = kNoPassSlot;
3269 for (u32 i = 0; i < pass_time_pool_.size(); ++i) {
3270 if (!pass_time_pool_[i].pending) { slot = i; break; }
3271 }
3272 if (slot == kNoPassSlot) {
3273 if (pass_time_pool_.size() >= kPassTimePool) return kNoPassSlot; // readbacks are not coming back: skip, don't grow
3274 WGPUBufferDescriptor bd{};
3275 bd.usage = WGPUBufferUsage_MapRead | WGPUBufferUsage_CopyDst;
3276 bd.size = 16;
3277 PassTimeSlot fresh;
3278 fresh.buf = wgpuDeviceCreateBuffer(device_, &bd);
3279 if (!fresh.buf) return kNoPassSlot;
3280 pass_time_pool_.push_back(fresh);
3281 slot = static_cast<u32>(pass_time_pool_.size() - 1);
3282 }
3283 pass_time_pool_[slot].tag = tag;
3284 return slot;
3285}
3286
3287void WebGPUDevice::resolvePassTime(WGPUCommandEncoder encoder, u32 slot) {
3288 wgpuCommandEncoderResolveQuerySet(encoder, timestamp_qset_, 0, 2, timestamp_resolve_, 0);
3289 wgpuCommandEncoderCopyBufferToBuffer(encoder, timestamp_resolve_, 0, pass_time_pool_[slot].buf, 0, 16);
3290}
3292void WebGPUDevice::mapPassTime(u32 slot) {
3293 pass_time_pool_[slot].pending = true;
3294 auto cb = mapCallback(CompletionKind::PassTime, slot);
3295 wgpuBufferMapAsync(pass_time_pool_[slot].buf, WGPUMapMode_Read, 0, 16, cb);
3296}
3297
3298void WebGPUDevice::onPassTimeMapped(WGPUMapAsyncStatus status, u32 slot) {
3299 if (slot >= pass_time_pool_.size()) return;
3300 PassTimeSlot& ps = pass_time_pool_[slot];
3301 if (status == WGPUMapAsyncStatus_Success && ps.buf) {
3302 const auto* ts = static_cast<const u64*>(wgpuBufferGetConstMappedRange(ps.buf, 0, 16));
3303 if (ts && ts[1] >= ts[0]) pass_time_results_[ps.tag] = ts[1] - ts[0];
3304 wgpuBufferUnmap(ps.buf);
3305 }
3306 ps.pending = false;
3307}
3308
3309void WebGPUDevice::onGpuTimeMapped(WGPUMapAsyncStatus status, u32 slot) {
3310 if (slot >= kGpuTimeRing) return;
3311 WGPUBuffer buf = gpu_time_ring_[slot].buf;
3312 const u32 passes = gpu_time_ring_[slot].passes;
3313 if (status == WGPUMapAsyncStatus_Success && buf) {
3314 const auto* ts = static_cast<const u64*>(wgpuBufferGetConstMappedRange(buf, 0, 16ull * passes));
3315 // Either one elapsed interval or the sum of per-pass pairs. Discard pairs spanning a timestamp reset.
3316 u64 total = 0;
3317 for (u32 i = 0; ts && i < passes; ++i) {
3318 if (ts[2 * i + 1] >= ts[2 * i]) total += ts[2 * i + 1] - ts[2 * i];
3319 }
3320 // Cap the FIFO so a stalled consumer can't grow it without bound.
3321 if (ts && gpu_time_results_.size() < 16) gpu_time_results_.push_back(total);
3322 wgpuBufferUnmap(buf);
3323 }
3324 gpu_time_ring_[slot].pending = false;
3325}
3326
3327void WebGPUDevice::setWireframe(bool) {}
3328u32 WebGPUDevice::getError() { return 0; }
3329
3330std::string WebGPUDevice::getString(GfxStringName name) {
3331 switch (name) {
3332 case GfxStringName::Renderer: return "WebGPU (Dawn/emdawnwebgpu)";
3333 case GfxStringName::Vendor: return "WebGPU";
3334 case GfxStringName::Version: return "WebGPU 1.0";
3335 case GfxStringName::ShadingLanguageVersion: return "WGSL";
3336 default: return {};
3337 }
3338}
3339
3340i32 WebGPUDevice::getInt(GfxIntParam param) {
3341 switch (param) {
3342 case GfxIntParam::MaxTextureSize: return 8192;
3343 case GfxIntParam::MaxTextureImageUnits: return 16;
3344 case GfxIntParam::MaxVertexAttribs: return 16;
3345 default: return 0;
3347}
3348
3349
3350// =============================================================================
3351// Compute
3352// =============================================================================
3353
3354namespace {
3356u32 storageTexelBytes(WGPUTextureFormat format) {
3357 switch (format) {
3358 case WGPUTextureFormat_RGBA8Unorm:
3359 case WGPUTextureFormat_BGRA8Unorm:
3360 case WGPUTextureFormat_RGBA8UnormSrgb: return 4;
3361 case WGPUTextureFormat_RGBA16Float: return 8;
3362 case WGPUTextureFormat_RGBA32Float: return 16;
3363 default: return 0;
3364 }
3365}
3366
3367} // namespace
3368
3369bool WebGPUDevice::backendCreateCompute(u32 id, const GfxComputeSource& source, std::string* outLog) {
3370 if (source.language != GfxShaderLanguage::WGSL || !source.source) {
3371 if (outLog) *outLog = "WebGPUDevice compiles WGSL only";
3372 return false;
3373 }
3374 if (!device_) {
3375 if (outLog) *outLog = "no WGPUDevice";
3376 return false;
3377 }
3378 WGPUShaderSourceWGSL wgsl{};
3379 wgsl.chain.sType = WGPUSType_ShaderSourceWGSL;
3380 wgsl.code = sv(source.source);
3381 WGPUShaderModuleDescriptor md{};
3382 md.nextInChain = &wgsl.chain;
3383 WGPUShaderModule module = wgpuDeviceCreateShaderModule(device_, &md);
3384 if (!module) {
3385 if (outLog) *outLog = "shader module creation failed";
3386 return false;
3387 }
3388 ComputeRec rec;
3389 rec.module = module;
3390 rec.entry = source.entry && *source.entry ? source.entry : "main";
3391 computes_[id] = std::move(rec);
3392 return true;
3393}
3394
3395void WebGPUDevice::backendDeleteCompute(u32 id) {
3396#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
3397 if (metal_compute_) metal_compute_->forgetProgram(id);
3398#endif
3399 auto it = computes_.find(id);
3400 if (it == computes_.end()) return;
3401 for (auto& [key, pipeline] : it->second.pipelines) {
3402 if (pipeline) wgpuComputePipelineRelease(pipeline);
3403 }
3404 if (it->second.module) wgpuShaderModuleRelease(it->second.module);
3405 computes_.erase(it);
3406}
3407
3408bool WebGPUDevice::backendDispatchCompute(u32 id, const GfxComputeBinding* bindings, u32 bindingCount,
3409 u32 groupsX, u32 groupsY, u32 groupsZ) {
3410 if (inPass()) {
3411 ES_LOG_ERROR("WebGPUDevice::dispatchCompute: must be called outside a render pass");
3412 return false;
3413 }
3414 auto program = computes_.find(id);
3415 if (program == computes_.end() || !program->second.module) return false;
3416 if (groupsX > kMaxWorkgroupsPerDimension || groupsY > kMaxWorkgroupsPerDimension ||
3417 groupsZ > kMaxWorkgroupsPerDimension || bindingCount > kMaxComputeBindings) {
3418 ES_LOG_ERROR("WebGPUDevice::dispatchCompute: {}x{}x{} groups with {} bindings is over the limit",
3419 groupsX, groupsY, groupsZ, bindingCount);
3420 return false;
3421 }
3422
3423 WGPUBindGroupLayoutEntry layoutEntries[kMaxComputeBindings] = {};
3424 WGPUBindGroupEntry groupEntries[kMaxComputeBindings] = {};
3425 std::string key;
3426 for (u32 i = 0; i < bindingCount; ++i) {
3427 const GfxComputeBinding& b = bindings[i];
3428 WGPUBindGroupLayoutEntry& le = layoutEntries[i];
3429 WGPUBindGroupEntry& ge = groupEntries[i];
3430 le.binding = ge.binding = b.binding;
3431 le.visibility = WGPUShaderStage_Compute;
3432 key += std::to_string(b.binding) + "." + std::to_string(static_cast<u32>(b.kind));
3433 switch (b.kind) {
3434 case GfxComputeBinding::Kind::Uniform:
3435 case GfxComputeBinding::Kind::StorageRead:
3436 case GfxComputeBinding::Kind::Storage: {
3437 auto it = buffers_.find(static_cast<u32>(b.buffer));
3438 if (it == buffers_.end() || !it->second.buffer) {
3439 ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} names a buffer that is gone", b.binding);
3440 return false;
3441 }
3442 const bool uniform = b.kind == GfxComputeBinding::Kind::Uniform;
3443 if ((uniform && it->second.usage != GfxBufferUsage::Uniform) ||
3444 (!uniform && it->second.usage != GfxBufferUsage::Storage)) {
3445 ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} is bound as {} but the buffer was not made for it",
3446 b.binding, uniform ? "a uniform" : "storage");
3447 return false;
3448 }
3449 le.buffer.type = uniform ? WGPUBufferBindingType_Uniform
3450 : b.kind == GfxComputeBinding::Kind::StorageRead ? WGPUBufferBindingType_ReadOnlyStorage
3451 : WGPUBufferBindingType_Storage;
3452 ge.buffer = it->second.buffer;
3453 ge.offset = b.offset;
3454 const u32 whole = webgpu::alignedWriteSize(it->second.size);
3455 ge.size = b.size ? b.size : (whole > b.offset ? whole - b.offset : 0);
3456 break;
3457 }
3458 case GfxComputeBinding::Kind::Texture: {
3459 auto it = textures_.find(static_cast<u32>(b.texture));
3460 if (it == textures_.end() || !it->second.texture) {
3461 ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} names a texture that is gone", b.binding);
3462 return false;
3463 }
3464 const WGPUTextureFormat f = it->second.format;
3465 le.texture.sampleType = isDepthFormat(f) ? WGPUTextureSampleType_Depth
3466 : f == WGPUTextureFormat_RGBA32Float ? WGPUTextureSampleType_UnfilterableFloat
3467 : WGPUTextureSampleType_Float;
3468 le.texture.viewDimension = WGPUTextureViewDimension_2D;
3469 ge.textureView = it->second.sampleView;
3470 key += "." + std::to_string(static_cast<u32>(le.texture.sampleType));
3471 break;
3472 }
3473 case GfxComputeBinding::Kind::DepthTexture: {
3474 auto it = textures_.find(static_cast<u32>(b.texture));
3475 const TextureRec* rec = (it != textures_.end() && it->second.texture && isDepthFormat(it->second.format)) ? &it->second : nullptr;
3476 if (!rec) {
3477 ensureDummies();
3478 rec = &dummy_depth_texture_;
3479 }
3480 le.texture.sampleType = WGPUTextureSampleType_Depth;
3481 le.texture.viewDimension = WGPUTextureViewDimension_2D;
3482 ge.textureView = rec->sampleView;
3483 break;
3484 }
3485 case GfxComputeBinding::Kind::StorageTexture: {
3486 auto it = textures_.find(static_cast<u32>(b.texture));
3487 if (it == textures_.end() || !it->second.texture) {
3488 ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} names a texture that is gone", b.binding);
3489 return false;
3490 }
3491 if (!it->second.storage) {
3492 ES_LOG_ERROR("WebGPUDevice::dispatchCompute: binding {} is a storage texture but the texture was not made with storage", b.binding);
3493 return false;
3494 }
3495 le.storageTexture.access = WGPUStorageTextureAccess_WriteOnly;
3496 le.storageTexture.format = it->second.format;
3497 le.storageTexture.viewDimension = WGPUTextureViewDimension_2D;
3498 ge.textureView = it->second.view;
3499 key += "." + std::to_string(static_cast<u32>(it->second.format));
3500 break;
3501 }
3502 case GfxComputeBinding::Kind::Sampler:
3503 le.sampler.type = WGPUSamplerBindingType_Filtering;
3504 ge.sampler = samplerFor(packSamplerKey(b.filter, b.filter, TextureWrap::ClampToEdge, TextureWrap::ClampToEdge));
3505 break;
3506 }
3507 key += "/";
3508 }
3509
3510 WGPUBindGroupLayout layout = nullptr;
3511 auto cachedLayout = compute_layouts_.find(key);
3512 if (cachedLayout != compute_layouts_.end()) {
3513 layout = cachedLayout->second;
3514 } else {
3515 WGPUBindGroupLayoutDescriptor bld{};
3516 bld.entryCount = bindingCount;
3517 bld.entries = layoutEntries;
3518 layout = wgpuDeviceCreateBindGroupLayout(device_, &bld);
3519 compute_layouts_[key] = layout;
3520 }
3521 if (!layout) return false;
3522
3523 WGPUPipelineLayout pipelineLayout = nullptr;
3524 auto cachedPipelineLayout = compute_pipeline_layouts_.find(key);
3525 if (cachedPipelineLayout != compute_pipeline_layouts_.end()) {
3526 pipelineLayout = cachedPipelineLayout->second;
3527 } else {
3528 WGPUPipelineLayoutDescriptor pld{};
3529 pld.bindGroupLayoutCount = 1;
3530 pld.bindGroupLayouts = &layout;
3531 pipelineLayout = wgpuDeviceCreatePipelineLayout(device_, &pld);
3532 compute_pipeline_layouts_[key] = pipelineLayout;
3533 }
3534 if (!pipelineLayout) return false;
3535
3536 WGPUComputePipeline pipeline = nullptr;
3537 auto cachedPipeline = program->second.pipelines.find(key);
3538 if (cachedPipeline != program->second.pipelines.end()) {
3539 pipeline = cachedPipeline->second;
3540 } else {
3541 WGPUComputePipelineDescriptor cpd = WGPU_COMPUTE_PIPELINE_DESCRIPTOR_INIT;
3542 cpd.layout = pipelineLayout;
3543 cpd.compute.module = program->second.module;
3544 cpd.compute.entryPoint = sv(program->second.entry.c_str());
3545 pipeline = wgpuDeviceCreateComputePipeline(device_, &cpd);
3546 program->second.pipelines[key] = pipeline;
3547 }
3548 if (!pipeline) return false;
3549
3550 WGPUBindGroupDescriptor bgd{};
3551 bgd.layout = layout;
3552 bgd.entryCount = bindingCount;
3553 bgd.entries = groupEntries;
3554 WGPUBindGroup group = wgpuDeviceCreateBindGroup(device_, &bgd);
3555 if (!group) return false;
3556
3557 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
3558 WGPUComputePassDescriptor pd = WGPU_COMPUTE_PASS_DESCRIPTOR_INIT;
3559 const u32 passSlot = takePassTimeSlot();
3560 // A kernel is the frame's GPU time as much as a draw is. No render pass is open here to carry a span past its
3561 // end, so this one is resolved and counted before the call returns.
3562 const bool inSpan = passSlot == kNoPassSlot && spanTakesPass();
3563 WGPUPassTimestampWrites tw{};
3564 if (passSlot != kNoPassSlot || inSpan) {
3565 tw.querySet = timestamp_qset_;
3566 tw.beginningOfPassWriteIndex = 0;
3567 tw.endOfPassWriteIndex = 1;
3568 pd.timestampWrites = &tw;
3569 }
3570 WGPUComputePassEncoder pass = wgpuCommandEncoderBeginComputePass(encoder, &pd);
3571 wgpuComputePassEncoderSetPipeline(pass, pipeline);
3572 wgpuComputePassEncoderSetBindGroup(pass, 0, group, 0, nullptr);
3573 wgpuComputePassEncoderDispatchWorkgroups(pass, groupsX, groupsY, groupsZ);
3574 wgpuComputePassEncoderEnd(pass);
3575 wgpuComputePassEncoderRelease(pass);
3576 if (passSlot != kNoPassSlot) resolvePassTime(encoder, passSlot);
3577 if (inSpan) resolveSpanPass(encoder);
3578 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
3579 wgpuCommandEncoderRelease(encoder);
3580 wgpuQueueSubmit(queue_, 1, &commands);
3581 wgpuCommandBufferRelease(commands);
3582 if (passSlot != kNoPassSlot) mapPassTime(passSlot);
3583 wgpuBindGroupRelease(group);
3584 return true;
3585}
3586
3587u32 WebGPUDevice::allocRawReadback(u32 w, u32 h, u32 bytesPerTexel, u32 tightBytes) {
3588 // A texture copy wants 256-byte rows; a buffer copy is one row of any multiple of four.
3589 const u32 padded = (h > 1 || bytesPerTexel != 1) ? ((w * bytesPerTexel + 255u) & ~255u) : tightBytes;
3590 WGPUBufferDescriptor bd{};
3591 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
3592 bd.size = static_cast<u64>(padded) * h;
3593 WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);
3594 if (!buffer) return 0;
3595 const u32 id = next_readback_id_++;
3596 ReadbackRec rec{buffer, w, h, padded, GfxReadbackStatus::Pending};
3597 rec.raw = true;
3598 rec.bytesPerTexel = bytesPerTexel;
3599 rec.tightBytes = tightBytes;
3600 readbacks_[id] = rec;
3601 return id;
3602}
3603
3604ReadbackHandle WebGPUDevice::requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
3605 if (!isDeviceUsable() || !device_ || sizeBytes == 0 || (offsetBytes & 3u) || (sizeBytes & 3u)) {
3606 return ReadbackHandle::Invalid;
3607 }
3608 if (inPass()) {
3609 ES_LOG_ERROR("WebGPUDevice::requestBufferReadback: must be called outside a render pass");
3610 return ReadbackHandle::Invalid;
3611 }
3612 auto it = buffers_.find(static_cast<u32>(buffer));
3613 if (it == buffers_.end() || !it->second.buffer || it->second.usage != GfxBufferUsage::Storage ||
3614 static_cast<u64>(offsetBytes) + sizeBytes > webgpu::alignedWriteSize(it->second.size)) {
3615 return ReadbackHandle::Invalid;
3616 }
3617 // One row of sizeBytes bytes: width counts bytes, a texel is one.
3618 const u32 id = allocRawReadback(sizeBytes, 1, 1, sizeBytes);
3619 if (!id) return ReadbackHandle::Invalid;
3620 WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
3621 wgpuCommandEncoderCopyBufferToBuffer(encoder, it->second.buffer, offsetBytes, readbacks_[id].buffer, 0, sizeBytes);
3622 WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
3623 wgpuCommandEncoderRelease(encoder);
3624 wgpuQueueSubmit(queue_, 1, &commands);
3625 wgpuCommandBufferRelease(commands);
3626 mapReadback(id);
3627 return static_cast<ReadbackHandle>(id);
3628}
3629
3630ReadbackHandle WebGPUDevice::requestTextureReadback(TextureHandle texture) {
3631 if (!isDeviceUsable() || !device_) return ReadbackHandle::Invalid;
3632 if (inPass()) {
3633 ES_LOG_ERROR("WebGPUDevice::requestTextureReadback: must be called outside a render pass");
3634 return ReadbackHandle::Invalid;
3635 }
3636 auto it = textures_.find(static_cast<u32>(texture));
3637 if (it == textures_.end() || !it->second.texture || it->second.samples > 1) return ReadbackHandle::Invalid;
3638 const u32 bpt = storageTexelBytes(it->second.format);
3639 if (bpt == 0) return ReadbackHandle::Invalid;
3640 const u32 w = it->second.width, h = it->second.height;
3641 const u32 id = allocRawReadback(w, h, bpt, w * h * bpt);
3642 if (!id) return ReadbackHandle::Invalid;
3643 submitReadbackCopy(id, it->second.texture);
3644 return static_cast<ReadbackHandle>(id);
3645}
3646
3647} // namespace esengine
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Row arithmetic shared by the backends' texture uploads.
WebGPU (Dawn / emdawnwebgpu) backend for GfxDevice (REARCH_WGSL Phase 2).
Pure RHI-enum → WebGPU translations (REARCH_WGSL Phase 2).
bool markDeviceLost(GfxDeviceLostReason reason, std::string message={}, std::string context={})
The single transition into Lost. Backends call this on detection.
Definition GfxDevice.cpp:60
Viewport viewport_
Backends record what they were last handed; see viewport.
virtual void backendSetAsyncComputeEnabled(bool)
bool asyncComputeEnabled() const
bool isDeviceUsable() const
Whether work may be submitted — the one check the guards make.
void manualComputeBarrier()
Order dispatches across queues. Each inline dispatch is already a complete compute pass.
void setDeviceIdentity(std::string backend, std::string vendor, std::string renderer, std::string version)
Records the backend identity; see captureDeviceIdentity.
void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override
Binds a vertex buffer to a layout slot for subsequent draws.
void bindTexture(u32 slot, TextureHandle texture) override
Activates a texture slot and binds a 2D texture.
void setIndexBuffer(BufferHandle buffer) override
Binds the index buffer for subsequent indexed draws.
void clearStencil(i32 value) override
Mid-pass stencil reset (the one clear that isn't a pass load-op).
void endFrame() override
The frame is over — everything drawn for it has been submitted.
static u32 colorVariantOf(WGPUTextureFormat format)
Which variant slot a pass's colour format uses. Beside the enum because the two are one decision: a f...
void setScissorTest(bool enabled) override
Enables or disables scissor test.
WebGPUDevice(WGPUDevice device=nullptr, WGPUInstance instance=nullptr, WGPUAdapter adapter=nullptr)
device may be null for bookkeeping-only use (tests, bring-up).
void backendDeleteTexture(u32 id) override
void captureDeviceIdentity() override
Records who this backend is, so a later loss report can name it.
void endRenderPass() override
Ends the current pass, restoring the default framebuffer.
void setViewport(i32 x, i32 y, u32 w, u32 h) override
Sets the rendering viewport.
void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height, const void *pixels, bool flipY) override
void backendSetPipeline(u32 id, const PipelineDesc &desc) override
bool configureSurface(const NativeSurface &window, u32 width, u32 height)
Binds a native window as the render target; shares configureSwapchain with the web path....
void init() override
Initializes the graphics device.
void endTimerQuery() override
Stops the active timer query.
void backendResizeBuffer(u32 id, const BufferDesc &desc, const void *data) override
static constexpr u32 kMsaaSamples
The multisampled count this backend offers. WebGPU guarantees 1 and 4 for every renderable format; no...
static GfxDeviceLostReason reasonFromWgpu(u32 wgpuReason)
Maps a WGPUDeviceLostReason to the backend-neutral reason.
void backendDeleteProgram(u32 id) override
u64 estimatedGpuBytes() const override
bool backendCreateTexture(u32 id, const TextureDesc &desc, const void *pixels) override
void reportUncapturedError(u32 wgpuErrorType, const char *message)
Routes the device's uncaptured-error callback; only fatal kinds become losses.
bool backendCreateBuffer(u32 id, const BufferDesc &desc, const void *data) override
bool recreateDevice() override
Backend half of recoverDevice: a working device again, with every id-to-native map and derived cache ...
bool surfaceBytesAreBGRA() const
Whether bytes read back from the DEFAULT framebuffer are BGRA rather than RGBA.
void backendDeleteBuffer(u32 id) override
void backendUpdateBuffer(u32 id, u32 offsetBytes, const void *data, u32 sizeBytes) override
u32 maxSamples() override
Most samples an offscreen colour attachment may carry; 1 = none.
void backendMoveTexture(u32 into, u32 from) override
Re-keys from's native texture under into; into holds none on entry.
void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override
bool backendCreateProgram(u32 id, const GfxShaderSource &source, const GfxAttribBinding *bindings, u32 bindingCount, std::string *outLog, GfxShaderStage *outFailedStage) override
std::string getString(GfxStringName name) override
Queries a backend identification string (diagnostics).
void present()
Flips the swapchain to the display. The web path relies on the browser presenting the canvas after th...
void backendGenerateMipmaps(u32 id) override
void setScissor(i32 x, i32 y, i32 w, i32 h) override
Sets the scissor rectangle.
void resizeBackbuffer(u32 width, u32 height) override
Resizes the default backbuffer to the viewport size.
bool backendAcceptsVertexLayout(const VertexLayoutDesc &desc) override
False for a layout this backend has no way to express.
bool backendCreateCompressedTexture(u32 id, const TextureDesc &desc, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels) override
void setStencilReference(i32 reference) override
WebGPU stores a texture from the top down.
u32 validation_errors_logged_
Validation errors said so far (reportUncapturedError says the first few).
bool supportsCompressedFormat(GfxCompressedFormat format) override
Reports whether the backend can sample the given compressed format.
void backendSetTextureParams(u32 id, const TextureDesc &desc) override
bool pollDeviceLost() override
Pumps backend-native loss detection.
void drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) override
Draws indexed triangles.
void shutdown() override
Shuts down the graphics device.
constexpr u64 fnv1aWord(u64 h, u64 word)
Definition Hash.hpp:17
constexpr u64 kFnv64Offset
Definition Hash.hpp:12
bool writeFitsInBuffer(u32 offset, u32 size, u32 capacity)
WGPUVertexFormat toWGPUVertexFormat(u8 components, GfxDataType type, bool normalized)
Maps one RHI attribute (components × type × normalized) to a WGPUVertexFormat, or kInvalidVertexForma...
u64 scanWGSLVolumeTextureMask(const char *source, u32 group)
Bit mask of the group's bindings a WGSL source declares as texture_3d.
WGPUDepthStencilState toWGPUDepthStencil(const PipelineDesc &desc, WGPUTextureFormat format)
A pipeline's full depth-stencil state against a pass attachment format.
u32 wgpuBytesPerPixel(GfxPixelFormat fmt)
WGPUIndexFormat toWGPUIndexFormat(GfxDataType type)
Index type for drawElements' GfxDataType.
bool hasStencilPlanes(WGPUTextureFormat format)
True when a depth-stencil format carries stencil planes (drives whether a pass may set stencil load/s...
bool needsWriteStaging(u32 size)
BlendStateWGPU toWGPUBlend(BlendMode mode, bool layerAlpha=false)
Maps BlendMode to its WebGPU blend components — mirrors GLDevice's setBlendMode table (Overlay render...
WGPUFeatureName compressionFeatureFor(GfxCompressedFormat fmt)
constexpr WGPUVertexFormat kInvalidVertexFormat
Sentinel for "no WGPU spelling": the header defines no Undefined vertex format, so the enum's non-val...
u64 scanWGSLArrayTextureMask(const char *source, u32 group)
Bit mask of the group's bindings a WGSL source declares as texture_2d_array.
constexpr u32 kGroup1TextureUnits
Texture units the group-1 convention spans — see WGSL_MAX_TEXTURE_UNITS.
WGPUCullMode toWGPUCullMode(bool enabled, bool front)
Cull state (PipelineDesc.cullEnabled/cullFront). Front face is CCW, matching the GL backend's default...
WGPUColor toWGPUClearColor(const RenderPassDesc &desc)
WGPUBufferUsage toWGPUBufferUsage(GfxBufferUsage usage)
WGPUTextureFormat toWGPUTextureFormat(GfxPixelFormat fmt)
WGPULoadOp toWGPULoadOp(bool clearRequested, bool scoped)
WGPUTextureFormat toWGPUCompressedFormat(GfxCompressedFormat fmt)
u64 scanWGSLDepthTextureMask(const char *source, u32 group)
Bit mask of the group's bindings a WGSL source declares as DEPTH textures.
u32 alignedWriteSize(u32 size)
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
u64 scanWGSLBindingMask(const char *source, u32 group)
Bit mask of the @group(N) @binding(i) indices a WGSL source declares.
bool writesStencil(GfxStencilMode mode)
constexpr u32 samplerBindingForUnit(u32 unit)
Group-1 binding of a texture unit's sampler (see textureBindingForUnit).
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
constexpr u32 textureBindingForUnit(u32 unit)
Group-1 binding of a texture unit. Units 0-7 are the batch stream and take bindings 0-7; a material's...
void scanWGSLReachedUnits(const char *source, u32 &textures, u32 &samplers)
The tN / sN names a WGSL source REACHES, by unit.
GfxDeviceLostReason
Why the device was lost. The report leads with this.
Definition GfxEnums.hpp:543
@ Destroyed
We destroyed it. A loss report that is not a failure.
Definition GfxEnums.hpp:549
@ Internal
The backend failed inside itself and said no more than that.
Definition GfxEnums.hpp:551
@ OutOfMemory
An allocation the backend could not satisfy.
Definition GfxEnums.hpp:546
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
void stageTextureRows(u8 *dst, const u8 *src, u32 width, u32 height, u32 srcBpp, u32 dstBpp, bool reverseRows)
@ Nearest
No interpolation (pixelated look).
Definition GfxEnums.hpp:58
GfxShaderStage
Which pipeline stage rejected a program during createProgram().
Definition GfxEnums.hpp:736
PipelineHandle
Opaque handle to a cached pipeline; PipelineHandle{0} is the null/invalid handle.
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
Definition GfxEnums.hpp:326
@ ETC2_RGBA8_SRGB
GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC (core).
Definition GfxEnums.hpp:333
@ S3TC_DXT5
GL_COMPRESSED_RGBA_S3TC_DXT5_EXT (extension).
Definition GfxEnums.hpp:332
@ ETC2_RGB8
GL_COMPRESSED_RGB8_ETC2 (core).
Definition GfxEnums.hpp:327
@ S3TC_DXT5_SRGB
GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT (extension).
Definition GfxEnums.hpp:335
@ ASTC_8x8
GL_COMPRESSED_RGBA_ASTC_8x8_KHR (extension).
Definition GfxEnums.hpp:330
@ S3TC_DXT1
GL_COMPRESSED_RGBA_S3TC_DXT1_EXT (extension).
Definition GfxEnums.hpp:331
@ ASTC_4x4_SRGB
GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR (extension).
Definition GfxEnums.hpp:334
@ ETC2_RGBA8
GL_COMPRESSED_RGBA8_ETC2_EAC (core).
Definition GfxEnums.hpp:328
@ ASTC_4x4
GL_COMPRESSED_RGBA_ASTC_4x4_KHR (extension).
Definition GfxEnums.hpp:329
GfxReadbackStatus
State of an in-flight readback. GL completes at request time (first poll reports Ready); WebGPU resol...
Definition GfxEnums.hpp:47
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
static bool isSrgbFormat(WGPUTextureFormat f)
u32 gfxBytesPerPixel(GfxPixelFormat fmt)
Bytes one pixel occupies in the CALLER's upload buffer — the single source both backends size a read ...
Definition GfxEnums.hpp:299
GfxBlockInfo gfxCompressedBlockInfo(GfxCompressedFormat fmt)
Definition GfxEnums.hpp:346
ReadbackHandle
An in-flight framebuffer readback (GfxDevice::requestReadback).
Definition GfxEnums.hpp:43
float f32
32-bit floating point
Definition Types.hpp:59
Immutable creation parameters of a GPU buffer.
Definition GfxEnums.hpp:403
GfxBufferUsage usage
Definition GfxEnums.hpp:404
Vertex attribute location binding applied before a program is linked.
Definition GfxEnums.hpp:730
Block footprint of a compressed format, the single source both backends use to size each mip level's ...
Definition GfxEnums.hpp:341
A program's source pair, tagged with the language it is written in.
Definition GfxEnums.hpp:660
GfxShaderLanguage language
Definition GfxEnums.hpp:661
Immutable description of a draw pipeline. Equality keys the pipeline cache, so two draws with the sam...
Immutable creation parameters of a 2D texture or 2D texture array.
Definition GfxEnums.hpp:414
TextureFilter minFilter
Definition GfxEnums.hpp:422
TextureFilter magFilter
Definition GfxEnums.hpp:423
GfxPixelFormat format
Definition GfxEnums.hpp:421
Describes how vertex-buffer bytes map to shader attributes.
Definition GfxEnums.hpp:235
GfxVertexAttribute attributes[MAX_VERTEX_ATTRIBUTES]
Definition GfxEnums.hpp:236