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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix: work around WeChat WebGL VAO state restoration bug
esenginee13cca41d931
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 80439a114..0443f9be6 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -51,9 +51,43 @@ static Unique<PostProcessPipeline> g_postProcessPipeline;static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE g_webglContext = 0;static bool g_initialized = false;static bool g_immediateDrawActive = false;+static bool g_glErrorCheckEnabled = false;static u32 g_viewportWidth = 1280;static u32 g_viewportHeight = 720;static glm::vec4 g_clearColor{0.0f, 0.0f, 0.0f, 1.0f};+static u32 checkGLErrors(const char* context) {+ if (!g_glErrorCheckEnabled) return 0;+ u32 errorCount = 0;+ GLenum err;+ while ((err = glGetError()) != GL_NO_ERROR) {+ const char* errStr = "UNKNOWN";+ switch (err) {+ case GL_INVALID_ENUM: errStr = "INVALID_ENUM"; break;+ case GL_INVALID_VALUE: errStr = "INVALID_VALUE"; break;+ case GL_INVALID_OPERATION: errStr = "INVALID_OPERATION"; break;+ case GL_INVALID_FRAMEBUFFER_OPERATION: errStr = "INVALID_FRAMEBUFFER_OPERATION"; break;+ case GL_OUT_OF_MEMORY: errStr = "OUT_OF_MEMORY"; break;+ }+ ES_LOG_ERROR("[GL Error] {} at: {}", errStr, context);+ errorCount++;+ }+ return errorCount;+}++static void flushImmediateDrawIfActive() {+ if (g_immediateDrawActive && g_immediateDraw) {+ g_immediateDraw->flush();+ }+}++static void restoreImmediateDrawState() {+ if (g_immediateDrawActive) {+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);+ glEnable(GL_BLEND);+ glDisable(GL_DEPTH_TEST);+ glActiveTexture(GL_TEXTURE0);+ }+}EM_JS(void, callMaterialProvider, (int materialId, int outShaderIdPtr, int outBlendModePtr, int outUniformBufPtr, int outUniformCountPtr), {var fn = Module['materialDataProvider'];@@ -438,6 +472,8 @@ static glm::mat4 g_currentViewProjection{1.0f};void draw_begin(uintptr_t matrixPtr) {if (!g_initialized || !g_immediateDraw) return;+ glViewport(0, 0, g_viewportWidth, g_viewportHeight);+const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);g_currentViewProjection = glm::make_mat4(matrixData);g_immediateDraw->begin(g_currentViewProjection);@@ -449,6 +485,7 @@ void draw_end() {g_immediateDraw->end();g_immediateDrawActive = false;+ checkGLErrors("draw_end");}void draw_line(f32 fromX, f32 fromY, f32 toX, f32 toY,@@ -559,10 +596,12 @@ u32 draw_getPrimitiveCount() {}void draw_setBlendMode(i32 mode) {+ flushImmediateDrawIfActive();RenderCommand::setBlendMode(static_cast<BlendMode>(mode));}void draw_setDepthTest(bool enabled) {+ flushImmediateDrawIfActive();RenderCommand::setDepthTest(enabled);}@@ -660,6 +699,8 @@ void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {Shader* shader = g_resourceManager->getShader(resource::ShaderHandle(shaderHandle));if (!shader) return;+ flushImmediateDrawIfActive();+const f32* transformData = reinterpret_cast<const f32*>(transformPtr);glm::mat4 transform = glm::make_mat4(transformData);@@ -670,15 +711,18 @@ void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {geom->bind();if (geom->hasIndices()) {- auto* vao = geom->getVAO();- if (vao) {- RenderCommand::drawIndexed(*vao, geom->getIndexCount());+ auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;+ if (ib) {+ GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;+ glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);}} else {- RenderCommand::drawArrays(geom->getVertexCount());+ glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));}geom->unbind();+ checkGLErrors("draw_mesh");+ restoreImmediateDrawState();}void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr,@@ -691,6 +735,8 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transShader* shader = g_resourceManager->getShader(resource::ShaderHandle(shaderHandle));if (!shader) return;+ flushImmediateDrawIfActive();+const f32* transformData = reinterpret_cast<const f32*>(transformPtr);glm::mat4 transform = glm::make_mat4(transformData);@@ -757,15 +803,18 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transgeom->bind();if (geom->hasIndices()) {- auto* vao = geom->getVAO();- if (vao) {- RenderCommand::drawIndexed(*vao, geom->getIndexCount());+ auto* ib = geom->getVAO() ? geom->getVAO()->getIndexBuffer().get() : nullptr;+ if (ib) {+ GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;+ glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(geom->getIndexCount()), type, nullptr);}} else {- RenderCommand::drawArrays(geom->getVertexCount());+ glDrawArrays(GL_TRIANGLES, 0, static_cast<GLsizei>(geom->getVertexCount()));}geom->unbind();+ checkGLErrors("draw_meshWithUniforms");+ restoreImmediateDrawState();}// =============================================================================@@ -780,6 +829,8 @@ bool postprocess_init(u32 width, u32 height) {}g_postProcessPipeline->init(width, height);+ glBindFramebuffer(GL_FRAMEBUFFER, 0);+return g_postProcessPipeline->isInitialized();}@@ -893,9 +944,16 @@ void renderer_begin(uintptr_t matrixPtr, u32 targetHandle) {g_renderFrame->begin(viewProjection, targetHandle);}+void renderer_flush() {+ if (!g_renderFrame) return;+ g_renderFrame->flush();+ checkGLErrors("renderer_flush");+}+void renderer_end() {if (!g_renderFrame) return;g_renderFrame->end();+ checkGLErrors("renderer_end");}void renderer_submitSprites(ecs::Registry& registry) {@@ -908,6 +966,7 @@ void renderer_submitSpine(ecs::Registry& registry) {if (!g_renderFrame || !g_spineSystem) return;g_spineSystem->update(registry, 0.016f);g_renderFrame->submitSpine(registry, *g_spineSystem);+ checkGLErrors("renderer_submitSpine");}void renderer_setStage(i32 stage) {@@ -973,6 +1032,57 @@ void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a) {g_clearColor = glm::vec4(r, g, b, a);}+void renderer_diagnose() {+ if (!g_initialized) {+ ES_LOG_ERROR("[Diagnose] Renderer not initialized");+ return;+ }++ const char* version = reinterpret_cast<const char*>(glGetString(GL_VERSION));+ const char* rendererStr = reinterpret_cast<const char*>(glGetString(GL_RENDERER));+ const char* vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR));+ const char* slVersion = reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION));+ ES_LOG_INFO("[Diagnose] GL Version: {}", version ? version : "null");+ ES_LOG_INFO("[Diagnose] GL Renderer: {}", rendererStr ? rendererStr : "null");+ ES_LOG_INFO("[Diagnose] GL Vendor: {}", vendor ? vendor : "null");+ ES_LOG_INFO("[Diagnose] GLSL Version: {}", slVersion ? slVersion : "null");++ GLint viewport[4];+ glGetIntegerv(GL_VIEWPORT, viewport);+ ES_LOG_INFO("[Diagnose] GL Viewport: {}x{} at ({},{})", viewport[2], viewport[3], viewport[0], viewport[1]);+ ES_LOG_INFO("[Diagnose] Stored viewport: {}x{}", g_viewportWidth, g_viewportHeight);++ GLint maxTextureUnits;+ glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &maxTextureUnits);+ ES_LOG_INFO("[Diagnose] Max texture units: {}", maxTextureUnits);++ GLint maxAttribs;+ glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &maxAttribs);+ ES_LOG_INFO("[Diagnose] Max vertex attribs: {}", maxAttribs);++ while (glGetError() != GL_NO_ERROR) {}+ ES_LOG_INFO("[Diagnose] No pending GL errors (cleared)");+}++void gl_enableErrorCheck(bool enabled) {+ g_glErrorCheckEnabled = enabled;+ if (enabled) {+ while (glGetError() != GL_NO_ERROR) {}+ ES_LOG_INFO("[GL] Error checking enabled");+ }+}++u32 gl_checkErrors(const std::string& context) {+ bool prev = g_glErrorCheckEnabled;+ g_glErrorCheckEnabled = true;+ u32 count = checkGLErrors(context.c_str());+ g_glErrorCheckEnabled = prev;+ if (count == 0 && prev) {+ ES_LOG_INFO("[GL] No errors at: {}", context);+ }+ return count;+}+} // namespace esengineEMSCRIPTEN_BINDINGS(esengine_renderer) {@@ -1052,6 +1162,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("renderer_init", &esengine::renderer_init);emscripten::function("renderer_resize", &esengine::renderer_resize);emscripten::function("renderer_begin", &esengine::renderer_begin);+ emscripten::function("renderer_flush", &esengine::renderer_flush);emscripten::function("renderer_end", &esengine::renderer_end);emscripten::function("renderer_submitSprites", &esengine::renderer_submitSprites);emscripten::function("renderer_submitSpine", &esengine::renderer_submitSpine);@@ -1067,6 +1178,11 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("renderer_getMeshes", &esengine::renderer_getMeshes);emscripten::function("renderer_getCulled", &esengine::renderer_getCulled);emscripten::function("renderer_setClearColor", &esengine::renderer_setClearColor);++ // GL Debug API+ emscripten::function("gl_enableErrorCheck", &esengine::gl_enableErrorCheck);+ emscripten::function("gl_checkErrors", &esengine::gl_checkErrors);+ emscripten::function("renderer_diagnose", &esengine::renderer_diagnose);}int main() {diff --git a/src/esengine/renderer/CustomGeometry.cpp b/src/esengine/renderer/CustomGeometry.cppindex ecdb18372..1820a1b26 100644--- a/src/esengine/renderer/CustomGeometry.cpp+++ b/src/esengine/renderer/CustomGeometry.cpp@@ -10,6 +10,8 @@*/#include "CustomGeometry.hpp"++#include "OpenGLHeaders.hpp"#include "../core/Log.hpp"namespace esengine {@@ -66,8 +68,46 @@ void CustomGeometry::updateVertices(const f32* vertices, u32 vertexCount, u32 of}void CustomGeometry::bind() const {- if (vao_) {- vao_->bind();+ if (!vao_) return;++ vao_->bind();++ // Explicitly rebind VBO + attribute pointers + IBO to work around+ // WeChat WebGL VAO state restoration bug+ if (vbo_) {+ vbo_->bind();+ const auto& layout = vbo_->getLayout();+ u32 index = 0;+ for (const auto& attr : layout) {+ GLenum glType = GL_FLOAT;+ switch (attr.type) {+ case ShaderDataType::Int:+ case ShaderDataType::Int2:+ case ShaderDataType::Int3:+ case ShaderDataType::Int4:+ glType = GL_INT;+ break;+ case ShaderDataType::Bool:+ glType = GL_UNSIGNED_BYTE;+ break;+ default:+ glType = GL_FLOAT;+ break;+ }+ glEnableVertexAttribArray(index);+ glVertexAttribPointer(+ index,+ static_cast<GLint>(shaderDataTypeComponentCount(attr.type)),+ glType,+ attr.normalized ? GL_TRUE : GL_FALSE,+ static_cast<GLsizei>(layout.getStride()),+ reinterpret_cast<const void*>(static_cast<uintptr_t>(attr.offset))+ );+ ++index;+ }+ }+ if (ibo_) {+ ibo_->bind();}}diff --git a/src/esengine/renderer/ImmediateDraw.cpp b/src/esengine/renderer/ImmediateDraw.cppindex d819aeea1..b7c45e8f6 100644--- a/src/esengine/renderer/ImmediateDraw.cpp+++ b/src/esengine/renderer/ImmediateDraw.cpp@@ -15,6 +15,15 @@#include "../resource/ResourceManager.hpp"#include "../core/Log.hpp"+#ifdef ES_PLATFORM_WEB+ #include <GLES3/gl3.h>+#else+ #ifdef _WIN32+ #include <windows.h>+ #endif+ #include <glad/glad.h>+#endif+#include <glm/gtc/constants.hpp>#include <cmath>@@ -63,6 +72,10 @@ void ImmediateDraw::shutdown() {void ImmediateDraw::begin(const glm::mat4& viewProjection) {if (!initialized_) return;+ glEnable(GL_BLEND);+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);+ glDisable(GL_DEPTH_TEST);+impl_->viewProjection = viewProjection;impl_->batcher->setProjection(viewProjection);impl_->batcher->beginBatch();@@ -78,6 +91,12 @@ void ImmediateDraw::end() {inFrame_ = false;}+void ImmediateDraw::flush() {+ if (!initialized_ || !inFrame_) return;++ impl_->batcher->flush();+}+void ImmediateDraw::line(const glm::vec2& from, const glm::vec2& to,const glm::vec4& color, f32 thickness) {if (!inFrame_) return;diff --git a/src/esengine/renderer/ImmediateDraw.hpp b/src/esengine/renderer/ImmediateDraw.hppindex e44d93763..b0f64fa42 100644--- a/src/esengine/renderer/ImmediateDraw.hpp+++ b/src/esengine/renderer/ImmediateDraw.hpp@@ -83,6 +83,13 @@ public:*/void end();+ /**+ * @brief Flushes pending draw commands without ending the frame+ * @details Use this before operations that change GL state (e.g. custom geometry draws)+ * to ensure accumulated primitives are rendered with the correct state.+ */+ void flush();+// =========================================================================// Line Drawing// =========================================================================diff --git a/src/esengine/renderer/RenderContext.cpp b/src/esengine/renderer/RenderContext.cppindex 43b16c5e8..569ae0395 100644--- a/src/esengine/renderer/RenderContext.cpp+++ b/src/esengine/renderer/RenderContext.cpp@@ -66,7 +66,7 @@ void RenderContext::initQuadData() {-0.5f, 0.5f, 0.0f, 1.0f};- u32 indices[] = { 0, 1, 2, 2, 3, 0 };+ u16 indices[] = { 0, 1, 2, 2, 3, 0 };quadVAO_ = VertexArray::create();diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cppindex 9b273e81e..e536eae3e 100644--- a/src/esengine/renderer/RenderFrame.cpp+++ b/src/esengine/renderer/RenderFrame.cpp@@ -159,8 +159,10 @@ void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::H}}-void RenderFrame::end() {- if (!in_frame_) return;+void RenderFrame::flush() {+ if (!in_frame_ || flushed_) return;++ flushed_ = true;sortAndBucket();@@ -172,6 +174,14 @@ void RenderFrame::end() {executeStage(RenderStage::Opaque);executeStage(RenderStage::Transparent);executeStage(RenderStage::Overlay);+}++void RenderFrame::end() {+ if (!in_frame_) return;++ if (!flushed_) {+ flush();+ }bool usePostProcess = post_process_ && post_process_->isInitialized() &&!post_process_->isBypassed() && post_process_->getPassCount() > 0;@@ -186,6 +196,7 @@ void RenderFrame::end() {}in_frame_ = false;+ flushed_ = false;}void RenderFrame::submitSprites(ecs::Registry& registry) {@@ -529,7 +540,7 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {f32 b = skelColor.b * slotColor.b * attachColor.b * item->tint_color.b;f32 a = skelColor.a * slotColor.a * attachColor.a * item->tint_color.a;- u32 baseIndex = static_cast<u32>(spine_vertices_.size());+ u16 baseIndex = static_cast<u16>(spine_vertices_.size());for (size_t j = 0; j < 4; ++j) {glm::vec4 pos(spine_world_vertices_[j * 2], spine_world_vertices_[j * 2 + 1], 0.0f, 1.0f);@@ -581,7 +592,7 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {f32 b = skelColor.b * slotColor.b * attachColor.b * item->tint_color.b;f32 a = skelColor.a * slotColor.a * attachColor.a * item->tint_color.a;- u32 baseIndex = static_cast<u32>(spine_vertices_.size());+ u16 baseIndex = static_cast<u16>(spine_vertices_.size());for (size_t j = 0; j < vertexCount; ++j) {glm::vec4 pos(spine_world_vertices_[j * 2], spine_world_vertices_[j * 2 + 1], 0.0f, 1.0f);@@ -595,7 +606,7 @@ void RenderFrame::renderSpine(u32 begin, u32 end) {}for (size_t j = 0; j < triangles.size(); ++j) {- spine_indices_.push_back(baseIndex + triangles[j]);+ spine_indices_.push_back(static_cast<u16>(baseIndex + triangles[j]));}}@@ -637,7 +648,7 @@ void RenderFrame::flushSpineBatch() {}glBufferSubData(GL_ARRAY_BUFFER, 0, vboBytes, spine_vertices_.data());- auto eboBytes = static_cast<GLsizeiptr>(spine_indices_.size() * sizeof(u32));+ auto eboBytes = static_cast<GLsizeiptr>(spine_indices_.size() * sizeof(u16));glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, spine_ebo_);if (static_cast<u32>(eboBytes) > spine_ebo_capacity_) {spine_ebo_capacity_ = static_cast<u32>(eboBytes) * 2;@@ -646,7 +657,7 @@ void RenderFrame::flushSpineBatch() {glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, eboBytes, spine_indices_.data());glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(spine_indices_.size()),- GL_UNSIGNED_INT, nullptr);+ GL_UNSIGNED_SHORT, nullptr);glBindVertexArray(0);@@ -747,7 +758,7 @@ void RenderFrame::renderSpriteWithMaterial(RenderItem* item) {}if (!mat_sprite_ebo_initialized_) {- u32 indices[] = { 0, 1, 2, 2, 3, 0 };+ u16 indices[] = { 0, 1, 2, 2, 3, 0 };glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mat_sprite_ebo_);glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);mat_sprite_ebo_initialized_ = true;@@ -755,7 +766,7 @@ void RenderFrame::renderSpriteWithMaterial(RenderItem* item) {glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mat_sprite_ebo_);}- glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);+ glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, nullptr);if (locPos >= 0) glDisableVertexAttribArray(locPos);if (locTex >= 0) glDisableVertexAttribArray(locTex);diff --git a/src/esengine/renderer/RenderFrame.hpp b/src/esengine/renderer/RenderFrame.hppindex d6024f7d1..b61fa59c2 100644--- a/src/esengine/renderer/RenderFrame.hpp+++ b/src/esengine/renderer/RenderFrame.hpp@@ -42,6 +42,7 @@ public:void resize(u32 width, u32 height);void begin(const glm::mat4& view_projection, RenderTargetManager::Handle target = 0);+ void flush();void end();void submitSprites(ecs::Registry& registry);@@ -81,6 +82,7 @@ private:Stats stats_;bool in_frame_ = false;+ bool flushed_ = false;u32 width_ = 0;u32 height_ = 0;@@ -97,7 +99,7 @@ private:glm::vec4 color;};std::vector<SpineVertex> spine_vertices_;- std::vector<u32> spine_indices_;+ std::vector<u16> spine_indices_;u32 spine_current_texture_ = 0;BlendMode spine_current_blend_ = BlendMode::Normal;diff --git a/src/esengine/renderer/Renderer.cpp b/src/esengine/renderer/Renderer.cppindex edfe2752c..cbdaa4cef 100644--- a/src/esengine/renderer/Renderer.cpp+++ b/src/esengine/renderer/Renderer.cpp@@ -335,8 +335,8 @@ void BatchRenderer2D::init() {data_->vao->addVertexBuffer(data_->vbo);- std::vector<u32> indices(MAX_INDICES);- u32 offset = 0;+ std::vector<u16> indices(MAX_INDICES);+ u16 offset = 0;for (u32 i = 0; i < MAX_INDICES; i += 6) {indices[i + 0] = offset + 0;indices[i + 1] = offset + 1;@@ -360,13 +360,51 @@ void BatchRenderer2D::init() {);}+ Shader* batchShader = resource_manager_.getShader(data_->shader_handle);++ if (!batchShader || !batchShader->isValid()) {+ ES_LOG_WARN("GLSL ES 3.0 batch shader failed, trying GLSL ES 1.0 fallback");+ data_->shader_handle = resource_manager_.createShader(+ ShaderSources::BATCH_VERTEX_COMPAT,+ ShaderSources::BATCH_FRAGMENT_COMPAT+ );+ batchShader = resource_manager_.getShader(data_->shader_handle);+ }++ if (batchShader && batchShader->isValid()) {+ GLuint prog = batchShader->getProgramId();+ glBindAttribLocation(prog, 0, "a_position");+ glBindAttribLocation(prog, 1, "a_color");+ glBindAttribLocation(prog, 2, "a_texCoord");+ glBindAttribLocation(prog, 3, "a_texIndex");+ glLinkProgram(prog);++ GLint linkStatus;+ glGetProgramiv(prog, GL_LINK_STATUS, &linkStatus);+ if (linkStatus) {+ ES_LOG_INFO("Batch shader ready (program ID: {})", prog);+ batchShader->bind();+ GLint baseLoc = glGetUniformLocation(prog, "u_textures[0]");+ if (baseLoc >= 0) {+ for (i32 i = 0; i < static_cast<i32>(MAX_TEXTURE_SLOTS); ++i) {+ glUniform1i(baseLoc + i, i);+ }+ }+ } else {+ ES_LOG_ERROR("Batch shader re-link failed after attribute binding");+ }+ } else {+ ES_LOG_ERROR("All batch shader variants FAILED!");+ }+data_->textureSlots[0] = context_.getWhiteTextureId();for (u32 i = 1; i < MAX_TEXTURE_SLOTS; ++i) {data_->textureSlots[i] = 0;}data_->initialized = true;- ES_LOG_INFO("BatchRenderer2D initialized (max {} quads per batch)", MAX_QUADS);+ ES_LOG_INFO("BatchRenderer2D initialized (max {} quads per batch, {} texture slots)",+ MAX_QUADS, MAX_TEXTURE_SLOTS);}void BatchRenderer2D::shutdown() {@@ -402,22 +440,30 @@ void BatchRenderer2D::flush() {static_cast<u32>(data_->vertices.size() * sizeof(BatchVertex)));- for (u32 i = 0; i < MAX_TEXTURE_SLOTS; ++i) {+ for (u32 i = 0; i < data_->textureSlotIndex; ++i) {glActiveTexture(GL_TEXTURE0 + i);- glBindTexture(GL_TEXTURE_2D, i < data_->textureSlotIndex ? data_->textureSlots[i] : data_->textureSlots[0]);+ glBindTexture(GL_TEXTURE_2D, data_->textureSlots[i]);}shader->bind();shader->setUniform("u_projection", data_->projection);- i32 samplers[MAX_TEXTURE_SLOTS] = { 0, 1, 2, 3, 4, 5, 6, 7 };- glUniform1iv(glGetUniformLocation(shader->getProgramId(), "u_textures"),- MAX_TEXTURE_SLOTS, samplers);-- RenderCommand::drawIndexed(*data_->vao, data_->indexCount);+ data_->vao->bind();+ data_->vbo->bind();+ constexpr u32 STRIDE = sizeof(BatchVertex);+ glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(0));+ glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(12));+ glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(28));+ glVertexAttribPointer(3, 1, GL_FLOAT, GL_FALSE, STRIDE, reinterpret_cast<void*>(36));++ auto ib = data_->vao->getIndexBuffer();+ if (ib) {+ ib->bind();+ GLenum type = ib->is16Bit() ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;+ glDrawElements(GL_TRIANGLES, static_cast<GLsizei>(data_->indexCount), type, nullptr);+ }data_->drawCallCount++;-data_->vertices.clear();data_->indexCount = 0;data_->textureSlotIndex = 1;diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hppindex a20cc1578..89d6782f2 100644--- a/src/esengine/renderer/Shader.hpp+++ b/src/esengine/renderer/Shader.hpp@@ -325,38 +325,99 @@ inline const char* BATCH_FRAGMENT = R"(#version 300 esin vec2 v_texCoord;in float v_texIndex;- uniform sampler2D u_textures[16];+ uniform sampler2D u_textures[8];out vec4 fragColor;void main() {- int index = int(v_texIndex);- vec4 texColor = vec4(1.0);-- // WebGL2 requires constant index for sampler arrays- switch(index) {- case 0: texColor = texture(u_textures[0], v_texCoord); break;- case 1: texColor = texture(u_textures[1], v_texCoord); break;- case 2: texColor = texture(u_textures[2], v_texCoord); break;- case 3: texColor = texture(u_textures[3], v_texCoord); break;- case 4: texColor = texture(u_textures[4], v_texCoord); break;- case 5: texColor = texture(u_textures[5], v_texCoord); break;- case 6: texColor = texture(u_textures[6], v_texCoord); break;- case 7: texColor = texture(u_textures[7], v_texCoord); break;- case 8: texColor = texture(u_textures[8], v_texCoord); break;- case 9: texColor = texture(u_textures[9], v_texCoord); break;- case 10: texColor = texture(u_textures[10], v_texCoord); break;- case 11: texColor = texture(u_textures[11], v_texCoord); break;- case 12: texColor = texture(u_textures[12], v_texCoord); break;- case 13: texColor = texture(u_textures[13], v_texCoord); break;- case 14: texColor = texture(u_textures[14], v_texCoord); break;- case 15: texColor = texture(u_textures[15], v_texCoord); break;+ int index = int(v_texIndex + 0.5);+ vec4 texColor;++ if (index <= 0) {+ texColor = vec4(1.0);+ } else if (index == 1) {+ texColor = texture(u_textures[1], v_texCoord);+ } else if (index == 2) {+ texColor = texture(u_textures[2], v_texCoord);+ } else if (index == 3) {+ texColor = texture(u_textures[3], v_texCoord);+ } else if (index == 4) {+ texColor = texture(u_textures[4], v_texCoord);+ } else if (index == 5) {+ texColor = texture(u_textures[5], v_texCoord);+ } else if (index == 6) {+ texColor = texture(u_textures[6], v_texCoord);+ } else {+ texColor = texture(u_textures[7], v_texCoord);}fragColor = texColor * v_color;})";+/**+ * @brief GLSL ES 1.0 fallback vertex shader for batched sprite rendering+ * @details Used when #version 300 es is not supported by the GPU driver.+ * Requires glBindAttribLocation before linking for correct attribute mapping.+ */+inline const char* BATCH_VERTEX_COMPAT = R"(+ attribute vec3 a_position;+ attribute vec4 a_color;+ attribute vec2 a_texCoord;+ attribute float a_texIndex;++ uniform mat4 u_projection;++ varying vec4 v_color;+ varying vec2 v_texCoord;+ varying float v_texIndex;++ void main() {+ gl_Position = u_projection * vec4(a_position, 1.0);+ v_color = a_color;+ v_texCoord = a_texCoord;+ v_texIndex = a_texIndex;+ }+)";++/**+ * @brief GLSL ES 1.0 fallback fragment shader for batched sprite rendering+ */+inline const char* BATCH_FRAGMENT_COMPAT = R"(+ precision mediump float;++ varying vec4 v_color;+ varying vec2 v_texCoord;+ varying float v_texIndex;++ uniform sampler2D u_textures[8];++ void main() {+ int index = int(v_texIndex + 0.5);+ vec4 texColor;++ if (index <= 0) {+ texColor = vec4(1.0);+ } else if (index == 1) {+ texColor = texture2D(u_textures[1], v_texCoord);+ } else if (index == 2) {+ texColor = texture2D(u_textures[2], v_texCoord);+ } else if (index == 3) {+ texColor = texture2D(u_textures[3], v_texCoord);+ } else if (index == 4) {+ texColor = texture2D(u_textures[4], v_texCoord);+ } else if (index == 5) {+ texColor = texture2D(u_textures[5], v_texCoord);+ } else if (index == 6) {+ texColor = texture2D(u_textures[6], v_texCoord);+ } else {+ texColor = texture2D(u_textures[7], v_texCoord);+ }++ gl_FragColor = texColor * v_color;+ }+)";+} // namespace ShaderSources} // namespace esengine