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
perf(render): the GL device skips state sets and uniform-buffer binds the context already holds
yhhdab33c02eaff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 89b7f2ec5..c48f7082c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -42,6 +42,7 @@ published separately; it ships inside the editor.### Changed+- **The GL device no longer sets state the context already holds.** Enabling or disabling depth test, stencil, culling and blend, the depth, colour and stencil write masks, and the binding of a uniform-buffer slot were each sent to the driver on every draw even when the value had not changed. The device now remembers the last value and skips the call (a buffer that is deleted forgets the slots it held). On the terrain-water example a frame makes 10,709 GL calls instead of 26,223, and the CPU side of the frame is about 0.3 to 0.5 ms lighter on a desktop browser; a phone, where each call costs more, gains more. Pixels are unchanged: the 262 WebGL2 render scenes still draw what they claim.- **Writing one material uniform sends that one value, and asking whether the GPU can render to float no longer walks its extension list.** `Material.setUniform` re-defined the whole material and pushed every one of its uniforms into wasm (a string across the boundary each) for each value written, and then did the same for every instance that inherits it, so a system that sets twenty values a frame on a material of sixty made twelve hundred crossings. It sends the value that changed, to the instances that inherit it and not to those that override it; a value the engine already holds is not sent at all; a texture still takes the whole flush, since its lease is counted. In the terrain and water example `setUniform` went from 0.40 to 0.03 ms a frame. The post-process chain asked `supportsFloatTargets()` several times a frame and each ask read every extension the context has through the browser; it is answered once per context. The frame is 6.2-6.7 ms with the engine's profiler off (it was 6.7-6.9 after the last change, and 8.4 before it); every render scene draws what it did (262 of 262 on WebGL2, 248 of 248 on WebGPU). A value handed to two materials as one object and then edited used to reach each of them whenever it next flushed; now each sees the value as it was when written to it.- **A mesh draw no longer searches its shader's source or rebuilds a feature list to find a program it already has.** `MaterialStore::meshProgram`, asked once per mesh draw, looked for "ES_GBUFFER" through the whole text of the material's shader every time and built nine strings and a vector before it checked its cache. The mention is found once when the source is stored and the cache is asked first. With the engine's own profiler off, the terrain and water example's frame at a CPU-bound size went from 8.4 to 6.7-6.9 ms (about 19% less), the same programs are chosen, and every render scene draws what it did (262 of 262 on WebGL2, 248 of 248 on WebGPU). Note for anyone reading the frame costs: switching the engine's profiler on (`render()`, `costs()`, `gpu()` on the cooked hook) made that frame 76% dearer, so a per-phase number from it says where time goes, not what it costs; `render.collect.mesh.<scene|depth>.walks/.visits/.ms` now say which pass walked the meshes and how many times (two per frame in that example: the scene and the sun's shadow).- **The engine's wasm is 239KB smaller, with no change to what it does.** Reordering a component's storage (`Sprite.order` and the authored entity order reach the draw list through it) sorted inside `SparseSet<T>::reorderBy`, so each of the hundred-odd component types carried its own copy of `std::stable_sort` and its merge helpers: 275KB, 15% of the engine's code. The sort never looked at the component, so it is one function now (`SparseSetBase::stablePermutation`) and the template only moves the components along the permutation it returns. The web engine is 2,437,989 bytes, now 2,199,086 (238,903 less); the same sort and the same order: 300 random cases with ties and unranked entities came out identical to the old one, and the terrain and water example draws the same frame at the same cost. `ESTELLA_WASM_NAMES=1` keeps the name section through the optimizer, for a build made to find where the bytes are.diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex 455587794..74b923e08 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -293,6 +293,21 @@ std::string readProgramInfoLog(GLuint program) {// Lifecycle// =============================================================================+void GLDevice::resetDrawStateCaches() {+ for (i8& state : cap_state_) state = -1;+ depth_mask_ = -1;+ color_mask_ = -1;+ stencil_mask_ = -1;+ uniform_bound_.clear();+}++void GLDevice::setCap(Cap cap, u32 glCap, bool enabled) {+ const i8 want = enabled ? 1 : 0;+ if (cap_state_[cap] == want) return;+ cap_state_[cap] = want;+ setCapability(static_cast<GLenum>(glCap), enabled);+}+void GLDevice::init() {float_targets_ = -1;glEnable(GL_DEPTH_TEST);@@ -301,6 +316,8 @@ void GLDevice::init() {glDepthFunc(GL_LESS);glEnable(GL_BLEND);glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);+ // Depth test and blend were just turned on, but a new context knows nothing the old one was told: nothing is assumed held.+ resetDrawStateCaches();captureDeviceIdentity();ES_LOG_DEBUG("GLDevice initialized");}@@ -427,6 +444,7 @@ void GLDevice::resetStateCache() {surface_blend_off_ = false;current_framebuffer_ = 0;timer_query_state_ = 0;+ resetDrawStateCaches();}void GLDevice::shutdown() {@@ -506,8 +524,11 @@ void GLDevice::clear(bool color, bool depth, bool stencil) {// =============================================================================void GLDevice::setBlendEnabled(bool enabled) {+ // Enable/Disable without an index sets every draw buffer: the surface record's own state is gone with it. So while that record's blending is+ // off, asking for what the context holds still has to be made, and only the ask that changes nothing anywhere is skipped.+ if (cap_state_[kCapBlend] == (enabled ? 1 : 0) && !surface_blend_off_) return;setCapability(GL_BLEND, enabled);- // Enable/Disable without an index sets every draw buffer: the surface record's own state is gone with it.+ cap_state_[kCapBlend] = enabled ? 1 : 0;surface_blend_off_ = false;}@@ -563,10 +584,13 @@ void GLDevice::setBlendMode(BlendMode mode) {// =============================================================================void GLDevice::setDepthTest(bool enabled) {- setCapability(GL_DEPTH_TEST, enabled);+ setCap(kCapDepthTest, GL_DEPTH_TEST, enabled);}void GLDevice::setDepthWrite(bool enabled) {+ const i8 want = enabled ? 1 : 0;+ if (depth_mask_ == want) return;+ depth_mask_ = want;glDepthMask(enabled ? GL_TRUE : GL_FALSE);}@@ -575,7 +599,7 @@ void GLDevice::setDepthWrite(bool enabled) {// =============================================================================void GLDevice::setStencilTest(bool enabled) {- setCapability(GL_STENCIL_TEST, enabled);+ setCap(kCapStencilTest, GL_STENCIL_TEST, enabled);}void GLDevice::setStencilFunc(GfxStencilFunc func, i32 ref, u32 mask) {@@ -587,10 +611,15 @@ void GLDevice::setStencilOp(GfxStencilOp sfail, GfxStencilOp dpfail, GfxStencilO}void GLDevice::setStencilMask(u32 mask) {+ if (stencil_mask_ == static_cast<i64>(mask)) return;+ stencil_mask_ = static_cast<i64>(mask);glStencilMask(mask);}void GLDevice::setColorMask(bool r, bool g, bool b, bool a) {+ const i16 bits = static_cast<i16>((r ? 1 : 0) | (g ? 2 : 0) | (b ? 4 : 0) | (a ? 8 : 0));+ if (color_mask_ == bits) return;+ color_mask_ = bits;glColorMask(r ? GL_TRUE : GL_FALSE, g ? GL_TRUE : GL_FALSE,b ? GL_TRUE : GL_FALSE, a ? GL_TRUE : GL_FALSE);}@@ -615,7 +644,7 @@ void GLDevice::setScissor(i32 x, i32 y, i32 w, i32 h) {// =============================================================================void GLDevice::setCulling(bool enabled) {- setCapability(GL_CULL_FACE, enabled);+ setCap(kCapCull, GL_CULL_FACE, enabled);}void GLDevice::setCullFace(bool front) {@@ -945,6 +974,10 @@ void GLDevice::backendDeleteBuffer(u32 id) {if (!name) return;glDeleteBuffers(1, &name);setName(buffer_names_, id, 0);+ // The context unbinds a deleted buffer from the slots that held it; the record of those slots must not go on saying it is there.+ for (UniformBound& bound : uniform_bound_) {+ if (bound.known && bound.name == name) bound = {};+ }}void GLDevice::backendUpdateBuffer(u32 id, u32 offsetBytes, const void* data, u32 sizeBytes) {@@ -964,6 +997,13 @@ void GLDevice::backendSetUniformBuffer(u32 slot, BufferHandle buffer, u32 offsetvoid GLDevice::bindUniformSlot(u32 slot, u32 name) {const UniformRange range = slot < uniform_ranges_.size() ? uniform_ranges_[slot] : UniformRange{};+ // Most binds of a frame are to what the slot holds already: the same frame constants and the same material block, once per draw.+ if (slot >= uniform_bound_.size()) uniform_bound_.resize(static_cast<usize>(slot) + 1);+ UniformBound& held = uniform_bound_[slot];+ const u32 wantSize = name ? range.size : 0;+ const u32 wantOffset = (name && range.size) ? range.offset : 0;+ if (held.known && held.name == name && held.offset == wantOffset && held.size == wantSize) return;+ held = {name, wantOffset, wantSize, true};if (name && range.size) {glBindBufferRange(GL_UNIFORM_BUFFER, slot, name, range.offset, range.size);} else {diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hppindex 3d9b72ae8..ea144f442 100644--- a/src/esengine/renderer/rhi/GLDevice.hpp+++ b/src/esengine/renderer/rhi/GLDevice.hpp@@ -242,6 +242,20 @@ private:std::vector<UniformRange> uniform_ranges_;void bindUniformSlot(u32 slot, u32 name);+ /// What the context is known to hold for the states every draw sets, so one a pipeline sets to what it already is costs no call. A frame of+ /// the terrain and water example made 26,000 GL calls and over half of them said what the context already knew: through the browser each is a+ /// crossing, and on a phone a dear one. -1 is unknown (after init, after a lost context): the next set is made.+ enum Cap : u32 { kCapDepthTest, kCapStencilTest, kCapCull, kCapBlend, kCapCount };+ i8 cap_state_[kCapCount] = {-1, -1, -1, -1};+ i8 depth_mask_ = -1;+ i16 color_mask_ = -1; ///< the four channels as bits+ i64 stencil_mask_ = -1;+ /// The buffer, offset and size each uniform slot was last bound to. A buffer's deletion forgets the slots that held it.+ struct UniformBound { u32 name = 0; u32 offset = 0; u32 size = 0; bool known = false; };+ std::vector<UniformBound> uniform_bound_;+ void setCap(Cap cap, u32 glCap, bool enabled); ///< glCap is the GL enum of the capability (this header holds no GL types)+ void resetDrawStateCaches();+u32 current_pipeline_id_ = 0;GfxTopology current_topology_ = GfxTopology::Triangles;GfxStencilMode current_stencil_mode_ = GfxStencilMode::Off;diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 3bbe90bec..7e216eb3a 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -3030,4 +3030,6 @@ export const NOTED = {{"note":"A mesh draw no longer searches its shader's source or rebuilds a feature list"},"perf(render): writing one material uniform sends one value, and the float-target check is asked once":{"note":"Writing one material uniform sends that one value"},+ "perf(render): the GL device skips state sets and uniform-buffer binds the context already holds":+ {"note":"The GL device skips state sets the context already holds"},};