Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
GfxDevice.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
18#pragma once
19
20// =============================================================================
21// Includes
22// =============================================================================
23
24#include "../../core/Types.hpp"
25#include "../draw/BlendMode.hpp"
26#include "./GfxContent.hpp"
27#include "./GfxEnums.hpp"
29#include "./PipelineState.hpp"
30
31#include <functional>
32#include <map>
33#include <string>
34#include <utility>
35#include <vector>
36
37namespace esengine {
38
39// =============================================================================
40// GfxDevice Interface
41// =============================================================================
42
44static constexpr u32 GFX_INVALID_UNIFORM_BLOCK = 0xFFFFFFFFu;
45
47static constexpr u32 GFX_UNIFORM_OFFSET_ALIGNMENT = 256;
48
66
75class GfxDevice {
76public:
77 virtual ~GfxDevice() = default;
78
79 // =========================================================================
80 // Lifecycle
81 // =========================================================================
82
84 virtual void init() = 0;
85
87 virtual void shutdown() = 0;
88
89 // =========================================================================
90 // Device Loss
91 // =========================================================================
92
93 // The state machine lives here, not in each backend: a backend only has to
94 // DETECT its own kind of loss and call markDeviceLost. What "lost" then MEANS
95 // — one report, one transition, submission stopped — stays identical.
96
98 GfxDeviceStatus deviceStatus() const { return device_status_; }
99
101 bool isDeviceLive() const { return device_status_ == GfxDeviceStatus::Live; }
102
110 bool isDeviceUsable() const {
111 return device_status_ == GfxDeviceStatus::Live ||
112 device_status_ == GfxDeviceStatus::Recovering;
113 }
114
121 u64 deviceGeneration() const { return device_generation_; }
122
130 u64 geometryWrites() const { return geometry_writes_; }
131
134 return device_status_ == GfxDeviceStatus::Live ? nullptr : &device_info_;
135 }
136
143 const GfxDeviceIdentity& deviceIdentity() const { return identity_; }
144
152 virtual ClipDepthRange clipDepthRange() const = 0;
153
154 virtual bool copyFramebufferColor(FramebufferHandle source, TextureHandle dst) { (void)source; (void)dst; return false; }
155
163 void notifyDeviceLost(GfxDeviceLostReason reason, std::string message = {},
164 std::string context = {}) {
165 markDeviceLost(reason, std::move(message), std::move(context));
166 }
167
174 bool recoverDevice();
175
177 std::vector<GfxOwedContent> owedContent() const { return registry_.owed(); }
178
183 void forgoContent(const GfxOwedContent& owed);
184
191 void restoreContent(const GfxOwedContent& owed);
192
198 usize retainedBytes() const { return retained_bytes_; }
199
206 u32 takeDraws() { const u32 n = draws_; draws_ = 0; return n; }
207
213 retained_budget_ = bytes;
214 over_retained_budget_ = false;
215 }
216
223 if (device_status_ == GfxDeviceStatus::Dead) return;
224 if (device_status_ == GfxDeviceStatus::Live) {
226 }
227 device_status_ = GfxDeviceStatus::Dead;
228 }
229
237 virtual bool provideReplacementDevice(void* nativeDevice) {
238 (void)nativeDevice;
239 return false;
240 }
241
250 virtual bool pollDeviceLost() { return false; }
251
261 ++device_frame_;
263 return isDeviceUsable();
264 }
265
271 void setDeviceLostHandler(std::function<void(const GfxDeviceLostInfo&)> handler) {
272 device_lost_handler_ = std::move(handler);
273 }
274
275 // =========================================================================
276 // Viewport & Clear
277 // =========================================================================
278
280 virtual void setViewport(i32 x, i32 y, u32 w, u32 h) = 0;
281
288 struct Viewport { i32 x = 0, y = 0; u32 w = 0, h = 0; };
289 const Viewport& viewport() const { return viewport_; }
290
291 // Clears are pass-scoped: RenderPassDesc carries the load-ops AND their values
292 // (color / stencil / optional region). There is no public clear entry point and
293 // no sticky clear state a pass could inherit by accident.
294
295 // =========================================================================
296 // Dynamic Per-Draw State (deliberately outside the pipeline; see PipelineState.hpp)
297 // =========================================================================
298
306 virtual void clearStencil(i32 value) = 0;
307
309 virtual void setScissorTest(bool enabled) = 0;
310
312 virtual void setScissor(i32 x, i32 y, i32 w, i32 h) = 0;
313
314 // =========================================================================
315 // Buffers
316 // =========================================================================
317
323 BufferHandle createBuffer(const BufferDesc& desc, GfxContent content, const void* initialData);
324
326 void deleteBuffer(BufferHandle buffer);
327
329 void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes);
330
336 void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data);
337
339 const BufferDesc* bufferDesc(BufferHandle buffer) const;
340
346 void setUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes = 0, u32 sizeBytes = 0) {
347 backendSetUniformBuffer(slot, buffer, offsetBytes, sizeBytes);
348 }
349
350 // =========================================================================
351 // Vertex Input (layout in the pipeline, buffers bound per draw)
352 // =========================================================================
353
356
359
362
368 virtual void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes) = 0;
369
371 virtual void setIndexBuffer(BufferHandle buffer) = 0;
372
373 // =========================================================================
374 // Textures
375 // =========================================================================
376
382 TextureHandle createTexture(const TextureDesc& desc, GfxContent content, const void* pixels);
383
395 GfxCompressedFormat format, const void* data,
396 u32 byteLength, u32 mipLevels);
397
400 const void* data, u32 byteLength, u32 mipLevels);
401
407 TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc, GfxContent content);
408
410 bool restoreTextureFromNative(TextureHandle texture, u32 nativeId);
411
419
421 void deleteTexture(TextureHandle texture);
422
427 void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,
428 const void* pixels, bool flipY);
429
432 TextureWrap wrapS, TextureWrap wrapT);
433
435 void generateMipmaps(TextureHandle texture);
436
440 u64 textureRevision(TextureHandle texture) const;
445 u64 textureShapes() const { return texture_shapes_; }
446 const TextureDesc* textureDesc(TextureHandle texture) const;
447
449 virtual void bindTexture(u32 slot, TextureHandle texture) = 0;
450
458
466 virtual bool supportsFloatTargets() = 0;
467
475 virtual bool supportsUnblendedSurfaceTarget() const { return false; }
476
484 virtual u32 maxSamples() = 0;
485
492 virtual bool resolvesDepth() const { return false; }
493
500 virtual void setSurfaceSamples(u32 samples) { (void)samples; }
501
502 // =========================================================================
503 // Shader Programs
504 // =========================================================================
505
517 const GfxAttribBinding* bindings, u32 bindingCount,
518 std::string* outLog, GfxShaderStage* outFailedStage);
519
521 virtual bool supportsShaderLanguage(GfxShaderLanguage language) const = 0;
522
524 virtual bool supportsDeferredLink() const { return false; }
525
530 void onProgramLinked(ShaderHandle program, std::function<void()> callback);
531
533 bool finishProgram(ShaderHandle program) { return backendFinishProgram(static_cast<u32>(program)); }
534
539 bool programReady(ShaderHandle program) { return backendProgramReady(static_cast<u32>(program)); }
540
549
555 void setSkipPendingPrograms(bool on) { skip_pending_programs_ = on; }
556 bool skipPendingPrograms() const { return skip_pending_programs_; }
557
559 void deleteProgram(ShaderHandle program);
560
561 // =========================================================================
562 // Compute
563 // =========================================================================
564
570 virtual bool supportsCompute() const { return false; }
572 virtual bool supportsAsyncCompute() const { return false; }
573 void setAsyncComputeEnabled(bool enabled);
574 bool asyncComputeEnabled() const { return async_compute_enabled_; }
582
587 ComputeHandle createCompute(const GfxComputeSource& source, std::string* outLog = nullptr);
588
590 void deleteCompute(ComputeHandle program);
591
602 bool dispatchCompute(ComputeHandle program, const GfxComputeBinding* bindings, u32 bindingCount,
603 u32 groupsX, u32 groupsY = 1, u32 groupsZ = 1);
604
610 virtual ReadbackHandle requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) {
611 (void)buffer; (void)offsetBytes; (void)sizeBytes;
613 }
614
621 (void)texture;
623 }
624
629 void useProgram(ShaderHandle program);
630
636 i32 getUniformLocation(ShaderHandle program, const char* name);
637
639 i32 getAttribLocation(ShaderHandle program, const char* name);
640
648
650 void setUniform1i(i32 location, i32 value);
651
653 void setUniform1f(i32 location, f32 value);
654
656 void setUniform2f(i32 location, f32 x, f32 y);
657
659 void setUniform3f(i32 location, f32 x, f32 y, f32 z);
660
662 void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w);
663
665 void setUniformMat3(i32 location, const f32* data);
666
668 void setUniformMat4(i32 location, const f32* data);
669
671 std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle program);
672
674 u32 getUniformBlockIndex(ShaderHandle program, const char* name);
675
677 void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint);
678
679 // =========================================================================
680 // Pipeline State (immutable "how to draw"; see PipelineState.hpp)
681 // =========================================================================
682
685
687 const PipelineDesc* pipelineDesc(PipelineHandle handle) const;
688
690 void setPipeline(PipelineHandle handle);
691
693 virtual void setStencilReference(i32 ref) = 0;
694
702
703 // =========================================================================
704 // Draw Calls
705 // =========================================================================
706
708 virtual void drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) = 0;
709
711 virtual void drawArrays(u32 first, u32 vertexCount) = 0;
712
714 virtual void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) = 0;
715
717 virtual bool supportsMultiDraw() const { return false; }
718
725 virtual void drawElementsInstancedMulti(GfxDataType indexType, const u32* counts, const u32* byteOffsets,
726 const u32* instanceCounts, u32 drawCount) {
727 for (u32 k = 0; k < drawCount; ++k) drawElementsInstanced(counts[k], indexType, byteOffsets[k], instanceCounts[k]);
728 }
729
730 // =========================================================================
731 // Framebuffers
732 // =========================================================================
733
740
742 void deleteFramebuffer(FramebufferHandle framebuffer);
743
745 const FramebufferDesc* framebufferDesc(FramebufferHandle framebuffer) const;
746
747 // =========================================================================
748 // Render Pass
749 // =========================================================================
750
757 virtual void beginRenderPass(const RenderPassDesc& desc) = 0;
758
760 virtual void endRenderPass() = 0;
761
772 virtual void endFrame() {}
773
780 virtual bool framePending() { return false; }
781
790 virtual void resizeBackbuffer(u32 width, u32 height) {
791 (void)width;
792 (void)height;
793 }
794
795 // =========================================================================
796 // Readback (asynchronous seam — the one backend-neutral pixel-return path)
797 // =========================================================================
798
811
815
821 virtual bool takeReadback(ReadbackHandle handle, void* dest, usize destSize) = 0;
822
824 virtual void discardReadback(ReadbackHandle handle) = 0;
825
835
838 virtual bool frameCaptureIsBGRA() const { return false; }
839
840 // =========================================================================
841 // GPU Timing (optional; EXT_disjoint_timer_query on WebGL2)
842 // =========================================================================
843
846
852 virtual void beginTimerQuery(u32 query) = 0;
853
855 virtual void endTimerQuery() = 0;
856
861 virtual bool timerDisjoint() = 0;
862
864 virtual bool getTimerQueryNs(u32 query, u64* outNanoseconds) = 0;
865
871 virtual bool timesPassesByArming() const { return false; }
872
878 virtual void armPassTimer(u32 query) { (void)query; }
879
880 // =========================================================================
881 // Debug
882 // =========================================================================
883
885 virtual void setWireframe(bool enabled) = 0;
886
888 virtual u32 getError() = 0;
889
891 virtual std::string getString(GfxStringName name) = 0;
892
894 virtual i32 getInt(GfxIntParam name) = 0;
895
898
901 virtual u64 estimatedGpuBytes() const;
902
909 virtual u32 nativeTextureName(TextureHandle texture) const { (void)texture; return 0; }
910
911protected:
913 void countDraw() { ++draws_; }
914
915 // =========================================================================
916 // Backend primitives. `id` is the handle's value; the backend maps it to its
917 // own object for the current generation and nothing else.
918 // =========================================================================
919
920 virtual bool backendCreateBuffer(u32 id, const BufferDesc& desc, const void* data) = 0;
921 virtual void backendDeleteBuffer(u32 id) = 0;
922 virtual void backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) = 0;
923 virtual void backendResizeBuffer(u32 id, const BufferDesc& desc, const void* data) = 0;
924 virtual void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes) = 0;
925
926 virtual bool backendCreateTexture(u32 id, const TextureDesc& desc, const void* pixels) = 0;
928 const void* data, u32 byteLength, u32 mipLevels) = 0;
930 virtual bool backendAdoptTexture(u32 id, u32 nativeId, const TextureDesc& desc) = 0;
931 virtual void backendDeleteTexture(u32 id) = 0;
933 virtual void backendMoveTexture(u32 into, u32 from) = 0;
934 virtual void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height,
935 const void* pixels, bool flipY) = 0;
936 virtual void backendSetTextureParams(u32 id, const TextureDesc& desc) = 0;
937 virtual void backendGenerateMipmaps(u32 id) = 0;
938
939 virtual bool backendCreateCompute(u32 id, const GfxComputeSource& source, std::string* outLog) {
940 (void)id; (void)source;
941 if (outLog) *outLog = "this device has no compute stage";
942 return false;
943 }
944 bool computeJobOpen() const { return compute_job_open_; }
945 const GfxResourceRegistry& resourceRecords() const { return registry_; }
946 virtual void backendSetAsyncComputeEnabled(bool) {}
947 virtual bool backendComputeScopeAvailable() const { return true; }
949 u32, u32, u32, u32) { return false; }
950 virtual void backendWaitAsyncCompute() {}
951 virtual void backendDeleteCompute(u32 id) { (void)id; }
952 virtual bool backendDispatchCompute(u32 id, const GfxComputeBinding* bindings, u32 bindingCount,
953 u32 groupsX, u32 groupsY, u32 groupsZ) {
954 (void)id; (void)bindings; (void)bindingCount; (void)groupsX; (void)groupsY; (void)groupsZ;
955 return false;
956 }
957 virtual bool backendCreateProgram(u32 id, const GfxShaderSource& source,
958 const GfxAttribBinding* bindings, u32 bindingCount,
959 std::string* outLog, GfxShaderStage* outFailedStage) = 0;
960 virtual void backendDeleteProgram(u32 id) = 0;
962 virtual bool backendProgramPending(u32 id) const { (void)id; return false; }
963 virtual bool backendProgramReady(u32 id) { (void)id; return true; }
964 virtual u32 backendPendingProgramCount() { return 0; }
965 virtual std::string backendPendingProgramLabels() { return {}; }
967 virtual bool backendFinishProgram(u32 id) { (void)id; return true; }
969 void notifyProgramLinked(u32 id);
970 virtual void backendUseProgram(u32 id) = 0;
972 virtual i32 backendUniformLocation(u32 program, const char* name) = 0;
973 virtual i32 backendAttribLocation(u32 program, const char* name) = 0;
974 virtual void backendSetUniform(i32 nativeLocation, const GfxUniformValue& value) = 0;
976 virtual u32 backendBoundSamplerUnits() { return 0xFFFFFFFFu; }
978 virtual void backendIntUniformSet(u32 program) { (void)program; }
979 virtual std::vector<GfxUniformInfo> backendActiveUniforms(u32 program) = 0;
980 virtual u32 backendUniformBlockIndex(u32 program, const char* name) = 0;
981 virtual void backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint) = 0;
982
984 virtual bool backendAcceptsVertexLayout(const VertexLayoutDesc& desc) { (void)desc; return true; }
986 virtual void backendDeleteVertexLayout(u32 id) = 0;
987 virtual void backendSetPipeline(u32 id, const PipelineDesc& desc) = 0;
989
990 virtual bool backendCreateFramebuffer(u32 id, const FramebufferDesc& desc) = 0;
991 virtual void backendDeleteFramebuffer(u32 id) = 0;
992
993 virtual bool backendCreateTimerQuery(u32 id) = 0;
994
996 virtual u32 backendReadbackCount() const = 0;
997
999 PipelineHandle currentPipeline() const { return current_pipeline_; }
1002
1010 virtual void captureDeviceIdentity() {}
1011
1018 virtual bool recreateDevice() { return false; }
1019
1021 void setDeviceIdentity(std::string backend, std::string vendor,
1022 std::string renderer, std::string version) {
1023 identity_.backend = std::move(backend);
1024 identity_.vendor = std::move(vendor);
1025 identity_.renderer = std::move(renderer);
1026 identity_.version = std::move(version);
1027 }
1028
1035 bool markDeviceLost(GfxDeviceLostReason reason, std::string message = {},
1036 std::string context = {});
1037
1045 virtual void onDeviceLost() {}
1046
1047private:
1049 void realizeRegistry();
1050 void realizeProgramState(u32 id, GfxProgramRecord& record);
1052 void settleRecovery();
1053 void payTexture(u32 id, GfxTextureRecord& record);
1054 void keepBytes(std::vector<u8>& slot, std::vector<u8> bytes);
1055 void dropBytes(std::vector<u8>& slot);
1056 std::vector<u8> takeBytes(std::vector<u8>& slot);
1057 void judgeRetainedBudget(usize grownBy);
1058 void eraseBuffer(u32 id);
1059 void eraseTexture(u32 id);
1060 i32 nativeUniformLocation(GfxProgramRecord& record, u32 id, i32 location);
1061 void setUniformValue(i32 location, const GfxUniformValue& value);
1062
1063 bool async_compute_enabled_ = false;
1064 bool compute_job_open_ = false;
1066 AsyncComputeFence next_compute_fence_ = 0;
1067 AsyncComputeFence pending_compute_fence_ = kNoAsyncComputeFence;
1068 GfxDeviceStatus device_status_ = GfxDeviceStatus::Live;
1069 GfxDeviceIdentity identity_;
1070 GfxDeviceLostInfo device_info_;
1071 u64 device_frame_ = 0;
1072 u64 device_generation_ = 0;
1073 u64 geometry_writes_ = 0;
1074 u64 texture_shapes_ = 0;
1075 void countGeometryWrite(const BufferDesc& desc) {
1076 if (!desc.dynamic && (desc.usage == GfxBufferUsage::Vertex || desc.usage == GfxBufferUsage::Index)) ++geometry_writes_;
1077 }
1078 std::function<void(const GfxDeviceLostInfo&)> device_lost_handler_;
1079
1080 GfxResourceRegistry registry_;
1081 u32 owed_count_ = 0;
1082 usize retained_bytes_ = 0;
1083 u32 draws_ = 0;
1084 usize retained_budget_ = 0;
1085 bool over_retained_budget_ = false;
1086 ShaderHandle current_program_ = ShaderHandle::Invalid;
1087 bool skip_pending_programs_ = false;
1088 PipelineHandle current_pipeline_ = PipelineHandle::Invalid;
1090 std::map<u32, std::vector<i32>> native_locations_;
1091};
1092
1093} // namespace esengine
Blend mode enumeration for custom rendering.
Who restores a GPU object's contents after the device is lost.
Backend-agnostic graphics enumerations.
Every GPU object a device has issued, described well enough to build again.
Immutable GPU pipeline state — the backend-agnostic unit of "how to draw".
Core type definitions and utilities for ESEngine.
A content policy. provider names who refills a Sourced object and key what it refills; both are the p...
Abstract graphics device interface.
Definition GfxDevice.hpp:75
virtual bool backendAcceptsVertexLayout(const VertexLayoutDesc &desc)
False for a layout this backend has no way to express.
virtual bool frameCaptureIsBGRA() const
Whether a captured frame's bytes are BGRA rather than RGBA — the surface's choice on a backend that h...
bool markDeviceLost(GfxDeviceLostReason reason, std::string message={}, std::string context={})
The single transition into Lost. Backends call this on detection.
Definition GfxDevice.cpp:60
virtual bool resolvesDepth() const
Whether this backend can resolve a multisampled DEPTH attachment.
void deleteCompute(ComputeHandle program)
Deletes a compute program.
virtual void armPassTimer(u32 query)
Times the next render or compute pass into query (0 disarms), read back with getTimerQueryNs.
virtual ClipDepthRange clipDepthRange() const =0
The clip volume this device keeps along z.
void setDeviceLostHandler(std::function< void(const GfxDeviceLostInfo &)> handler)
Called once per loss, with the completed report.
void deleteVertexLayout(VertexLayoutHandle layout)
Deletes a vertex layout (no pipeline may reference it afterwards).
void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height, const void *pixels, bool flipY)
Uploads pixels to a sub-rectangle of a texture (transfer format from its desc).
Viewport viewport_
Backends record what they were last handed; see viewport.
virtual void resizeBackbuffer(u32 width, u32 height)
Resizes the default backbuffer to the viewport size.
virtual bool backendCreateBuffer(u32 id, const BufferDesc &desc, const void *data)=0
virtual bool backendCreateTexture(u32 id, const TextureDesc &desc, const void *pixels)=0
virtual bool backendCreateCompute(u32 id, const GfxComputeSource &source, std::string *outLog)
void setUniform3f(i32 location, f32 x, f32 y, f32 z)
Sets a vec3 uniform.
bool finishProgram(ShaderHandle program)
Waits for program to link if it has not yet. False when it failed to.
virtual void backendSetAsyncComputeEnabled(bool)
virtual void setViewport(i32 x, i32 y, u32 w, u32 h)=0
Sets the rendering viewport.
virtual u32 backendPendingProgramCount()
virtual i32 backendUniformLocation(u32 program, const char *name)=0
The backend's own location this generation, -1 when absent.
void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint)
Links a program's uniform block to an indexed binding slot.
virtual void backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes, u32 sizeBytes)=0
virtual bool supportsAsyncCompute() const
Hardware with an independent queue. Individual bindings can still require the graphics queue.
virtual void bindTexture(u32 slot, TextureHandle texture)=0
Activates a texture slot and binds a 2D texture.
virtual void backendUseProgram(u32 id)=0
bool beginDeviceFrame()
Opens a frame: polls for loss, and numbers the frame a report is stamped with.
GfxDeviceStatus deviceStatus() const
Whether the device can be drawn to (see GfxDeviceStatus).
Definition GfxDevice.hpp:98
BufferHandle createBuffer(const BufferDesc &desc, GfxContent content, const void *initialData)
Creates a buffer with fixed capacity and optional initial contents.
i32 getUniformLocation(ShaderHandle program, const char *name)
Gets a uniform location by name, -1 when the linked program has none.
virtual void backendUpdateTexture(u32 id, i32 x, i32 y, u32 width, u32 height, const void *pixels, bool flipY)=0
virtual void beginTimerQuery(u32 query)=0
Starts timing GPU work into a query; one query may be active at a time.
void setUniform2f(i32 location, f32 x, f32 y)
Sets a vec2 uniform.
bool programReady(ShaderHandle program)
Whether program can be drawn with now, without waiting: linked, or finished linking in the background...
virtual GfxReadbackStatus pollReadback(ReadbackHandle handle)=0
The state of an in-flight readback; pumps backend completion events. A Failed readback is released by...
const GfxDeviceLostInfo * deviceLostInfo() const
The loss report, or null while the device is Live.
virtual void setSurfaceSamples(u32 samples)
Asks for the backbuffer to be drawn with this many samples.
virtual bool backendCreateFramebuffer(u32 id, const FramebufferDesc &desc)=0
virtual ReadbackHandle requestTextureReadback(TextureHandle texture)
Copies a storage texture's pixels out, tightly packed in the texture's own format (rows top-down).
virtual void setVertexBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes)=0
Binds a vertex buffer to a layout slot for subsequent draws.
void invalidatePipelineCache()
Forces the next setPipeline to re-apply, dropping the cached current pipeline.
virtual void drawElementsInstancedMulti(GfxDataType indexType, const u32 *counts, const u32 *byteOffsets, const u32 *instanceCounts, u32 drawCount)
drawCount indexed instanced draws through the bound pipeline and buffers, as one call where supportsM...
virtual u64 estimatedGpuBytes() const
void forgoContent(const GfxOwedContent &owed)
Gives up on one owed object's contents: it keeps its placeholder.
u32 pendingProgramCount()
How many programs made with deferLink are still compiling.
void setUniform4f(i32 location, f32 x, f32 y, f32 z, f32 w)
Sets a vec4 uniform.
bool skipPendingPrograms() const
void setSkipPendingPrograms(bool on)
Whether a draw whose program is not ready is left out, instead of waited for.
void useProgram(ShaderHandle program)
Binds a program directly, for setup-time uniform seeding.
void generateMipmaps(TextureHandle texture)
Generates mipmaps for a texture.
virtual void shutdown()=0
Shuts down the graphics device.
virtual bool backendCreateTimerQuery(u32 id)=0
bool isDeviceLive() const
Strictly Live: recovered but still-refilling counts as false.
FramebufferHandle createFramebuffer(const FramebufferDesc &desc)
Creates a framebuffer from its attachments and validates completeness.
const GfxDeviceIdentity & deviceIdentity() const
Who this device is — available WHILE it is alive, unlike the loss report.
const VertexLayoutDesc * vertexLayoutDesc(VertexLayoutHandle layout) const
A layout's description, or null for a handle that names none.
virtual std::string backendPendingProgramLabels()
u32 createTimerQuery()
Creates a GPU elapsed-time query, or 0 when the backend cannot time GPU work.
virtual void drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset)=0
Draws indexed triangles.
void notifyDeviceLost(GfxDeviceLostReason reason, std::string message={}, std::string context={})
Declares the device lost from outside the backend.
virtual bool recreateDevice()
Backend half of recoverDevice: a working device again, with every id-to-native map and derived cache ...
virtual void backendUpdateBuffer(u32 id, u32 offsetBytes, const void *data, u32 sizeBytes)=0
virtual void captureDeviceIdentity()
Records who this backend is, so a later loss report can name it.
virtual void setIndexBuffer(BufferHandle buffer)=0
Binds the index buffer for subsequent indexed draws.
virtual bool supportsDeferredLink() const
Whether createProgram honours GfxShaderSource::deferLink (GL: yes; a backend that links at once does ...
TextureHandle importExternalTexture(u32 nativeId, const TextureDesc &desc, GfxContent content)
Adopts a texture a host created with the device's own API (a JS-side WebGL upload).
virtual void endTimerQuery()=0
Stops the active timer query.
virtual std::string getString(GfxStringName name)=0
Queries a backend identification string (diagnostics).
virtual bool takeReadback(ReadbackHandle handle, void *dest, usize destSize)=0
Copies a Ready readback's pixels (w*h*4 bytes) into dest and releases it.
virtual bool backendCreateCompressedTexture(u32 id, const TextureDesc &desc, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels)=0
std::string pendingProgramLabels()
What each program still compiling in the background is, one line each: what a "compiling shaders" rea...
AsyncComputeFence endAsyncComputeJob()
A fence for submitted work, or -1 when it is already ordered on the graphics queue.
virtual void backendUniformBlockBinding(u32 program, u32 nativeBlockIndex, u32 bindingPoint)=0
virtual void backendWaitAsyncCompute()
virtual void backendResizeBuffer(u32 id, const BufferDesc &desc, const void *data)=0
virtual u32 getError()=0
Queries the last error.
virtual u32 maxSamples()=0
Most samples an offscreen colour attachment may carry; 1 = none.
virtual bool supportsShaderLanguage(GfxShaderLanguage language) const =0
Whether this backend compiles language (GL: GLSL ES 300; WebGPU: WGSL).
u32 boundSamplerUnits()
The texture units the bound program samples, one bit a unit; every unit where the backend cannot say.
bool asyncComputeEnabled() const
virtual void beginRenderPass(const RenderPassDesc &desc)=0
Targets a framebuffer for subsequent draws and applies the pass's clears.
i32 getAttribLocation(ShaderHandle program, const char *name)
Gets a vertex attribute location by name (-1 if not found).
u64 geometryWrites() const
How many times a static vertex or index buffer has been written or resized since the device was made.
virtual bool provideReplacementDevice(void *nativeDevice)
Takes a replacement device from the host, for backends that cannot make their own.
virtual void backendDeleteProgram(u32 id)=0
virtual void backendInvalidatePipelineCache()=0
virtual u32 backendReadbackCount() const =0
Readbacks in flight, the one live object the registry does not hold.
void notifyProgramLinked(u32 id)
For a backend finishing a deferred program: runs its onLinked callback, leaving the bound program as ...
virtual void backendMoveTexture(u32 into, u32 from)=0
Re-keys from's native texture under into; into holds none on entry.
std::vector< GfxOwedContent > owedContent() const
Sourced objects that have storage again and are waiting for their contents.
void setUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetBytes=0, u32 sizeBytes=0)
Binds a buffer to a uniform binding slot (the block index shaders are linked to).
virtual i32 backendAttribLocation(u32 program, const char *name)=0
virtual void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount)=0
Draws indexed triangles with instancing.
std::vector< GfxUniformInfo > getActiveUniforms(ShaderHandle program)
Enumerates all active uniforms of a linked shader program.
virtual bool pollDeviceLost()
Pumps backend-native loss detection.
virtual bool timesPassesByArming() const
True when a pass is timed by arming it, not by bracketing it with begin/endTimerQuery.
u64 trackedTextureRevision(TextureHandle texture) const
Zero for content that can change without an upload, including render targets and host textures.
virtual bool backendProgramPending(u32 id) const
True while a program created with deferLink has not been waited for.
virtual void setScissorTest(bool enabled)=0
Enables or disables scissor test.
virtual void discardReadback(ReadbackHandle handle)=0
Abandons a readback (any state); its resources are released.
void markDeviceDead()
Gives up on the device: no further recovery will be attempted.
bool restoreCompressedTexture(TextureHandle texture, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels)
Puts compressed contents back behind an owed texture's handle.
void restoreContent(const GfxOwedContent &owed)
Settles one owed object whose provider wrote its contents itself.
void deleteTexture(TextureHandle texture)
Deletes a texture.
virtual bool supportsUnblendedSurfaceTarget() const
Whether a blended draw can write the surface record's second attachment unblended.
virtual bool backendAdoptTexture(u32 id, u32 nativeId, const TextureDesc &desc)=0
Takes over a native texture the host created; false when this backend cannot.
virtual void backendGenerateMipmaps(u32 id)=0
virtual void endRenderPass()=0
Ends the current pass, restoring the default framebuffer.
u64 textureShapes() const
Counts every texture made, deleted, or given new storage under its handle (a restore,...
virtual void setWireframe(bool enabled)=0
Enables or disables wireframe rendering (desktop only).
virtual void endFrame()
The frame is over — everything drawn for it has been submitted.
void setAsyncComputeEnabled(bool enabled)
virtual bool backendComputeScopeAvailable() const
void setUniformMat3(i32 location, const f32 *data)
Sets a mat3 uniform.
bool isDeviceUsable() const
Whether work may be submitted — the one check the guards make.
virtual bool backendCreateProgram(u32 id, const GfxShaderSource &source, const GfxAttribBinding *bindings, u32 bindingCount, std::string *outLog, GfxShaderStage *outFailedStage)=0
void setUniform1f(i32 location, f32 value)
Sets a float uniform.
TextureHandle createTexture(const TextureDesc &desc, GfxContent content, const void *pixels)
Creates a 2D texture; uploads pixels (tightly packed, desc-sized) when non-null.
void setPipeline(PipelineHandle handle)
Binds a pipeline: applies its program, blend, depth, stencil compare/op and culling.
virtual void drawArrays(u32 first, u32 vertexCount)=0
Draws non-indexed triangles.
void countDraw()
A backend has issued one draw (see takeDraws).
ComputeHandle createCompute(const GfxComputeSource &source, std::string *outLog=nullptr)
Compiles a compute program.
void graphicsWaitOnAsyncComputeJob(AsyncComputeFence fence)
virtual ~GfxDevice()=default
virtual bool supportsFloatTargets()=0
Whether RGBA16F color attachments are renderable.
u32 takeDraws()
Every draw the GPU was asked for since the last call, and the tally started again.
virtual void backendSetUniform(i32 nativeLocation, const GfxUniformValue &value)=0
void setUniformMat4(i32 location, const f32 *data)
Sets a mat4 uniform.
const GfxResourceRegistry & resourceRecords() const
u32 getUniformBlockIndex(ShaderHandle program, const char *name)
Returns a program's uniform-block index by name, or GFX_INVALID_UNIFORM_BLOCK if absent.
void deleteBuffer(BufferHandle buffer)
Deletes a buffer.
bool computeJobOpen() const
VertexLayoutHandle createVertexLayout(const VertexLayoutDesc &desc)
Registers an immutable vertex layout; pipelines reference it by handle.
virtual bool timerDisjoint()=0
True when GPU timing was disturbed since the last check.
virtual void backendSetTextureParams(u32 id, const TextureDesc &desc)=0
ShaderHandle createProgram(const GfxShaderSource &source, const GfxAttribBinding *bindings, u32 bindingCount, std::string *outLog, GfxShaderStage *outFailedStage)
Compiles and links a GPU program from GLSL sources.
const Viewport & viewport() const
virtual bool backendDispatchCompute(u32 id, const GfxComputeBinding *bindings, u32 bindingCount, u32 groupsX, u32 groupsY, u32 groupsZ)
virtual void onDeviceLost()
Release what only this backend can name, while the dead device is still the current one.
virtual bool backendFinishProgram(u32 id)
Waits for a deferred program, runs its onLinked callback; false when it failed to link....
const FramebufferDesc * framebufferDesc(FramebufferHandle framebuffer) const
A framebuffer's description, or null for Default and unknown handles.
PipelineHandle createPipeline(const PipelineDesc &desc)
Resolves a pipeline description to a cached handle (creating it on first use).
const BufferDesc * bufferDesc(BufferHandle buffer) const
A buffer's description as it stands, or null for a handle that names none.
virtual ReadbackHandle captureNextFrame(u32 w, u32 h)
Requests the next completed frame's on-screen image as a readback.
virtual void backendDeleteFramebuffer(u32 id)=0
void manualComputeBarrier()
Order dispatches across queues. Each inline dispatch is already a complete compute pass.
virtual void clearStencil(i32 value)=0
Mid-pass stencil reset (the one clear that isn't a pass load-op).
virtual void init()=0
Initializes the graphics device.
virtual void backendDeleteTexture(u32 id)=0
bool beginAsyncComputeJob(AsyncComputePriority priority=AsyncComputePriority::Default)
Opens a compute-only scope, including on single-queue devices. Scopes cannot nest.
virtual void backendSetPipeline(u32 id, const PipelineDesc &desc)=0
virtual u32 backendBoundSamplerUnits()
void setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag, TextureWrap wrapS, TextureWrap wrapT)
Sets texture filtering and wrap parameters.
virtual bool supportsCompute() const
Whether this device runs compute shaders.
virtual void backendIntUniformSet(u32 program)
bool adoptTextureContent(TextureHandle into, TextureHandle from)
Moves from's storage and description behind into, and ends from.
bool restoreTextureFromNative(TextureHandle texture, u32 nativeId)
Replaces the native texture behind texture with one the host created again.
virtual bool backendDispatchAsyncCompute(AsyncComputePriority, u32, const GfxComputeBinding *, u32, u32, u32, u32)
u64 textureRevision(TextureHandle texture) const
A texture's description as it stands, or null for a handle that names none.
virtual bool framePending()
Whether the GPU is still working on the frame last ended (see endFrame).
TextureHandle createCompressedTexture(const TextureDesc &desc, GfxContent content, GfxCompressedFormat format, const void *data, u32 byteLength, u32 mipLevels)
Creates a texture from pre-compressed GPU block data.
virtual u32 nativeTextureName(TextureHandle texture) const
The backend's own name for the object behind texture, or 0.
const PipelineDesc * pipelineDesc(PipelineHandle handle) const
A pipeline's description, or null for a handle that names none.
virtual void setStencilReference(i32 ref)=0
Sets the dynamic stencil reference for the bound pipeline's stencil mode (no-op if Off).
virtual bool supportsCompressedFormat(GfxCompressedFormat format)=0
Reports whether the backend can sample the given compressed format.
virtual bool getTimerQueryNs(u32 query, u64 *outNanoseconds)=0
Fetches a completed query's elapsed nanoseconds; false while still pending.
void setRetainedBudget(usize bytes)
Warns once when retainedBytes() grows past bytes; 0 never warns.
virtual bool supportsMultiDraw() const
Whether drawElementsInstancedMulti is one call here, its draws told apart by gl_DrawID (WEBGL_multi_d...
GfxLiveObjects liveObjects() const
GPU objects alive right now (see GfxLiveObjects), read off the registry.
void deleteFramebuffer(FramebufferHandle framebuffer)
Deletes a framebuffer (its attachment textures are owned by the caller).
virtual u32 backendUniformBlockIndex(u32 program, const char *name)=0
virtual bool copyFramebufferColor(FramebufferHandle source, TextureHandle dst)
virtual void backendDeleteBuffer(u32 id)=0
bool recoverDevice()
Rebuilds the device and every object it issued, behind the same handles.
Definition GfxDevice.cpp:89
void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void *data, u32 sizeBytes)
Updates a sub-range of a buffer; must fit within its capacity.
void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void *data)
Re-specifies a buffer's store with a new capacity, discarding prior contents.
const TextureDesc * textureDesc(TextureHandle texture) const
void setUniform1i(i32 location, i32 value)
Sets an integer uniform of the bound program.
virtual void setScissor(i32 x, i32 y, i32 w, i32 h)=0
Sets the scissor rectangle.
virtual void backendDeleteCompute(u32 id)
usize retainedBytes() const
CPU bytes the device holds to put content back after a loss.
virtual ReadbackHandle requestReadback(FramebufferHandle target, u32 w, u32 h)=0
Requests an RGBA8 readback of a framebuffer's color attachment.
void deleteProgram(ShaderHandle program)
Deletes a shader program.
bool dispatchCompute(ComputeHandle program, const GfxComputeBinding *bindings, u32 bindingCount, u32 groupsX, u32 groupsY=1, u32 groupsZ=1)
Runs program over groupsX x groupsY x groupsZ workgroups, with these resources bound.
PipelineHandle currentPipeline() const
The pipeline most recently bound, whose program uniforms are set on.
virtual i32 getInt(GfxIntParam name)=0
Queries a backend integer capability/limit.
void setDeviceIdentity(std::string backend, std::string vendor, std::string renderer, std::string version)
Records the backend identity; see captureDeviceIdentity.
virtual void backendDeleteVertexLayout(u32 id)=0
Drops what the backend derived from a layout (a GL VAO); the desc stays here.
u64 deviceGeneration() const
Which generation of the device the live GPU objects belong to.
virtual ReadbackHandle requestBufferReadback(BufferHandle buffer, u32 offsetBytes, u32 sizeBytes)
Copies bytes of a storage buffer out, to be taken with pollReadback / takeReadback.
virtual std::vector< GfxUniformInfo > backendActiveUniforms(u32 program)=0
virtual bool backendProgramReady(u32 id)
void onProgramLinked(ShaderHandle program, std::function< void()> callback)
Runs callback when program has linked, once: now if it already has, at the first thing that needs it ...
FramebufferHandle
Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted.
Definition GfxEnums.hpp:41
constexpr AsyncComputeFence kNoAsyncComputeFence
Definition GfxEnums.hpp:25
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
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
ComputeHandle
A compute program (GfxDevice::createCompute); only a device that supportsCompute() issues one.
Definition GfxEnums.hpp:39
GfxShaderLanguage
Shader source language a backend consumes.
Definition GfxEnums.hpp:654
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
GfxDeviceStatus
Whether the device can still be drawn to.
Definition GfxEnums.hpp:535
@ Dead
Unrecoverable — the renderer will not draw again this run.
Definition GfxEnums.hpp:539
@ Recovering
A replacement device is being built; old handles stay dead.
Definition GfxEnums.hpp:538
@ Live
Normal operation.
Definition GfxEnums.hpp:536
static constexpr u32 GFX_UNIFORM_OFFSET_ALIGNMENT
What a uniform binding's offset must be a multiple of: the largest either API may ask.
Definition GfxDevice.hpp:47
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
i32 AsyncComputeFence
Definition GfxEnums.hpp:24
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
GfxBufferUsage usage
Definition GfxEnums.hpp:404
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
Everything a human needs to know about one device loss.
Definition GfxEnums.hpp:582
The viewport last set, so a pass that borrows the device can give it back.
GPU objects the device has created and not yet destroyed.
Definition GfxDevice.hpp:57
A Sourced object that has storage again and is waiting for its contents.
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