Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
WebGPUDevice.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
32#pragma once
33
34#include "../rhi/GfxDevice.hpp"
35
36#include <webgpu/webgpu.h>
37
38#include <array>
39#include <map>
40#include <memory>
41#include <mutex>
42#include <string>
43#include <unordered_map>
44#include <unordered_set>
45#include <vector>
46
47namespace esengine {
48
50
51class WebGPUDevice final : public GfxDevice {
52public:
53 u64 estimatedGpuBytes() const override;
58
67
72
75 static constexpr u32 kMsaaSamples = 4;
76
80 static u32 colorVariantOf(WGPUTextureFormat format);
81
90 explicit WebGPUDevice(WGPUDevice device = nullptr, WGPUInstance instance = nullptr,
91 WGPUAdapter adapter = nullptr);
92 ~WebGPUDevice() override;
93
95
96 void init() override;
97 void shutdown() override;
98
99 // Device loss reaches this class from OUTSIDE it: WebGPU accepts a
100 // device-lost callback only in the descriptor that creates the device, and
101 // both hosts create theirs before handing it over. Hence these entry points.
102
104 static GfxDeviceLostReason reasonFromWgpu(u32 wgpuReason);
105
107 void reportUncapturedError(u32 wgpuErrorType, const char* message);
110
111 bool pollDeviceLost() override;
112
114 void ownDeviceReference() { owns_device_ = true; }
116 bool provideReplacementDevice(void* nativeDevice) override {
117 if (!nativeDevice) return false;
118 if (owns_device_ && pending_device_) wgpuDeviceRelease(pending_device_);
119 pending_device_ = static_cast<WGPUDevice>(nativeDevice);
120 return true;
121 }
122
123 void setViewport(i32 x, i32 y, u32 w, u32 h) override;
124 void clearStencil(i32 value) override;
125
126 void setScissorTest(bool enabled) override;
127 void setScissor(i32 x, i32 y, i32 w, i32 h) override;
128
129 void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) override;
130 void setIndexBuffer(BufferHandle buffer) override;
131
132 void bindTexture(u32 slot, TextureHandle texture) override;
133 bool supportsCompressedFormat(GfxCompressedFormat format) override;
134 // Float-target rendering is a WebGPU core capability.
135 bool supportsFloatTargets() override { return true; }
137 bool supportsUnblendedSurfaceTarget() const override { return true; }
138 u32 maxSamples() override;
142 bool resolvesDepth() const override { return true; }
150 void setSurfaceSamples(u32 samples) override {
151 surface_samples_ = samples > 1 ? kMsaaSamples : 1;
152 }
153
155#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
156 bool supportsAsyncCompute() const override;
157#endif
158 bool supportsCompute() const override { return device_ != nullptr; }
159 ReadbackHandle requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override;
161
162 bool supportsShaderLanguage(GfxShaderLanguage language) const override {
163 return language == GfxShaderLanguage::WGSL;
164 }
165
167
168 void setStencilReference(i32 reference) override;
169
170 void drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) override;
171 void drawArrays(u32 firstVertex, u32 vertexCount) override;
172 void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset,
173 u32 instanceCount) override;
174
175 void beginRenderPass(const RenderPassDesc& desc) override;
176 void endRenderPass() override;
177 void resizeBackbuffer(u32 width, u32 height) override;
178
181 bool takeReadback(ReadbackHandle handle, void* dest, usize destSize) override;
182 void discardReadback(ReadbackHandle handle) override;
183
184 void beginTimerQuery(u32 query) override;
185 void endTimerQuery() override;
186 bool timerDisjoint() override;
187 bool getTimerQueryNs(u32 query, u64* outNs) override;
188
189 void setWireframe(bool enabled) override;
190 u32 getError() override;
191 std::string getString(GfxStringName name) override;
192 i32 getInt(GfxIntParam param) override;
193
194protected:
195 void captureDeviceIdentity() override;
196 bool recreateDevice() override;
197
198 bool backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) override;
199 void backendDeleteBuffer(u32 id) override;
200 void backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) override;
201 void backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) override;
202 void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override;
203
204 bool backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) override;
206 const void* data, u32 byteLength, u32 mipLevels) override;
208 bool backendAdoptTexture(u32, u32, const TextureDesc&) override { return false; }
209 void backendDeleteTexture(u32 id) override;
210 void backendMoveTexture(u32 into, u32 from) override;
211 void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,
212 const void* pixels, bool flipY) override;
213 void backendSetTextureParams(u32 id, const TextureDesc& desc) override;
214 void backendGenerateMipmaps(u32 id) override;
215
216 bool backendCreateCompute(u32 id, const GfxComputeSource& source, std::string* outLog) override;
217 void backendDeleteCompute(u32 id) override;
218 bool backendDispatchCompute(u32 id, const GfxComputeBinding* bindings, u32 bindingCount,
219 u32 groupsX, u32 groupsY, u32 groupsZ) override;
220
221 bool backendCreateProgram(u32 id, const GfxShaderSource& source,
222 const GfxAttribBinding* bindings, u32 bindingCount,
223 std::string* outLog, GfxShaderStage* outFailedStage) override;
224 void backendDeleteProgram(u32 id) override;
225 // Programs bind through pipelines, uniforms through UBO bindings and blocks by
226 // @group/@binding: the GL-shaped program state has nothing to reach here.
227 void backendUseProgram(u32) override {}
228 i32 backendUniformLocation(u32, const char*) override { return -1; }
229 i32 backendAttribLocation(u32, const char*) override { return -1; }
230 void backendSetUniform(i32, const GfxUniformValue&) override {}
231 std::vector<GfxUniformInfo> backendActiveUniforms(u32) override { return {}; }
234
235 bool backendAcceptsVertexLayout(const VertexLayoutDesc& desc) override;
237 void backendSetPipeline(u32 id, const PipelineDesc& desc) override;
239
240 bool backendCreateFramebuffer(u32 id, const FramebufferDesc& desc) override;
242
243 bool backendCreateTimerQuery(u32 id) override;
244 u32 backendReadbackCount() const override { return static_cast<u32>(readbacks_.size()); }
245
246public:
247 // -------------------------------------------------------------------------
248 // Bring-up introspection (tests / slice-2 plumbing)
249 // -------------------------------------------------------------------------
250
251 bool hasDevice() const { return device_ != nullptr; }
252
260#if defined(__EMSCRIPTEN__)
261 bool configureSurface(const char* selector, u32 width, u32 height);
262#endif
263
268
276 void* handle;
280 void* instance = nullptr;
281 };
282
283#if !defined(__EMSCRIPTEN__)
286 bool configureSurface(const NativeSurface& window, u32 width, u32 height);
287
292 void present();
293
294#endif
295
303 bool surfaceBytesAreBGRA() const;
304
305 bool frameCaptureIsBGRA() const override { return surfaceBytesAreBGRA(); }
306
314 void setPreferredSurfaceBGRA(bool bgra) { prefer_surface_bgra_ = bgra; }
315
323 void setSurfaceReadback(bool enabled) { surface_readback_ = enabled; }
325 void setLateSurfaceAcquire(bool enabled) { late_surface_acquire_ = enabled; }
326
335 void setPresentUncapped(bool enabled) { present_uncapped_ = enabled; }
336
347 ReadbackHandle captureNextFrame(u32 w, u32 h) override;
348
349 void endFrame() override;
350 bool framePending() override;
351
352private:
353 static constexpr u32 kMaxComputeBindings = 16;
354 static constexpr u32 kMaxWorkgroupsPerDimension = 65535;
355 bool backendComputeScopeAvailable() const override { return !inPass(); }
356#ifdef ES_ENABLE_METAL_ASYNC_COMPUTE
357 friend class MetalComputeQueue;
358 std::unique_ptr<MetalComputeQueue> metal_compute_;
359 bool metal_compute_attempted_ = false;
360 void backendSetAsyncComputeEnabled(bool enabled) override;
361 bool backendDispatchAsyncCompute(AsyncComputePriority, u32, const GfxComputeBinding*, u32, u32, u32, u32) override;
362 void backendWaitAsyncCompute() override;
363#endif
365 bool ensureSurfaceDepth(u32 width, u32 height);
366
371 bool adoptDevice(WGPUDevice device);
372
375
376 struct BufferRec {
377 WGPUBuffer buffer = nullptr;
378 u32 size = 0;
380 };
381 struct TextureRec {
382 WGPUTexture texture = nullptr;
383 WGPUTextureView view = nullptr;
387 WGPUTextureView sampleView = nullptr;
388 u32 width = 0;
389 u32 height = 0;
390 WGPUTextureFormat format = WGPUTextureFormat_RGBA8Unorm;
395 u8 samplerKey = 0;
397 u32 samples = 1;
400 u32 mipLevels = 1;
402 bool storage = false;
404 u32 layers = 1;
406 bool volume = false;
407 };
408 struct ProgramRec {
409 WGPUShaderModule vertex = nullptr;
410 WGPUShaderModule fragment = nullptr;
417 u32 group0Mask = 0;
418 u64 group1Mask = 0;
420 u64 group1VertexMask = 0;
421 u64 group1FragmentMask = 0;
423 u64 group1DepthMask = 0;
425 u64 group1ArrayMask = 0;
427 u64 group1VolumeMask = 0;
428 };
431 enum GBufferVariant : u32 { kGBufferNone = 0, kGBufferWrites = 1, kGBufferSkips = 2, kGBufferWritesAlbedo = 3, kGBufferVariantCount = 4 };
432 struct PipelineRec {
435 WGPURenderPipeline variants[static_cast<u32>(kDsVariantCount) * static_cast<u32>(kColorVariantCount)
436 * static_cast<u32>(kSampleVariantCount)
437 * static_cast<u32>(kGBufferVariantCount)] = {};
438 };
439 struct ComputeRec {
440 WGPUShaderModule module = nullptr;
441 std::string entry;
443 std::unordered_map<std::string, WGPUComputePipeline> pipelines;
444 };
445 struct ReadbackRec {
446 WGPUBuffer buffer = nullptr;
447 u32 width = 0;
448 u32 height = 0;
449 u32 paddedBytesPerRow = 0;
452 bool raw = false;
453 u32 bytesPerTexel = 4;
454 u32 tightBytes = 0;
455 };
456
458 void stubOnce(const char* what);
459
463 bool configureSwapchain(u32 width, u32 height);
464
467 WGPURenderPipeline ensurePipeline(u32 id);
468
469 WGPUBuffer makeBuffer(GfxBufferUsage usage, u32 size, const void* data);
471 bool makeTexture(const TextureDesc& desc, const void* pixels, TextureRec& out);
473 void writeTexture(const TextureRec& rec, i32 x, i32 y, u32 width, u32 height,
474 const void* pixels, bool flipY, u32 layer = 0);
476 void releaseTexture(TextureRec& rec);
482 WGPUBindGroupLayout groupLayoutFor(u32 group, u64 mask, u64 depthMask = 0,
483 u64 vertexMask = 0, u64 arrayMask = 0, u64 volumeMask = 0, u64 fragmentMask = 0);
487 WGPUPipelineLayout pipelineLayoutFor(u32 group0Mask, u64 group1Mask, u64 group1DepthMask = 0,
488 u64 group1VertexMask = 0, u64 group1ArrayMask = 0,
489 u64 group1VolumeMask = 0, u64 group1FragmentMask = 0);
494 void ensureDummies();
501 void flushBindGroup();
503 WGPUSampler samplerFor(u8 key);
507 WGPURenderPipeline ensureClearPipeline(bool color, bool depth, bool stencil);
511 bool copyFramebufferColor(FramebufferHandle source, TextureHandle dst) override;
512 WGPURenderPipeline ensureFlipPipeline(WGPUTextureFormat format, bool flip = true);
513 bool surfaceAllowsCopy() const;
514 void drawInternalClear(bool color, bool depth, bool stencil,
515 const f32 rgba[4], i32 stencilValue, const RenderPassDesc* region);
517 bool inPass() const { return pass_ != nullptr; }
518
519 WGPUDevice device_ = nullptr;
520 bool owns_device_ = false;
521 WGPUQueue queue_ = nullptr;
522 WGPUDevice pending_device_ = nullptr;
523 WGPUInstance instance_ = nullptr;
524 WGPUAdapter adapter_ = nullptr;
525 bool owns_instance_ = true;
526
527 // Surface (the Default framebuffer target). The companion depth-stencil
528 // texture mirrors the WebGL canvas's depth+stencil planes — engine stencil
529 // masks and depth-tested draws target the backbuffer and expect them.
530 WGPUSurface surface_ = nullptr;
531 WGPUTextureFormat surface_format_ = WGPUTextureFormat_RGBA8Unorm;
533 bool prefer_surface_bgra_ = false;
535 bool surface_readback_ = false;
536 bool surface_reconfigure_ = false;
537 WGPUTexture surface_copy_ = nullptr;
538 WGPUTextureView surface_copy_view_ = nullptr;
539 WGPUTextureFormat surface_copy_format_ = WGPUTextureFormat_Undefined;
540 u32 surface_copy_width_ = 0;
541 u32 surface_copy_height_ = 0;
543 bool present_uncapped_ = false;
545 WGPUPresentMode pickUncappedPresentMode() const;
547 bool pass_is_surface_ = false;
549 bool capture_copied_ = false;
551 u32 capture_id_ = 0;
552 u32 surface_width_ = 0;
553 u32 surface_height_ = 0;
555 std::string surface_selector_;
556 WGPUTexture surface_depth_texture_ = nullptr;
557 WGPUTextureView surface_depth_view_ = nullptr;
558
559 // In-flight readbacks: staging buffers whose mapAsync callback flips status.
560 std::unordered_map<u32, ReadbackRec> readbacks_;
561 u32 next_readback_id_ = 1;
562
563 // Driver callbacks may run on any thread, including after device replacement.
564 // They own only this generation's mailbox; the render owner consumes the results.
565 enum class CompletionKind { Frame, Readback, PassTime, GpuTime };
566 struct Completion { CompletionKind kind; u64 id; WGPUMapAsyncStatus status{}; };
567 struct Mailbox { std::mutex mutex; std::vector<Completion> ready; };
568 struct Ticket { std::shared_ptr<Mailbox> mailbox; Completion result; };
569 std::shared_ptr<Mailbox> mailbox_ = std::make_shared<Mailbox>();
570 static void publishCompletion(void* ticket, WGPUMapAsyncStatus status = {});
571 WGPUBufferMapCallbackInfo mapCallback(CompletionKind kind, u32 id);
572 void drainCompletions();
573 void onReadbackMapped(WGPUMapAsyncStatus status, u32 id);
575 void releaseReadback(u32 id);
576
578 void releaseDeviceObjects();
580 u32 allocReadback(u32 w, u32 h);
582 u32 allocRawReadback(u32 w, u32 h, u32 bytesPerTexel, u32 tightBytes);
583 void submitReadbackCopy(u32 id, WGPUTexture source);
584 void encodeReadbackCopy(WGPUCommandEncoder encoder, u32 id, WGPUTexture source);
585 void mapReadback(u32 id);
586
587 // Internal clear family (region-scoped clears + mid-pass clearStencil).
588 // Explicit layout so ONE bind group serves every write-mask variant.
589 std::unordered_map<u32, WGPURenderPipeline> clear_pipelines_;
590 std::unordered_map<u32, WGPURenderPipeline> flip_pipelines_;
591 WGPUBindGroupLayout flip_bgl_ = nullptr;
592 WGPUPipelineLayout flip_layout_ = nullptr;
593 WGPUBindGroupLayout clear_bgl_ = nullptr;
594 WGPUPipelineLayout clear_layout_ = nullptr;
595 WGPUBindGroup clear_bind_group_ = nullptr;
596 WGPUBuffer clear_color_buffer_ = nullptr;
597
598 // Per-pass state.
599 u32 pass_width_ = 0;
600 u32 pass_height_ = 0;
601 WGPUTextureFormat pass_ds_format_ = WGPUTextureFormat_Undefined;
602 WGPUTextureFormat pass_color_format_ = WGPUTextureFormat_RGBA8Unorm;
604 u32 pass_samples_ = 1;
606 bool pass_gbuffer_ = false;
608 bool pass_albedo_ = false;
611 u32 pass_depth_msaa_ = 0;
612 u32 pass_depth_resolve_ = 0;
614 u32 surface_samples_ = 1;
617 WGPUTexture surface_msaa_texture_ = nullptr;
618 WGPUTextureView surface_msaa_view_ = nullptr;
619 u32 surface_msaa_width_ = 0;
620 u32 surface_msaa_height_ = 0;
621 u32 surface_msaa_samples_ = 0;
623 u32 surface_depth_samples_ = 1;
624 bool ensureSurfaceMsaa(u32 width, u32 height);
628 WGPUTexture surface_proxy_ = nullptr;
629 WGPUTextureView surface_proxy_view_ = nullptr;
630 WGPUTextureFormat surface_proxy_format_ = WGPUTextureFormat_Undefined;
631 u32 surface_proxy_width_ = 0;
632 u32 surface_proxy_height_ = 0;
634 bool acquireFrameView();
635 bool late_surface_acquire_ = false;
636 bool surface_proxy_drawn_ = false;
637 bool ensureSurfaceProxy(u32 width, u32 height);
638 void releaseSurfaceProxy();
640 void presentSurfaceProxy();
641
645 void resolveDepthAttachment(u32 msaaDepth, u32 resolveDepth);
646 WGPURenderPipeline ensureDepthResolvePipeline(WGPUTextureFormat format);
649 void buildMipChain(const TextureRec& rec);
650 WGPURenderPipeline ensureMipPipeline(WGPUTextureFormat format);
651 WGPUShaderModule mip_module_ = nullptr;
652 WGPUBindGroupLayout mip_bgl_ = nullptr;
653 WGPUPipelineLayout mip_layout_ = nullptr;
654 WGPUSampler mip_sampler_ = nullptr;
655 std::unordered_map<u32, WGPURenderPipeline> mip_pipelines_;
656 WGPUShaderModule depth_resolve_vs_ = nullptr;
657 WGPUShaderModule depth_resolve_fs_ = nullptr;
658 WGPUBindGroupLayout depth_resolve_bgl_ = nullptr;
659 WGPUPipelineLayout depth_resolve_layout_ = nullptr;
660 std::unordered_map<u32, WGPURenderPipeline> depth_resolve_pipelines_;
663 u32 pass_color_texture_ = 0;
664 u32 pass_depth_texture_ = 0;
665 WGPUCommandEncoder encoder_ = nullptr;
666 WGPURenderPassEncoder pass_ = nullptr;
667 WGPURenderPipeline pass_pipeline_ = nullptr;
668 void* surface_window_ = nullptr;
669 u32 surface_depth_width_ = 0;
670 u32 surface_depth_height_ = 0;
671 WGPUTexture frame_texture_ = nullptr;
672 WGPUTextureView frame_view_ = nullptr;
673 u32 bound_pipeline_ = 0;
674 u32 bound_index_buffer_ = 0;
675 i32 stencil_ref_ = 0;
678 static constexpr u32 kUniformSlots = 10;
679 u32 uniform_slots_[kUniformSlots] = {};
680 u32 uniform_offsets_[kUniformSlots] = {};
681 u32 uniform_sizes_[kUniformSlots] = {};
684 static constexpr u32 kTextureSlots = 17;
685 u32 texture_slots_[kTextureSlots] = {};
686 bool bind_group_dirty_ = true;
687 WGPUBindGroup bind_group_ = nullptr;
688 WGPUBindGroup texture_group_ = nullptr;
689
690 // Reuse immutable bind groups only when their layout and ordered bindings match.
691 // Evict before resource release: emscripten reuses WGPU handle indices immediately.
692 // Layouts belong to the device and outlive this cache.
693 struct BindGroupCacheEntry {
694 WGPUBindGroupLayout layout;
695 std::vector<u64> ids;
696 WGPUBindGroup bg;
697 u64 used;
698 };
701 static constexpr u32 kBindGroupCacheCap = 4096;
703 std::unordered_map<u64, std::vector<BindGroupCacheEntry>> bind_group_cache_;
704 u32 bind_group_count_ = 0;
705 u64 bind_group_frame_ = 0;
707 WGPUBindGroup cachedBindGroup(const u64* ids, u32 idCount,
708 const WGPUBindGroupDescriptor& desc);
710 void evictBindGroups(u64 id);
711
715 void writeBufferPadded(WGPUBuffer buffer, u32 offset, const void* data, u32 size);
716
717 // GPU timing requires TimestampQuery. Single-queue spans sum pass durations. With independent
718 // compute enabled, two timestamps on the graphics queue bracket all work, including the final GPU wait.
719 bool timestamp_supported_ = false;
720 bool timestamp_init_done_ = false;
721 WGPUQuerySet timestamp_qset_ = nullptr;
722 WGPUComputePipeline clock_pipeline_ = nullptr;
723 bool parallel_span_ = false;
724 void stampParallelSpan(bool end);
725 WGPUBuffer timestamp_resolve_ = nullptr;
726 static constexpr u32 kGpuTimeRing = 4;
728 static constexpr u32 kSpanPasses = 96;
729 struct GpuTimeSlot { WGPUBuffer buf = nullptr; bool pending = false; u32 passes = 0; };
730 GpuTimeSlot gpu_time_ring_[kGpuTimeRing] = {};
731 u32 gpu_time_next_ = 0;
732 bool span_open_ = false;
733 bool span_closing_ = false;
734 u32 span_slot_ = kGpuTimeRing;
735 u32 span_passes_ = 0;
736 bool pass_timed_ = false;
737 std::vector<u64> gpu_time_results_;
738 void ensureTimestamps();
739 bool spanTakesPass() const;
740 void resolveSpanPass(WGPUCommandEncoder encoder);
741 void finishSpan();
742
743 // Per-pass timing: armPassTimer names the next pass, which carries the timestamps and has them resolved into a
744 // pooled readback buffer; the result is filed under the name (a timer query id) it was armed with.
745 bool timesPassesByArming() const override { return true; }
746 void armPassTimer(u32 query) override;
747 static constexpr u32 kNoPassSlot = ~0u;
748 static constexpr u32 kPassTimePool = 256;
749 struct PassTimeSlot { WGPUBuffer buf = nullptr; bool pending = false; u32 tag = 0; };
750 std::vector<PassTimeSlot> pass_time_pool_;
751 std::unordered_map<u32, u64> pass_time_results_;
752 std::unordered_set<u32> pass_time_tags_;
753 u32 armed_pass_tag_ = 0;
754 u32 pass_time_slot_ = kNoPassSlot;
756 u32 takePassTimeSlot();
757 void resolvePassTime(WGPUCommandEncoder encoder, u32 slot);
758 void mapPassTime(u32 slot);
759 void onPassTimeMapped(WGPUMapAsyncStatus status, u32 slot);
760 void onGpuTimeMapped(WGPUMapAsyncStatus status, u32 slot);
761
762 std::unordered_map<u8, WGPUSampler> samplers_;
763
764 // Explicit layouts, cached by every mask that shapes them: {group, mask, depth, vertex, array} for
765 // bind-group layouts, {group0, group1, depth, vertex, array} for pipeline layouts. Pipelines and bind groups
766 // share the cached objects, so group compatibility holds by identity.
767 std::map<std::array<u64, 7>, WGPUBindGroupLayout> group_layouts_;
768 std::map<std::array<u64, 7>, WGPUPipelineLayout> pipeline_layouts_;
769 // Backfill belongs to this backend, not to the registry: nothing above it can
770 // name these, so they are made again lazily rather than recovered.
771 BufferRec dummy_ubo_;
772 TextureRec dummy_texture_;
776 TextureRec dummy_depth_texture_;
779 TextureRec dummy_array_texture_;
781 TextureRec dummy_volume_texture_;
782
784 std::unordered_map<u32, BufferRec> buffers_;
785 std::unordered_map<u32, TextureRec> textures_;
786 std::unordered_map<u32, ProgramRec> programs_;
787 std::unordered_map<u32, ComputeRec> computes_;
789 std::unordered_map<std::string, WGPUBindGroupLayout> compute_layouts_;
790 std::unordered_map<std::string, WGPUPipelineLayout> compute_pipeline_layouts_;
791 std::unordered_map<u32, PipelineRec> pipelines_;
792 std::vector<std::string> stub_logged_;
794 u64 frames_ended_ = 0;
795 u64 frames_done_ = 0;
796};
797
798} // namespace esengine
Abstract graphics device interface.
Abstract graphics device interface.
Definition GfxDevice.hpp:75
virtual void backendSetAsyncComputeEnabled(bool)
virtual bool supportsAsyncCompute() const
Hardware with an independent queue. Individual bindings can still require the graphics queue.
virtual void backendWaitAsyncCompute()
virtual bool timesPassesByArming() const
True when a pass is timed by arming it, not by bracketing it with begin/endTimerQuery.
virtual bool backendComputeScopeAvailable() const
virtual bool backendDispatchAsyncCompute(AsyncComputePriority, u32, const GfxComputeBinding *, u32, u32, u32, u32)
void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 indexByteOffset, u32 instanceCount) override
Draws indexed triangles with instancing.
void setWireframe(bool enabled) override
Enables or disables wireframe rendering (desktop only).
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.
ReadbackHandle requestTextureReadback(TextureHandle texture) override
Copies a storage texture's pixels out, tightly packed in the texture's own format (rows top-down).
ColorVariant
Color attachment format of a pass — like DsVariant, WebGPU validates the pipeline's color target form...
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).
bool supportsShaderLanguage(GfxShaderLanguage language) const override
Whether this backend compiles language (GL: GLSL ES 300; WebGPU: WGSL).
bool getTimerQueryNs(u32 query, u64 *outNs) override
Fetches a completed query's elapsed nanoseconds; false while still pending.
void endFrame() override
The frame is over — everything drawn for it has been submitted.
void backendDeleteVertexLayout(u32) override
Drops what the backend derived from a layout (a GL VAO); the desc stays here.
u32 backendUniformBlockIndex(u32, const char *) override
void setPresentUncapped(bool enabled)
Present as fast as the surface allows instead of waiting for the display. Set BEFORE the surface is c...
void backendDeleteCompute(u32 id) override
void discardReadback(ReadbackHandle handle) override
Abandons a readback (any state); its resources are released.
void backendInvalidatePipelineCache() override
bool backendCreateFramebuffer(u32 id, const FramebufferDesc &desc) override
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.
bool supportsCompute() const override
WebGPU is the backend with a compute stage; a device-less instance (bookkeeping only) has none to off...
void backendUseProgram(u32) override
NativeWindowKind
Binds a canvas as the default render target (bring-up entry, not part of the GfxDevice interface)....
void setSurfaceReadback(bool enabled)
Configure the swapchain with CopySrc, so captureNextFrame can read it. Must be set BEFORE the surface...
ReadbackHandle requestReadback(FramebufferHandle target, u32 w, u32 h) override
Requests an RGBA8 readback of a framebuffer's color attachment.
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.
bool frameCaptureIsBGRA() const override
Whether a captured frame's bytes are BGRA rather than RGBA — the surface's choice on a backend that h...
void endRenderPass() override
Ends the current pass, restoring the default framebuffer.
void beginTimerQuery(u32 query) override
Starts timing GPU work into a query; one query may be active at a time.
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
bool timerDisjoint() override
True when GPU timing was disturbed since the last check.
void backendSetPipeline(u32 id, const PipelineDesc &desc) override
bool backendCreateTimerQuery(u32 id) 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.
u32 backendReadbackCount() const override
Readbacks in flight, the one live object the registry does not hold.
bool resolvesDepth() const override
bool takeReadback(ReadbackHandle handle, void *dest, usize destSize) override
Copies a Ready readback's pixels (w*h*4 bytes) into dest and releases it.
bool backendCreateCompute(u32 id, const GfxComputeSource &source, std::string *outLog) override
bool backendAdoptTexture(u32, u32, const TextureDesc &) override
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...
bool supportsFloatTargets() override
Whether RGBA16F color attachments are renderable.
static GfxDeviceLostReason reasonFromWgpu(u32 wgpuReason)
Maps a WGPUDeviceLostReason to the backend-neutral reason.
void backendDeleteProgram(u32 id) override
bool backendDispatchCompute(u32 id, const GfxComputeBinding *bindings, u32 bindingCount, u32 groupsX, u32 groupsY, u32 groupsZ) override
SampleVariant
Sample count of a pass — a third thing WebGPU validates a pipeline against, and the reason a multisam...
u64 estimatedGpuBytes() const override
void drawArrays(u32 firstVertex, u32 vertexCount) override
Draws non-indexed triangles.
bool backendCreateTexture(u32 id, const TextureDesc &desc, const void *pixels) override
ClipDepthRange clipDepthRange() const override
The clip volume this device keeps along z.
ReadbackHandle requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) override
Copies bytes of a storage buffer out, to be taken with pollReadback / takeReadback.
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
void backendUniformBlockBinding(u32, u32, u32) 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.
ReadbackHandle captureNextFrame(u32 w, u32 h) override
Copy the next completed frame's swapchain image into a readback.
void backendDeleteBuffer(u32 id) override
bool framePending() 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.
i32 backendAttribLocation(u32, const char *) override
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 setLateSurfaceAcquire(bool enabled)
Worker passes can span browser tasks. Acquire their expiring canvas texture at present.
void resizeBackbuffer(u32 width, u32 height) override
Resizes the default backbuffer to the viewport size.
i32 backendUniformLocation(u32, const char *) override
The backend's own location this generation, -1 when absent.
void setSurfaceSamples(u32 samples) override
How many samples a SURFACE pass draws with — a frame with no post chain draws straight to the backbuf...
DsVariant
Depth-stencil attachment shape of a pass — one WGPURenderPipeline per shape, since WebGPU validates a...
bool backendAcceptsVertexLayout(const VertexLayoutDesc &desc) override
False for a layout this backend has no way to express.
std::vector< GfxUniformInfo > backendActiveUniforms(u32) override
bool backendCreateCompressedTexture(u32 id, const TextureDesc &desc, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels) override
i32 getInt(GfxIntParam param) override
Queries a backend integer capability/limit.
void backendSetUniform(i32, const GfxUniformValue &) override
void beginRenderPass(const RenderPassDesc &desc) override
Targets a framebuffer for subsequent draws and applies the pass's clears.
void setPreferredSurfaceBGRA(bool bgra)
The surface format the host says its canvas prefers.
void setStencilReference(i32 reference) override
WebGPU stores a texture from the top down.
GfxReadbackStatus pollReadback(ReadbackHandle handle) override
The state of an in-flight readback; pumps backend completion events. A Failed readback is released by...
bool supportsUnblendedSurfaceTarget() const override
u32 validation_errors_logged_
Validation errors said so far (reportUncapturedError says the first few).
void backendDeleteFramebuffer(u32) override
bool supportsCompressedFormat(GfxCompressedFormat format) override
Reports whether the backend can sample the given compressed format.
void ownDeviceReference()
The web host transfers the reference it imported from JavaScript.
u32 getError() override
Queries the last error.
void backendSetTextureParams(u32 id, const TextureDesc &desc) override
bool pollDeviceLost() override
Pumps backend-native loss detection.
bool provideReplacementDevice(void *nativeDevice) override
Hands a replacement in for the next recovery attempt to take up.
void drawElements(u32 indexCount, GfxDataType indexType, u32 indexByteOffset) override
Draws indexed triangles.
void shutdown() override
Shuts down the graphics device.
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
Definition GfxEnums.hpp:41
static constexpr u32 GFX_INVALID_UNIFORM_BLOCK
Sentinel returned by getUniformBlockIndex when a program has no such block (GL_INVALID_INDEX).
Definition GfxDevice.hpp:44
AsyncComputePriority
Definition GfxEnums.hpp:23
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
GfxStringName
Backend identification strings.
Definition GfxEnums.hpp:509
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
GfxDeviceLostReason
Why the device was lost. The report leads with this.
Definition GfxEnums.hpp:543
ClipDepthRange
What a device's clip volume does with depth.
Definition GfxEnums.hpp:562
@ ZeroToOne
WebGPU, and every native API behind it.
Definition GfxEnums.hpp:564
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
GfxShaderLanguage
Shader source language a backend consumes.
Definition GfxEnums.hpp:654
GfxShaderStage
Which pipeline stage rejected a program during createProgram().
Definition GfxEnums.hpp:736
GfxCompressedFormat
GPU-compressed texture internal formats for createCompressedTexture.
Definition GfxEnums.hpp:326
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
GfxIntParam
Backend integer capabilities/limits.
Definition GfxEnums.hpp:517
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
Attachments of an offscreen render target. The attach point of depthStencil follows its texture's pix...
Definition GfxEnums.hpp:451
Vertex attribute location binding applied before a program is linked.
Definition GfxEnums.hpp:730
One resource a compute dispatch binds, at @group(0) @binding(binding).
Definition GfxEnums.hpp:689
A compute program's source. Compute is WGSL only: GLSL ES 3.00 has no compute stage.
Definition GfxEnums.hpp:673
A program's source pair, tagged with the language it is written in.
Definition GfxEnums.hpp:660
The last value a program was given for one uniform, replayed after a relink.
Immutable description of a draw pipeline. Equality keys the pipeline cache, so two draws with the sam...
One render pass: a target, which attachments to clear on entry, and the clear values — full load-op s...
Definition GfxEnums.hpp:485
Immutable creation parameters of a 2D texture or 2D texture array.
Definition GfxEnums.hpp:414
Describes how vertex-buffer bytes map to shader attributes.
Definition GfxEnums.hpp:235