Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(renderer): typed GPU resource handles + descriptor-based creation

yhh6d48bebac98a
diff --git a/src/esengine/bindings/GeometryBindings.cpp b/src/esengine/bindings/GeometryBindings.cpp
index a78b7e3ac..317f569df 100644
--- a/src/esengine/bindings/GeometryBindings.cpp
+++ b/src/esengine/bindings/GeometryBindings.cpp
@@ -42,7 +42,7 @@ static void restoreImmediateDrawState() {
dev->setBlendEnabled(true);
dev->setBlendMode(BlendMode::Normal);
dev->setDepthTest(false);
- dev->bindTexture(0, 0);
+ dev->bindTexture(0, TextureHandle::Invalid);
}
}
@@ -220,7 +220,7 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t trans
case 10: {
i32 slot = static_cast<i32>(uniforms[idx++]);
u32 textureId = static_cast<u32>(uniforms[idx++]);
- g_device->bindTexture(static_cast<u32>(slot), textureId);
+ g_device->bindTexture(static_cast<u32>(slot), TextureHandle{textureId});
shader->setUniform(name, slot);
break;
}
diff --git a/src/esengine/bindings/PostProcessBindings.cpp b/src/esengine/bindings/PostProcessBindings.cpp
index 86ac21a4c..5ca58edb1 100644
--- a/src/esengine/bindings/PostProcessBindings.cpp
+++ b/src/esengine/bindings/PostProcessBindings.cpp
@@ -35,7 +35,7 @@ bool postprocess_init(u32 width, u32 height) {
}
g_postProcessPipeline->init(width, height);
- g_device->bindFramebuffer(0);
+ g_device->bindFramebuffer(FramebufferHandle::Default);
return g_postProcessPipeline->isInitialized();
}
@@ -131,7 +131,7 @@ void postprocess_clearPasses() {
void postprocess_setOutputTarget(u32 fboId) {
if (g_postProcessPipeline) {
- g_postProcessPipeline->setOutputTarget(fboId);
+ g_postProcessPipeline->setOutputTarget(FramebufferHandle{fboId});
}
}
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 13a45ee00..2fb0b8be7 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -374,7 +374,7 @@ u32 renderer_createTarget(u32 width, u32 height, i32 flags) {
u32 renderer_getTargetDepthTexture(u32 handle) {
if (!g_renderFrame) return 0;
auto* target = g_renderFrame->targetManager().get(handle);
- return target ? target->getDepthTexture() : 0;
+ return target ? static_cast<u32>(target->getDepthTexture()) : 0;
}
void renderer_releaseTarget(u32 handle) {
@@ -385,7 +385,7 @@ void renderer_releaseTarget(u32 handle) {
u32 renderer_getTargetTexture(u32 handle) {
if (!g_renderFrame) return 0;
auto* target = g_renderFrame->targetManager().get(handle);
- return target ? target->getColorTexture() : 0;
+ return target ? static_cast<u32>(target->getColorTexture()) : 0;
}
u32 renderer_getDrawCalls() {
@@ -739,7 +739,7 @@ void renderer_setTextureParams(u32 textureId, i32 minFilter, i32 magFilter, i32
auto* device = g_device;
if (!device) return;
device->setTextureParams(
- textureId,
+ TextureHandle{textureId},
static_cast<TextureFilter>(minFilter),
static_cast<TextureFilter>(magFilter),
static_cast<TextureWrap>(wrapS),
diff --git a/src/esengine/renderer/Buffer.cpp b/src/esengine/renderer/Buffer.cpp
index 6f1192614..db1616a41 100644
--- a/src/esengine/renderer/Buffer.cpp
+++ b/src/esengine/renderer/Buffer.cpp
@@ -75,25 +75,25 @@ GfxDataType toGfxDataType(ShaderDataType type) {
// ========================================
VertexBuffer::~VertexBuffer() {
- if (bufferId_ != 0 && device_) {
- device_->deleteBuffer(bufferId_);
+ if (handle_ != BufferHandle::Invalid && device_) {
+ device_->deleteBuffer(handle_);
}
}
VertexBuffer::VertexBuffer(VertexBuffer&& other) noexcept
- : device_(other.device_), bufferId_(other.bufferId_), layout_(std::move(other.layout_)) {
- other.bufferId_ = 0;
+ : device_(other.device_), handle_(other.handle_), layout_(std::move(other.layout_)) {
+ other.handle_ = BufferHandle::Invalid;
}
VertexBuffer& VertexBuffer::operator=(VertexBuffer&& other) noexcept {
if (this != &other) {
- if (bufferId_ != 0 && device_) {
- device_->deleteBuffer(bufferId_);
+ if (handle_ != BufferHandle::Invalid && device_) {
+ device_->deleteBuffer(handle_);
}
device_ = other.device_;
- bufferId_ = other.bufferId_;
+ handle_ = other.handle_;
layout_ = std::move(other.layout_);
- other.bufferId_ = 0;
+ other.handle_ = BufferHandle::Invalid;
}
return *this;
}
@@ -101,39 +101,33 @@ VertexBuffer& VertexBuffer::operator=(VertexBuffer&& other) noexcept {
Unique<VertexBuffer> VertexBuffer::createRaw(GfxDevice& device, const void* data, u32 sizeBytes) {
auto buffer = makeUnique<VertexBuffer>();
buffer->device_ = &device;
- buffer->bufferId_ = device.createBuffer();
- device.bindVertexBuffer(buffer->bufferId_);
- device.bufferData(GfxBufferTarget::Vertex, data, sizeBytes, false);
+ buffer->handle_ = device.createBuffer({GfxBufferUsage::Vertex, sizeBytes, /*dynamic=*/false}, data);
return buffer;
}
Unique<VertexBuffer> VertexBuffer::create(GfxDevice& device, u32 size) {
auto buffer = makeUnique<VertexBuffer>();
buffer->device_ = &device;
- buffer->bufferId_ = device.createBuffer();
- device.bindVertexBuffer(buffer->bufferId_);
- device.bufferData(GfxBufferTarget::Vertex, nullptr, size, true);
+ buffer->handle_ = device.createBuffer({GfxBufferUsage::Vertex, size, /*dynamic=*/true}, nullptr);
return buffer;
}
void VertexBuffer::bind() const {
- if (device_) device_->bindVertexBuffer(bufferId_);
+ if (device_) device_->bindVertexBuffer(handle_);
}
void VertexBuffer::unbind() const {
- if (device_) device_->bindVertexBuffer(0);
+ if (device_) device_->bindVertexBuffer(BufferHandle::Invalid);
}
void VertexBuffer::setDataRaw(const void* data, u32 sizeBytes) {
if (!device_) return;
- device_->bindVertexBuffer(bufferId_);
- device_->bufferSubData(GfxBufferTarget::Vertex, 0, data, sizeBytes);
+ device_->updateBuffer(handle_, 0, data, sizeBytes);
}
void VertexBuffer::setSubDataRaw(const void* data, u32 sizeBytes, u32 offsetBytes) {
if (!device_) return;
- device_->bindVertexBuffer(bufferId_);
- device_->bufferSubData(GfxBufferTarget::Vertex, offsetBytes, data, sizeBytes);
+ device_->updateBuffer(handle_, offsetBytes, data, sizeBytes);
}
// ========================================
@@ -141,27 +135,27 @@ void VertexBuffer::setSubDataRaw(const void* data, u32 sizeBytes, u32 offsetByte
// ========================================
IndexBuffer::~IndexBuffer() {
- if (bufferId_ != 0 && device_) {
- device_->deleteBuffer(bufferId_);
+ if (handle_ != BufferHandle::Invalid && device_) {
+ device_->deleteBuffer(handle_);
}
}
IndexBuffer::IndexBuffer(IndexBuffer&& other) noexcept
- : device_(other.device_), bufferId_(other.bufferId_), count_(other.count_), is16Bit_(other.is16Bit_) {
- other.bufferId_ = 0;
+ : device_(other.device_), handle_(other.handle_), count_(other.count_), is16Bit_(other.is16Bit_) {
+ other.handle_ = BufferHandle::Invalid;
other.count_ = 0;
}
IndexBuffer& IndexBuffer::operator=(IndexBuffer&& other) noexcept {
if (this != &other) {
- if (bufferId_ != 0 && device_) {
- device_->deleteBuffer(bufferId_);
+ if (handle_ != BufferHandle::Invalid && device_) {
+ device_->deleteBuffer(handle_);
}
device_ = other.device_;
- bufferId_ = other.bufferId_;
+ handle_ = other.handle_;
count_ = other.count_;
is16Bit_ = other.is16Bit_;
- other.bufferId_ = 0;
+ other.handle_ = BufferHandle::Invalid;
other.count_ = 0;
}
return *this;
@@ -172,9 +166,8 @@ Unique<IndexBuffer> IndexBuffer::create(GfxDevice& device, const u32* indices, u
buffer->device_ = &device;
buffer->count_ = count;
buffer->is16Bit_ = false;
- buffer->bufferId_ = device.createBuffer();
- device.bindIndexBuffer(buffer->bufferId_);
- device.bufferData(GfxBufferTarget::Index, indices, count * sizeof(u32), false);
+ buffer->handle_ = device.createBuffer(
+ {GfxBufferUsage::Index, count * static_cast<u32>(sizeof(u32)), /*dynamic=*/false}, indices);
return buffer;
}
@@ -183,18 +176,17 @@ Unique<IndexBuffer> IndexBuffer::create(GfxDevice& device, const u16* indices, u
buffer->device_ = &device;
buffer->count_ = count;
buffer->is16Bit_ = true;
- buffer->bufferId_ = device.createBuffer();
- device.bindIndexBuffer(buffer->bufferId_);
- device.bufferData(GfxBufferTarget::Index, indices, count * sizeof(u16), false);
+ buffer->handle_ = device.createBuffer(
+ {GfxBufferUsage::Index, count * static_cast<u32>(sizeof(u16)), /*dynamic=*/false}, indices);
return buffer;
}
void IndexBuffer::bind() const {
- if (device_) device_->bindIndexBuffer(bufferId_);
+ if (device_) device_->bindIndexBuffer(handle_);
}
void IndexBuffer::unbind() const {
- if (device_) device_->bindIndexBuffer(0);
+ if (device_) device_->bindIndexBuffer(BufferHandle::Invalid);
}
// ========================================
diff --git a/src/esengine/renderer/Buffer.hpp b/src/esengine/renderer/Buffer.hpp
index 61b5bb930..64c984374 100644
--- a/src/esengine/renderer/Buffer.hpp
+++ b/src/esengine/renderer/Buffer.hpp
@@ -21,6 +21,7 @@
// Project includes
#include "../core/Types.hpp"
+#include "GfxEnums.hpp"
// Standard library
#include <span>
@@ -300,11 +301,8 @@ public:
*/
const VertexLayout& getLayout() const { return layout_; }
- /**
- * @brief Gets the GPU buffer ID
- * @return GPU buffer handle
- */
- u32 getId() const { return bufferId_; }
+ /** @brief Gets the device buffer handle */
+ BufferHandle handle() const { return handle_; }
// =========================================================================
// Raw API for internal use only
@@ -336,7 +334,7 @@ public:
private:
GfxDevice* device_ = nullptr; ///< Set by the create* factories; all GL goes through it.
- u32 bufferId_ = 0;
+ BufferHandle handle_ = BufferHandle::Invalid;
VertexLayout layout_;
};
@@ -413,15 +411,15 @@ public:
/** @brief Gets the number of indices */
u32 getCount() const { return count_; }
- /** @brief Gets the GPU buffer ID */
- u32 getId() const { return bufferId_; }
+ /** @brief Gets the device buffer handle */
+ BufferHandle handle() const { return handle_; }
/** @brief Returns true if using 16-bit indices */
bool is16Bit() const { return is16Bit_; }
private:
GfxDevice* device_ = nullptr; ///< Set by the create* factories; all GL goes through it.
- u32 bufferId_ = 0;
+ BufferHandle handle_ = BufferHandle::Invalid;
u32 count_ = 0;
bool is16Bit_ = false;
};
diff --git a/src/esengine/renderer/DrawList.cpp b/src/esengine/renderer/DrawList.cpp
index 345c3f74c..ca3dfc92b 100644
--- a/src/esengine/renderer/DrawList.cpp
+++ b/src/esengine/renderer/DrawList.cpp
@@ -114,7 +114,7 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
// its material, or the 2D defaults: depth_write on with the test off). createPipeline
// caches; a one-entry memo skips the lookup for identical consecutive (sorted) commands.
PipelineDesc desc{};
- desc.program = cmd.shader_id;
+ desc.program = ShaderHandle{cmd.shader_id};
desc.vertexLayout = cmd.layout_id;
desc.blend = cmd.blend_mode;
desc.blendEnabled = true;
@@ -153,11 +153,11 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
if (cmd.layout_id == LayoutId::Batch) {
for (u8 slot = 0; slot < MAX_CMD_TEXTURE_SLOTS; ++slot) {
u32 tex = (slot < cmd.texture_count) ? cmd.texture_ids[slot] : cmd.texture_ids[0];
- device.bindTexture(slot, tex);
+ device.bindTexture(slot, TextureHandle{tex});
}
} else {
for (u8 slot = 0; slot < cmd.texture_count; ++slot) {
- device.bindTexture(slot, cmd.texture_ids[slot]);
+ device.bindTexture(slot, TextureHandle{cmd.texture_ids[slot]});
}
}
diff --git a/src/esengine/renderer/Framebuffer.cpp b/src/esengine/renderer/Framebuffer.cpp
index 41fcba097..b3714cc27 100644
--- a/src/esengine/renderer/Framebuffer.cpp
+++ b/src/esengine/renderer/Framebuffer.cpp
@@ -30,12 +30,12 @@ Framebuffer::~Framebuffer() {
Framebuffer::Framebuffer(Framebuffer&& other) noexcept
: device_(other.device_),
spec_(other.spec_),
- framebufferId_(other.framebufferId_),
+ handle_(other.handle_),
colorAttachment_(other.colorAttachment_),
depthAttachment_(other.depthAttachment_) {
- other.framebufferId_ = 0;
- other.colorAttachment_ = 0;
- other.depthAttachment_ = 0;
+ other.handle_ = FramebufferHandle::Default;
+ other.colorAttachment_ = TextureHandle::Invalid;
+ other.depthAttachment_ = TextureHandle::Invalid;
}
Framebuffer& Framebuffer::operator=(Framebuffer&& other) noexcept {
@@ -43,12 +43,12 @@ Framebuffer& Framebuffer::operator=(Framebuffer&& other) noexcept {
cleanup();
device_ = other.device_;
spec_ = other.spec_;
- framebufferId_ = other.framebufferId_;
+ handle_ = other.handle_;
colorAttachment_ = other.colorAttachment_;
depthAttachment_ = other.depthAttachment_;
- other.framebufferId_ = 0;
- other.colorAttachment_ = 0;
- other.depthAttachment_ = 0;
+ other.handle_ = FramebufferHandle::Default;
+ other.colorAttachment_ = TextureHandle::Invalid;
+ other.depthAttachment_ = TextureHandle::Invalid;
}
return *this;
}
@@ -75,11 +75,11 @@ Unique<Framebuffer> Framebuffer::create(GfxDevice& device, const FramebufferSpec
// =============================================================================
void Framebuffer::bind() const {
- if (device_) device_->bindFramebuffer(framebufferId_);
+ if (device_) device_->bindFramebuffer(handle_);
}
void Framebuffer::unbind() const {
- if (device_) device_->bindFramebuffer(0);
+ if (device_) device_->bindFramebuffer(FramebufferHandle::Default);
}
void Framebuffer::resize(u32 width, u32 height) {
@@ -104,56 +104,50 @@ void Framebuffer::resize(u32 width, u32 height) {
bool Framebuffer::initialize() {
const TextureFilter filter = spec_.linearFilter ? TextureFilter::Linear : TextureFilter::Nearest;
- framebufferId_ = device_->createFramebuffer();
- device_->bindFramebuffer(framebufferId_);
-
- colorAttachment_ = device_->createTexture();
- device_->texImage2D(colorAttachment_, spec_.width, spec_.height, GfxPixelFormat::RGBA8, nullptr);
- device_->setTextureParams(colorAttachment_, filter, filter,
- TextureWrap::ClampToEdge, TextureWrap::ClampToEdge);
- device_->framebufferTexture2D(framebufferId_, GfxAttachment::Color0, colorAttachment_);
+ TextureDesc colorDesc;
+ colorDesc.width = spec_.width;
+ colorDesc.height = spec_.height;
+ colorDesc.format = GfxPixelFormat::RGBA8;
+ colorDesc.minFilter = filter;
+ colorDesc.magFilter = filter;
+ colorAttachment_ = device_->createTexture(colorDesc, nullptr);
if (spec_.depthStencil) {
- depthAttachment_ = device_->createTexture();
- device_->texImage2D(depthAttachment_, spec_.width, spec_.height,
- GfxPixelFormat::Depth24Stencil8, nullptr);
- device_->setTextureParams(depthAttachment_, TextureFilter::Nearest, TextureFilter::Nearest,
- TextureWrap::ClampToEdge, TextureWrap::ClampToEdge);
- device_->framebufferTexture2D(framebufferId_, GfxAttachment::DepthStencil, depthAttachment_);
- }
-
- if (u32 err = device_->getError(); err != 0) {
- ES_LOG_ERROR("Framebuffer GL error before completeness check: 0x{:X} (size: {}x{})",
- err, spec_.width, spec_.height);
+ TextureDesc depthDesc;
+ depthDesc.width = spec_.width;
+ depthDesc.height = spec_.height;
+ depthDesc.format = GfxPixelFormat::Depth24Stencil8;
+ depthDesc.minFilter = TextureFilter::Nearest;
+ depthDesc.magFilter = TextureFilter::Nearest;
+ depthAttachment_ = device_->createTexture(depthDesc, nullptr);
}
- if (!device_->checkFramebufferStatus()) {
- ES_LOG_ERROR("Framebuffer is incomplete! (size: {}x{})", spec_.width, spec_.height);
- device_->bindFramebuffer(0);
+ handle_ = device_->createFramebuffer({colorAttachment_, depthAttachment_});
+ if (handle_ == FramebufferHandle::Default) {
+ ES_LOG_ERROR("Framebuffer is incomplete! (size: {}x{}, GL error 0x{:X})",
+ spec_.width, spec_.height, device_->getError());
cleanup();
return false;
}
-
- device_->bindFramebuffer(0);
return true;
}
void Framebuffer::cleanup() {
if (!device_) return;
- if (colorAttachment_) {
+ if (colorAttachment_ != TextureHandle::Invalid) {
device_->deleteTexture(colorAttachment_);
- colorAttachment_ = 0;
+ colorAttachment_ = TextureHandle::Invalid;
}
- if (depthAttachment_) {
+ if (depthAttachment_ != TextureHandle::Invalid) {
device_->deleteTexture(depthAttachment_);
- depthAttachment_ = 0;
+ depthAttachment_ = TextureHandle::Invalid;
}
- if (framebufferId_) {
- device_->deleteFramebuffer(framebufferId_);
- framebufferId_ = 0;
+ if (handle_ != FramebufferHandle::Default) {
+ device_->deleteFramebuffer(handle_);
+ handle_ = FramebufferHandle::Default;
}
}
diff --git a/src/esengine/renderer/Framebuffer.hpp b/src/esengine/renderer/Framebuffer.hpp
index 5e12f7246..2ad787889 100644
--- a/src/esengine/renderer/Framebuffer.hpp
+++ b/src/esengine/renderer/Framebuffer.hpp
@@ -81,7 +81,7 @@ struct FramebufferSpec {
* fbo->unbind();
*
* // Use color texture
- * u32 textureId = fbo->getColorAttachment();
+ * TextureHandle texture = fbo->getColorAttachment();
* @endcode
*/
class Framebuffer {
@@ -140,11 +140,11 @@ public:
// Properties
// =========================================================================
- /** @brief Gets the color attachment texture ID */
- u32 getColorAttachment() const { return colorAttachment_; }
+ /** @brief Gets the color attachment texture */
+ TextureHandle getColorAttachment() const { return colorAttachment_; }
- /** @brief Gets the depth attachment texture ID (0 if none) */
- u32 getDepthAttachment() const { return depthAttachment_; }
+ /** @brief Gets the depth attachment texture (Invalid if none) */
+ TextureHandle getDepthAttachment() const { return depthAttachment_; }
/** @brief Gets the framebuffer width in pixels */
u32 getWidth() const { return spec_.width; }
@@ -155,8 +155,8 @@ public:
/** @brief Gets the framebuffer specification */
const FramebufferSpec& getSpecification() const { return spec_; }
- /** @brief Gets the underlying GL framebuffer object ID */
- u32 getFramebufferId() const { return framebufferId_; }
+ /** @brief Gets the device framebuffer handle */
+ FramebufferHandle handle() const { return handle_; }
private:
/**
@@ -172,9 +172,9 @@ private:
GfxDevice* device_ = nullptr; ///< Set by create(); all GL goes through it.
FramebufferSpec spec_;
- u32 framebufferId_ = 0;
- u32 colorAttachment_ = 0;
- u32 depthAttachment_ = 0;
+ FramebufferHandle handle_ = FramebufferHandle::Default;
+ TextureHandle colorAttachment_ = TextureHandle::Invalid;
+ TextureHandle depthAttachment_ = TextureHandle::Invalid;
};
} // namespace esengine
diff --git a/src/esengine/renderer/GLDevice.cpp b/src/esengine/renderer/GLDevice.cpp
index 555ebdce2..098dee4c5 100644
--- a/src/esengine/renderer/GLDevice.cpp
+++ b/src/esengine/renderer/GLDevice.cpp
@@ -15,6 +15,10 @@
#include "OpenGLHeaders.hpp"
#include "../core/Log.hpp"
+#ifdef __EMSCRIPTEN__
+#include <emscripten/html5.h>
+#endif
+
#include <cstring>
#ifndef GL_DEPTH_STENCIL
@@ -53,6 +57,13 @@
#ifndef GL_UNPACK_FLIP_Y_WEBGL
#define GL_UNPACK_FLIP_Y_WEBGL 0x9240
#endif
+// EXT_disjoint_timer_query_webgl2 enums — not guaranteed in <GLES3/gl3.h>.
+#ifndef GL_TIME_ELAPSED_EXT
+ #define GL_TIME_ELAPSED_EXT 0x88BF
+#endif
+#ifndef GL_GPU_DISJOINT_EXT
+ #define GL_GPU_DISJOINT_EXT 0x8FBB
+#endif
namespace esengine {
@@ -87,11 +98,11 @@ void setCapability(GLenum cap, bool enabled) {
}
}
-GLenum toGLBufferTarget(GfxBufferTarget target) {
- switch (target) {
- case GfxBufferTarget::Vertex: return GL_ARRAY_BUFFER;
- case GfxBufferTarget::Index: return GL_ELEMENT_ARRAY_BUFFER;
- case GfxBufferTarget::Uniform: return GL_UNIFORM_BUFFER;
+GLenum toGLBufferTarget(GfxBufferUsage usage) {
+ switch (usage) {
+ case GfxBufferUsage::Vertex: return GL_ARRAY_BUFFER;
+ case GfxBufferUsage::Index: return GL_ELEMENT_ARRAY_BUFFER;
+ case GfxBufferUsage::Uniform: return GL_UNIFORM_BUFFER;
default: return GL_ARRAY_BUFFER;
}
}
@@ -175,15 +186,6 @@ bool glExtensionPresent(const char* name) {
return false;
}
-GLenum toGLAttachment(GfxAttachment attachment) {
- switch (attachment) {
- case GfxAttachment::Color0: return GL_COLOR_ATTACHMENT0;
- case GfxAttachment::Depth: return GL_DEPTH_ATTACHMENT;
- case GfxAttachment::DepthStencil: return GL_DEPTH_STENCIL_ATTACHMENT;
- default: return GL_COLOR_ATTACHMENT0;
- }
-}
-
std::string readShaderInfoLog(GLuint shader) {
GLint logLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
@@ -355,22 +357,13 @@ void GLDevice::setCullFace(bool front) {
glCullFace(front ? GL_FRONT : GL_BACK);
}
-// =============================================================================
-// Texture Binding
-// =============================================================================
-
-void GLDevice::bindTexture(u32 slot, u32 textureId) {
- glActiveTexture(GL_TEXTURE0 + slot);
- glBindTexture(GL_TEXTURE_2D, textureId);
-}
-
// =============================================================================
// Shader Program
// =============================================================================
-u32 GLDevice::createProgram(const char* vertexSrc, const char* fragmentSrc,
- const GfxAttribBinding* bindings, u32 bindingCount,
- std::string* outLog, GfxShaderStage* outFailedStage) {
+ShaderHandle GLDevice::createProgram(const char* vertexSrc, const char* fragmentSrc,
+ const GfxAttribBinding* bindings, u32 bindingCount,
+ std::string* outLog, GfxShaderStage* outFailedStage) {
auto setFailure = [&](GfxShaderStage stage, std::string&& log) {
if (outLog) *outLog = std::move(log);
if (outFailedStage) *outFailedStage = stage;
@@ -387,7 +380,7 @@ u32 GLDevice::createProgram(const char* vertexSrc, const char* fragmentSrc,
ES_LOG_ERROR("Vertex shader compilation failed: {}", log);
setFailure(GfxShaderStage::Vertex, std::move(log));
glDeleteShader(vertexShader);
- return 0;
+ return ShaderHandle::Invalid;
}
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
@@ -401,7 +394,7 @@ u32 GLDevice::createProgram(const char* vertexSrc, const char* fragmentSrc,
setFailure(GfxShaderStage::Fragment, std::move(log));
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
- return 0;
+ return ShaderHandle::Invalid;
}
GLuint program = glCreateProgram();
@@ -422,30 +415,30 @@ u32 GLDevice::createProgram(const char* vertexSrc, const char* fragmentSrc,
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glDeleteProgram(program);
- return 0;
+ return ShaderHandle::Invalid;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
if (outFailedStage) *outFailedStage = GfxShaderStage::None;
- return static_cast<u32>(program);
+ return ShaderHandle{program};
}
-void GLDevice::deleteProgram(u32 programId) {
- if (programId != 0) glDeleteProgram(programId);
+void GLDevice::deleteProgram(ShaderHandle program) {
+ if (program != ShaderHandle::Invalid) glDeleteProgram(static_cast<GLuint>(program));
}
-void GLDevice::useProgram(u32 programId) {
- glUseProgram(programId);
+void GLDevice::useProgram(ShaderHandle program) {
+ glUseProgram(static_cast<GLuint>(program));
}
-i32 GLDevice::getUniformLocation(u32 programId, const char* name) {
- return glGetUniformLocation(programId, name);
+i32 GLDevice::getUniformLocation(ShaderHandle program, const char* name) {
+ return glGetUniformLocation(static_cast<GLuint>(program), name);
}
-i32 GLDevice::getAttribLocation(u32 programId, const char* name) {
- return glGetAttribLocation(programId, name);
+i32 GLDevice::getAttribLocation(ShaderHandle program, const char* name) {
+ return glGetAttribLocation(static_cast<GLuint>(program), name);
}
void GLDevice::setUniform1i(i32 location, i32 value) {
@@ -500,9 +493,10 @@ GfxUniformType fromGLUniformType(GLenum type) {
} // namespace
-std::vector<GfxUniformInfo> GLDevice::getActiveUniforms(u32 programId) {
+std::vector<GfxUniformInfo> GLDevice::getActiveUniforms(ShaderHandle program) {
std::vector<GfxUniformInfo> result;
- if (programId == 0) return result;
+ if (program == ShaderHandle::Invalid) return result;
+ const GLuint programId = static_cast<GLuint>(program);
GLint count = 0;
glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &count);
@@ -545,47 +539,68 @@ std::vector<GfxUniformInfo> GLDevice::getActiveUniforms(u32 programId) {
// Buffer Operations
// =============================================================================
-u32 GLDevice::createBuffer() {
+void GLDevice::uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const void* data,
+ u32 sizeBytes, bool respec) {
+ const u32 id = static_cast<u32>(buffer);
+ auto it = buffer_meta_.find(id);
+ if (it == buffer_meta_.end()) return;
+ const BufferMeta& meta = it->second;
+
+ // GL_ELEMENT_ARRAY_BUFFER binding is VAO state: uploading through it while some
+ // VAO is bound would silently rewire that VAO's index buffer. Detach first.
+ if (meta.usage == GfxBufferUsage::Index) {
+ glBindVertexArray(0);
+ }
+
+ const GLenum target = toGLBufferTarget(meta.usage);
+ glBindBuffer(target, id);
+ if (respec) {
+ glBufferData(target, sizeBytes, data, meta.dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
+ } else {
+ glBufferSubData(target, offsetBytes, sizeBytes, data);
+ }
+}
+
+BufferHandle GLDevice::createBuffer(const BufferDesc& desc, const void* initialData) {
GLuint id = 0;
glGenBuffers(1, &id);
- return static_cast<u32>(id);
+ buffer_meta_[id] = BufferMeta{desc.usage, desc.dynamic};
+ uploadBufferStore(BufferHandle{id}, 0, initialData, desc.size, /*respec=*/true);
+ return BufferHandle{id};
}
-void GLDevice::deleteBuffer(u32 bufferId) {
- GLuint id = static_cast<GLuint>(bufferId);
+void GLDevice::deleteBuffer(BufferHandle buffer) {
+ GLuint id = static_cast<GLuint>(buffer);
glDeleteBuffers(1, &id);
+ buffer_meta_.erase(static_cast<u32>(buffer));
}
-void GLDevice::bindVertexBuffer(u32 bufferId) {
- glBindBuffer(GL_ARRAY_BUFFER, bufferId);
+void GLDevice::updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) {
+ uploadBufferStore(buffer, offsetBytes, data, sizeBytes, /*respec=*/false);
}
-void GLDevice::bindIndexBuffer(u32 bufferId) {
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferId);
+void GLDevice::resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) {
+ uploadBufferStore(buffer, 0, data, sizeBytes, /*respec=*/true);
}
-void GLDevice::bufferData(GfxBufferTarget target, const void* data, u32 sizeBytes, bool dynamic) {
- glBufferData(toGLBufferTarget(target), sizeBytes, data, dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
+void GLDevice::setUniformBuffer(u32 slot, BufferHandle buffer) {
+ glBindBufferBase(GL_UNIFORM_BUFFER, slot, static_cast<GLuint>(buffer));
}
-void GLDevice::bufferSubData(GfxBufferTarget target, u32 offset, const void* data, u32 sizeBytes) {
- glBufferSubData(toGLBufferTarget(target), offset, sizeBytes, data);
+void GLDevice::bindVertexBuffer(BufferHandle buffer) {
+ glBindBuffer(GL_ARRAY_BUFFER, static_cast<GLuint>(buffer));
}
-void GLDevice::bindUniformBuffer(u32 bufferId) {
- glBindBuffer(GL_UNIFORM_BUFFER, bufferId);
+void GLDevice::bindIndexBuffer(BufferHandle buffer) {
+ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLuint>(buffer));
}
-void GLDevice::bindBufferBase(u32 bindingPoint, u32 bufferId) {
- glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, bufferId);
+u32 GLDevice::getUniformBlockIndex(ShaderHandle program, const char* name) {
+ return static_cast<u32>(glGetUniformBlockIndex(static_cast<GLuint>(program), name));
}
-u32 GLDevice::getUniformBlockIndex(u32 programId, const char* name) {
- return static_cast<u32>(glGetUniformBlockIndex(programId, name));
-}
-
-void GLDevice::uniformBlockBinding(u32 programId, u32 blockIndex, u32 bindingPoint) {
- glUniformBlockBinding(programId, blockIndex, bindingPoint);
+void GLDevice::uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) {
+ glUniformBlockBinding(static_cast<GLuint>(program), blockIndex, bindingPoint);
}
// =============================================================================
@@ -717,96 +732,132 @@ void GLDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32
}
// =============================================================================
-// Texture Creation
+// Textures
// =============================================================================
-u32 GLDevice::createTexture() {
+void GLDevice::bindTexture(u32 slot, TextureHandle texture) {
+ glActiveTexture(GL_TEXTURE0 + slot);
+ glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
+}
+
+TextureHandle GLDevice::createTexture(const TextureDesc& desc, const void* pixels) {
GLuint id = 0;
glGenTextures(1, &id);
- return static_cast<u32>(id);
+ texture_formats_[id] = desc.format;
+
+ auto gl = toGLPixelFormat(desc.format);
+ glBindTexture(GL_TEXTURE_2D, id);
+ if (pixels && desc.flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_TRUE);
+ glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(gl.internalFormat),
+ static_cast<GLsizei>(desc.width), static_cast<GLsizei>(desc.height),
+ 0, gl.format, gl.type, pixels);
+ if (pixels && desc.flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_FALSE);
+
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLFilter(desc.minFilter));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
+
+ if (desc.mipmaps) {
+ glGenerateMipmap(GL_TEXTURE_2D);
+ }
+ return TextureHandle{id};
}
-void GLDevice::deleteTexture(u32 textureId) {
- GLuint id = static_cast<GLuint>(textureId);
- glDeleteTextures(1, &id);
+TextureHandle GLDevice::createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,
+ const void* data, u32 byteLength) {
+ GLuint id = 0;
+ glGenTextures(1, &id);
+ texture_formats_[id] = desc.format;
+
+ glBindTexture(GL_TEXTURE_2D, id);
+ glCompressedTexImage2D(GL_TEXTURE_2D, 0, toGLCompressedFormat(format),
+ static_cast<GLsizei>(desc.width), static_cast<GLsizei>(desc.height),
+ 0, static_cast<GLsizei>(byteLength), data);
+
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLFilter(desc.minFilter));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(desc.magFilter));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(desc.wrapS));
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(desc.wrapT));
+ return TextureHandle{id};
}
-void GLDevice::texImage2D(u32 textureId, u32 width, u32 height,
- GfxPixelFormat format, const void* data) {
- auto gl = toGLPixelFormat(format);
- glBindTexture(GL_TEXTURE_2D, textureId);
- glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(gl.internalFormat),
- static_cast<GLsizei>(width), static_cast<GLsizei>(height),
- 0, gl.format, gl.type, data);
+TextureHandle GLDevice::importExternalTexture(u32 nativeId, const TextureDesc& desc) {
+ texture_formats_[nativeId] = desc.format;
+ return TextureHandle{nativeId};
}
-void GLDevice::texSubImage2D(u32 textureId, i32 xoffset, i32 yoffset,
- u32 width, u32 height,
- GfxPixelFormat format, const void* data) {
- auto gl = toGLPixelFormat(format);
- glBindTexture(GL_TEXTURE_2D, textureId);
- glTexSubImage2D(GL_TEXTURE_2D, 0, xoffset, yoffset,
- static_cast<GLsizei>(width), static_cast<GLsizei>(height),
- gl.format, gl.type, data);
+void GLDevice::deleteTexture(TextureHandle texture) {
+ GLuint id = static_cast<GLuint>(texture);
+ glDeleteTextures(1, &id);
+ texture_formats_.erase(static_cast<u32>(texture));
}
-void GLDevice::compressedTexImage2D(u32 textureId, u32 width, u32 height,
- GfxCompressedFormat format,
- const void* data, u32 byteLength) {
- glBindTexture(GL_TEXTURE_2D, textureId);
- glCompressedTexImage2D(GL_TEXTURE_2D, 0, toGLCompressedFormat(format),
- static_cast<GLsizei>(width), static_cast<GLsizei>(height),
- 0, static_cast<GLsizei>(byteLength), data);
+void GLDevice::updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,
+ const void* pixels, bool flipY) {
+ auto it = texture_formats_.find(static_cast<u32>(texture));
+ auto gl = toGLPixelFormat(it != texture_formats_.end() ? it->second : GfxPixelFormat::RGBA8);
+ glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
+ if (flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_TRUE);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, x, y,
+ static_cast<GLsizei>(width), static_cast<GLsizei>(height),
+ gl.format, gl.type, pixels);
+ if (flipY) glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, GL_FALSE);
}
-void GLDevice::setTextureParams(u32 textureId, TextureFilter min, TextureFilter mag,
+void GLDevice::setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag,
TextureWrap wrapS, TextureWrap wrapT) {
- glBindTexture(GL_TEXTURE_2D, textureId);
+ glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, toGLFilter(min));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, toGLFilter(mag));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, toGLWrap(wrapS));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, toGLWrap(wrapT));
}
-void GLDevice::generateMipmaps(u32 textureId) {
- glBindTexture(GL_TEXTURE_2D, textureId);
+void GLDevice::generateMipmaps(TextureHandle texture) {
+ glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture));
glGenerateMipmap(GL_TEXTURE_2D);
}
-void GLDevice::pixelStorei(u32 pname, i32 param) {
- glPixelStorei(pname, param);
-}
-
-void GLDevice::setUnpackFlipY(bool enabled) {
- glPixelStorei(GL_UNPACK_FLIP_Y_WEBGL, enabled ? GL_TRUE : GL_FALSE);
-}
-
// =============================================================================
// Framebuffer
// =============================================================================
-u32 GLDevice::createFramebuffer() {
+FramebufferHandle GLDevice::createFramebuffer(const FramebufferDesc& desc) {
GLuint id = 0;
glGenFramebuffers(1, &id);
- return static_cast<u32>(id);
-}
+ glBindFramebuffer(GL_FRAMEBUFFER, id);
-void GLDevice::deleteFramebuffer(u32 fboId) {
- GLuint id = static_cast<GLuint>(fboId);
- glDeleteFramebuffers(1, &id);
-}
+ if (desc.color0 != TextureHandle::Invalid) {
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
+ static_cast<GLuint>(desc.color0), 0);
+ }
+ if (desc.depthStencil != TextureHandle::Invalid) {
+ // Attach point follows the texture's pixel format (depth-only vs packed depth+stencil).
+ auto it = texture_formats_.find(static_cast<u32>(desc.depthStencil));
+ const bool depthOnly = it != texture_formats_.end()
+ && it->second == GfxPixelFormat::DepthComponent24;
+ glFramebufferTexture2D(GL_FRAMEBUFFER,
+ depthOnly ? GL_DEPTH_ATTACHMENT : GL_DEPTH_STENCIL_ATTACHMENT,
+ GL_TEXTURE_2D, static_cast<GLuint>(desc.depthStencil), 0);
+ }
-void GLDevice::bindFramebuffer(u32 fboId) {
- glBindFramebuffer(GL_FRAMEBUFFER, fboId);
+ const bool complete = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
+ if (!complete) {
+ glDeleteFramebuffers(1, &id);
+ return FramebufferHandle::Default;
+ }
+ return FramebufferHandle{id};
}
-void GLDevice::framebufferTexture2D(u32 fboId, GfxAttachment attachment, u32 textureId) {
- glBindFramebuffer(GL_FRAMEBUFFER, fboId);
- glFramebufferTexture2D(GL_FRAMEBUFFER, toGLAttachment(attachment), GL_TEXTURE_2D, textureId, 0);
+void GLDevice::deleteFramebuffer(FramebufferHandle framebuffer) {
+ GLuint id = static_cast<GLuint>(framebuffer);
+ if (id != 0) glDeleteFramebuffers(1, &id);
}
-bool GLDevice::checkFramebufferStatus() {
- return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+void GLDevice::bindFramebuffer(FramebufferHandle framebuffer) {
+ glBindFramebuffer(GL_FRAMEBUFFER, static_cast<GLuint>(framebuffer));
}
// =============================================================================
@@ -818,6 +869,52 @@ void GLDevice::readPixels(i32 x, i32 y, u32 w, u32 h, GfxPixelFormat format, voi
glReadPixels(x, y, static_cast<GLsizei>(w), static_cast<GLsizei>(h), gl.format, gl.type, data);
}
+// =============================================================================
+// GPU Timing
+// =============================================================================
+
+u32 GLDevice::createTimerQuery() {
+ if (timer_query_state_ == 0) {
+#ifdef __EMSCRIPTEN__
+ // Must ENABLE the extension (not just check presence) so emscripten routes the
+ // TIME_ELAPSED query entry points.
+ EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
+ timer_query_state_ =
+ (ctx && emscripten_webgl_enable_extension(ctx, "EXT_disjoint_timer_query_webgl2")) ? 1 : 2;
+#else
+ timer_query_state_ = 2;
+#endif
+ }
+ if (timer_query_state_ != 1) return 0;
+ GLuint id = 0;
+ glGenQueries(1, &id);
+ return static_cast<u32>(id);
+}
+
+void GLDevice::beginTimerQuery(u32 query) {
+ glBeginQuery(GL_TIME_ELAPSED_EXT, query);
+}
+
+void GLDevice::endTimerQuery() {
+ glEndQuery(GL_TIME_ELAPSED_EXT);
+}
+
+bool GLDevice::timerDisjoint() {
+ GLint disjoint = 0;
+ glGetIntegerv(GL_GPU_DISJOINT_EXT, &disjoint);
+ return disjoint != 0;
+}
+
+bool GLDevice::getTimerQueryNs(u32 query, u64* outNanoseconds) {
+ GLuint available = 0;
+ glGetQueryObjectuiv(query, GL_QUERY_RESULT_AVAILABLE, &available);
+ if (!available) return false;
+ GLuint ns = 0;
+ glGetQueryObjectuiv(query, GL_QUERY_RESULT, &ns);
+ if (outNanoseconds) *outNanoseconds = ns;
+ return true;
+}
+
// =============================================================================
// Debug
// =============================================================================
diff --git a/src/esengine/renderer/GLDevice.hpp b/src/esengine/renderer/GLDevice.hpp
index f9fe536fc..9944cfbb2 100644
--- a/src/esengine/renderer/GLDevice.hpp
+++ b/src/esengine/renderer/GLDevice.hpp
@@ -19,6 +19,7 @@
#include "GfxDevice.hpp"
+#include <unordered_map>
#include <vector>
namespace esengine {
@@ -61,15 +62,34 @@ public:
void setCulling(bool enabled) override;
void setCullFace(bool front) override;
- void bindTexture(u32 slot, u32 textureId) override;
+ BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) override;
+ void deleteBuffer(BufferHandle buffer) override;
+ void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) override;
+ void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) override;
+ void setUniformBuffer(u32 slot, BufferHandle buffer) override;
+ void bindVertexBuffer(BufferHandle buffer) override;
+ void bindIndexBuffer(BufferHandle buffer) override;
+
+ TextureHandle createTexture(const TextureDesc& desc, const void* pixels) override;
+ TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,
+ const void* data, u32 byteLength) override;
+ TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc) override;
+ void deleteTexture(TextureHandle texture) override;
+ void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,
+ const void* pixels, bool flipY) override;
+ void setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag,
+ TextureWrap wrapS, TextureWrap wrapT) override;
+ void generateMipmaps(TextureHandle texture) override;
+ void bindTexture(u32 slot, TextureHandle texture) override;
+ bool supportsCompressedFormat(GfxCompressedFormat format) override;
- u32 createProgram(const char* vertexSrc, const char* fragmentSrc,
- const GfxAttribBinding* bindings, u32 bindingCount,
- std::string* outLog, GfxShaderStage* outFailedStage) override;
- void deleteProgram(u32 programId) override;
- void useProgram(u32 programId) override;
- i32 getUniformLocation(u32 programId, const char* name) override;
- i32 getAttribLocation(u32 programId, const char* name) override;
+ ShaderHandle createProgram(const char* vertexSrc, const char* fragmentSrc,
+ const GfxAttribBinding* bindings, u32 bindingCount,
+ std::string* outLog, GfxShaderStage* outFailedStage) override;
+ void deleteProgram(ShaderHandle program) override;
+ void useProgram(ShaderHandle program) override;
+ i32 getUniformLocation(ShaderHandle program, const char* name) override;
+ i32 getAttribLocation(ShaderHandle program, const char* name) override;
void setUniform1i(i32 location, i32 value) override;
void setUniform1f(i32 location, f32 value) override;
void setUniform2f(i32 location, f32 x, f32 y) override;
@@ -78,19 +98,10 @@ public:
void setUniformMat3(i32 location, const f32* data) override;
void setUniformMat4(i32 location, const f32* data) override;
- std::vector<GfxUniformInfo> getActiveUniforms(u32 programId) override;
-
- u32 createBuffer() override;
- void deleteBuffer(u32 bufferId) override;
- void bindVertexBuffer(u32 bufferId) override;
- void bindIndexBuffer(u32 bufferId) override;
- void bufferData(GfxBufferTarget target, const void* data, u32 sizeBytes, bool dynamic) override;
- void bufferSubData(GfxBufferTarget target, u32 offset, const void* data, u32 sizeBytes) override;
+ std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle program) override;
- void bindUniformBuffer(u32 bufferId) override;
- void bindBufferBase(u32 bindingPoint, u32 bufferId) override;
- u32 getUniformBlockIndex(u32 programId, const char* name) override;
- void uniformBlockBinding(u32 programId, u32 blockIndex, u32 bindingPoint) override;
+ u32 getUniformBlockIndex(ShaderHandle program, const char* name) override;
+ void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) override;
PipelineHandle createPipeline(const PipelineDesc& desc) override;
void setPipeline(PipelineHandle handle) override;
@@ -109,35 +120,22 @@ public:
void drawArrays(u32 first, u32 vertexCount) override;
void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) override;
- u32 createTexture() override;
- void deleteTexture(u32 textureId) override;
- void texImage2D(u32 textureId, u32 width, u32 height,
- GfxPixelFormat format, const void* data) override;
- void texSubImage2D(u32 textureId, i32 xoffset, i32 yoffset,
- u32 width, u32 height,
- GfxPixelFormat format, const void* data) override;
- void compressedTexImage2D(u32 textureId, u32 width, u32 height,
- GfxCompressedFormat format,
- const void* data, u32 byteLength) override;
- void setTextureParams(u32 textureId, TextureFilter min, TextureFilter mag,
- TextureWrap wrapS, TextureWrap wrapT) override;
- void generateMipmaps(u32 textureId) override;
- void pixelStorei(u32 pname, i32 param) override;
- void setUnpackFlipY(bool enabled) override;
-
- u32 createFramebuffer() override;
- void deleteFramebuffer(u32 fboId) override;
- void bindFramebuffer(u32 fboId) override;
- void framebufferTexture2D(u32 fboId, GfxAttachment attachment, u32 textureId) override;
- bool checkFramebufferStatus() override;
+ FramebufferHandle createFramebuffer(const FramebufferDesc& desc) override;
+ void deleteFramebuffer(FramebufferHandle framebuffer) override;
+ void bindFramebuffer(FramebufferHandle framebuffer) override;
void readPixels(i32 x, i32 y, u32 w, u32 h, GfxPixelFormat format, void* data) override;
+ u32 createTimerQuery() override;
+ void beginTimerQuery(u32 query) override;
+ void endTimerQuery() override;
+ bool timerDisjoint() override;
+ bool getTimerQueryNs(u32 query, u64* outNanoseconds) override;
+
void setWireframe(bool enabled) override;
u32 getError() override;
std::string getString(GfxStringName name) override;
i32 getInt(GfxIntParam name) override;
- bool supportsCompressedFormat(GfxCompressedFormat format) override;
private:
// Pipeline cache: a handle is (index + 1) into pipelines_; PipelineHandle::Invalid is 0.
@@ -145,9 +143,24 @@ private:
// state, deduped by comparing handles (same pipeline -> skip the whole state apply).
void applyStencilMode(GfxStencilMode mode);
+ void uploadBufferStore(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes, bool respec);
+
std::vector<PipelineDesc> pipelines_;
PipelineHandle current_pipeline_ = PipelineHandle::Invalid;
GfxStencilMode current_stencil_mode_ = GfxStencilMode::Off;
+
+ // Per-handle metadata the GL bind-to-edit protocol needs but the interface no
+ // longer carries: buffer target/usage for uploads, texture transfer format for
+ // sub-image updates.
+ struct BufferMeta {
+ GfxBufferUsage usage;
+ bool dynamic;
+ };
+ std::unordered_map<u32, BufferMeta> buffer_meta_;
+ std::unordered_map<u32, GfxPixelFormat> texture_formats_;
+
+ // 0 = unprobed, 1 = timer queries available, 2 = unavailable.
+ int timer_query_state_ = 0;
};
} // namespace esengine
diff --git a/src/esengine/renderer/GfxDevice.hpp b/src/esengine/renderer/GfxDevice.hpp
index 68b6545e1..74d2d1f95 100644
--- a/src/esengine/renderer/GfxDevice.hpp
+++ b/src/esengine/renderer/GfxDevice.hpp
@@ -3,9 +3,11 @@
/**
* @file GfxDevice.hpp
* @brief Abstract graphics device interface
- * @details Thin abstraction layer over graphics APIs (OpenGL ES, WebGPU, Vulkan).
- * Upper-layer code (DrawList, RenderFrame, plugins) depends only on this
- * interface, isolating all API-specific calls into concrete implementations.
+ * @details The render backend boundary (RHI). Upper-layer code (DrawList,
+ * RenderFrame, plugins) depends only on this interface: typed resource
+ * handles created from descriptors, immutable pipelines, and draw
+ * submission. Concrete backends (GLDevice today; WebGPU and native APIs
+ * later) own every API-specific concept behind it.
*
* @author ESEngine Team
* @date 2026
@@ -23,7 +25,6 @@
#include "BlendMode.hpp"
#include "GfxEnums.hpp"
#include "PipelineState.hpp"
-#include "Texture.hpp"
#include <string>
#include <vector>
@@ -34,6 +35,9 @@ namespace esengine {
// GfxDevice Interface
// =============================================================================
+/** @brief Sentinel returned by getUniformBlockIndex when a program has no such block (GL_INVALID_INDEX). */
+static constexpr u32 GFX_INVALID_UNIFORM_BLOCK = 0xFFFFFFFFu;
+
/**
* @brief Abstract graphics device interface
*
@@ -42,9 +46,6 @@ namespace esengine {
* through an external tracker. Per-draw dynamic state (scissor, stencil ref,
* textures) is applied directly; sorted+merged draws already group it coarsely.
*/
-/** @brief Sentinel returned by getUniformBlockIndex when a program has no such block (GL_INVALID_INDEX). */
-static constexpr u32 GFX_INVALID_UNIFORM_BLOCK = 0xFFFFFFFFu;
-
class GfxDevice {
public:
virtual ~GfxDevice() = default;
@@ -135,14 +136,94 @@ public:
virtual void setCullFace(bool front) = 0;
// =========================================================================
- // Texture Binding
+ // Buffers
+ // =========================================================================
+
+ /**
+ * @brief Creates a buffer with fixed capacity and optional initial contents.
+ * @param initialData When non-null, `desc.size` bytes uploaded at creation.
+ */
+ virtual BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) = 0;
+
+ /** @brief Deletes a buffer */
+ virtual void deleteBuffer(BufferHandle buffer) = 0;
+
+ /** @brief Updates a sub-range of a buffer; must fit within its capacity. */
+ virtual void updateBuffer(BufferHandle buffer, u32 offsetBytes, const void* data, u32 sizeBytes) = 0;
+
+ /**
+ * @brief Re-specifies a buffer's store with a new capacity, discarding prior contents.
+ * @details The handle stays valid (streaming growth without re-wiring vertex
+ * layouts). `data` may be null to allocate uninitialized storage.
+ */
+ virtual void resizeBuffer(BufferHandle buffer, u32 sizeBytes, const void* data) = 0;
+
+ /** @brief Binds a buffer to a uniform binding slot (the block index shaders are linked to). */
+ virtual void setUniformBuffer(u32 slot, BufferHandle buffer) = 0;
+
+ /** @brief Binds a vertex buffer for vertex-layout setup */
+ virtual void bindVertexBuffer(BufferHandle buffer) = 0;
+
+ /** @brief Binds an index buffer for vertex-layout setup */
+ virtual void bindIndexBuffer(BufferHandle buffer) = 0;
+
+ // =========================================================================
+ // Textures
// =========================================================================
+ /**
+ * @brief Creates a 2D texture; uploads `pixels` (tightly packed, desc-sized) when non-null.
+ * @details Storage is allocated either way. `desc.mipmaps` generates mipmaps
+ * after the initial upload.
+ */
+ virtual TextureHandle createTexture(const TextureDesc& desc, const void* pixels) = 0;
+
+ /**
+ * @brief Creates a texture from pre-compressed GPU block data.
+ * @details The caller must first confirm the backend supports `format`
+ * (see supportsCompressedFormat) and fall back to an uncompressed
+ * createTexture otherwise. Data is uploaded as-is; no CPU-side decode.
+ */
+ virtual TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,
+ const void* data, u32 byteLength) = 0;
+
+ /**
+ * @brief Wraps a texture created outside the device (e.g. a JS-side WebGL upload).
+ * @details Registers the metadata updates/binds need; ownership stays external,
+ * so the wrapper must not delete it.
+ */
+ virtual TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc) = 0;
+
+ /** @brief Deletes a texture */
+ virtual void deleteTexture(TextureHandle texture) = 0;
+
+ /**
+ * @brief Uploads pixels to a sub-rectangle of a texture (transfer format from its desc).
+ * @param flipY Vertical flip on upload (WebGL upload state; no-op on native backends).
+ */
+ virtual void updateTexture(TextureHandle texture, i32 x, i32 y, u32 width, u32 height,
+ const void* pixels, bool flipY) = 0;
+
+ /** @brief Sets texture filtering and wrap parameters */
+ virtual void setTextureParams(TextureHandle texture, TextureFilter min, TextureFilter mag,
+ TextureWrap wrapS, TextureWrap wrapT) = 0;
+
+ /** @brief Generates mipmaps for a texture */
+ virtual void generateMipmaps(TextureHandle texture) = 0;
+
/** @brief Activates a texture slot and binds a 2D texture */
- virtual void bindTexture(u32 slot, u32 textureId) = 0;
+ virtual void bindTexture(u32 slot, TextureHandle texture) = 0;
+
+ /**
+ * @brief Reports whether the backend can sample the given compressed format.
+ * @details ETC2/EAC is always true on a WebGL2/GLES3 backend (core spec);
+ * ASTC and S3TC depend on driver extensions. Probe this before
+ * calling createCompressedTexture with a non-core format.
+ */
+ virtual bool supportsCompressedFormat(GfxCompressedFormat format) = 0;
// =========================================================================
- // Shader Program
+ // Shader Programs
// =========================================================================
/**
@@ -153,26 +234,26 @@ public:
* @param bindingCount Number of entries in @p bindings.
* @param outLog Optional; receives the driver info log on failure.
* @param outFailedStage Optional; receives the stage that rejected the source.
- * @return The linked program id, or 0 on failure.
- * @details Collapses the multi-step GL shader protocol behind the device so
- * no upper layer ever issues raw shader GL. Uniform reflection is a
- * separate call (getActiveUniforms).
+ * @return The linked program handle, or Invalid on failure.
*/
- virtual u32 createProgram(const char* vertexSrc, const char* fragmentSrc,
- const GfxAttribBinding* bindings, u32 bindingCount,
- std::string* outLog, GfxShaderStage* outFailedStage) = 0;
+ virtual ShaderHandle createProgram(const char* vertexSrc, const char* fragmentSrc,
+ const GfxAttribBinding* bindings, u32 bindingCount,
+ std::string* outLog, GfxShaderStage* outFailedStage) = 0;
/** @brief Deletes a shader program */
- virtual void deleteProgram(u32 programId) = 0;
+ virtual void deleteProgram(ShaderHandle program) = 0;
- /** @brief Binds a shader program */
- virtual void useProgram(u32 programId) = 0;
+ /**
+ * @brief Binds a program directly, for setup-time uniform seeding.
+ * @details Per-frame rendering binds programs through setPipeline.
+ */
+ virtual void useProgram(ShaderHandle program) = 0;
/** @brief Gets a uniform location by name */
- virtual i32 getUniformLocation(u32 programId, const char* name) = 0;
+ virtual i32 getUniformLocation(ShaderHandle program, const char* name) = 0;
/** @brief Gets a vertex attribute location by name (-1 if not found) */
- virtual i32 getAttribLocation(u32 programId, const char* name) = 0;
+ virtual i32 getAttribLocation(ShaderHandle program, const char* name) = 0;
/** @brief Sets an integer uniform */
virtual void setUniform1i(i32 location, i32 value) = 0;
@@ -196,45 +277,13 @@ public:
virtual void setUniformMat4(i32 location, const f32* data) = 0;
/** @brief Enumerates all active uniforms of a linked shader program */
- virtual std::vector<GfxUniformInfo> getActiveUniforms(u32 programId) = 0;
-
- // =========================================================================
- // Buffer Operations
- // =========================================================================
-
- /** @brief Creates a new buffer and returns its ID */
- virtual u32 createBuffer() = 0;
-
- /** @brief Deletes a buffer */
- virtual void deleteBuffer(u32 bufferId) = 0;
-
- /** @brief Binds a buffer to the vertex (array) target */
- virtual void bindVertexBuffer(u32 bufferId) = 0;
-
- /** @brief Binds a buffer to the index (element) target */
- virtual void bindIndexBuffer(u32 bufferId) = 0;
-
- /** @brief Uploads data to a buffer target */
- virtual void bufferData(GfxBufferTarget target, const void* data, u32 sizeBytes, bool dynamic) = 0;
-
- /** @brief Updates a sub-region of a buffer target */
- virtual void bufferSubData(GfxBufferTarget target, u32 offset, const void* data, u32 sizeBytes) = 0;
-
- // =========================================================================
- // Uniform Buffer Objects (per-frame / shared constants)
- // =========================================================================
-
- /** @brief Binds a buffer to the uniform target (for data upload via bufferData/bufferSubData). */
- virtual void bindUniformBuffer(u32 bufferId) = 0;
-
- /** @brief Binds a buffer to an indexed uniform binding point (the slot shaders read from). */
- virtual void bindBufferBase(u32 bindingPoint, u32 bufferId) = 0;
+ virtual std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle program) = 0;
/** @brief Returns a program's uniform-block index by name, or GFX_INVALID_UNIFORM_BLOCK if absent. */
- virtual u32 getUniformBlockIndex(u32 programId, const char* name) = 0;
+ virtual u32 getUniformBlockIndex(ShaderHandle program, const char* name) = 0;
- /** @brief Links a program's uniform block to an indexed binding point. */
- virtual void uniformBlockBinding(u32 programId, u32 blockIndex, u32 bindingPoint) = 0;
+ /** @brief Links a program's uniform block to an indexed binding slot. */
+ virtual void uniformBlockBinding(ShaderHandle program, u32 blockIndex, u32 bindingPoint) = 0;
// =========================================================================
// Pipeline State (immutable "how to draw"; see PipelineState.hpp)
@@ -294,79 +343,50 @@ public:
virtual void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) = 0;
// =========================================================================
- // Texture Creation
+ // Framebuffers
// =========================================================================
- /** @brief Creates a new texture and returns its ID */
- virtual u32 createTexture() = 0;
-
- /** @brief Deletes a texture */
- virtual void deleteTexture(u32 textureId) = 0;
-
- /** @brief Allocates texture storage with optional initial data */
- virtual void texImage2D(u32 textureId, u32 width, u32 height,
- GfxPixelFormat format, const void* data) = 0;
-
- /** @brief Updates a sub-region of a texture */
- virtual void texSubImage2D(u32 textureId, i32 xoffset, i32 yoffset,
- u32 width, u32 height,
- GfxPixelFormat format, const void* data) = 0;
-
/**
- * @brief Allocates texture storage from pre-compressed GPU block data.
- * @param byteLength Size of the compressed payload in bytes.
- * @details Pure addition alongside texImage2D — the uncompressed path is
- * unchanged. The caller must first confirm the backend supports
- * `format` (see supportsCompressedFormat) and fall back to RGBA8
- * otherwise. Data is uploaded as-is; no CPU-side decode.
+ * @brief Creates a framebuffer from its attachments and validates completeness.
+ * @return The framebuffer handle, or Default (0) when incomplete — the default
+ * framebuffer can never be created, so 0 unambiguously means failure.
*/
- virtual void compressedTexImage2D(u32 textureId, u32 width, u32 height,
- GfxCompressedFormat format,
- const void* data, u32 byteLength) = 0;
+ virtual FramebufferHandle createFramebuffer(const FramebufferDesc& desc) = 0;
- /** @brief Sets texture filtering and wrap parameters */
- virtual void setTextureParams(u32 textureId, TextureFilter min, TextureFilter mag,
- TextureWrap wrapS, TextureWrap wrapT) = 0;
+ /** @brief Deletes a framebuffer (its attachment textures are owned by the caller) */
+ virtual void deleteFramebuffer(FramebufferHandle framebuffer) = 0;
- /** @brief Generates mipmaps for a texture */
- virtual void generateMipmaps(u32 textureId) = 0;
-
- /** @brief Sets pixel store parameter */
- virtual void pixelStorei(u32 pname, i32 param) = 0;
-
- /**
- * @brief Toggles vertical flip on subsequent texture uploads.
- * @details WebGL-only (GL_UNPACK_FLIP_Y_WEBGL); a no-op on native, where
- * image data is flipped CPU-side at load time. Keeping the WebGL
- * constant inside the device avoids leaking it to upper layers.
- */
- virtual void setUnpackFlipY(bool enabled) = 0;
+ /** @brief Binds a framebuffer (Default = backbuffer) */
+ virtual void bindFramebuffer(FramebufferHandle framebuffer) = 0;
// =========================================================================
- // Framebuffer
+ // Readback
// =========================================================================
- /** @brief Creates a framebuffer and returns its ID */
- virtual u32 createFramebuffer() = 0;
+ /** @brief Reads pixels from the current framebuffer */
+ virtual void readPixels(i32 x, i32 y, u32 w, u32 h, GfxPixelFormat format, void* data) = 0;
- /** @brief Deletes a framebuffer */
- virtual void deleteFramebuffer(u32 fboId) = 0;
+ // =========================================================================
+ // GPU Timing (optional; EXT_disjoint_timer_query on WebGL2)
+ // =========================================================================
- /** @brief Binds a framebuffer (0 = default) */
- virtual void bindFramebuffer(u32 fboId) = 0;
+ /** @brief Creates a GPU elapsed-time query, or 0 when the backend cannot time GPU work. */
+ virtual u32 createTimerQuery() = 0;
- /** @brief Attaches a texture to a framebuffer */
- virtual void framebufferTexture2D(u32 fboId, GfxAttachment attachment, u32 textureId) = 0;
+ /** @brief Starts timing GPU work into a query; one query may be active at a time. */
+ virtual void beginTimerQuery(u32 query) = 0;
- /** @brief Checks framebuffer completeness */
- virtual bool checkFramebufferStatus() = 0;
+ /** @brief Stops the active timer query */
+ virtual void endTimerQuery() = 0;
- // =========================================================================
- // Readback
- // =========================================================================
+ /**
+ * @brief True when GPU timing was disturbed since the last check.
+ * @details In-flight query results are then meaningless and must be discarded.
+ */
+ virtual bool timerDisjoint() = 0;
- /** @brief Reads pixels from the current framebuffer */
- virtual void readPixels(i32 x, i32 y, u32 w, u32 h, GfxPixelFormat format, void* data) = 0;
+ /** @brief Fetches a completed query's elapsed nanoseconds; false while still pending. */
+ virtual bool getTimerQueryNs(u32 query, u64* outNanoseconds) = 0;
// =========================================================================
// Debug
@@ -383,14 +403,6 @@ public:
/** @brief Queries a backend integer capability/limit */
virtual i32 getInt(GfxIntParam name) = 0;
-
- /**
- * @brief Reports whether the backend can sample the given compressed format.
- * @details ETC2/EAC is always true on a WebGL2/GLES3 backend (core spec);
- * ASTC and S3TC depend on driver extensions. Probe this before
- * calling compressedTexImage2D with a non-core format.
- */
- virtual bool supportsCompressedFormat(GfxCompressedFormat format) = 0;
};
} // namespace esengine
diff --git a/src/esengine/renderer/GfxEnums.hpp b/src/esengine/renderer/GfxEnums.hpp
index 198954e49..999773e3b 100644
--- a/src/esengine/renderer/GfxEnums.hpp
+++ b/src/esengine/renderer/GfxEnums.hpp
@@ -21,10 +21,39 @@
namespace esengine {
// =============================================================================
-// Buffer Target
+// Resource Handles
// =============================================================================
-enum class GfxBufferTarget : u8 {
+// Opaque, type-safe GPU resource handles. On the GL backend the value is the GL
+// object id (0 is GL's null object, matching Invalid); other backends map the
+// value to an internal resource table.
+
+enum class BufferHandle : u32 { Invalid = 0 };
+enum class TextureHandle : u32 { Invalid = 0 };
+enum class ShaderHandle : u32 { Invalid = 0 };
+/** @brief Handle 0 is the default framebuffer (backbuffer); it cannot be created or deleted. */
+enum class FramebufferHandle : u32 { Default = 0 };
+
+// =============================================================================
+// Texture Sampling
+// =============================================================================
+
+enum class TextureFilter : u8 {
+ Nearest, ///< No interpolation (pixelated look)
+ Linear, ///< Bilinear interpolation (smooth)
+};
+
+enum class TextureWrap : u8 {
+ Repeat, ///< Tile the texture
+ ClampToEdge, ///< Clamp to edge pixels
+ MirroredRepeat, ///< Tile with mirroring
+};
+
+// =============================================================================
+// Buffer Usage
+// =============================================================================
+
+enum class GfxBufferUsage : u8 {
Vertex,
Index,
Uniform,
@@ -105,7 +134,7 @@ enum class GfxPixelFormat : u8 {
// =============================================================================
/**
- * @brief GPU-compressed texture internal formats for compressedTexImage2D.
+ * @brief GPU-compressed texture internal formats for createCompressedTexture.
*
* @details Decoded textures stay compressed in VRAM (4–8× smaller than RGBA8),
* the key constraint on mobile. Tiering:
@@ -128,13 +157,45 @@ enum class GfxCompressedFormat : u8 {
};
// =============================================================================
-// Framebuffer Attachment
+// Resource Descriptors
// =============================================================================
-enum class GfxAttachment : u8 {
- Color0,
- Depth,
- DepthStencil,
+/**
+ * @brief Immutable creation parameters of a GPU buffer.
+ * @details `size` is the buffer's capacity; updateBuffer must stay within it.
+ * Growing is an explicit resizeBuffer (contents discarded), keeping the
+ * handle stable so vertex-layout associations survive.
+ */
+struct BufferDesc {
+ GfxBufferUsage usage = GfxBufferUsage::Vertex;
+ u32 size = 0;
+ bool dynamic = false;
+};
+
+/**
+ * @brief Immutable creation parameters of a 2D texture.
+ * @details `flipY` applies to the initial pixel upload only (WebGL upload state;
+ * native backends flip CPU-side at load time).
+ */
+struct TextureDesc {
+ u32 width = 1;
+ u32 height = 1;
+ GfxPixelFormat format = GfxPixelFormat::RGBA8;
+ TextureFilter minFilter = TextureFilter::Linear;
+ TextureFilter magFilter = TextureFilter::Linear;
+ TextureWrap wrapS = TextureWrap::ClampToEdge;
+ TextureWrap wrapT = TextureWrap::ClampToEdge;
+ bool mipmaps = false;
+ bool flipY = false;
+};
+
+/**
+ * @brief Attachments of an offscreen render target. The attach point of
+ * `depthStencil` follows its texture's pixel format.
+ */
+struct FramebufferDesc {
+ TextureHandle color0 = TextureHandle::Invalid;
+ TextureHandle depthStencil = TextureHandle::Invalid;
};
// =============================================================================
diff --git a/src/esengine/renderer/ImmediateDraw.cpp b/src/esengine/renderer/ImmediateDraw.cpp
index 47c7c203a..236dd88c2 100644
--- a/src/esengine/renderer/ImmediateDraw.cpp
+++ b/src/esengine/renderer/ImmediateDraw.cpp
@@ -71,20 +71,20 @@ void ImmediateDraw::init() {
);
Shader* shader = resource_manager_.getShader(handle);
if (shader && shader->isValid()) {
- batch_shader_id_ = shader->getProgramId();
- device_.useProgram(batch_shader_id_);
+ batch_shader_ = shader->handle();
+ device_.useProgram(batch_shader_);
// Immediate draw is single-texture (slot 0), but bind all 8 samplers for parity
// with the world batch shader.
for (i32 i = 0; i < 8; ++i) {
- i32 loc = device_.getUniformLocation(batch_shader_id_, ("u_textures[" + std::to_string(i) + "]").c_str());
+ i32 loc = device_.getUniformLocation(batch_shader_, ("u_textures[" + std::to_string(i) + "]").c_str());
if (loc >= 0) device_.setUniform1i(loc, i);
}
- device_.useProgram(0);
+ device_.useProgram(ShaderHandle::Invalid);
// One immutable pipeline: the batch shader, Batch layout, normal blend, depth
// test off (write on, matching the world batch path), no stencil, no culling.
PipelineDesc desc{};
- desc.program = batch_shader_id_;
+ desc.program = batch_shader_;
desc.vertexLayout = LayoutId::Batch;
desc.blend = BlendMode::Normal;
desc.blendEnabled = true;
@@ -130,7 +130,7 @@ void ImmediateDraw::flush() {
pool_.upload();
device_.setPipeline(pipeline_);
- device_.bindTexture(0, currentTexture_);
+ device_.bindTexture(0, TextureHandle{currentTexture_});
pool_.bindLayout(LayoutId::Batch);
device_.drawElements(pool_.indicesUsed(LayoutId::Batch), GfxDataType::UnsignedInt, 0);
diff --git a/src/esengine/renderer/ImmediateDraw.hpp b/src/esengine/renderer/ImmediateDraw.hpp
index c3e6bac0d..863603d81 100644
--- a/src/esengine/renderer/ImmediateDraw.hpp
+++ b/src/esengine/renderer/ImmediateDraw.hpp
@@ -172,7 +172,7 @@ private:
resource::ResourceManager& resource_manager_;
TransientBufferPool pool_;
- u32 batch_shader_id_ = 0;
+ ShaderHandle batch_shader_ = ShaderHandle::Invalid;
PipelineHandle pipeline_ = PipelineHandle::Invalid;
u32 white_texture_id_ = 0;
u32 currentTexture_ = 0;
diff --git a/src/esengine/renderer/LightStore.cpp b/src/esengine/renderer/LightStore.cpp
index 5823d8eea..8e09307bc 100644
--- a/src/esengine/renderer/LightStore.cpp
+++ b/src/esengine/renderer/LightStore.cpp
@@ -14,22 +14,21 @@ namespace esengine {
void LightStore::uploadAndBind() {
if (!device_) return;
- if (ubo_ == 0) {
- ubo_ = device_->createBuffer();
- dirty_ = true;
- }
- device_->bindUniformBuffer(ubo_);
- if (dirty_) {
- device_->bufferData(GfxBufferTarget::Uniform, &data_, sizeof(LightConstants), /*dynamic=*/true);
+ if (ubo_ == BufferHandle::Invalid) {
+ ubo_ = device_->createBuffer(
+ {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(LightConstants)), /*dynamic=*/true}, &data_);
+ dirty_ = false;
+ } else if (dirty_) {
+ device_->updateBuffer(ubo_, 0, &data_, sizeof(LightConstants));
dirty_ = false;
}
- device_->bindBufferBase(LIGHT_CONSTANTS_BINDING, ubo_);
+ device_->setUniformBuffer(LIGHT_CONSTANTS_BINDING, ubo_);
}
void LightStore::free() {
- if (ubo_ != 0 && device_) {
+ if (ubo_ != BufferHandle::Invalid && device_) {
device_->deleteBuffer(ubo_);
- ubo_ = 0;
+ ubo_ = BufferHandle::Invalid;
}
dirty_ = true;
}
diff --git a/src/esengine/renderer/LightStore.hpp b/src/esengine/renderer/LightStore.hpp
index 72cba12d6..cec0c3711 100644
--- a/src/esengine/renderer/LightStore.hpp
+++ b/src/esengine/renderer/LightStore.hpp
@@ -17,6 +17,7 @@
*/
#pragma once
+#include "GfxEnums.hpp"
#include "LightConstants.hpp"
#include <glm/glm.hpp>
@@ -83,7 +84,7 @@ public:
private:
LightConstants data_{};
u32 count_ = 0;
- u32 ubo_ = 0;
+ BufferHandle ubo_ = BufferHandle::Invalid;
bool dirty_ = true;
GfxDevice* device_ = nullptr;
};
diff --git a/src/esengine/renderer/MaterialStore.cpp b/src/esengine/renderer/MaterialStore.cpp
index 7fc298026..e765b53f5 100644
--- a/src/esengine/renderer/MaterialStore.cpp
+++ b/src/esengine/renderer/MaterialStore.cpp
@@ -15,14 +15,14 @@ namespace esengine {
void MaterialStore::undefine(u32 materialId) {
auto it = materials_.find(materialId);
if (it == materials_.end()) return;
- if (it->second.ubo != 0 && device_) device_->deleteBuffer(it->second.ubo);
+ if (it->second.ubo != BufferHandle::Invalid && device_) device_->deleteBuffer(it->second.ubo);
materials_.erase(it);
}
void MaterialStore::clear() {
if (device_) {
for (auto& [id, rec] : materials_) {
- if (rec.ubo != 0) device_->deleteBuffer(rec.ubo);
+ if (rec.ubo != BufferHandle::Invalid) device_->deleteBuffer(rec.ubo);
}
}
materials_.clear();
@@ -40,17 +40,18 @@ void MaterialStore::bindForDraw(u32 materialId) {
// Per-material constants UBO (binding 1) — present only when the shader declares params.
if (!rec.uboBytes.empty()) {
- if (rec.ubo == 0) {
- rec.ubo = device_->createBuffer();
- rec.uboDirty = true;
- }
- device_->bindUniformBuffer(rec.ubo);
- if (rec.uboDirty) {
- device_->bufferData(GfxBufferTarget::Uniform, rec.uboBytes.data(),
- static_cast<u32>(rec.uboBytes.size()), /*dynamic=*/true);
+ const u32 byteSize = static_cast<u32>(rec.uboBytes.size());
+ if (rec.ubo == BufferHandle::Invalid) {
+ rec.ubo = device_->createBuffer({GfxBufferUsage::Uniform, byteSize, /*dynamic=*/true},
+ rec.uboBytes.data());
+ rec.uboDirty = false;
+ } else if (rec.uboDirty) {
+ // Full re-spec (not a sub-update): orphans the old store so a draw still
+ // reading it does not stall the upload.
+ device_->resizeBuffer(rec.ubo, byteSize, rec.uboBytes.data());
rec.uboDirty = false;
}
- device_->bindBufferBase(MATERIAL_CONSTANTS_BINDING, rec.ubo);
+ device_->setUniformBuffer(MATERIAL_CONSTANTS_BINDING, rec.ubo);
}
// Texture params — bound to their sampler units (>= MATERIAL_TEXTURE_UNIT_BASE), above the
@@ -63,7 +64,7 @@ void MaterialStore::bindForDraw(u32 materialId) {
for (const auto& b : rec.textures) {
if (b.unit == slot.unit) { glTexture = b.glTexture; break; }
}
- if (glTexture != 0) device_->bindTexture(slot.unit, glTexture);
+ if (glTexture != 0) device_->bindTexture(slot.unit, TextureHandle{glTexture});
}
}
}
diff --git a/src/esengine/renderer/MaterialStore.hpp b/src/esengine/renderer/MaterialStore.hpp
index ae05c41d8..39fc00d68 100644
--- a/src/esengine/renderer/MaterialStore.hpp
+++ b/src/esengine/renderer/MaterialStore.hpp
@@ -24,6 +24,7 @@
#include "../core/Types.hpp"
#include "BlendMode.hpp"
+#include "GfxEnums.hpp"
#include <algorithm>
#include <cstring>
@@ -98,7 +99,7 @@ struct MaterialRecord {
/// Packed std140 MaterialConstants payload (sized to the shader's blockSize), the GPU
/// UBO it uploads to (lazy), and whether the bytes changed since the last upload.
std::vector<u8> uboBytes;
- u32 ubo = 0;
+ BufferHandle ubo = BufferHandle::Invalid;
bool uboDirty = false;
/// Texture params bound to sampler units (GL texture ids, resolved at set time).
@@ -132,7 +133,7 @@ public:
}
MaterialRecord& rec = it->second;
const bool shaderChanged = rec.shader != record.shader;
- const u32 ubo = rec.ubo;
+ const BufferHandle ubo = rec.ubo;
std::vector<u8> bytes = std::move(rec.uboBytes);
std::vector<MaterialTextureBinding> texs = std::move(rec.textures);
rec = record; // render state
diff --git a/src/esengine/renderer/PipelineState.hpp b/src/esengine/renderer/PipelineState.hpp
index 5612369cb..bf1dbc1cb 100644
--- a/src/esengine/renderer/PipelineState.hpp
+++ b/src/esengine/renderer/PipelineState.hpp
@@ -41,7 +41,7 @@ enum class GfxStencilMode : u8 {
* two draws with the same description share one PipelineHandle.
*/
struct PipelineDesc {
- u32 program = 0;
+ ShaderHandle program = ShaderHandle::Invalid;
LayoutId vertexLayout = LayoutId::Batch;
BlendMode blend = BlendMode::Normal;
bool blendEnabled = true;
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index b1e443303..25d2281a9 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -118,9 +118,9 @@ void PostProcessPipeline::shutdown() {
screenPasses_.clear();
auto* device = &device_;
- if (screen_quad_vbo_ != 0 && device) {
+ if (screen_quad_vbo_ != BufferHandle::Invalid && device) {
device->deleteBuffer(screen_quad_vbo_);
- screen_quad_vbo_ = 0;
+ screen_quad_vbo_ = BufferHandle::Invalid;
}
if (screen_quad_vao_ != 0 && device) {
device->deleteVertexArray(screen_quad_vao_);
@@ -135,7 +135,7 @@ void PostProcessPipeline::shutdown() {
fboOriginalCreated_ = false;
screenCaptureActive_ = false;
screenFBOCreated_ = false;
- sceneTexture_ = 0;
+ sceneTexture_ = TextureHandle::Invalid;
if (blitShader_.isValid()) {
resourceManager_.releaseShader(blitShader_);
@@ -260,9 +260,9 @@ void PostProcessPipeline::ensureScreenQuad() {
u32 vao = device->createVertexArray();
device->bindVertexArray(vao);
- u32 vbo = device->createBuffer();
+ BufferHandle vbo = device->createBuffer(
+ {GfxBufferUsage::Vertex, static_cast<u32>(sizeof(vertices)), /*dynamic=*/false}, vertices);
device->bindVertexBuffer(vbo);
- device->bufferData(GfxBufferTarget::Vertex, vertices, static_cast<u32>(sizeof(vertices)), false);
device->enableVertexAttrib(0);
device->vertexAttribPointer(0, 2, GfxDataType::Float, false, STRIDE, 0);
@@ -319,11 +319,11 @@ void PostProcessPipeline::end() {
if (enabledCount == 0) {
blitToOutput(sceneTexture_);
} else {
- u32 inputTexture = sceneTexture_;
+ TextureHandle inputTexture = sceneTexture_;
currentFBO_ = 0;
device->bindTexture(1, sceneTexture_);
- device->bindTexture(0, 0);
+ device->bindTexture(0, TextureHandle::Invalid);
for (const auto& pass : passes_) {
if (!pass.enabled) continue;
@@ -347,10 +347,10 @@ void PostProcessPipeline::end() {
device->setBlendEnabled(true);
device->setDepthTest(true);
inFrame_ = false;
- output_target_fbo_ = 0;
+ output_target_fbo_ = FramebufferHandle::Default;
}
-void PostProcessPipeline::renderPass(const PostProcessPass& pass, u32 inputTexture) {
+void PostProcessPipeline::renderPass(const PostProcessPass& pass, TextureHandle inputTexture) {
Shader* shader = resourceManager_.getShader(pass.shader);
if (!shader) return;
@@ -386,8 +386,8 @@ void PostProcessPipeline::clearPasses() {
passes_.clear();
}
-void PostProcessPipeline::setOutputTarget(u32 fboId) {
- output_target_fbo_ = fboId;
+void PostProcessPipeline::setOutputTarget(FramebufferHandle target) {
+ output_target_fbo_ = target;
}
void PostProcessPipeline::setOutputViewport(u32 x, u32 y, u32 w, u32 h) {
@@ -397,7 +397,7 @@ void PostProcessPipeline::setOutputViewport(u32 x, u32 y, u32 w, u32 h) {
output_vp_h_ = h;
}
-void PostProcessPipeline::blitToOutput(u32 texture) {
+void PostProcessPipeline::blitToOutput(TextureHandle texture) {
Shader* shader = resourceManager_.getShader(blitShader_);
if (!shader) return;
@@ -417,12 +417,13 @@ void PostProcessPipeline::blitToOutput(u32 texture) {
}
u32 PostProcessPipeline::getSourceTexture() const {
- return fboOriginal_ ? fboOriginal_->getColorAttachment() : 0;
+ return fboOriginal_ ? static_cast<u32>(fboOriginal_->getColorAttachment()) : 0;
}
u32 PostProcessPipeline::getOutputTexture() const {
if (!fboA_ || !fboB_) return 0;
- return (currentFBO_ == 0) ? fboA_->getColorAttachment() : fboB_->getColorAttachment();
+ return static_cast<u32>((currentFBO_ == 0) ? fboA_->getColorAttachment()
+ : fboB_->getColorAttachment());
}
void PostProcessPipeline::ensureScreenFBO() {
@@ -489,11 +490,11 @@ void PostProcessPipeline::executeScreenPasses() {
sceneTexture_ = screenFBO_->getColorAttachment();
screenFBO_->unbind();
- u32 inputTexture = sceneTexture_;
+ TextureHandle inputTexture = sceneTexture_;
u32 pingPong = 0;
device->bindTexture(1, sceneTexture_);
- device->bindTexture(0, 0);
+ device->bindTexture(0, TextureHandle::Invalid);
for (const auto& pass : screenPasses_) {
if (!pass.enabled) continue;
@@ -511,7 +512,7 @@ void PostProcessPipeline::executeScreenPasses() {
Framebuffer* lastFBO = (pingPong == 0) ? fboA_.get() : fboB_.get();
lastFBO->unbind();
- device->bindFramebuffer(0);
+ device->bindFramebuffer(FramebufferHandle::Default);
device->setViewport(0, 0, width_, height_);
blitToOutput(inputTexture);
diff --git a/src/esengine/renderer/PostProcessPipeline.hpp b/src/esengine/renderer/PostProcessPipeline.hpp
index bbf21ffdf..b1aa85904 100644
--- a/src/esengine/renderer/PostProcessPipeline.hpp
+++ b/src/esengine/renderer/PostProcessPipeline.hpp
@@ -163,9 +163,9 @@ public:
void clearPasses();
/**
- * @brief Sets the output target FBO for the final blit (0 = default framebuffer / screen)
+ * @brief Sets the output target for the final blit (Default = screen)
*/
- void setOutputTarget(u32 fboId);
+ void setOutputTarget(FramebufferHandle target);
/**
* @brief Sets the output viewport for the final blit
@@ -222,8 +222,8 @@ private:
void ensureFBOs();
void ensureScreenQuad();
void drawScreenQuad();
- void renderPass(const PostProcessPass& pass, u32 inputTexture);
- void blitToOutput(u32 texture);
+ void renderPass(const PostProcessPass& pass, TextureHandle inputTexture);
+ void blitToOutput(TextureHandle texture);
GfxDevice& device_;
RenderContext& context_;
@@ -233,7 +233,7 @@ private:
Unique<Framebuffer> fboB_;
Unique<Framebuffer> fboOriginal_;
u32 screen_quad_vao_ = 0;
- u32 screen_quad_vbo_ = 0;
+ BufferHandle screen_quad_vbo_ = BufferHandle::Invalid;
resource::ShaderHandle blitShader_;
std::vector<PostProcessPass> passes_;
@@ -245,9 +245,9 @@ private:
bool inFrame_ = false;
bool bypass_ = false;
u32 currentFBO_ = 0;
- u32 sceneTexture_ = 0;
+ TextureHandle sceneTexture_ = TextureHandle::Invalid;
- u32 output_target_fbo_ = 0;
+ FramebufferHandle output_target_fbo_ = FramebufferHandle::Default;
u32 output_vp_x_ = 0;
u32 output_vp_y_ = 0;
u32 output_vp_w_ = 0;
diff --git a/src/esengine/renderer/RenderContext.cpp b/src/esengine/renderer/RenderContext.cpp
index b26bb92a7..fc454e48f 100644
--- a/src/esengine/renderer/RenderContext.cpp
+++ b/src/esengine/renderer/RenderContext.cpp
@@ -50,20 +50,20 @@ void RenderContext::shutdown() {
return;
}
- for (u32* tex : {&whiteTextureId_, &blackTextureId_, &flatNormalTextureId_}) {
- if (*tex != 0) {
+ for (TextureHandle* tex : {&whiteTexture_, &blackTexture_, &flatNormalTexture_}) {
+ if (*tex != TextureHandle::Invalid) {
device_.deleteTexture(*tex);
- *tex = 0;
+ *tex = TextureHandle::Invalid;
}
}
- if (frameUbo_ != 0) {
+ if (frameUbo_ != BufferHandle::Invalid) {
device_.deleteBuffer(frameUbo_);
- frameUbo_ = 0;
+ frameUbo_ = BufferHandle::Invalid;
}
- if (timeUbo_ != 0) {
+ if (timeUbo_ != BufferHandle::Invalid) {
device_.deleteBuffer(timeUbo_);
- timeUbo_ = 0;
+ timeUbo_ = BufferHandle::Invalid;
}
materials_.clear(); // free per-material UBOs while the device is still valid
@@ -74,55 +74,52 @@ void RenderContext::shutdown() {
ES_LOG_INFO("RenderContext shutdown");
}
-u32 RenderContext::make1x1Texture(u32 rgba) {
- u32 id = device_.createTexture();
- device_.texImage2D(id, 1, 1, GfxPixelFormat::RGBA8, &rgba);
- device_.setTextureParams(id, TextureFilter::Nearest, TextureFilter::Nearest,
- TextureWrap::ClampToEdge, TextureWrap::ClampToEdge);
- return id;
+TextureHandle RenderContext::make1x1Texture(u32 rgba) {
+ TextureDesc desc;
+ desc.width = 1;
+ desc.height = 1;
+ desc.minFilter = TextureFilter::Nearest;
+ desc.magFilter = TextureFilter::Nearest;
+ return device_.createTexture(desc, &rgba);
}
void RenderContext::initDefaultTextures() {
// Byte order in memory is R,G,B,A; these u32s are little-endian (so 0xAABBGGRR).
- whiteTextureId_ = make1x1Texture(0xFFFFFFFF); // RGBA(255,255,255,255)
- blackTextureId_ = make1x1Texture(0xFF000000); // RGBA(0,0,0,255)
- flatNormalTextureId_ = make1x1Texture(0xFFFF8080); // RGB(128,128,255) → normal (0,0,1)
+ whiteTexture_ = make1x1Texture(0xFFFFFFFF); // RGBA(255,255,255,255)
+ blackTexture_ = make1x1Texture(0xFF000000); // RGBA(0,0,0,255)
+ flatNormalTexture_ = make1x1Texture(0xFFFF8080); // RGB(128,128,255) → normal (0,0,1)
ES_LOG_DEBUG("Default textures created (white {}, black {}, flatNormal {})",
- whiteTextureId_, blackTextureId_, flatNormalTextureId_);
+ static_cast<u32>(whiteTexture_), static_cast<u32>(blackTexture_),
+ static_cast<u32>(flatNormalTexture_));
}
u32 RenderContext::defaultTextureByName(const std::string& name) const {
- if (name == "black") return blackTextureId_;
- if (name == "flatnormal" || name == "normal") return flatNormalTextureId_;
- return whiteTextureId_; // "white" / empty / unknown
+ if (name == "black") return static_cast<u32>(blackTexture_);
+ if (name == "flatnormal" || name == "normal") return static_cast<u32>(flatNormalTexture_);
+ return static_cast<u32>(whiteTexture_); // "white" / empty / unknown
}
void RenderContext::initFrameUbo() {
- frameUbo_ = device_.createBuffer();
-
FrameConstants initial{};
- device_.bindUniformBuffer(frameUbo_);
- device_.bufferData(GfxBufferTarget::Uniform, &initial, sizeof(FrameConstants), /*dynamic=*/true);
+ frameUbo_ = device_.createBuffer(
+ {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(FrameConstants)), /*dynamic=*/true}, &initial);
- // The binding point persists for the context lifetime; only the contents change
- // per frame. Every engine shader's FrameConstants block is linked to this point
+ // The binding slot persists for the context lifetime; only the contents change
+ // per frame. Every engine shader's FrameConstants block is linked to this slot
// at compile time (Shader::compile).
- device_.bindBufferBase(FRAME_CONSTANTS_BINDING, frameUbo_);
+ device_.setUniformBuffer(FRAME_CONSTANTS_BINDING, frameUbo_);
- timeUbo_ = device_.createBuffer();
TimeConstants time{};
- device_.bindUniformBuffer(timeUbo_);
- device_.bufferData(GfxBufferTarget::Uniform, &time, sizeof(TimeConstants), /*dynamic=*/true);
- device_.bindBufferBase(TIME_CONSTANTS_BINDING, timeUbo_);
+ timeUbo_ = device_.createBuffer(
+ {GfxBufferUsage::Uniform, static_cast<u32>(sizeof(TimeConstants)), /*dynamic=*/true}, &time);
+ device_.setUniformBuffer(TIME_CONSTANTS_BINDING, timeUbo_);
- ES_LOG_DEBUG("FrameConstants UBO created (ID: {})", frameUbo_);
+ ES_LOG_DEBUG("FrameConstants UBO created (handle: {})", static_cast<u32>(frameUbo_));
}
void RenderContext::updateFrameConstants(const glm::mat4& viewProjection) {
viewProjection_ = viewProjection;
- device_.bindUniformBuffer(frameUbo_);
- device_.bufferSubData(GfxBufferTarget::Uniform, 0, glm::value_ptr(viewProjection),
- sizeof(glm::mat4));
+ device_.updateBuffer(frameUbo_, 0, glm::value_ptr(viewProjection), sizeof(glm::mat4));
}
void RenderContext::setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH) {
@@ -134,8 +131,7 @@ void RenderContext::setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH) {
glm::vec4(elapsedSec, dt, 0.0f, 0.0f),
glm::vec4(w, h, w > 0.0f ? 1.0f / w : 0.0f, h > 0.0f ? 1.0f / h : 0.0f),
};
- device_.bindUniformBuffer(timeUbo_);
- device_.bufferSubData(GfxBufferTarget::Uniform, 0, &time, sizeof(TimeConstants));
+ device_.updateBuffer(timeUbo_, 0, &time, sizeof(TimeConstants));
}
} // namespace esengine
diff --git a/src/esengine/renderer/RenderContext.hpp b/src/esengine/renderer/RenderContext.hpp
index 8181fd935..8ae67fb7c 100644
--- a/src/esengine/renderer/RenderContext.hpp
+++ b/src/esengine/renderer/RenderContext.hpp
@@ -21,6 +21,7 @@
// Project includes
#include "../core/Types.hpp"
#include "Buffer.hpp"
+#include "GfxEnums.hpp"
#include "LightStore.hpp"
#include "MaterialStore.hpp"
#include "Shader.hpp"
@@ -137,14 +138,13 @@ public:
// =========================================================================
/**
- * @brief Gets the white texture ID (for untextured quads)
- * @return GPU texture handle
+ * @brief Gets the white texture handle's raw value (for untextured quads)
*/
- u32 getWhiteTextureId() const { return whiteTextureId_; }
+ u32 getWhiteTextureId() const { return static_cast<u32>(whiteTexture_); }
/**
- * @brief GL texture id for a named built-in default texture, used to resolve a material
- * texture param's `#pragma param ... texture default(<name>)`.
+ * @brief Texture handle value for a named built-in default texture, used to resolve a
+ * material texture param's `#pragma param ... texture default(<name>)`.
* @details "black" → opaque black, "flatnormal"/"normal" → a flat tangent-space normal
* (RGB 128,128,255 → (0,0,1)); anything else (incl. "white" / empty) → white.
*/
@@ -180,17 +180,17 @@ public:
private:
void initDefaultTextures();
- u32 make1x1Texture(u32 rgba);
+ TextureHandle make1x1Texture(u32 rgba);
void initFrameUbo();
glm::mat4 viewProjection_{1.0f};
RenderContextStats stats_;
- u32 whiteTextureId_ = 0;
- u32 blackTextureId_ = 0;
- u32 flatNormalTextureId_ = 0;
- u32 frameUbo_ = 0;
- u32 timeUbo_ = 0;
+ TextureHandle whiteTexture_ = TextureHandle::Invalid;
+ TextureHandle blackTexture_ = TextureHandle::Invalid;
+ TextureHandle flatNormalTexture_ = TextureHandle::Invalid;
+ BufferHandle frameUbo_ = BufferHandle::Invalid;
+ BufferHandle timeUbo_ = BufferHandle::Invalid;
f32 lastElapsed_ = 0.0f;
MaterialStore materials_;
LightStore lights_;
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index 2b0988337..0bdc1b1de 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -10,10 +10,6 @@
#include "../resource/ShaderParser.hpp"
#include "../core/Log.hpp"
#include "../core/FrameProfiler.hpp"
-#include "OpenGLHeaders.hpp"
-#ifdef __EMSCRIPTEN__
-#include <emscripten/html5.h>
-#endif
#include <glm/gtc/type_ptr.hpp>
@@ -23,59 +19,40 @@
namespace esengine {
-// EXT_disjoint_timer_query_webgl2 enums — not guaranteed in <GLES3/gl3.h>.
-#ifndef GL_TIME_ELAPSED_EXT
-#define GL_TIME_ELAPSED_EXT 0x88BF
-#endif
-#ifndef GL_GPU_DISJOINT_EXT
-#define GL_GPU_DISJOINT_EXT 0x8FBB
-#endif
-
-void GpuTimer::ensureInit() {
- if (state_ != 0) return;
-#ifdef __EMSCRIPTEN__
- // Must ENABLE the extension (not just check presence) so emscripten routes the
- // TIME_ELAPSED query entry points.
- EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
- if (ctx && emscripten_webgl_enable_extension(ctx, "EXT_disjoint_timer_query_webgl2")) {
- glGenQueries(kRing, queries_);
- state_ = 1;
- return;
+void GpuTimer::begin(GfxDevice& device) {
+ if (state_ == 0) {
+ // Lazy probe: the device reports timer support by whether it can create a query.
+ queries_[0] = device.createTimerQuery();
+ if (queries_[0] != 0) {
+ for (int i = 1; i < kRing; ++i) queries_[i] = device.createTimerQuery();
+ state_ = 1;
+ } else {
+ state_ = 2;
+ }
}
-#endif
- state_ = 2;
-}
-
-void GpuTimer::begin() {
- ensureInit();
if (state_ != 1 || inflight_[write_]) return;
- glBeginQuery(GL_TIME_ELAPSED_EXT, queries_[write_]);
+ device.beginTimerQuery(queries_[write_]);
active_ = true;
}
-void GpuTimer::end() {
+void GpuTimer::end(GfxDevice& device) {
if (!active_) return;
- glEndQuery(GL_TIME_ELAPSED_EXT);
+ device.endTimerQuery();
inflight_[write_] = true;
write_ = (write_ + 1) % kRing;
active_ = false;
}
-void GpuTimer::poll() {
+void GpuTimer::poll(GfxDevice& device) {
if (state_ != 1) return;
- GLint disjoint = 0;
- glGetIntegerv(GL_GPU_DISJOINT_EXT, &disjoint);
- if (disjoint) { // timing disturbed — drop everything in flight
+ if (device.timerDisjoint()) { // timing disturbed — drop everything in flight
for (int i = 0; i < kRing; ++i) inflight_[i] = false;
read_ = write_;
return;
}
while (inflight_[read_]) {
- GLuint avail = 0;
- glGetQueryObjectuiv(queries_[read_], GL_QUERY_RESULT_AVAILABLE, &avail);
- if (!avail) break;
- GLuint ns = 0;
- glGetQueryObjectuiv(queries_[read_], GL_QUERY_RESULT, &ns);
+ u64 ns = 0;
+ if (!device.getTimerQueryNs(queries_[read_], &ns)) break;
last_ms_ = static_cast<f32>(ns) / 1.0e6f;
inflight_[read_] = false;
read_ = (read_ + 1) % kRing;
@@ -228,7 +205,7 @@ void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::H
if (target != RenderTargetManager::INVALID_HANDLE) {
auto* rt = target_manager_.get(target);
if (rt) {
- post_process_->setOutputTarget(rt->getFramebufferId());
+ post_process_->setOutputTarget(rt->getFramebuffer());
}
}
post_process_->begin();
@@ -260,12 +237,12 @@ void RenderFrame::flush() {
context_.updateFrameConstants(view_projection_);
context_.lights().uploadAndBind();
- gpu_timer_.poll();
+ gpu_timer_.poll(device_);
{
ES_PROFILE_SCOPE("render.submit");
- gpu_timer_.begin();
+ gpu_timer_.begin(device_);
draw_list_.execute(device_, pool_, context_.materials(), &frame_capture_);
- gpu_timer_.end();
+ gpu_timer_.end(device_);
}
FrameProfiler::get().gpuScope("submit", gpu_timer_.lastMs());
@@ -318,10 +295,10 @@ void RenderFrame::end() {
if (usePostProcess) {
#ifdef ES_ENABLE_POSTPROCESS
ES_PROFILE_SCOPE("render.postprocess");
- gpu_timer_pp_.poll();
- gpu_timer_pp_.begin();
+ gpu_timer_pp_.poll(device_);
+ gpu_timer_pp_.begin(device_);
post_process_->end();
- gpu_timer_pp_.end();
+ gpu_timer_pp_.end(device_);
FrameProfiler::get().gpuScope("postprocess", gpu_timer_pp_.lastMs());
#endif
} else if (current_target_ != RenderTargetManager::INVALID_HANDLE) {
@@ -625,15 +602,15 @@ u32 RenderFrame::compileBatchVariant(const std::vector<std::string>& features) {
Shader* shader = resource_manager_.getShader(handle);
if (shader && shader->isValid()) {
- u32 prog = shader->getProgramId();
shader->bind();
// Bind the 8 multi-texture samplers to units 0..7 (per-program, set once).
for (i32 i = 0; i < 8; ++i) {
- i32 loc = device_.getUniformLocation(prog, ("u_textures[" + std::to_string(i) + "]").c_str());
+ i32 loc = device_.getUniformLocation(shader->handle(),
+ ("u_textures[" + std::to_string(i) + "]").c_str());
if (loc >= 0) device_.setUniform1i(loc, i);
}
shader->unbind();
- return prog;
+ return shader->getProgramId();
}
const std::string vk = resource::ShaderParser::variantKey(features);
diff --git a/src/esengine/renderer/RenderFrame.hpp b/src/esengine/renderer/RenderFrame.hpp
index 9dbe89a2d..23513f6c6 100644
--- a/src/esengine/renderer/RenderFrame.hpp
+++ b/src/esengine/renderer/RenderFrame.hpp
@@ -38,19 +38,18 @@ struct Frustum {
bool intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtents) const;
};
-// GPU frame timer (EXT_disjoint_timer_query). POD state only; the GL methods live
-// in RenderFrame.cpp so no GL headers leak through this header.
+// GPU frame timer: a small ring of device timer queries so a frame's result is
+// read a few frames later without stalling the CPU on the GPU.
class GpuTimer {
public:
- void begin();
- void end();
- void poll();
+ void begin(GfxDevice& device);
+ void end(GfxDevice& device);
+ void poll(GfxDevice& device);
f32 lastMs() const { return last_ms_; }
private:
- void ensureInit(); // lazy: enable the extension + gen queries on first use
static constexpr int kRing = 3;
- unsigned queries_[kRing] = {0, 0, 0};
+ u32 queries_[kRing] = {0, 0, 0};
bool inflight_[kRing] = {false, false, false};
int write_ = 0;
int read_ = 0;
diff --git a/src/esengine/renderer/RenderTarget.cpp b/src/esengine/renderer/RenderTarget.cpp
index 6250d4179..3a9ee7c3a 100644
--- a/src/esengine/renderer/RenderTarget.cpp
+++ b/src/esengine/renderer/RenderTarget.cpp
@@ -48,16 +48,16 @@ void RenderTarget::resize(u32 width, u32 height) {
}
}
-u32 RenderTarget::getColorTexture() const {
- return framebuffer_ ? framebuffer_->getColorAttachment() : 0;
+TextureHandle RenderTarget::getColorTexture() const {
+ return framebuffer_ ? framebuffer_->getColorAttachment() : TextureHandle::Invalid;
}
-u32 RenderTarget::getDepthTexture() const {
- return framebuffer_ ? framebuffer_->getDepthAttachment() : 0;
+TextureHandle RenderTarget::getDepthTexture() const {
+ return framebuffer_ ? framebuffer_->getDepthAttachment() : TextureHandle::Invalid;
}
-u32 RenderTarget::getFramebufferId() const {
- return framebuffer_ ? framebuffer_->getFramebufferId() : 0;
+FramebufferHandle RenderTarget::getFramebuffer() const {
+ return framebuffer_ ? framebuffer_->handle() : FramebufferHandle::Default;
}
RenderTargetManager::Handle RenderTargetManager::create(u32 width, u32 height, bool depth, bool linearFilter) {
diff --git a/src/esengine/renderer/RenderTarget.hpp b/src/esengine/renderer/RenderTarget.hpp
index 2d31b74f4..573ee628c 100644
--- a/src/esengine/renderer/RenderTarget.hpp
+++ b/src/esengine/renderer/RenderTarget.hpp
@@ -27,14 +27,14 @@ public:
void unbind();
void resize(u32 width, u32 height);
- u32 getColorTexture() const;
- u32 getDepthTexture() const;
+ TextureHandle getColorTexture() const;
+ TextureHandle getDepthTexture() const;
glm::uvec2 getSize() const { return { width_, height_ }; }
u32 getWidth() const { return width_; }
u32 getHeight() const { return height_; }
bool isValid() const { return framebuffer_ != nullptr; }
- u32 getFramebufferId() const;
+ FramebufferHandle getFramebuffer() const;
private:
Unique<Framebuffer> framebuffer_;
diff --git a/src/esengine/renderer/Shader.cpp b/src/esengine/renderer/Shader.cpp
index 0db467be8..49a31a261 100644
--- a/src/esengine/renderer/Shader.cpp
+++ b/src/esengine/renderer/Shader.cpp
@@ -27,32 +27,32 @@
namespace esengine {
Shader::~Shader() {
- if (programId_ != 0 && device_) {
- device_->deleteProgram(programId_);
- programId_ = 0;
+ if (program_ != ShaderHandle::Invalid && device_) {
+ device_->deleteProgram(program_);
+ program_ = ShaderHandle::Invalid;
}
}
Shader::Shader(Shader&& other) noexcept
: device_(other.device_)
- , programId_(other.programId_)
+ , program_(other.program_)
, uniformCache_(std::move(other.uniformCache_))
, attribCache_(std::move(other.attribCache_))
, activeUniforms_(std::move(other.activeUniforms_)) {
- other.programId_ = 0;
+ other.program_ = ShaderHandle::Invalid;
}
Shader& Shader::operator=(Shader&& other) noexcept {
if (this != &other) {
- if (programId_ != 0 && device_) {
- device_->deleteProgram(programId_);
+ if (program_ != ShaderHandle::Invalid && device_) {
+ device_->deleteProgram(program_);
}
device_ = other.device_;
- programId_ = other.programId_;
+ program_ = other.program_;
uniformCache_ = std::move(other.uniformCache_);
attribCache_ = std::move(other.attribCache_);
activeUniforms_ = std::move(other.activeUniforms_);
- other.programId_ = 0;
+ other.program_ = ShaderHandle::Invalid;
}
return *this;
}
@@ -120,11 +120,11 @@ Unique<Shader> Shader::createFromFile(GfxDevice& device,
void Shader::bind() const {
// Direct program bind for setup-time use (e.g. seeding a sampler uniform). Per-frame
// rendering binds programs through GfxDevice::setPipeline, not here.
- if (device_) device_->useProgram(programId_);
+ if (device_) device_->useProgram(program_);
}
void Shader::unbind() const {
- if (device_) device_->useProgram(0);
+ if (device_) device_->useProgram(ShaderHandle::Invalid);
}
bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrc,
@@ -138,9 +138,9 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
}
GfxShaderStage stage = GfxShaderStage::None;
- programId_ = device_->createProgram(vertexSrc.c_str(), fragmentSrc.c_str(),
- binds.data(), static_cast<u32>(binds.size()),
- outLog, &stage);
+ program_ = device_->createProgram(vertexSrc.c_str(), fragmentSrc.c_str(),
+ binds.data(), static_cast<u32>(binds.size()),
+ outLog, &stage);
if (outFailedStage) {
switch (stage) {
@@ -151,7 +151,7 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
}
}
- if (programId_ == 0) {
+ if (program_ == ShaderHandle::Invalid) {
return false;
}
@@ -160,33 +160,33 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
// Link the per-frame constants block to its shared binding point, so the program
// reads u_projection from the FrameConstants UBO with no loose uniform upload.
// Programs without the block (custom/user shaders) simply skip this.
- u32 frameBlock = device_->getUniformBlockIndex(programId_, FRAME_CONSTANTS_BLOCK);
+ u32 frameBlock = device_->getUniformBlockIndex(program_, FRAME_CONSTANTS_BLOCK);
if (frameBlock != GFX_INVALID_UNIFORM_BLOCK) {
- device_->uniformBlockBinding(programId_, frameBlock, FRAME_CONSTANTS_BINDING);
+ device_->uniformBlockBinding(program_, frameBlock, FRAME_CONSTANTS_BINDING);
}
// Same for the per-material constants block (ShaderParser auto-generates it for shaders
// authored with #pragma param); the render path binds each material's UBO here per draw.
- u32 materialBlock = device_->getUniformBlockIndex(programId_, MATERIAL_CONSTANTS_BLOCK);
+ u32 materialBlock = device_->getUniformBlockIndex(program_, MATERIAL_CONSTANTS_BLOCK);
if (materialBlock != GFX_INVALID_UNIFORM_BLOCK) {
- device_->uniformBlockBinding(programId_, materialBlock, MATERIAL_CONSTANTS_BINDING);
+ device_->uniformBlockBinding(program_, materialBlock, MATERIAL_CONSTANTS_BINDING);
}
// Same for the per-frame 2D light block (ShaderParser injects it for Lit2D-domain shaders);
// the render path uploads + binds the shared LightConstants UBO here once per frame.
- u32 lightBlock = device_->getUniformBlockIndex(programId_, LIGHT_CONSTANTS_BLOCK);
+ u32 lightBlock = device_->getUniformBlockIndex(program_, LIGHT_CONSTANTS_BLOCK);
if (lightBlock != GFX_INVALID_UNIFORM_BLOCK) {
- device_->uniformBlockBinding(programId_, lightBlock, LIGHT_CONSTANTS_BINDING);
+ device_->uniformBlockBinding(program_, lightBlock, LIGHT_CONSTANTS_BINDING);
}
// Same for the injected frame clock (u_time).
- u32 timeBlock = device_->getUniformBlockIndex(programId_, TIME_CONSTANTS_BLOCK);
+ u32 timeBlock = device_->getUniformBlockIndex(program_, TIME_CONSTANTS_BLOCK);
if (timeBlock != GFX_INVALID_UNIFORM_BLOCK) {
- device_->uniformBlockBinding(programId_, timeBlock, TIME_CONSTANTS_BINDING);
+ device_->uniformBlockBinding(program_, timeBlock, TIME_CONSTANTS_BINDING);
}
- ES_LOG_DEBUG("Shader compiled successfully (program ID: {}, active uniforms: {})",
- programId_, activeUniforms_.size());
+ ES_LOG_DEBUG("Shader compiled successfully (program handle: {}, active uniforms: {})",
+ static_cast<u32>(program_), activeUniforms_.size());
return true;
}
@@ -205,16 +205,16 @@ ShaderCompileOutcome Shader::createEx(GfxDevice& device,
}
void Shader::reflectActiveUniforms() {
- activeUniforms_ = device_->getActiveUniforms(programId_);
+ activeUniforms_ = device_->getActiveUniforms(program_);
}
i32 Shader::cacheUniformLocation(const std::string& name, bool warnOnMiss) const {
auto [it, inserted] = uniformCache_.emplace(name, -1);
if (inserted) {
- it->second = device_->getUniformLocation(programId_, name.c_str());
+ it->second = device_->getUniformLocation(program_, name.c_str());
if (it->second < 0 && warnOnMiss) {
ES_LOG_WARN("Shader {}: uniform '{}' not found (typo or optimized out)",
- programId_, name);
+ static_cast<u32>(program_), name);
}
}
return it->second;
@@ -287,7 +287,7 @@ void Shader::setUniform(i32 location, const glm::mat4& value) const {
i32 Shader::getAttribLocation(const std::string& name) const {
auto [it, inserted] = attribCache_.emplace(name, -1);
if (inserted) {
- it->second = device_->getAttribLocation(programId_, name.c_str());
+ it->second = device_->getAttribLocation(program_, name.c_str());
}
return it->second;
}
diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hpp
index 677b1904e..d7897a9f9 100644
--- a/src/esengine/renderer/Shader.hpp
+++ b/src/esengine/renderer/Shader.hpp
@@ -206,13 +206,13 @@ public:
* @brief Checks if the shader compiled and linked successfully
* @return True if the shader is usable
*/
- bool isValid() const { return programId_ != 0; }
+ bool isValid() const { return program_ != ShaderHandle::Invalid; }
- /**
- * @brief Gets the OpenGL program ID
- * @return GPU program handle
- */
- u32 getProgramId() const { return programId_; }
+ /** @brief Gets the device program handle */
+ ShaderHandle handle() const { return program_; }
+
+ /** @brief Gets the program handle's raw value, for command payloads and sort keys */
+ u32 getProgramId() const { return static_cast<u32>(program_); }
private:
/**
@@ -232,7 +232,7 @@ private:
i32 cacheUniformLocation(const std::string& name, bool warnOnMiss) const;
GfxDevice* device_ = nullptr; ///< Set by the create* factories; all GL goes through it.
- u32 programId_ = 0;
+ ShaderHandle program_ = ShaderHandle::Invalid;
/** @brief Cached uniform locations (mutable for const uniform setters) */
mutable std::unordered_map<std::string, i32> uniformCache_;
diff --git a/src/esengine/renderer/Texture.cpp b/src/esengine/renderer/Texture.cpp
index 3a00053b1..d2c667842 100644
--- a/src/esengine/renderer/Texture.cpp
+++ b/src/esengine/renderer/Texture.cpp
@@ -40,19 +40,19 @@ u32 bytesPerPixel(TextureFormat format) {
} // namespace
Texture::~Texture() {
- if (textureId_ != 0 && device_ && owns_) {
- device_->deleteTexture(textureId_);
+ if (handle_ != TextureHandle::Invalid && device_ && owns_) {
+ device_->deleteTexture(handle_);
}
}
Texture::Texture(Texture&& other) noexcept
: device_(other.device_)
- , textureId_(other.textureId_)
+ , handle_(other.handle_)
, width_(other.width_)
, height_(other.height_)
, format_(other.format_)
, owns_(other.owns_) {
- other.textureId_ = 0;
+ other.handle_ = TextureHandle::Invalid;
other.width_ = 0;
other.height_ = 0;
other.format_ = TextureFormat::None;
@@ -60,16 +60,16 @@ Texture::Texture(Texture&& other) noexcept
Texture& Texture::operator=(Texture&& other) noexcept {
if (this != &other) {
- if (textureId_ != 0 && device_ && owns_) {
- device_->deleteTexture(textureId_);
+ if (handle_ != TextureHandle::Invalid && device_ && owns_) {
+ device_->deleteTexture(handle_);
}
device_ = other.device_;
- textureId_ = other.textureId_;
+ handle_ = other.handle_;
width_ = other.width_;
height_ = other.height_;
format_ = other.format_;
owns_ = other.owns_;
- other.textureId_ = 0;
+ other.handle_ = TextureHandle::Invalid;
other.width_ = 0;
other.height_ = 0;
other.format_ = TextureFormat::None;
@@ -80,7 +80,7 @@ Texture& Texture::operator=(Texture&& other) noexcept {
Unique<Texture> Texture::create(GfxDevice& device, const TextureSpecification& spec) {
auto texture = makeUnique<Texture>();
texture->device_ = &device;
- if (!texture->initialize(spec)) {
+ if (!texture->initialize(spec, nullptr, false)) {
return nullptr;
}
return texture;
@@ -110,22 +110,22 @@ Unique<Texture> Texture::createRaw(GfxDevice& device, u32 width, u32 height, con
auto texture = makeUnique<Texture>();
texture->device_ = &device;
- if (!texture->initialize(spec)) {
+ if (!texture->initialize(spec, data, flipY)) {
return nullptr;
}
-
- if (data) {
- texture->setDataRaw(data, width * height * bytesPerPixel(format), flipY);
- }
-
return texture;
}
Unique<Texture> Texture::createFromExternalId(GfxDevice& device, u32 glTextureId, u32 width, u32 height,
TextureFormat format) {
+ TextureDesc desc;
+ desc.width = width;
+ desc.height = height;
+ desc.format = toGfxPixelFormat(format);
+
auto texture = makeUnique<Texture>();
texture->device_ = &device;
- texture->textureId_ = glTextureId;
+ texture->handle_ = device.importExternalTexture(glTextureId, desc);
texture->width_ = width;
texture->height_ = height;
texture->format_ = format;
@@ -133,35 +133,40 @@ Unique<Texture> Texture::createFromExternalId(GfxDevice& device, u32 glTextureId
return texture;
}
-bool Texture::initialize(const TextureSpecification& spec) {
+bool Texture::initialize(const TextureSpecification& spec, const void* pixels, bool flipY) {
width_ = spec.width;
height_ = spec.height;
format_ = spec.format;
- textureId_ = device_->createTexture();
- if (textureId_ == 0) {
+ TextureDesc desc;
+ desc.width = spec.width;
+ desc.height = spec.height;
+ desc.format = toGfxPixelFormat(spec.format);
+ desc.minFilter = spec.minFilter;
+ desc.magFilter = spec.magFilter;
+ desc.wrapS = spec.wrapS;
+ desc.wrapT = spec.wrapT;
+ desc.mipmaps = spec.generateMips;
+ desc.flipY = flipY;
+
+ handle_ = device_->createTexture(desc, pixels);
+ if (handle_ == TextureHandle::Invalid) {
// Out of memory or a lost context: surface the failure instead of
- // returning a "valid" texture wrapping id 0 (which renders as black).
+ // returning a "valid" texture wrapping the null handle (renders as black).
ES_LOG_ERROR("Texture::initialize: createTexture failed for {}x{}", width_, height_);
return false;
}
- device_->texImage2D(textureId_, width_, height_, toGfxPixelFormat(spec.format), nullptr);
- device_->setTextureParams(textureId_, spec.minFilter, spec.magFilter, spec.wrapS, spec.wrapT);
-
- if (spec.generateMips) {
- device_->generateMipmaps(textureId_);
- }
- ES_LOG_DEBUG("Created texture {}x{} (ID: {})", width_, height_, textureId_);
+ ES_LOG_DEBUG("Created texture {}x{} (handle: {})", width_, height_, static_cast<u32>(handle_));
return true;
}
void Texture::bind(u32 slot) const {
- if (device_) device_->bindTexture(slot, textureId_);
+ if (device_) device_->bindTexture(slot, handle_);
}
void Texture::unbind() const {
- if (device_) device_->bindTexture(0, 0);
+ if (device_) device_->bindTexture(0, TextureHandle::Invalid);
}
void Texture::setData(std::span<const u8> pixels) {
@@ -176,7 +181,7 @@ void Texture::setData(const std::vector<u8>& pixels) {
void Texture::setDataRaw(const void* data, u32 sizeBytes, bool flipY) {
// Always-on size guard (independent of ES_ASSERT, which is stripped in release).
- // texSubImage2D below reads width_*height_*bpp bytes from `data`; a smaller
+ // updateTexture below reads width_*height_*bpp bytes from `data`; a smaller
// buffer would cause an out-of-bounds read of WASM linear memory.
u32 expectedSize = width_ * height_ * bytesPerPixel(format_);
if (sizeBytes < expectedSize) {
@@ -185,21 +190,19 @@ void Texture::setDataRaw(const void* data, u32 sizeBytes, bool flipY) {
return;
}
- if (flipY) device_->setUnpackFlipY(true);
- device_->texSubImage2D(textureId_, 0, 0, width_, height_, toGfxPixelFormat(format_), data);
- if (flipY) device_->setUnpackFlipY(false);
+ device_->updateTexture(handle_, 0, 0, width_, height_, data, flipY);
}
void Texture::updateSubRegion(u32 xoffset, u32 yoffset, u32 width, u32 height,
const void* data, u32 sizeBytes, bool flipY) {
- // The sub-rect must lie fully inside the texture; otherwise texSubImage2D
- // writes outside the allocated GL texture (GL error / undefined).
+ // The sub-rect must lie fully inside the texture; otherwise the upload
+ // writes outside the allocated texture storage (GL error / undefined).
if (xoffset + width > width_ || yoffset + height > height_) {
ES_LOG_ERROR("Texture::updateSubRegion: rect {}x{} at ({},{}) exceeds texture {}x{}; skipping",
width, height, xoffset, yoffset, width_, height_);
return;
}
- // Always-on size guard (ES_ASSERT is stripped in release): texSubImage2D
+ // Always-on size guard (ES_ASSERT is stripped in release): updateTexture
// reads width*height*bpp bytes from `data`; a smaller buffer would OOB-read
// WASM linear memory.
u32 expectedSize = width * height * bytesPerPixel(format_);
@@ -209,9 +212,8 @@ void Texture::updateSubRegion(u32 xoffset, u32 yoffset, u32 width, u32 height,
return;
}
- if (flipY) device_->setUnpackFlipY(true);
- device_->texSubImage2D(textureId_, xoffset, yoffset, width, height, toGfxPixelFormat(format_), data);
- if (flipY) device_->setUnpackFlipY(false);
+ device_->updateTexture(handle_, static_cast<i32>(xoffset), static_cast<i32>(yoffset),
+ width, height, data, flipY);
}
} // namespace esengine
diff --git a/src/esengine/renderer/Texture.hpp b/src/esengine/renderer/Texture.hpp
index b4bb4e238..5341092a7 100644
--- a/src/esengine/renderer/Texture.hpp
+++ b/src/esengine/renderer/Texture.hpp
@@ -20,6 +20,7 @@
// Project includes
#include "../core/Types.hpp"
+#include "GfxEnums.hpp"
// Standard library
#include <span>
@@ -34,6 +35,9 @@ class GfxDevice;
// Texture Enums
// =============================================================================
+// TextureFilter / TextureWrap live in GfxEnums.hpp with the other backend-agnostic
+// sampling enums; TextureFormat below is this wrapper's user-facing format set.
+
/**
* @brief Texture pixel format
*/
@@ -44,28 +48,6 @@ enum class TextureFormat {
Depth24 ///< Depth buffer format (24 bits)
};
-/**
- * @brief Texture filtering mode
- *
- * @details Controls how texels are sampled when the texture is
- * scaled up or down.
- */
-enum class TextureFilter {
- Nearest, ///< No interpolation (pixelated look)
- Linear ///< Bilinear interpolation (smooth)
-};
-
-/**
- * @brief Texture wrapping mode
- *
- * @details Controls behavior when sampling outside [0,1] UV range.
- */
-enum class TextureWrap {
- Repeat, ///< Tile the texture
- ClampToEdge, ///< Clamp to edge pixels
- MirroredRepeat ///< Tile with mirroring
-};
-
// =============================================================================
// Texture Specification
// =============================================================================
@@ -216,8 +198,11 @@ public:
// Properties
// =========================================================================
- /** @brief Gets the OpenGL texture ID */
- u32 getId() const { return textureId_; }
+ /** @brief Gets the device texture handle */
+ TextureHandle handle() const { return handle_; }
+
+ /** @brief Gets the texture handle's raw value, for command payloads and the WASM boundary */
+ u32 getId() const { return static_cast<u32>(handle_); }
/** @brief Gets the texture width in pixels */
u32 getWidth() const { return width_; }
@@ -234,7 +219,7 @@ public:
* @return True if same GPU texture
*/
bool operator==(const Texture& other) const {
- return textureId_ == other.textureId_;
+ return handle_ == other.handle_;
}
// =========================================================================
@@ -275,12 +260,14 @@ private:
/**
* @brief Initializes the texture on GPU
* @param spec Texture parameters
+ * @param pixels Optional initial pixel data
+ * @param flipY Vertical flip on the initial upload
* @return True on success
*/
- bool initialize(const TextureSpecification& spec);
+ bool initialize(const TextureSpecification& spec, const void* pixels, bool flipY);
GfxDevice* device_ = nullptr; ///< Set by the create* factories; all GL goes through it.
- u32 textureId_ = 0;
+ TextureHandle handle_ = TextureHandle::Invalid;
u32 width_ = 0;
u32 height_ = 0;
TextureFormat format_ = TextureFormat::None;
diff --git a/src/esengine/renderer/TransientBufferPool.cpp b/src/esengine/renderer/TransientBufferPool.cpp
index bda7dad85..dfb2d732d 100644
--- a/src/esengine/renderer/TransientBufferPool.cpp
+++ b/src/esengine/renderer/TransientBufferPool.cpp
@@ -29,9 +29,9 @@ void TransientBufferPool::shutdown() {
for (auto& s : streams_) {
if (s.vao) { device_.deleteVertexArray(s.vao); s.vao = 0; }
- if (s.vbo) { device_.deleteBuffer(s.vbo); s.vbo = 0; }
- if (s.ebo) { device_.deleteBuffer(s.ebo); s.ebo = 0; }
- if (s.quad_vbo) { device_.deleteBuffer(s.quad_vbo); s.quad_vbo = 0; }
+ if (s.vbo != BufferHandle::Invalid) { device_.deleteBuffer(s.vbo); s.vbo = BufferHandle::Invalid; }
+ if (s.ebo != BufferHandle::Invalid) { device_.deleteBuffer(s.ebo); s.ebo = BufferHandle::Invalid; }
+ if (s.quad_vbo != BufferHandle::Invalid) { device_.deleteBuffer(s.quad_vbo); s.quad_vbo = BufferHandle::Invalid; }
s.vertex_staging.clear();
s.index_staging.clear();
s.vertex_write_pos = 0;
@@ -100,41 +100,31 @@ u32 TransientBufferPool::appendIndices(LayoutId layout, const u32* data, u32 cou
}
void TransientBufferPool::upload() {
+ // Growth goes through resizeBuffer, which keeps the handle stable — the stream's
+ // VAO association survives. Index uploads are safe against VAO capture because the
+ // device detaches the bound VAO before touching the element-array target.
for (auto& s : streams_) {
- if (!s.vbo) continue;
+ if (s.vbo == BufferHandle::Invalid) continue;
if (s.vertex_write_pos == 0 && s.index_write_pos == 0) continue;
- // Bind THIS stream's own VAO before touching its EBO below. GL_ELEMENT_ARRAY_BUFFER
- // is VAO state, so binding/growing the index buffer mutates the currently-bound VAO;
- // without this, upload() edits whichever VAO a prior draw left bound and rebinds its
- // element buffer to this stream's EBO. That VAO's next draw then runs against a
- // wrong-sized EBO → "glDrawElements: insufficient buffer size" on strict GL / real
- // GPUs (SwiftShader silently tolerates it). The VBO (GL_ARRAY_BUFFER) is global state,
- // so it's unaffected either way — but scoping everything to the stream's VAO keeps the
- // per-stream upload self-contained.
- device_.bindVertexArray(s.vao);
-
- device_.bindVertexBuffer(s.vbo);
if (s.vertex_write_pos > s.vbo_capacity) {
s.vbo_capacity = s.vertex_write_pos;
- device_.bufferData(GfxBufferTarget::Vertex, s.vertex_staging.data(), s.vbo_capacity, true);
+ device_.resizeBuffer(s.vbo, s.vbo_capacity, s.vertex_staging.data());
} else if (s.vertex_write_pos > 0) {
- device_.bufferSubData(GfxBufferTarget::Vertex, 0, s.vertex_staging.data(), s.vertex_write_pos);
+ device_.updateBuffer(s.vbo, 0, s.vertex_staging.data(), s.vertex_write_pos);
}
- device_.bindIndexBuffer(s.ebo);
u32 eboBytes = s.index_write_pos * sizeof(u32);
u32 eboCapBytes = s.ebo_capacity * sizeof(u32);
if (eboBytes > eboCapBytes) {
s.ebo_capacity = s.index_write_pos;
- device_.bufferData(GfxBufferTarget::Index, s.index_staging.data(),
- s.ebo_capacity * sizeof(u32), true);
+ device_.resizeBuffer(s.ebo, static_cast<u32>(s.ebo_capacity * sizeof(u32)),
+ s.index_staging.data());
} else if (eboBytes > 0) {
- device_.bufferSubData(GfxBufferTarget::Index, 0, s.index_staging.data(), eboBytes);
+ device_.updateBuffer(s.ebo, 0, s.index_staging.data(), eboBytes);
}
}
- // Leave a neutral VAO bound so execute()'s bindLayout starts from a known state and no
- // stream VAO is left mid-upload.
+ // Leave a neutral VAO bound so execute()'s bindLayout starts from a known state.
device_.bindVertexArray(0);
}
@@ -169,11 +159,11 @@ u32 TransientBufferPool::indicesUsed(LayoutId layout) const {
return stream(layout).index_write_pos;
}
-u32 TransientBufferPool::vboId(LayoutId layout) const {
+BufferHandle TransientBufferPool::vertexBuffer(LayoutId layout) const {
return stream(layout).vbo;
}
-u32 TransientBufferPool::eboId(LayoutId layout) const {
+BufferHandle TransientBufferPool::indexBuffer(LayoutId layout) const {
return stream(layout).ebo;
}
@@ -184,9 +174,7 @@ void TransientBufferPool::setupStream(LayoutId layout) {
// Per-instance (per-particle) stream: dynamic, streamed each frame.
s.vertex_staging.resize(initial_vertex_bytes_);
s.vbo_capacity = initial_vertex_bytes_;
- s.vbo = device_.createBuffer();
- device_.bindVertexBuffer(s.vbo);
- device_.bufferData(GfxBufferTarget::Vertex, nullptr, s.vbo_capacity, true);
+ s.vbo = device_.createBuffer({GfxBufferUsage::Vertex, s.vbo_capacity, /*dynamic=*/true}, nullptr);
// Static unit quad (pos + uv) and its 6 indices, uploaded once. UVs are laid out
// so the instance shader's a_texCoord*uvScale+uvOffset reproduces the prior
@@ -199,12 +187,10 @@ void TransientBufferPool::setupStream(LayoutId layout) {
{ -0.5f, 0.5f, 0.0f, 0.0f },
};
const u32 quadIdx[6] = { 0, 1, 2, 2, 3, 0 };
- s.quad_vbo = device_.createBuffer();
- device_.bindVertexBuffer(s.quad_vbo);
- device_.bufferData(GfxBufferTarget::Vertex, quad, sizeof(quad), false);
- s.ebo = device_.createBuffer();
- device_.bindIndexBuffer(s.ebo);
- device_.bufferData(GfxBufferTarget::Index, quadIdx, sizeof(quadIdx), false);
+ s.quad_vbo = device_.createBuffer(
+ {GfxBufferUsage::Vertex, static_cast<u32>(sizeof(quad)), /*dynamic=*/false}, quad);
+ s.ebo = device_.createBuffer(
+ {GfxBufferUsage::Index, static_cast<u32>(sizeof(quadIdx)), /*dynamic=*/false}, quadIdx);
s.vao = device_.createVertexArray();
device_.bindVertexArray(s.vao);
@@ -228,8 +214,8 @@ void TransientBufferPool::setupStream(LayoutId layout) {
device_.enableVertexAttrib(7); device_.vertexAttribPointer(7, 2, GfxDataType::Float, false, IS, 32); device_.vertexAttribDivisor(7, 1);
device_.bindVertexArray(0);
- device_.bindVertexBuffer(0);
- device_.bindIndexBuffer(0);
+ device_.bindVertexBuffer(BufferHandle::Invalid);
+ device_.bindIndexBuffer(BufferHandle::Invalid);
return;
}
@@ -238,14 +224,9 @@ void TransientBufferPool::setupStream(LayoutId layout) {
s.vbo_capacity = initial_vertex_bytes_;
s.ebo_capacity = initial_index_count_;
- s.vbo = device_.createBuffer();
- s.ebo = device_.createBuffer();
-
- device_.bindVertexBuffer(s.vbo);
- device_.bufferData(GfxBufferTarget::Vertex, nullptr, s.vbo_capacity, true);
-
- device_.bindIndexBuffer(s.ebo);
- device_.bufferData(GfxBufferTarget::Index, nullptr, s.ebo_capacity * sizeof(u32), true);
+ s.vbo = device_.createBuffer({GfxBufferUsage::Vertex, s.vbo_capacity, /*dynamic=*/true}, nullptr);
+ s.ebo = device_.createBuffer(
+ {GfxBufferUsage::Index, static_cast<u32>(s.ebo_capacity * sizeof(u32)), /*dynamic=*/true}, nullptr);
s.vao = device_.createVertexArray();
device_.bindVertexArray(s.vao);
@@ -292,8 +273,8 @@ void TransientBufferPool::setupStream(LayoutId layout) {
}
device_.bindVertexArray(0);
- device_.bindVertexBuffer(0);
- device_.bindIndexBuffer(0);
+ device_.bindVertexBuffer(BufferHandle::Invalid);
+ device_.bindIndexBuffer(BufferHandle::Invalid);
}
void TransientBufferPool::growVertexStaging(Stream& s, u32 requiredBytes) {
diff --git a/src/esengine/renderer/TransientBufferPool.hpp b/src/esengine/renderer/TransientBufferPool.hpp
index fcb81f844..66287dc7d 100644
--- a/src/esengine/renderer/TransientBufferPool.hpp
+++ b/src/esengine/renderer/TransientBufferPool.hpp
@@ -61,15 +61,15 @@ public:
u8* vertexData(LayoutId layout);
u32 vertexBytesUsed(LayoutId layout) const;
u32 indicesUsed(LayoutId layout) const;
- u32 vboId(LayoutId layout) const;
- u32 eboId(LayoutId layout) const;
+ BufferHandle vertexBuffer(LayoutId layout) const;
+ BufferHandle indexBuffer(LayoutId layout) const;
private:
struct Stream {
- u32 vbo = 0; // for ParticleInstance this is the per-instance (streamed) buffer
- u32 ebo = 0;
+ BufferHandle vbo = BufferHandle::Invalid; // for ParticleInstance: the per-instance (streamed) buffer
+ BufferHandle ebo = BufferHandle::Invalid;
u32 vao = 0;
- u32 quad_vbo = 0; // ParticleInstance only: static unit-quad geometry (divisor 0)
+ BufferHandle quad_vbo = BufferHandle::Invalid; // ParticleInstance only: static unit-quad geometry (divisor 0)
std::vector<u8> vertex_staging;
std::vector<u32> index_staging; // 32-bit indices: a single Batch stream can exceed 65535 vertices
u32 vertex_write_pos = 0;
diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hpp
index 432506c3c..d4ef8471e 100644
--- a/tests/renderer/MockGfxDevice.hpp
+++ b/tests/renderer/MockGfxDevice.hpp
@@ -1,4 +1,4 @@
-// Shared test double for the renderer GPU abstraction (RC5-GfxDevice).
+// Shared test double for the renderer GPU abstraction (GfxDevice).
//
// Records the device calls the renderer harnesses assert on; every other method
// is a no-op stub. Implementing the full GfxDevice contract here also proves the
@@ -25,35 +25,49 @@ struct MockGfxDevice final : GfxDevice {
int setUniform4fCalls = 0;
int getActiveUniformsCalls = 0;
int createTextureCalls = 0;
+ int createCompressedTextureCalls = 0;
+ int importExternalTextureCalls = 0;
int deleteTextureCalls = 0;
- int texImage2DCalls = 0;
- int texSubImage2DCalls = 0;
- int compressedTexImage2DCalls = 0;
+ int updateTextureCalls = 0;
int setTextureParamsCalls = 0;
int generateMipmapsCalls = 0;
- u32 nextTextureId = 100;
- bool createTextureFails = false; // toggle to exercise the OOM / lost-context path (createTexture -> 0)
- u32 lastDeletedTexture = 0;
- GfxCompressedFormat lastCompressedFormat = GfxCompressedFormat::ETC2_RGBA8;
- u32 lastCompressedByteLength = 0;
- bool compressedSupported = true; // toggle to exercise the RGBA8 fallback path
int createFramebufferCalls = 0;
int deleteFramebufferCalls = 0;
- int framebufferTexture2DCalls = 0;
- u32 nextFramebufferId = 500;
int createBufferCalls = 0;
int deleteBufferCalls = 0;
- int bufferDataCalls = 0;
- int bufferSubDataCalls = 0;
+ int updateBufferCalls = 0;
+ int resizeBufferCalls = 0;
+ int setUniformBufferCalls = 0;
int createVertexArrayCalls = 0;
int deleteVertexArrayCalls = 0;
int enableVertexAttribCalls = 0;
int vertexAttribPointerCalls = 0;
+ int setPipelineCalls = 0;
+
+ u32 nextTextureId = 100;
u32 nextBufferId = 200;
+ u32 nextFramebufferId = 500;
u32 nextVaoId = 800;
+ u32 nextPipelineId = 0;
+
+ bool createTextureFails = false; // toggle to exercise the OOM / lost-context path (-> Invalid)
+ bool compressedSupported = true; // toggle to exercise the RGBA8 fallback path
+
// last args
- u32 lastProgram = 0, lastVao = 0, lastVbo = 0, lastIbo = 0, lastFbo = 0;
+ ShaderHandle lastProgram = ShaderHandle::Invalid;
+ u32 lastVao = 0;
+ BufferHandle lastVbo = BufferHandle::Invalid;
+ BufferHandle lastIbo = BufferHandle::Invalid;
+ FramebufferHandle lastFbo = FramebufferHandle::Default;
i32 lastUniform1iLoc = -999, lastUniform1iVal = 0;
+ BufferDesc lastBufferDesc{};
+ bool lastCreateBufferHadData = false;
+ TextureDesc lastTextureDesc{};
+ bool lastCreateTextureHadPixels = false;
+ TextureHandle lastDeletedTexture = TextureHandle::Invalid;
+ GfxCompressedFormat lastCompressedFormat = GfxCompressedFormat::ETC2_RGBA8;
+ u32 lastCompressedByteLength = 0;
+ FramebufferDesc lastFramebufferDesc{};
void init() override {}
void shutdown() override {}
@@ -81,18 +95,57 @@ struct MockGfxDevice final : GfxDevice {
void setCulling(bool) override {}
void setCullFace(bool) override {}
- void bindTexture(u32, u32 textureId) override { ++bindTextureCalls; (void)textureId; }
+ BufferHandle createBuffer(const BufferDesc& desc, const void* initialData) override {
+ ++createBufferCalls;
+ lastBufferDesc = desc;
+ lastCreateBufferHadData = initialData != nullptr;
+ return BufferHandle{nextBufferId++};
+ }
+ void deleteBuffer(BufferHandle) override { ++deleteBufferCalls; }
+ void updateBuffer(BufferHandle, u32, const void*, u32) override { ++updateBufferCalls; }
+ void resizeBuffer(BufferHandle, u32, const void*) override { ++resizeBufferCalls; }
+ void setUniformBuffer(u32, BufferHandle) override { ++setUniformBufferCalls; }
+ void bindVertexBuffer(BufferHandle buffer) override { ++bindVertexBufferCalls; lastVbo = buffer; }
+ void bindIndexBuffer(BufferHandle buffer) override { ++bindIndexBufferCalls; lastIbo = buffer; }
+
+ TextureHandle createTexture(const TextureDesc& desc, const void* pixels) override {
+ ++createTextureCalls;
+ lastTextureDesc = desc;
+ lastCreateTextureHadPixels = pixels != nullptr;
+ return createTextureFails ? TextureHandle::Invalid : TextureHandle{nextTextureId++};
+ }
+ TextureHandle createCompressedTexture(const TextureDesc& desc, GfxCompressedFormat format,
+ const void*, u32 byteLength) override {
+ ++createCompressedTextureCalls;
+ lastTextureDesc = desc;
+ lastCompressedFormat = format;
+ lastCompressedByteLength = byteLength;
+ return TextureHandle{nextTextureId++};
+ }
+ TextureHandle importExternalTexture(u32 nativeId, const TextureDesc& desc) override {
+ ++importExternalTextureCalls;
+ lastTextureDesc = desc;
+ return TextureHandle{nativeId};
+ }
+ void deleteTexture(TextureHandle texture) override { ++deleteTextureCalls; lastDeletedTexture = texture; }
+ void updateTexture(TextureHandle, i32, i32, u32, u32, const void*, bool) override { ++updateTextureCalls; }
+ void setTextureParams(TextureHandle, TextureFilter, TextureFilter, TextureWrap, TextureWrap) override {
+ ++setTextureParamsCalls;
+ }
+ void generateMipmaps(TextureHandle) override { ++generateMipmapsCalls; }
+ void bindTexture(u32, TextureHandle) override { ++bindTextureCalls; }
+ bool supportsCompressedFormat(GfxCompressedFormat) override { return compressedSupported; }
- u32 createProgram(const char*, const char*, const GfxAttribBinding*, u32,
- std::string*, GfxShaderStage* stage) override {
+ ShaderHandle createProgram(const char*, const char*, const GfxAttribBinding*, u32,
+ std::string*, GfxShaderStage* stage) override {
++createProgramCalls;
if (stage) *stage = GfxShaderStage::None;
- return 1; // pretend link succeeds, program id 1
+ return ShaderHandle{1}; // pretend link succeeds, program 1
}
- void deleteProgram(u32) override { ++deleteProgramCalls; }
- void useProgram(u32 programId) override { ++useProgramCalls; lastProgram = programId; }
- i32 getUniformLocation(u32, const char*) override { return 0; }
- i32 getAttribLocation(u32, const char*) override { return 0; }
+ void deleteProgram(ShaderHandle) override { ++deleteProgramCalls; }
+ void useProgram(ShaderHandle program) override { ++useProgramCalls; lastProgram = program; }
+ i32 getUniformLocation(ShaderHandle, const char*) override { return 0; }
+ i32 getAttribLocation(ShaderHandle, const char*) override { return 0; }
void setUniform1i(i32 loc, i32 v) override { ++setUniform1iCalls; lastUniform1iLoc = loc; lastUniform1iVal = v; }
void setUniform1f(i32, f32) override {}
void setUniform2f(i32, f32, f32) override {}
@@ -100,22 +153,11 @@ struct MockGfxDevice final : GfxDevice {
void setUniform4f(i32, f32, f32, f32, f32) override { ++setUniform4fCalls; }
void setUniformMat3(i32, const f32*) override {}
void setUniformMat4(i32, const f32*) override {}
- std::vector<GfxUniformInfo> getActiveUniforms(u32) override { ++getActiveUniformsCalls; return {}; }
-
- u32 createBuffer() override { ++createBufferCalls; return nextBufferId++; }
- void deleteBuffer(u32) override { ++deleteBufferCalls; }
- void bindVertexBuffer(u32 bufferId) override { ++bindVertexBufferCalls; lastVbo = bufferId; }
- void bindIndexBuffer(u32 bufferId) override { ++bindIndexBufferCalls; lastIbo = bufferId; }
- void bufferData(GfxBufferTarget, const void*, u32, bool) override { ++bufferDataCalls; }
- void bufferSubData(GfxBufferTarget, u32, const void*, u32) override { ++bufferSubDataCalls; }
+ std::vector<GfxUniformInfo> getActiveUniforms(ShaderHandle) override { ++getActiveUniformsCalls; return {}; }
- void bindUniformBuffer(u32) override {}
- void bindBufferBase(u32, u32) override {}
- u32 getUniformBlockIndex(u32, const char*) override { return GFX_INVALID_UNIFORM_BLOCK; }
- void uniformBlockBinding(u32, u32, u32) override {}
+ u32 getUniformBlockIndex(ShaderHandle, const char*) override { return GFX_INVALID_UNIFORM_BLOCK; }
+ void uniformBlockBinding(ShaderHandle, u32, u32) override {}
- u32 nextPipelineId = 0;
- int setPipelineCalls = 0;
PipelineHandle createPipeline(const PipelineDesc&) override { return static_cast<PipelineHandle>(++nextPipelineId); }
void setPipeline(PipelineHandle) override { ++setPipelineCalls; }
void setStencilReference(i32) override {}
@@ -132,33 +174,26 @@ struct MockGfxDevice final : GfxDevice {
void drawArrays(u32, u32) override {}
void drawElementsInstanced(u32, GfxDataType, u32, u32) override {}
- u32 createTexture() override { ++createTextureCalls; return createTextureFails ? 0u : nextTextureId++; }
- void deleteTexture(u32 id) override { ++deleteTextureCalls; lastDeletedTexture = id; }
- void texImage2D(u32, u32, u32, GfxPixelFormat, const void*) override { ++texImage2DCalls; }
- void texSubImage2D(u32, i32, i32, u32, u32, GfxPixelFormat, const void*) override { ++texSubImage2DCalls; }
- void compressedTexImage2D(u32, u32, u32, GfxCompressedFormat format, const void*, u32 byteLength) override {
- ++compressedTexImage2DCalls;
- lastCompressedFormat = format;
- lastCompressedByteLength = byteLength;
+ FramebufferHandle createFramebuffer(const FramebufferDesc& desc) override {
+ ++createFramebufferCalls;
+ lastFramebufferDesc = desc;
+ return FramebufferHandle{nextFramebufferId++};
}
- void setTextureParams(u32, TextureFilter, TextureFilter, TextureWrap, TextureWrap) override { ++setTextureParamsCalls; }
- void generateMipmaps(u32) override { ++generateMipmapsCalls; }
- void pixelStorei(u32, i32) override {}
- void setUnpackFlipY(bool) override {}
-
- u32 createFramebuffer() override { ++createFramebufferCalls; return nextFramebufferId++; }
- void deleteFramebuffer(u32) override { ++deleteFramebufferCalls; }
- void bindFramebuffer(u32 fboId) override { ++bindFramebufferCalls; lastFbo = fboId; }
- void framebufferTexture2D(u32, GfxAttachment, u32) override { ++framebufferTexture2DCalls; }
- bool checkFramebufferStatus() override { return true; }
+ void deleteFramebuffer(FramebufferHandle) override { ++deleteFramebufferCalls; }
+ void bindFramebuffer(FramebufferHandle framebuffer) override { ++bindFramebufferCalls; lastFbo = framebuffer; }
void readPixels(i32, i32, u32, u32, GfxPixelFormat, void*) override {}
+ u32 createTimerQuery() override { return 0; } // report "no GPU timing" like a bare backend
+ void beginTimerQuery(u32) override {}
+ void endTimerQuery() override {}
+ bool timerDisjoint() override { return false; }
+ bool getTimerQueryNs(u32, u64*) override { return false; }
+
void setWireframe(bool) override {}
u32 getError() override { return 0; }
std::string getString(GfxStringName) override { return {}; }
i32 getInt(GfxIntParam) override { return 16; }
- bool supportsCompressedFormat(GfxCompressedFormat) override { return compressedSupported; }
};
} // namespace esengine
diff --git a/tests/renderer/test_buffer_device.cpp b/tests/renderer/test_buffer_device.cpp
index 44c9ebbe3..c4ccf4ee2 100644
--- a/tests/renderer/test_buffer_device.cpp
+++ b/tests/renderer/test_buffer_device.cpp
@@ -29,10 +29,12 @@ int main() {
auto vbo = VertexBuffer::createRaw(d, verts, sizeof(verts));
CHECK(vbo != nullptr, "VertexBuffer::createRaw returns a buffer");
CHECK(d.createBufferCalls == 1, "createRaw -> device.createBuffer");
- CHECK(d.bufferDataCalls == 1, "createRaw -> device.bufferData");
- CHECK(vbo->getId() == 200, "buffer id is device-assigned");
+ CHECK(d.lastCreateBufferHadData, "createRaw uploads its initial data at creation");
+ CHECK(d.lastBufferDesc.usage == GfxBufferUsage::Vertex, "createRaw declares Vertex usage");
+ CHECK(d.lastBufferDesc.size == sizeof(verts), "createRaw sizes the buffer to the data");
+ CHECK(vbo->handle() == BufferHandle{200}, "buffer handle is device-assigned");
vbo->setDataRaw(verts, sizeof(verts));
- CHECK(d.bufferSubDataCalls == 1, "setDataRaw -> device.bufferSubData");
+ CHECK(d.updateBufferCalls == 1, "setDataRaw -> device.updateBuffer");
}
CHECK(d.deleteBufferCalls == 1, "destructor -> device.deleteBuffer");
}
@@ -43,8 +45,8 @@ int main() {
u32 idx[] = { 0, 1, 2, 2, 3, 0 };
auto ibo = IndexBuffer::create(d, idx, 6);
CHECK(ibo != nullptr, "IndexBuffer::create returns a buffer");
- CHECK(d.createBufferCalls == 1 && d.bufferDataCalls == 1, "create -> device.createBuffer + bufferData");
- CHECK(d.bindIndexBufferCalls >= 1, "create binds via device.bindIndexBuffer");
+ CHECK(d.createBufferCalls == 1 && d.lastCreateBufferHadData, "create -> device.createBuffer with data");
+ CHECK(d.lastBufferDesc.usage == GfxBufferUsage::Index, "create declares Index usage");
CHECK(ibo->getCount() == 6, "index count stored");
CHECK(!ibo->is16Bit(), "u32 indices not flagged 16-bit");
}
diff --git a/tests/renderer/test_compressed_format.cpp b/tests/renderer/test_compressed_format.cpp
index 8992ed69c..f413f6963 100644
--- a/tests/renderer/test_compressed_format.cpp
+++ b/tests/renderer/test_compressed_format.cpp
@@ -21,15 +21,17 @@ static int g_failures = 0;
// The choice the asset upload path makes: prefer the compressed upload, fall back
// to an uncompressed RGBA8 upload when the backend can't sample the format.
-static void uploadTexture(GfxDevice& d, u32 tex, u32 w, u32 h,
- GfxCompressedFormat fmt,
- const void* compressed, u32 compressedLen,
- const void* rgba) {
+static TextureHandle uploadTexture(GfxDevice& d, u32 w, u32 h,
+ GfxCompressedFormat fmt,
+ const void* compressed, u32 compressedLen,
+ const void* rgba) {
+ TextureDesc desc;
+ desc.width = w;
+ desc.height = h;
if (d.supportsCompressedFormat(fmt)) {
- d.compressedTexImage2D(tex, w, h, fmt, compressed, compressedLen);
- } else {
- d.texImage2D(tex, w, h, GfxPixelFormat::RGBA8, rgba);
+ return d.createCompressedTexture(desc, fmt, compressed, compressedLen);
}
+ return d.createTexture(desc, rgba);
}
int main() {
@@ -40,11 +42,11 @@ int main() {
{
MockGfxDevice d;
d.compressedSupported = true;
- u32 tex = d.createTexture();
- uploadTexture(d, tex, 64, 64, GfxCompressedFormat::ASTC_4x4,
- blocks.data(), static_cast<u32>(blocks.size()), rgba.data());
- CHECK(d.compressedTexImage2DCalls == 1, "supported -> routes through device.compressedTexImage2D");
- CHECK(d.texImage2DCalls == 0, "supported -> no RGBA8 upload");
+ TextureHandle tex = uploadTexture(d, 64, 64, GfxCompressedFormat::ASTC_4x4,
+ blocks.data(), static_cast<u32>(blocks.size()), rgba.data());
+ CHECK(tex != TextureHandle::Invalid, "supported -> creation succeeds");
+ CHECK(d.createCompressedTextureCalls == 1, "supported -> routes through device.createCompressedTexture");
+ CHECK(d.createTextureCalls == 0, "supported -> no RGBA8 upload");
CHECK(d.lastCompressedFormat == GfxCompressedFormat::ASTC_4x4, "format forwarded to device");
CHECK(d.lastCompressedByteLength == blocks.size(), "compressed byte length forwarded");
}
@@ -53,19 +55,22 @@ int main() {
{
MockGfxDevice d;
d.compressedSupported = false;
- u32 tex = d.createTexture();
- uploadTexture(d, tex, 64, 64, GfxCompressedFormat::ASTC_4x4,
- blocks.data(), static_cast<u32>(blocks.size()), rgba.data());
- CHECK(d.compressedTexImage2DCalls == 0, "unsupported -> no compressed upload");
- CHECK(d.texImage2DCalls == 1, "unsupported -> RGBA8 fallback via device.texImage2D");
+ TextureHandle tex = uploadTexture(d, 64, 64, GfxCompressedFormat::ASTC_4x4,
+ blocks.data(), static_cast<u32>(blocks.size()), rgba.data());
+ CHECK(tex != TextureHandle::Invalid, "unsupported -> fallback creation succeeds");
+ CHECK(d.createCompressedTextureCalls == 0, "unsupported -> no compressed upload");
+ CHECK(d.createTextureCalls == 1 && d.lastCreateTextureHadPixels,
+ "unsupported -> RGBA8 fallback via device.createTexture");
}
// --- core ETC2/EAC baseline routes through the compressed entry ---
{
MockGfxDevice d;
- u32 tex = d.createTexture();
- d.compressedTexImage2D(tex, 32, 32, GfxCompressedFormat::ETC2_RGBA8, blocks.data(), 512);
- CHECK(d.compressedTexImage2DCalls == 1, "ETC2_RGBA8 routes through device");
+ TextureDesc desc;
+ desc.width = 32;
+ desc.height = 32;
+ d.createCompressedTexture(desc, GfxCompressedFormat::ETC2_RGBA8, blocks.data(), 512);
+ CHECK(d.createCompressedTextureCalls == 1, "ETC2_RGBA8 routes through device");
CHECK(d.lastCompressedFormat == GfxCompressedFormat::ETC2_RGBA8, "ETC2 format forwarded");
CHECK(d.lastCompressedByteLength == 512, "ETC2 byte length forwarded");
}
diff --git a/tests/renderer/test_shader_device.cpp b/tests/renderer/test_shader_device.cpp
index f4590680f..1769dfa28 100644
--- a/tests/renderer/test_shader_device.cpp
+++ b/tests/renderer/test_shader_device.cpp
@@ -37,9 +37,10 @@ int main() {
CHECK(d.setUniform4fCalls == 1, "setUniform(name,vec4) routes through device.setUniform4f");
shader->bind();
- CHECK(d.useProgramCalls == 1 && d.lastProgram == 1, "bind routes through device.useProgram");
+ CHECK(d.useProgramCalls == 1 && d.lastProgram == ShaderHandle{1}, "bind routes through device.useProgram");
shader->unbind();
- CHECK(d.useProgramCalls == 2 && d.lastProgram == 0, "unbind routes through device.useProgram(0)");
+ CHECK(d.useProgramCalls == 2 && d.lastProgram == ShaderHandle::Invalid,
+ "unbind routes through device.useProgram(Invalid)");
// shader destructed at scope end -> device.deleteProgram
}
diff --git a/tests/renderer/test_texture_fb.cpp b/tests/renderer/test_texture_fb.cpp
index 32421a6b6..0d2437ad9 100644
--- a/tests/renderer/test_texture_fb.cpp
+++ b/tests/renderer/test_texture_fb.cpp
@@ -1,4 +1,4 @@
-// Native MSVC/CTest harness for Texture + Framebuffer (RC5-GfxDevice).
+// Native MSVC/CTest harness for Texture + Framebuffer (GfxDevice).
//
// Compiles the CONVERTED Texture.cpp and Framebuffer.cpp against MockGfxDevice.
// Linking proves they no longer touch GL; the asserts confirm create/upload/
@@ -30,46 +30,51 @@ int main() {
auto tex = Texture::create(d, spec);
CHECK(tex != nullptr, "Texture::create returns a texture");
CHECK(d.createTextureCalls == 1, "create routes through device.createTexture");
- CHECK(d.texImage2DCalls == 1, "create allocates via device.texImage2D");
- CHECK(d.setTextureParamsCalls == 1, "create sets params via device.setTextureParams");
- CHECK(d.generateMipmapsCalls == 1, "generateMips routes through device.generateMipmaps");
- CHECK(tex->getId() == 100, "texture id is device-assigned");
+ CHECK(d.lastTextureDesc.width == 8 && d.lastTextureDesc.height == 8,
+ "creation descriptor carries the dimensions");
+ CHECK(d.lastTextureDesc.format == GfxPixelFormat::RGBA8,
+ "creation descriptor carries the pixel format");
+ CHECK(d.lastTextureDesc.mipmaps, "generateMips is declared in the descriptor");
+ CHECK(!d.lastCreateTextureHadPixels, "empty spec allocates without pixel data");
+ CHECK(tex->handle() == TextureHandle{100}, "texture handle is device-assigned");
tex->bind(2);
CHECK(d.bindTextureCalls == 1, "bind routes through device.bindTexture");
}
- CHECK(d.deleteTextureCalls == 1 && d.lastDeletedTexture == 100,
+ CHECK(d.deleteTextureCalls == 1 && d.lastDeletedTexture == TextureHandle{100},
"destructor routes through device.deleteTexture");
}
- // --- Texture: pixel upload ---
+ // --- Texture: pixel upload at creation ---
{
MockGfxDevice d;
std::vector<u8> pixels(2 * 2 * 4, 0xFF);
auto tex = Texture::create(d, 2, 2, pixels, TextureFormat::RGBA8, /*flipY*/ true);
CHECK(tex != nullptr, "Texture::create(pixels) returns a texture");
- CHECK(d.texSubImage2DCalls == 1, "pixel upload routes through device.texSubImage2D");
+ CHECK(d.createTextureCalls == 1 && d.lastCreateTextureHadPixels,
+ "pixels are uploaded with the creation call");
+ CHECK(d.lastTextureDesc.flipY, "flipY is declared in the creation descriptor");
}
// --- A2 regression: setDataRaw rejects undersized buffer (no OOB upload) ---
// Audit A2: ES_ASSERT is stripped in release, so an undersized buffer used to
- // reach texSubImage2D and read past its end. Guard must hold without asserts.
+ // reach the GPU upload and read past its end. Guard must hold without asserts.
{
MockGfxDevice d;
TextureSpecification spec;
spec.width = 4; spec.height = 4; spec.format = TextureFormat::RGBA8; // needs 4*4*4 = 64 bytes
auto tex = Texture::create(d, spec);
- const int before = d.texSubImage2DCalls;
+ const int before = d.updateTextureCalls;
std::vector<u8> tooSmall(16, 0xAB); // 16 < 64
tex->setDataRaw(tooSmall.data(), static_cast<u32>(tooSmall.size()));
- CHECK(d.texSubImage2DCalls == before, "setDataRaw skips upload for undersized buffer (no OOB read)");
+ CHECK(d.updateTextureCalls == before, "setDataRaw skips upload for undersized buffer (no OOB read)");
std::vector<u8> exact(64, 0xAB);
tex->setDataRaw(exact.data(), static_cast<u32>(exact.size()));
- CHECK(d.texSubImage2DCalls == before + 1, "setDataRaw uploads when size is sufficient");
+ CHECK(d.updateTextureCalls == before + 1, "setDataRaw uploads when size is sufficient");
}
// --- create() fails (returns null) when the device can't allocate a texture ---
- // createTexture returns 0 on OOM / lost context; initialize() must surface that
- // instead of returning a "valid" texture wrapping id 0 (which renders as black).
+ // createTexture returns Invalid on OOM / lost context; initialize() must surface
+ // that instead of returning a "valid" texture wrapping the null handle.
{
MockGfxDevice d;
d.createTextureFails = true;
@@ -77,16 +82,16 @@ int main() {
spec.width = 8; spec.height = 8; spec.format = TextureFormat::RGBA8;
auto tex = Texture::create(d, spec);
CHECK(tex == nullptr, "create returns null when device.createTexture fails");
- CHECK(d.texImage2DCalls == 0, "no upload is attempted after a failed allocation");
}
- // --- createFromExternalId must NOT delete the externally-owned GL texture ---
+ // --- createFromExternalId must NOT delete the externally-owned texture ---
// The external owner frees that id; deleting it here too is a double-free.
{
MockGfxDevice d;
{
auto tex = Texture::createFromExternalId(d, 42, 8, 8);
- CHECK(tex != nullptr && tex->getId() == 42, "wrapper holds the external id");
+ CHECK(tex != nullptr && tex->handle() == TextureHandle{42}, "wrapper holds the external id");
+ CHECK(d.importExternalTextureCalls == 1, "external id is registered with the device");
}
CHECK(d.deleteTextureCalls == 0, "destructor does NOT delete an externally-owned texture");
}
@@ -110,7 +115,9 @@ int main() {
CHECK(fbo != nullptr, "Framebuffer::create returns a framebuffer");
CHECK(d.createFramebufferCalls == 1, "create routes through device.createFramebuffer");
CHECK(d.createTextureCalls == 2, "color + depth attachments via device.createTexture");
- CHECK(d.framebufferTexture2DCalls == 2, "both attachments via device.framebufferTexture2D");
+ CHECK(d.lastFramebufferDesc.color0 != TextureHandle::Invalid &&
+ d.lastFramebufferDesc.depthStencil != TextureHandle::Invalid,
+ "both attachments are declared in the framebuffer descriptor");
fbo->bind();
CHECK(d.bindFramebufferCalls >= 1, "bind routes through device.bindFramebuffer");
}