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
refactor(render): rewrite DrawList::execute onto pipelines; retire StateTracker — REARCH_RENDER P2b
esengine07d3332b642e
diff --git a/CMakeLists.txt b/CMakeLists.txtindex b28d6e860..faca36d78 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -51,7 +51,6 @@ set(ESENGINE_SOURCESsrc/esengine/renderer/ImmediateDraw.cppsrc/esengine/renderer/CustomGeometry.cppsrc/esengine/renderer/GLDevice.cpp- src/esengine/renderer/StateTracker.cppsrc/esengine/renderer/TransientBufferPool.cppsrc/esengine/renderer/DrawList.cppsrc/esengine/renderer/BatchBuilder.cpp@@ -135,7 +134,6 @@ set(ESENGINE_HEADERSsrc/esengine/renderer/GfxEnums.hppsrc/esengine/renderer/GfxDevice.hppsrc/esengine/renderer/GLDevice.hpp- src/esengine/renderer/StateTracker.hppsrc/esengine/renderer/TransientBufferPool.hppsrc/esengine/renderer/DrawCommand.hppsrc/esengine/renderer/DrawList.hppdiff --git a/docs/REARCH_RENDER.md b/docs/REARCH_RENDER.mdindex 9fa883765..5fd6044ff 100644--- a/docs/REARCH_RENDER.md+++ b/docs/REARCH_RENDER.md@@ -129,12 +129,13 @@ TS/WASM 边界对 uniform 布局**不透明**:`renderer_begin(viewProjPtr, tar- **价值(修正)**:纯 WebGL2 的 per-frame uniform 节省 **可忽略**(实测路径每帧仅 1–3 次 `setUniformMat4`,按 shader 切换 gate,非 per-draw——原"显著下降"的说法不成立)。P1 的真实价值是 **(a) 最低风险地落地 UBO/bind 机制**(std140 + host 侧 block-binding + ES 版本升级,孤立可逐像素验证,避免与 P2 的 execute 重写纠缠)、**(b) 前向兼容 P2**(UBO 即 BindGroup 的首个非纹理资源,P1 写的 UBO API 被 P2 复用、非废弃)、**(c) WebGPU 前置形态**(WebGPU 无散装 uniform,全是 UBO/bind group)。- **验证**:headless `verify:render` 四场景逐像素不变(同 P0);FrameCapture 对比 draw call 数不变。-### P2 — PipelineState + BindGroup + 类型化句柄(keystone 主体)-- 引入 `PipelineState`/`BindGroup`/`TypedHandle`;`GfxDevice` 增 `createPipeline`/`createBindGroup`/`setPipeline`/`setBindGroup`/`draw`。-- **重写 `DrawList::execute`(`DrawList.cpp:60-131`)** 为命令编码三步;collect 阶段不动。-- ImmediateDraw / PostProcessPipeline 迁到同模型。-- 删散装 `setUniform*`/`bindTexture`/VAO 漏出接口(迁移完成后);删 material cache 死路径(病灶 E)。-- **价值**:单一后端无关命令编码层,WebGPU 可插入;UBO/批合并/材质有真正落点。+### P2 — PipelineState keystone 主体(DONE,实况记录)+分两 checkpoint 落地:+- **P2a(纯加法)**:`PipelineState.hpp`(`PipelineDesc` = program+vertexLayout+blend+depth+`GfxStencilMode`+cull → 缓存为不可变 `PipelineHandle`);`GfxDevice` 增 `createPipeline`/`setPipeline`/`setStencilReference`/`invalidatePipelineCache`;GLDevice 用 desc 表 + **句柄比较去冗余**(同 pipeline 跳过整组状态应用)实现,stencil 序列镜像旧 StateTracker。`LayoutId` 移到 `GfxEnums.hpp`(叶子头)破除 include 环。+- **P2b(状态归属收敛)**:**重写 `DrawList::execute`** — 每个合并命令解析出 PipelineDesc → `setPipeline` + 动态 scissor/stencilRef/纹理 + draw(一条路径,**删掉 `customDraw` 特例**,shape 变普通 pipeline:program=shape、layout=Shape)。**退役 `StateTracker`**(删 `.hpp/.cpp` + 单测):GPU 状态归属收归 GLDevice,`pipeline-skip` 替代了它对昂贵 program/blend/stencil 的去冗余,per-draw 动态状态直接应用(sort+merge 已粗粒度分组,几无冗余)。`ImmediateDraw` 迁到单一 pipeline + `setPipeline`;`RenderFrame`/`EstellaContext` 去掉 StateTracker 注入;`invalidatePipelineCache` 在 flush/replay/imm-begin 阶段首调用(防外部直接改 program 后 stale)。删了 RenderFrame 无调用者的 stencil 透传 API。+- **决策**:不采用"双缓存 + 每阶段 resync"的折中(那是补丁)——单一状态归属是最佳架构。`DrawCommand`/`buildSortKey`/`canMergeWith` **保持不变**(现有 key 已按 shader+blend+state+texture 分组 = pipeline 一致的批;execute 在 draw 时解析 handle,用 1-entry memo 跳过排序后连续相同 desc 的查找)。`depthWrite` 保持 on(test off),匹配旧 2D 状态以保像素一致。+- **价值**:单一后端无关命令编码层,`WebGPUDevice` 可作为 `GfxDevice` 子类插入;状态归属单一、无双缓存。+- **验证**:emscripten web 构建链接通过;headless `verify:render` 四场景(含 ui-layout 的 stencil 遮罩)像素与 P0/P1 基线**逐项完全一致**;渲染器单测编译通过。### P3 — 加法层(独立排期,依赖 P2)- `WebGPUDevice` 后端 + GLSL→WGSL;微信保 WebGL2 双后端(RC7-4)。@@ -185,8 +186,8 @@ TS/WASM 边界对 uniform 布局**不透明**:`renderer_begin(viewProjPtr, tar| 阶段 | 状态 ||---|---|| 方案文档 | ✅ 本文 |-| P0 提交路径统一 | ⬜ OPEN(建议先行) |-| P1 UBO + FrameUBO | ⬜ OPEN |-| P2 PipelineState/BindGroup keystone | ⬜ OPEN |-| P3 WebGPU / render graph / shader 变体 | ⬜ OPEN(加法层) |-| 正交快赢 RC7-1/7-2 | ⬜ OPEN(可并行) |+| P0 提交路径统一 | ✅ DONE(commit e23b1ff5 / 675777a3) |+| P1 FrameConstants UBO + batch ES3.00 | ✅ DONE(commit d80619e7) |+| P2 PipelineState keystone(P2a 抽象 + P2b 状态收敛) | ✅ DONE(P2a commit 1b1bc9c3;P2b 待提交) |+| P3 WebGPU / render graph / shader 变体 | ⬜ OPEN(加法层,依赖 P2) |+| 正交快赢 RC7-1/7-2 | ⬜ OPEN(可并行,不依赖 keystone) |diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cppindex f161cfd51..50a33ef69 100644--- a/src/esengine/core/EstellaContext.cpp+++ b/src/esengine/core/EstellaContext.cpp@@ -10,7 +10,6 @@#include "Log.hpp"#include "../renderer/GLDevice.hpp"-#include "../renderer/StateTracker.hpp"#include "../renderer/RenderContext.hpp"#include "../renderer/RenderFrame.hpp"#include "../renderer/ImmediateDraw.hpp"@@ -105,14 +104,8 @@ void EstellaContext::initSubsystems() {renderContext->init();services_.registerOwned<RenderContext>(std::move(renderContext));- // Single per-App GPU state cache. RenderContext::init() above already ran- // device_.init() (enabling the GL context), so the tracker's initial state- // sync is valid here. Every renderer subsystem borrows this one instance so- // the cache stays authoritative across the whole frame.- auto stateTracker = makeUnique<StateTracker>(*gfxDevicePtr);- stateTracker->init();- auto* statePtr = stateTracker.get();- services_.registerOwned<StateTracker>(std::move(stateTracker));+ // GPU state is owned by the device: pipelines (setPipeline) carry program/blend/depth/+ // stencil/cull, so there is no separate per-App state tracker to wire up here.// GPU-independent logic systems (Transform/UI/Tween) are registered here too// for the shutdown()+init() re-init path; the constructor already registered@@ -126,7 +119,7 @@ void EstellaContext::initSubsystems() {auto* rm = services_.getService<resource::ResourceManager>();auto* rc = services_.getService<RenderContext>();- auto immediateDraw = makeUnique<ImmediateDraw>(*gfxDevicePtr, *statePtr, *rc, *rm);+ auto immediateDraw = makeUnique<ImmediateDraw>(*gfxDevicePtr, *rc, *rm);immediateDraw->init();services_.registerOwned<ImmediateDraw>(std::move(immediateDraw));@@ -137,7 +130,7 @@ void EstellaContext::initSubsystems() {services_.registerOwned<tilemap::TiledMapLoader>(makeUnique<tilemap::TiledMapLoader>());#endif- auto renderFrame = makeUnique<RenderFrame>(*gfxDevicePtr, *statePtr, *rc, *rm);+ auto renderFrame = makeUnique<RenderFrame>(*gfxDevicePtr, *rc, *rm);renderFrame->addPlugin(std::make_unique<SpritePlugin>());renderFrame->addPlugin(std::make_unique<UIElementPlugin>());renderFrame->addPlugin(std::make_unique<TextPlugin>());diff --git a/src/esengine/renderer/DrawList.cpp b/src/esengine/renderer/DrawList.cppindex 1377323f4..387a22ddd 100644--- a/src/esengine/renderer/DrawList.cpp+++ b/src/esengine/renderer/DrawList.cpp@@ -58,50 +58,56 @@ void DrawList::finalize() {merged_draw_calls_ = writeIdx;}-void DrawList::execute(GfxDevice& device, StateTracker& state, TransientBufferPool& buffers,- FrameCapture* capture,- const CustomDrawFn& customDraw) {- u32 lastShader = 0;+void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,+ FrameCapture* capture) {+ PipelineDesc lastDesc{};+ PipelineHandle lastHandle = PipelineHandle::Invalid;+for (u32 i = 0; i < merged_draw_calls_; ++i) {const auto& cmd = commands_[i];- if (cmd.shader_id != lastShader) {- state.useProgram(cmd.shader_id);- lastShader = cmd.shader_id;+ GfxStencilMode stencil = GfxStencilMode::Off;+ if (cmd.state_flags & CMD_STATE_STENCIL_WRITE) stencil = GfxStencilMode::Write;+ else if (cmd.state_flags & CMD_STATE_STENCIL_TEST) stencil = GfxStencilMode::Test;++ // Resolve the immutable pipeline. depthWrite stays on with the test off, matching+ // the engine's 2D state. createPipeline caches; a one-entry memo skips the lookup+ // for the common run of identical consecutive (sorted) commands.+ PipelineDesc desc{};+ desc.program = cmd.shader_id;+ desc.vertexLayout = cmd.layout_id;+ desc.blend = cmd.blend_mode;+ desc.blendEnabled = true;+ desc.depthTest = false;+ desc.depthWrite = true;+ desc.stencil = stencil;+ desc.cullEnabled = false;++ if (lastHandle == PipelineHandle::Invalid || !(desc == lastDesc)) {+ lastHandle = device.createPipeline(desc);+ lastDesc = desc;}- state.setBlendMode(cmd.blend_mode);+ device.setPipeline(lastHandle);+ // Dynamic per-draw state (sorted+merged draws already group these coarsely).if (cmd.state_flags & CMD_STATE_SCISSOR) {- state.setScissorEnabled(true);- state.setScissor(cmd.scissor.x, cmd.scissor.y, cmd.scissor.w, cmd.scissor.h);+ device.setScissorTest(true);+ device.setScissor(cmd.scissor.x, cmd.scissor.y, cmd.scissor.w, cmd.scissor.h);} else {- state.setScissorEnabled(false);+ device.setScissorTest(false);}-- if (cmd.state_flags & CMD_STATE_STENCIL_WRITE) {- state.beginStencilWrite(cmd.stencil_ref);- } else if (cmd.state_flags & CMD_STATE_STENCIL_TEST) {- state.beginStencilTest(cmd.stencil_ref);- } else {- state.endStencilTest();+ if (stencil != GfxStencilMode::Off) {+ device.setStencilReference(cmd.stencil_ref);}-for (u8 slot = 0; slot < cmd.texture_count; ++slot) {- state.bindTexture(slot, cmd.texture_ids[slot]);+ device.bindTexture(slot, cmd.texture_ids[slot]);}- bool isCustom = (cmd.state_flags & CMD_STATE_CUSTOM_DRAW) != 0;-- if (isCustom && customDraw) {- customDraw(cmd, state, buffers);- } else {- buffers.bindLayout(cmd.layout_id);-- device.drawElements(- cmd.index_count,- GfxDataType::UnsignedInt,- static_cast<u32>(static_cast<uintptr_t>(cmd.index_offset) * sizeof(u32)));- }+ buffers.bindLayout(cmd.layout_id);+ device.drawElements(+ cmd.index_count,+ GfxDataType::UnsignedInt,+ static_cast<u32>(static_cast<uintptr_t>(cmd.index_offset) * sizeof(u32)));if (capture && capture->isCapturing()) {capture->recordDrawCall(diff --git a/src/esengine/renderer/DrawList.hpp b/src/esengine/renderer/DrawList.hppindex edc9dd09f..d876e1250 100644--- a/src/esengine/renderer/DrawList.hpp+++ b/src/esengine/renderer/DrawList.hpp@@ -3,21 +3,13 @@#include "../core/Types.hpp"#include "DrawCommand.hpp"#include "GfxDevice.hpp"-#include "StateTracker.hpp"#include "TransientBufferPool.hpp"#include "FrameCapture.hpp"-#include <glm/glm.hpp>#include <vector>-#include <functional>namespace esengine {-struct RenderFrameContext;--using CustomDrawFn = std::function<void(const DrawCommand& cmd, StateTracker& state,- TransientBufferPool& buffers)>;-class DrawList {public:void clear();@@ -25,11 +17,12 @@ public:void finalize();- // Per-frame constants (view-projection) come from the FrameConstants UBO bound by- // RenderContext, not a uniform argument — every batched shader reads it from there.- void execute(GfxDevice& device, StateTracker& state, TransientBufferPool& buffers,- FrameCapture* capture = nullptr,- const CustomDrawFn& customDraw = nullptr);+ // Each merged command resolves to an immutable pipeline (program + layout + blend ++ // depth + stencil + cull) bound via GfxDevice::setPipeline; per-draw dynamic state+ // (scissor, stencil ref, textures) is applied directly. Per-frame constants come from+ // the FrameConstants UBO bound by RenderContext.+ void execute(GfxDevice& device, TransientBufferPool& buffers,+ FrameCapture* capture = nullptr);u32 commandCount() const { return static_cast<u32>(commands_.size()); }u32 mergedDrawCallCount() const { return merged_draw_calls_; }diff --git a/src/esengine/renderer/GLDevice.cpp b/src/esengine/renderer/GLDevice.cppindex 78eb36f2b..43b9860f2 100644--- a/src/esengine/renderer/GLDevice.cpp+++ b/src/esengine/renderer/GLDevice.cpp@@ -657,6 +657,11 @@ void GLDevice::setStencilReference(i32 ref) {}}+void GLDevice::invalidatePipelineCache() {+ current_pipeline_ = PipelineHandle::Invalid;+ current_stencil_mode_ = GfxStencilMode::Off;+}+// =============================================================================// VAO Operations// =============================================================================diff --git a/src/esengine/renderer/GLDevice.hpp b/src/esengine/renderer/GLDevice.hppindex e2222c427..246e1baef 100644--- a/src/esengine/renderer/GLDevice.hpp+++ b/src/esengine/renderer/GLDevice.hpp@@ -93,6 +93,7 @@ public:PipelineHandle createPipeline(const PipelineDesc& desc) override;void setPipeline(PipelineHandle handle) override;void setStencilReference(i32 ref) override;+ void invalidatePipelineCache() override;u32 createVertexArray() override;void deleteVertexArray(u32 vaoId) override;diff --git a/src/esengine/renderer/GfxDevice.hpp b/src/esengine/renderer/GfxDevice.hppindex 35bd64b88..fc9c87b31 100644--- a/src/esengine/renderer/GfxDevice.hpp+++ b/src/esengine/renderer/GfxDevice.hpp@@ -35,8 +35,10 @@ namespace esengine {/*** @brief Abstract graphics device interface*- * @details Stateless command interface — each method maps 1:1 to a GPU API call.- * StateTracker wraps this with caching to eliminate redundant state changes.+ * @details The device owns its state: setPipeline binds an immutable pipeline and skips+ * re-applying it when unchanged, so the renderer no longer micro-manages GL state+ * 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;@@ -245,6 +247,14 @@ public:/** @brief Sets the dynamic stencil reference for the bound pipeline's stencil mode (no-op if Off). */virtual void setStencilReference(i32 ref) = 0;+ /**+ * @brief Forces the next setPipeline to re-apply, dropping the cached current pipeline.+ * @details Call at the start of a render phase (frame flush, immediate-draw begin) so a+ * pipeline left bound by a prior phase — or by a direct-state path like custom+ * geometry — is not mistaken for the current one.+ */+ virtual void invalidatePipelineCache() = 0;+// =========================================================================// VAO Operations// =========================================================================diff --git a/src/esengine/renderer/ImmediateDraw.cpp b/src/esengine/renderer/ImmediateDraw.cppindex f48a65806..505b6a2f6 100644--- a/src/esengine/renderer/ImmediateDraw.cpp+++ b/src/esengine/renderer/ImmediateDraw.cpp@@ -1,9 +1,9 @@/*** @file ImmediateDraw.cpp* @brief Immediate mode 2D drawing implementation- * @details Generates BatchVertex geometry into a TransientBufferPool and draws- * it through StateTracker + GfxDevice — the same path RenderFrame uses.- * Primitives are batched per texture and flushed in submission order.+ * @details Generates BatchVertex geometry into a TransientBufferPool and draws it+ * through a GfxDevice pipeline — the same path RenderFrame uses. Primitives+ * are batched per texture and flushed in submission order.** @author ESEngine Team* @date 2026@@ -14,7 +14,6 @@#include "ImmediateDraw.hpp"#include "GfxDevice.hpp"-#include "StateTracker.hpp"#include "RenderContext.hpp"#include "Shader.hpp"#include "BatchVertex.hpp"@@ -39,10 +38,9 @@ constexpr glm::vec2 QUAD_UV[4] = {} // namespace-ImmediateDraw::ImmediateDraw(GfxDevice& device, StateTracker& state, RenderContext& context,+ImmediateDraw::ImmediateDraw(GfxDevice& device, RenderContext& context,resource::ResourceManager& resource_manager): device_(device)- , state_(state), context_(context), resource_manager_(resource_manager), pool_(device) {@@ -68,10 +66,23 @@ void ImmediateDraw::init() {Shader* shader = resource_manager_.getShader(handle);if (shader && shader->isValid()) {batch_shader_id_ = shader->getProgramId();- state_.useProgram(batch_shader_id_);+ device_.useProgram(batch_shader_id_);i32 texLoc = device_.getUniformLocation(batch_shader_id_, "u_texture");if (texLoc >= 0) device_.setUniform1i(texLoc, 0);- state_.useProgram(0);+ device_.useProgram(0);++ // 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.vertexLayout = LayoutId::Batch;+ desc.blend = BlendMode::Normal;+ desc.blendEnabled = true;+ desc.depthTest = false;+ desc.depthWrite = true;+ desc.stencil = GfxStencilMode::Off;+ desc.cullEnabled = false;+ pipeline_ = device_.createPipeline(desc);} else {ES_LOG_ERROR("ImmediateDraw: failed to create batch shader");}@@ -92,9 +103,8 @@ void ImmediateDraw::begin(const glm::mat4& viewProjection) {// The batch shader reads u_projection from the shared FrameConstants UBO; update it// for this pass rather than uploading a loose uniform per flush.context_.updateFrameConstants(viewProjection);- state_.setBlendEnabled(true);- state_.setBlendMode(BlendMode::Normal);- state_.setDepthTest(false);+ // A prior phase may have left another pipeline bound; force our pipeline to re-apply.+ device_.invalidatePipelineCache();pool_.beginFrame();currentTexture_ = white_texture_id_;@@ -109,8 +119,8 @@ void ImmediateDraw::flush() {pool_.upload();- state_.useProgram(batch_shader_id_);- state_.bindTexture(0, currentTexture_);+ device_.setPipeline(pipeline_);+ device_.bindTexture(0, currentTexture_);pool_.bindLayout(LayoutId::Batch);device_.drawElements(pool_.indicesUsed(LayoutId::Batch), GfxDataType::UnsignedInt, 0);@@ -124,8 +134,8 @@ void ImmediateDraw::end() {if (!inFrame_) return;flush();- state_.setDepthTest(true);- state_.setBlendMode(BlendMode::Normal);+ // No state restore needed: the next render phase invalidates the pipeline cache and+ // binds its own pipeline, which sets blend/depth/stencil afresh.inFrame_ = false;}diff --git a/src/esengine/renderer/ImmediateDraw.hpp b/src/esengine/renderer/ImmediateDraw.hppindex 41ada1643..ef3a59e6d 100644--- a/src/esengine/renderer/ImmediateDraw.hpp+++ b/src/esengine/renderer/ImmediateDraw.hpp@@ -5,8 +5,8 @@* circles, polygons) with automatic batching for efficient rendering.* All draw commands are cleared each frame.*- * Backed by the same TransientBufferPool + StateTracker + GfxDevice- * machinery as RenderFrame — there is no separate batch renderer.+ * Backed by the same TransientBufferPool + GfxDevice pipeline machinery+ * as RenderFrame — there is no separate batch renderer.** @author ESEngine Team* @date 2026@@ -27,7 +27,6 @@namespace esengine {class GfxDevice;-class StateTracker;class RenderContext;namespace resource {@@ -57,11 +56,10 @@ public:/*** @brief Constructs an immediate draw instance* @param device Graphics device (GPU command sink)- * @param state Shared per-App GPU state cache* @param context Render context for shared resources (white texture)* @param resource_manager Resource manager for shader access*/- ImmediateDraw(GfxDevice& device, StateTracker& state, RenderContext& context,+ ImmediateDraw(GfxDevice& device, RenderContext& context,resource::ResourceManager& resource_manager);~ImmediateDraw();@@ -168,12 +166,12 @@ private:void useTexture(u32 textureId);GfxDevice& device_;- StateTracker& state_;RenderContext& context_;resource::ResourceManager& resource_manager_;TransientBufferPool pool_;u32 batch_shader_id_ = 0;+ PipelineHandle pipeline_ = PipelineHandle::Invalid;u32 white_texture_id_ = 0;u32 currentTexture_ = 0;bool pendingGeometry_ = false;diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cppindex d4db3df63..85ac611ad 100644--- a/src/esengine/renderer/RenderFrame.cpp+++ b/src/esengine/renderer/RenderFrame.cpp@@ -57,12 +57,11 @@ bool Frustum::intersectsAABB(const glm::vec3& center, const glm::vec3& halfExtenreturn true;}-RenderFrame::RenderFrame(GfxDevice& device, StateTracker& state_tracker, RenderContext& context,+RenderFrame::RenderFrame(GfxDevice& device, RenderContext& context,resource::ResourceManager& resource_manager): device_(device), context_(context), resource_manager_(resource_manager)- , state_tracker_(state_tracker), pool_(device) {target_manager_.setDevice(device);}@@ -171,28 +170,14 @@ void RenderFrame::flush() {flushed_ = true;- state_tracker_.reset();- state_tracker_.setBlendEnabled(true);- state_tracker_.setBlendMode(BlendMode::Normal);- state_tracker_.setDepthTest(false);+ // Drop any pipeline a prior phase left bound, so the first draw re-applies its state.+ device_.invalidatePipelineCache();pool_.upload();draw_list_.finalize();- auto ctx = makeContext();-- auto customDrawFn = [this, &ctx](const DrawCommand& cmd, StateTracker& state,- TransientBufferPool& buffers) {- for (auto& plugin : plugins_) {- if (plugin->needsCustomDraw() && plugin->handlesType(cmd.type)) {- plugin->customDraw(cmd, state, buffers, ctx);- return;- }- }- };-context_.updateFrameConstants(view_projection_);- draw_list_.execute(device_, state_tracker_, pool_, &frame_capture_, customDrawFn);+ draw_list_.execute(device_, pool_, &frame_capture_);stats_.draw_calls = draw_list_.mergedDrawCallCount();for (u32 i = 0; i < draw_list_.commandCount(); ++i) {@@ -264,22 +249,23 @@ void RenderFrame::replayToDrawCall(i32 stopAtDrawCall) {if (!rt) return;rt->bind();- state_tracker_.setViewport(0, 0, width_, height_);+ device_.setViewport(0, 0, width_, height_);device_.setClearColor(0.0f, 0.0f, 0.0f, 0.0f);device_.clear(true, false, false);- state_tracker_.reset();- state_tracker_.setBlendEnabled(true);- state_tracker_.setBlendMode(BlendMode::Normal);- state_tracker_.setDepthTest(false);+ device_.invalidatePipelineCache();frame_capture_.setReplayMode(stopAtDrawCall + 1);context_.updateFrameConstants(view_projection_);- draw_list_.execute(device_, state_tracker_, pool_, &frame_capture_);+ draw_list_.execute(device_, pool_, &frame_capture_);- state_tracker_.setScissorEnabled(false);- state_tracker_.endStencilTest();+ // Leave scissor/stencil disabled for whatever renders next; invalidate so the next+ // setPipeline re-applies (we changed stencil/scissor outside the pipeline here).+ device_.setScissorTest(false);+ device_.setStencilTest(false);+ device_.setStencilMask(0xFF);+ device_.invalidatePipelineCache();frame_capture_.clearReplayMode();@@ -318,30 +304,6 @@ void RenderFrame::clearAllStencilMasks() {stencil_masks_.clear();}-void RenderFrame::beginStencilWrite([[maybe_unused]] i32 refValue) {-#ifdef ES_PLATFORM_WEB- state_tracker_.beginStencilWrite(refValue);-#endif-}--void RenderFrame::endStencilWrite() {-#ifdef ES_PLATFORM_WEB- state_tracker_.endStencilWrite();-#endif-}--void RenderFrame::beginStencilTest([[maybe_unused]] i32 refValue) {-#ifdef ES_PLATFORM_WEB- state_tracker_.beginStencilTest(refValue);-#endif-}--void RenderFrame::endStencilTest() {-#ifdef ES_PLATFORM_WEB- state_tracker_.endStencilTest();-#endif-}-// ─── Mask Processing ── see RenderFrameMask.cpp ─────────────────────────────// ─── Tile/Spine Submit ── see RenderFrameSubmit.cpp ──────────────────────────diff --git a/src/esengine/renderer/RenderFrame.hpp b/src/esengine/renderer/RenderFrame.hppindex e44a8cf6b..7d301eb00 100644--- a/src/esengine/renderer/RenderFrame.hpp+++ b/src/esengine/renderer/RenderFrame.hpp@@ -10,7 +10,6 @@#endif#include "FrameCapture.hpp"#include "GfxDevice.hpp"-#include "StateTracker.hpp"#include "TransientBufferPool.hpp"#include "DrawList.hpp"#include "ClipState.hpp"@@ -52,7 +51,7 @@ public:u32 culled = 0;};- RenderFrame(GfxDevice& device, StateTracker& state_tracker, RenderContext& context,+ RenderFrame(GfxDevice& device, RenderContext& context,resource::ResourceManager& resource_manager);~RenderFrame();@@ -77,10 +76,6 @@ public:void setEntityStencilTest(u32 entity, i32 refValue);void clearEntityStencilMask(u32 entity);void clearAllStencilMasks();- void beginStencilWrite(i32 refValue);- void endStencilWrite();- void beginStencilTest(i32 refValue);- void endStencilTest();void submitTileQuad(const glm::vec2& position, const glm::vec2& size,@@ -125,7 +120,6 @@ private:GfxDevice& device_;RenderContext& context_;resource::ResourceManager& resource_manager_;- StateTracker& state_tracker_; // owned by EstellaContext (per-App service)#ifdef ES_ENABLE_POSTPROCESSUnique<PostProcessPipeline> post_process_;diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hppindex 115de2b6a..8b1d0ebe6 100644--- a/src/esengine/renderer/RenderTypePlugin.hpp+++ b/src/esengine/renderer/RenderTypePlugin.hpp@@ -7,7 +7,6 @@#include "DrawList.hpp"#include "ClipState.hpp"#include "TransientBufferPool.hpp"-#include "StateTracker.hpp"#include "../ecs/Registry.hpp"#include "../resource/ResourceManager.hpp"@@ -46,15 +45,6 @@ public:virtual u32 skipFlag() const { return 0; }virtual void collect(RenderCollectContext& ctx) = 0;-- virtual bool needsCustomDraw() const { return false; }- virtual bool handlesType(RenderType type) const { (void)type; return false; }- virtual void customDraw(const DrawCommand& cmd,- StateTracker& state,- TransientBufferPool& buffers,- RenderFrameContext& ctx) {- (void)cmd; (void)state; (void)buffers; (void)ctx;- }};} // namespace esenginediff --git a/src/esengine/renderer/Shader.cpp b/src/esengine/renderer/Shader.cppindex 9a9f12917..ea4d63eb3 100644--- a/src/esengine/renderer/Shader.cpp+++ b/src/esengine/renderer/Shader.cpp@@ -114,9 +114,8 @@ Unique<Shader> Shader::createFromFile(GfxDevice& device,}void Shader::bind() const {- // NOTE: routes through the device, not the StateTracker cache yet. Once the- // legacy Renderer/BatchRenderer2D are retired, the remaining bind sites flip- // to StateTracker::useProgram and this method is removed (RC5).+ // 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_);}diff --git a/src/esengine/renderer/StateTracker.cpp b/src/esengine/renderer/StateTracker.cppdeleted file mode 100644index c9738cc98..000000000--- a/src/esengine/renderer/StateTracker.cpp+++ /dev/null@@ -1,202 +0,0 @@-#include "StateTracker.hpp"--namespace esengine {--StateTracker::StateTracker(GfxDevice& device)- : device_(device) {-}--void StateTracker::init() {- reset();- initialized_ = true;-}--void StateTracker::reset() {- device_.setBlendEnabled(true);- device_.setBlendMode(BlendMode::Normal);- blend_mode_ = BlendMode::Normal;- blend_enabled_ = true;-- device_.setScissorTest(false);- scissor_enabled_ = false;- scissor_x_ = 0;- scissor_y_ = 0;- scissor_w_ = 0;- scissor_h_ = 0;-- device_.setStencilTest(false);- device_.setStencilMask(0xFF);- stencil_state_ = StencilState::Off;- stencil_ref_ = 0;-- device_.setDepthTest(false);- device_.setDepthWrite(true);- depth_test_ = false;- depth_write_ = true;-- device_.setCulling(false);- cull_enabled_ = false;- cull_front_ = false;-- current_program_ = 0;- bound_textures_.fill(0);-- // The actual VAO/buffer/framebuffer GL bindings are not forced here, so mark- // them unknown: the first bind of each per frame then always issues, which is- // correct regardless of leftover GL state and costs at most one bind/frame.- vao_bound_ = UNKNOWN_BINDING;- vertex_buffer_bound_ = UNKNOWN_BINDING;- index_buffer_bound_ = UNKNOWN_BINDING;- framebuffer_bound_ = UNKNOWN_BINDING;-- vp_x_ = -1;- vp_y_ = -1;- vp_w_ = 0;- vp_h_ = 0;-}--void StateTracker::setBlendEnabled(bool enabled) {- if (blend_enabled_ == enabled) return;- blend_enabled_ = enabled;- device_.setBlendEnabled(enabled);-}--void StateTracker::setBlendMode(BlendMode mode) {- if (mode == blend_mode_) return;- blend_mode_ = mode;- device_.setBlendMode(mode);-}--void StateTracker::resetBlendState() {- blend_mode_ = BlendMode::Normal;-}--void StateTracker::setScissorEnabled(bool enabled) {- if (scissor_enabled_ == enabled) return;- scissor_enabled_ = enabled;- device_.setScissorTest(enabled);-}--void StateTracker::setScissor(i32 x, i32 y, i32 w, i32 h) {- if (scissor_x_ == x && scissor_y_ == y && scissor_w_ == w && scissor_h_ == h) return;- scissor_x_ = x;- scissor_y_ = y;- scissor_w_ = w;- scissor_h_ = h;- device_.setScissor(x, y, w, h);-}--void StateTracker::beginStencilWrite(i32 refValue) {- if (stencil_state_ == StencilState::Write && stencil_ref_ == refValue) return;- stencil_state_ = StencilState::Write;- stencil_ref_ = refValue;- device_.setStencilTest(true);- device_.setStencilFunc(GfxStencilFunc::Always, refValue, 0xFF);- device_.setStencilOp(GfxStencilOp::Keep, GfxStencilOp::Keep, GfxStencilOp::Replace);- device_.setColorMask(false, false, false, false);- device_.setStencilMask(0xFF);-}--void StateTracker::endStencilWrite() {- device_.setColorMask(true, true, true, true);- device_.setStencilMask(0x00);-}--void StateTracker::beginStencilTest(i32 refValue) {- if (stencil_state_ == StencilState::Test && stencil_ref_ == refValue) return;- stencil_state_ = StencilState::Test;- stencil_ref_ = refValue;- device_.setStencilTest(true);- device_.setStencilFunc(GfxStencilFunc::Equal, refValue, 0xFF);- device_.setStencilOp(GfxStencilOp::Keep, GfxStencilOp::Keep, GfxStencilOp::Keep);- device_.setStencilMask(0x00);-}--void StateTracker::endStencilTest() {- if (stencil_state_ == StencilState::Off) return;- stencil_state_ = StencilState::Off;- stencil_ref_ = 0;- device_.setStencilTest(false);- device_.setStencilMask(0xFF);-}--void StateTracker::bindTexture(u32 slot, u32 textureId) {- if (slot < MAX_TEXTURE_SLOTS && bound_textures_[slot] == textureId) return;- if (slot < MAX_TEXTURE_SLOTS) {- bound_textures_[slot] = textureId;- }- device_.bindTexture(slot, textureId);-}--void StateTracker::useProgram(u32 programId) {- if (current_program_ == programId) return;- current_program_ = programId;- device_.useProgram(programId);-}--void StateTracker::bindVertexArray(u32 vaoId) {- if (vao_bound_ == vaoId) return;- vao_bound_ = vaoId;- device_.bindVertexArray(vaoId);- // The element-array (index) buffer binding is part of VAO state, so the- // freshly bound VAO now defines it — our cache no longer reflects reality.- index_buffer_bound_ = UNKNOWN_BINDING;-}--void StateTracker::bindVertexBuffer(u32 bufferId) {- if (vertex_buffer_bound_ == bufferId) return;- vertex_buffer_bound_ = bufferId;- device_.bindVertexBuffer(bufferId);-}--void StateTracker::bindIndexBuffer(u32 bufferId) {- if (index_buffer_bound_ == bufferId) return;- index_buffer_bound_ = bufferId;- device_.bindIndexBuffer(bufferId);-}--void StateTracker::bindFramebuffer(u32 fboId) {- if (framebuffer_bound_ == fboId) return;- framebuffer_bound_ = fboId;- device_.bindFramebuffer(fboId);-}--void StateTracker::invalidateBufferBindings() {- vertex_buffer_bound_ = UNKNOWN_BINDING;- index_buffer_bound_ = UNKNOWN_BINDING;-}--void StateTracker::setDepthTest(bool enabled) {- if (depth_test_ == enabled) return;- depth_test_ = enabled;- device_.setDepthTest(enabled);-}--void StateTracker::setDepthWrite(bool enabled) {- if (depth_write_ == enabled) return;- depth_write_ = enabled;- device_.setDepthWrite(enabled);-}--void StateTracker::setViewport(i32 x, i32 y, u32 w, u32 h) {- if (vp_x_ == x && vp_y_ == y && vp_w_ == w && vp_h_ == h) return;- vp_x_ = x;- vp_y_ = y;- vp_w_ = w;- vp_h_ = h;- device_.setViewport(x, y, w, h);-}--void StateTracker::setCulling(bool enabled) {- if (cull_enabled_ == enabled) return;- cull_enabled_ = enabled;- device_.setCulling(enabled);-}--void StateTracker::setCullFace(bool front) {- if (cull_front_ == front) return;- cull_front_ = front;- device_.setCullFace(front);-}--} // namespace esenginediff --git a/src/esengine/renderer/StateTracker.hpp b/src/esengine/renderer/StateTracker.hppdeleted file mode 100644index ceaf1f973..000000000--- a/src/esengine/renderer/StateTracker.hpp+++ /dev/null@@ -1,97 +0,0 @@-#pragma once--#include "../core/Types.hpp"-#include "BlendMode.hpp"-#include "GfxDevice.hpp"--#include <array>--namespace esengine {--class StateTracker {-public:- explicit StateTracker(GfxDevice& device);-- void init();- void reset();-- void setBlendEnabled(bool enabled);- void setBlendMode(BlendMode mode);- void resetBlendState();-- void setScissorEnabled(bool enabled);- void setScissor(i32 x, i32 y, i32 w, i32 h);-- void beginStencilWrite(i32 refValue);- void endStencilWrite();- void beginStencilTest(i32 refValue);- void endStencilTest();-- void bindTexture(u32 slot, u32 textureId);-- void useProgram(u32 programId);-- // -- Buffer / VAO / framebuffer binding (the binds resource classes used to- // issue raw, silently desyncing this cache). Routing them here keeps the- // cache authoritative for the whole engine.- void bindVertexArray(u32 vaoId);- void bindVertexBuffer(u32 bufferId);- void bindIndexBuffer(u32 bufferId);- void bindFramebuffer(u32 fboId);-- /**- * @brief Drops the cached vertex/index buffer bindings.- * @details Use before re-issuing the explicit VBO+attrib+IBO rebind that- * works around the WeChat WebGL VAO state-restoration bug, so the- * rebinds are not deduped away.- */- void invalidateBufferBindings();-- void setDepthTest(bool enabled);- void setDepthWrite(bool enabled);-- void setViewport(i32 x, i32 y, u32 w, u32 h);-- void setCulling(bool enabled);- void setCullFace(bool front);-- /** @brief Gets the underlying graphics device */- GfxDevice& device() { return device_; }-- static constexpr u32 MAX_TEXTURE_SLOTS = 16;--private:- GfxDevice& device_;-- BlendMode blend_mode_ = BlendMode::Normal;- bool blend_enabled_ = true;-- bool scissor_enabled_ = false;- i32 scissor_x_ = 0, scissor_y_ = 0, scissor_w_ = 0, scissor_h_ = 0;-- enum class StencilState : u8 { Off, Write, Test };- StencilState stencil_state_ = StencilState::Off;- i32 stencil_ref_ = 0;-- bool depth_test_ = false;- bool depth_write_ = true;-- u32 current_program_ = 0;- std::array<u32, MAX_TEXTURE_SLOTS> bound_textures_{};-- static constexpr u32 UNKNOWN_BINDING = 0xFFFFFFFFu;- u32 vao_bound_ = 0;- u32 vertex_buffer_bound_ = 0;- u32 index_buffer_bound_ = 0;- u32 framebuffer_bound_ = 0;-- i32 vp_x_ = -1, vp_y_ = -1;- u32 vp_w_ = 0, vp_h_ = 0;-- bool cull_enabled_ = false;- bool cull_front_ = false;-- bool initialized_ = false;-};--} // namespace esenginediff --git a/src/esengine/renderer/plugins/ShapePlugin.cpp b/src/esengine/renderer/plugins/ShapePlugin.cppindex 799209106..7987f5267 100644--- a/src/esengine/renderer/plugins/ShapePlugin.cpp+++ b/src/esengine/renderer/plugins/ShapePlugin.cpp@@ -111,7 +111,6 @@ void ShapePlugin::collect(RenderCollectContext& collect_ctx) {cmd.entity = entity;cmd.type = RenderType::Shape;cmd.layer = shape.layer;- cmd.state_flags |= CMD_STATE_CUSTOM_DRAW;clips.applyTo(entity, cmd);@@ -119,27 +118,4 @@ void ShapePlugin::collect(RenderCollectContext& collect_ctx) {}}-void ShapePlugin::customDraw(- const DrawCommand& cmd,- StateTracker& state,- TransientBufferPool& buffers,- RenderFrameContext& ctx-) {- Shader* shader = ctx.resources.getShader(shape_shader_handle_);- if (!shader || !shader->isValid()) return;-- shader->bind();- // u_projection comes from the shared FrameConstants UBO (linked at compile time).-- state.setBlendEnabled(true);- state.setBlendMode(BlendMode::Normal);-- buffers.bindLayout(LayoutId::Shape);-- state.device().drawElements(- cmd.index_count,- GfxDataType::UnsignedInt,- static_cast<u32>(cmd.index_offset * sizeof(u32)));-}-} // namespace esenginediff --git a/src/esengine/renderer/plugins/ShapePlugin.hpp b/src/esengine/renderer/plugins/ShapePlugin.hppindex 5a306d37e..3ea8bfeb8 100644--- a/src/esengine/renderer/plugins/ShapePlugin.hpp+++ b/src/esengine/renderer/plugins/ShapePlugin.hpp@@ -13,13 +13,6 @@ public:void collect(RenderCollectContext& ctx) override;- bool needsCustomDraw() const override { return true; }- bool handlesType(RenderType type) const override { return type == RenderType::Shape; }- void customDraw(const DrawCommand& cmd,- StateTracker& state,- TransientBufferPool& buffers,- RenderFrameContext& ctx) override;-private:struct ShapeVertex {f32 px, py;diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex 139deac21..e925aa8d3 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -45,16 +45,6 @@ add_executable(test_resource_pooltarget_link_libraries(test_resource_pool PRIVATE esengine)add_test(NAME test_resource_pool COMMAND test_resource_pool)-# Renderer GPU state-cache tests.-# Compiles StateTracker.cpp directly against a MockGfxDevice — no GL/engine link,-# so it runs on any C++20 toolchain (CI doesn't need emsdk for this).-add_executable(test_state_tracker- renderer/test_state_tracker.cpp- ${CMAKE_SOURCE_DIR}/src/esengine/renderer/StateTracker.cpp-)-target_include_directories(test_state_tracker PRIVATE ${CMAKE_SOURCE_DIR}/src)-add_test(NAME test_state_tracker COMMAND test_state_tracker)-# Shader-vs-device decoupling: compiles the converted Shader.cpp against a# MockGfxDevice. Linking proves Shader contains no GL; asserts confirm it routes# create/uniform/reflect/delete through GfxDevice.diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hppindex 68fea87db..432506c3c 100644--- a/tests/renderer/MockGfxDevice.hpp+++ b/tests/renderer/MockGfxDevice.hpp@@ -119,6 +119,7 @@ struct MockGfxDevice final : GfxDevice {PipelineHandle createPipeline(const PipelineDesc&) override { return static_cast<PipelineHandle>(++nextPipelineId); }void setPipeline(PipelineHandle) override { ++setPipelineCalls; }void setStencilReference(i32) override {}+ void invalidatePipelineCache() override {}u32 createVertexArray() override { ++createVertexArrayCalls; return nextVaoId++; }void deleteVertexArray(u32) override { ++deleteVertexArrayCalls; }diff --git a/tests/renderer/test_state_tracker.cpp b/tests/renderer/test_state_tracker.cppdeleted file mode 100644index c8b24a5e2..000000000--- a/tests/renderer/test_state_tracker.cpp+++ /dev/null@@ -1,95 +0,0 @@-// Native MSVC/CTest harness for StateTracker (RC5-GfxDevice).-//-// Compiles StateTracker.cpp against MockGfxDevice — no GL, no glm. Verifies the-// bind-dedup cache (program/texture/VAO/VBO/IBO/FBO) that makes StateTracker the-// single authoritative GPU-state cache.--#include "MockGfxDevice.hpp"-#include "esengine/renderer/StateTracker.hpp"--#include <cstdio>--using namespace esengine;--static int g_failures = 0;-#define CHECK(cond, msg) \- do { \- if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \- else { std::printf("ok: %s\n", msg); } \- } while (0)--int main() {- // --- program dedup ---- {- MockGfxDevice d;- StateTracker s(d);- s.init();- s.useProgram(7);- s.useProgram(7);- s.useProgram(9);- CHECK(d.useProgramCalls == 2, "useProgram dedups repeats (7,7,9 -> 2 calls)");- }-- // --- VAO dedup + IBO invalidation on VAO bind ---- {- MockGfxDevice d;- StateTracker s(d);- s.init();- s.bindVertexArray(5);- s.bindVertexArray(5); // deduped- CHECK(d.bindVertexArrayCalls == 1, "bindVertexArray dedups repeats");-- s.bindIndexBuffer(7); // VAO bind invalidated ibo cache -> issues- s.bindIndexBuffer(7); // now cached -> deduped- CHECK(d.bindIndexBufferCalls == 1, "bindIndexBuffer dedups after first bind");-- s.bindVertexArray(6); // new VAO -> ibo cache invalidated again- s.bindIndexBuffer(7); // must re-issue: VAO carries its own element binding- CHECK(d.bindIndexBufferCalls == 2, "VAO rebind re-issues index buffer (element binding is VAO state)");- CHECK(d.bindVertexArrayCalls == 2, "second distinct VAO issues");- }-- // --- VBO dedup is global (not VAO state) + invalidate forces rebind ---- {- MockGfxDevice d;- StateTracker s(d);- s.init();- s.bindVertexBuffer(3);- s.bindVertexBuffer(3); // deduped- CHECK(d.bindVertexBufferCalls == 1, "bindVertexBuffer dedups repeats");-- s.invalidateBufferBindings(); // WeChat VAO workaround path- s.bindVertexBuffer(3); // forced through- CHECK(d.bindVertexBufferCalls == 2, "invalidateBufferBindings forces VBO rebind");- }-- // --- framebuffer dedup ---- {- MockGfxDevice d;- StateTracker s(d);- s.init();- s.bindFramebuffer(2);- s.bindFramebuffer(2);- s.bindFramebuffer(0);- CHECK(d.bindFramebufferCalls == 2, "bindFramebuffer dedups repeats (2,2,0 -> 2 calls)");- }-- // --- reset() marks bindings unknown so first bind per frame always issues ---- {- MockGfxDevice d;- StateTracker s(d);- s.init();- s.bindVertexArray(5);- CHECK(d.bindVertexArrayCalls == 1, "initial VAO bind issues");- s.reset();- s.bindVertexArray(5); // same id, but reset marked unknown -> re-issues- CHECK(d.bindVertexArrayCalls == 2, "reset() forces re-issue of same VAO id");- }-- if (g_failures == 0) {- std::printf("\nALL STATE TRACKER TESTS PASSED\n");- return 0;- }- std::printf("\n%d FAILURE(S)\n", g_failures);- return 1;-}