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.

perf(render): writing one material uniform sends one value, and the float-target check is asked once

yhh50410ab1dbf0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5cf0dcff8..89b7f2ec5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,7 @@ published separately; it ships inside the editor.
### Changed
+- **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.
- **A blank mini-game package no longer carries terrain, water and timelines.** The mini-game build was shipping 47KB of terrain and 37KB of water code (and its component definitions) in a project that uses neither: the SDK's shared chunks hold every entry's code together, and a bundler cannot drop a top-level `defineComponent(...)` or `new SomePlugin()` it cannot tell is pure. The chunks now keep their `/* @__PURE__ */` annotations (the minifier that removed them is set to mangle names only; consumers minify again), and terrain, water and timelines mark what only defines something. A blank WeChat package was 3,345,193 bytes and is now 3,234,518 (111KB less, 79.8% of the 4MB main-package cap down to 77.1%); a project that uses terrain, water or a timeline installs them as before. A gate (`lean-bundle`) fails if a blank package carries them again.
diff --git a/sdk/src/render/material.ts b/sdk/src/render/material.ts
index bf1776447..d675e4098 100644
--- a/sdk/src/render/material.ts
+++ b/sdk/src/render/material.ts
@@ -146,6 +146,11 @@ export interface MaterialData {
dirty_: boolean;
cachedBuffer_: Float32Array | null;
cachedIdx_: number;
+ /** What the engine's store holds for each non-texture uniform of this material, as [arity, x, y, z, w]: what was last SENT, not what the caller's
+ * object says now (a caller may reuse and edit one object), which is what lets a write of the number already there be a no-op. */
+ sent_?: Map<string, number[]>;
+ /** The whole material has been defined and pushed once, so the engine holds the rest of it and one changed value may go alone. */
+ pushed_?: boolean;
}
// =============================================================================
@@ -277,9 +282,38 @@ function pushUniform(handle: MaterialHandle, name: string, value: UniformValue):
return;
}
const { arity, values } = classifyUniformArity(value);
+ const data = materials.get(handle);
+ if (data) {
+ let sent = data.sent_;
+ if (!sent) { sent = new Map(); data.sent_ = sent; }
+ const held = sent.get(name);
+ if (held) { held[0] = arity; held[1] = values[0]; held[2] = values[1]; held[3] = values[2]; held[4] = values[3]; }
+ else sent.set(name, [arity, values[0], values[1], values[2], values[3]]);
+ }
module.material_setUniform(handle, name, arity, values[0], values[1], values[2], values[3]);
}
+/** Whether the engine already holds exactly this value for the uniform. */
+function alreadySent(handle: MaterialHandle, name: string, value: Exclude<UniformValue, TextureRef>): boolean {
+ const held = materials.get(handle)?.sent_?.get(name);
+ if (!held) return false;
+ const { arity, values } = classifyUniformArity(value);
+ return held[0] === arity && held[1] === values[0] && held[2] === values[1] && held[3] === values[2] && held[4] === values[3];
+}
+
+/** One changed uniform to the engine, for this material and the instances that inherit it (those that override the name keep their own). */
+function pushChanged(handle: MaterialHandle, name: string, value: UniformValue): void {
+ pushUniform(handle, name, value);
+ const data = materials.get(handle);
+ if (data) data.dirty_ = true;
+ const kids = childrenOf.get(handle);
+ if (!kids) return;
+ for (const child of kids) {
+ if (materials.get(child)?.uniforms.has(name)) continue;
+ pushChanged(child, name, value);
+ }
+}
+
interface ResolvedMaterial {
shader: ShaderHandle;
blendMode: BlendMode;
@@ -326,12 +360,16 @@ function flushMaterial(handle: MaterialHandle, previous?: ReadonlyMap<MaterialHa
// define preserves existing constants and texture bindings. A deleted value
// must return to the shader default, including in inheriting descendants.
const old = previous?.get(handle);
- if (old && [...old.uniforms.keys()].some(name => !resolved.uniforms.has(name)))
+ if (old && [...old.uniforms.keys()].some(name => !resolved.uniforms.has(name))) {
module.material_undefine(handle);
+ materials.get(handle)?.sent_?.clear();
+ }
module.material_define(handle, resolved.shader, resolved.blendMode,
materialFlags(resolved.depthTest, resolved.depthWrite, resolved.cull),
resolved.depthBias);
for (const [name, value] of resolved.uniforms) pushUniform(handle, name, value);
+ const pushed = materials.get(handle);
+ if (pushed) pushed.pushed_ = true;
}
const data = materials.get(handle);
if (data) data.dirty_ = true;
@@ -515,6 +553,19 @@ export const Material = {
const data = materials.get(material);
if (data) {
warnUndeclared(shaderOf(material), name);
+ const previous = data.uniforms.get(name);
+ const plain = !isTextureRef(value) && !(previous !== undefined && isTextureRef(previous));
+ // A value written every frame (a time, a colour, a wave table) is mostly the number the engine already has, and the write is a string
+ // crossing into wasm; and when it does change, the engine holds the rest of the material already, so only that value goes. A texture
+ // is different (it is leased and counted), and a material not yet pushed has nothing to add to: both take the whole flush.
+ if (plain && data.pushed_ && module) {
+ // On an instance, the local uniforms map *is* the override set (presence = override).
+ data.uniforms.set(name, value);
+ if (alreadySent(material, name, value as Exclude<UniformValue, TextureRef>)) return;
+ data.dirty_ = true; // immediate-mode mesh path re-encodes its uniform cache.
+ pushChanged(material, name, value);
+ return;
+ }
// On an instance, the local uniforms map *is* the override set (presence = override).
data.uniforms.set(name, value);
const releasePrevious = replaceTextureOwnership(material, data.uniforms);
diff --git a/sdk/tests/material-uniform-push.test.ts b/sdk/tests/material-uniform-push.test.ts
new file mode 100644
index 000000000..5546067db
--- /dev/null
+++ b/sdk/tests/material-uniform-push.test.ts
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { Material, initMaterialAPI, shutdownMaterialAPI } from '../src/render/material';
+import type { ESEngineModule } from '../src/wasm';
+import { initResourceManager, shutdownResourceManager } from '../src/wasm/resourceManager';
+
+function createMock() {
+ const resourceManager = { createShader: vi.fn().mockReturnValue(1), releaseShader: vi.fn() };
+ return {
+ getResourceManager: vi.fn(() => resourceManager),
+ resourceManager,
+ material_compileEsshader: vi.fn().mockReturnValue(7),
+ material_define: vi.fn(),
+ material_setUniform: vi.fn(),
+ material_setTexture: vi.fn(),
+ material_undefine: vi.fn(),
+ };
+}
+
+describe('writing one uniform of a material', () => {
+ let mock: ReturnType<typeof createMock>;
+
+ beforeEach(() => {
+ mock = createMock();
+ initResourceManager(mock.resourceManager as never);
+ initMaterialAPI(mock as unknown as ESEngineModule);
+ });
+ afterEach(() => {
+ shutdownMaterialAPI();
+ shutdownResourceManager();
+ });
+
+ const made = (uniforms: Record<string, number | { x: number; y: number }> = { u_a: 1, u_b: 2, u_c: { x: 1, y: 2 } }) =>
+ Material.create({ shader: 1, uniforms } as never);
+
+ it('sends the one value that changed, not the whole material again', () => {
+ const m = made();
+ mock.material_define.mockClear();
+ mock.material_setUniform.mockClear();
+ Material.setUniform(m, 'u_a', 5);
+ expect(mock.material_setUniform).toHaveBeenCalledTimes(1);
+ expect(mock.material_setUniform).toHaveBeenCalledWith(m, 'u_a', 1, 5, 0, 0, 0);
+ expect(mock.material_define).not.toHaveBeenCalled();
+ expect(Material.getUniform(m, 'u_a')).toBe(5);
+ });
+
+ it('sends nothing for the number the engine already holds', () => {
+ const m = made();
+ mock.material_setUniform.mockClear();
+ Material.setUniform(m, 'u_a', 1);
+ Material.setUniform(m, 'u_c', { x: 1, y: 2 });
+ expect(mock.material_setUniform).not.toHaveBeenCalled();
+ });
+
+ it('sees a reused object that was edited between two writes', () => {
+ const m = made();
+ const v = { x: 1, y: 2 };
+ Material.setUniform(m, 'u_c', v);
+ mock.material_setUniform.mockClear();
+ v.x = 9;
+ Material.setUniform(m, 'u_c', v);
+ expect(mock.material_setUniform).toHaveBeenCalledWith(m, 'u_c', 2, 9, 2, 0, 0);
+ });
+
+ it('reaches an instance that inherits the value and leaves one that overrides it', () => {
+ const parent = made();
+ const inheriting = Material.createInstance(parent);
+ const overriding = Material.createInstance(parent);
+ Material.setUniform(overriding, 'u_a', 7);
+ mock.material_setUniform.mockClear();
+ Material.setUniform(parent, 'u_a', 3);
+ const hit = mock.material_setUniform.mock.calls.map((c) => c[0]);
+ expect(hit).toContain(parent);
+ expect(hit).toContain(inheriting);
+ expect(hit).not.toContain(overriding);
+ expect(Material.getUniform(overriding, 'u_a')).toBe(7);
+ expect(Material.getUniform(inheriting, 'u_a')).toBe(3);
+ });
+
+ it('still takes the whole flush for a texture', () => {
+ const m = made();
+ mock.material_define.mockClear();
+ Material.setUniform(m, 'u_tex', { __textureRef: true, textureId: 4 } as never);
+ expect(mock.material_define).toHaveBeenCalled();
+ expect(mock.material_setTexture).toHaveBeenCalledWith(m, 'u_tex', 4);
+ });
+
+ it('leaves the engine holding exactly what a full flush would, after any sequence of writes', () => {
+ // The engine's store, as the mock sees it: the last value written per (material, name), forgotten on undefine.
+ const engine = new Map<string, string>();
+ mock.material_setUniform.mockImplementation((id: number, name: string, arity: number, a: number, b: number, c: number, d: number) => {
+ engine.set(`${id}|${name}`, `${arity}:${a},${b},${c},${d}`);
+ });
+ mock.material_undefine.mockImplementation((id: number) => {
+ for (const key of [...engine.keys()]) if (key.startsWith(`${id}|`)) engine.delete(key);
+ });
+ const root = made({ u_a: 1, u_b: 2, u_c: { x: 1, y: 2 }, u_d: 4 });
+ const c1 = Material.createInstance(root);
+ const c2 = Material.createInstance(root);
+ const g = Material.createInstance(c1);
+ const all = [root, c1, c2, g];
+ const names = ['u_a', 'u_b', 'u_c', 'u_d'];
+ let seed = 12345;
+ const rnd = (n: number): number => { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; return (seed >>> 16) % n; };
+ // One edited-and-rewritten object per material: the same object handed to two materials and then edited is held by both, and which of them
+ // sees the edit used to depend on when each next flushed.
+ const reusedBy = new Map<number, { x: number; y: number }>(all.map((handle) => [handle, { x: 1, y: 2 }]));
+ for (let step = 0; step < 500; step++) {
+ const target = all[rnd(all.length)]!;
+ const op = rnd(10);
+ if (op < 7) {
+ const name = names[rnd(names.length)]!;
+ if (name === 'u_c') {
+ // Now a fresh object, now one object edited and written again.
+ if (rnd(2)) { const reused = reusedBy.get(target)!; reused.x = rnd(3); reused.y = rnd(3); Material.setUniform(target, name, reused); }
+ else Material.setUniform(target, name, { x: rnd(3), y: rnd(3) });
+ } else {
+ Material.setUniform(target, name, rnd(4));
+ }
+ } else if (op < 9) {
+ const uniforms: Record<string, number> = {};
+ for (const name of names) if (name !== 'u_c' && rnd(2)) uniforms[name] = rnd(4);
+ Material.applyState(target, { uniforms });
+ } else {
+ Material.setBlendMode(target, rnd(2));
+ }
+ const incremental = new Map(engine);
+ // A full flush of the whole tree: a blend mode that differs from the one it has is what makes the material push itself again.
+ const blend = Material.getBlendMode(root);
+ Material.setBlendMode(root, blend === 0 ? 1 : 0);
+ expect([...engine.entries()].sort()).toEqual([...incremental.entries()].sort());
+ Material.setBlendMode(root, blend);
+ }
+ });
+});
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index eaa51132d..455587794 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -294,6 +294,7 @@ std::string readProgramInfoLog(GLuint program) {
// =============================================================================
void GLDevice::init() {
+ float_targets_ = -1;
glEnable(GL_DEPTH_TEST);
// GL's own default, stated because the second backend states it too: a rule
// one backend declares and the other inherits can drift with neither saying so.
@@ -1824,10 +1825,14 @@ bool GLDevice::supportsCompressedFormat(GfxCompressedFormat format) {
}
bool GLDevice::supportsFloatTargets() {
- // Rendering INTO RGBA16F needs EXT_color_buffer_float on WebGL2 (sampling
- // half-float textures is core; only attachment renderability is gated).
- return glExtensionPresent("GL_EXT_color_buffer_float")
- || glExtensionPresent("EXT_color_buffer_float");
+ // Asked by the post-process chain several times a frame, and each ask walked the whole extension list across the wasm boundary (a call into the
+ // browser for every extension the context has). What a context supports does not change while it lives; init() runs again for a new one.
+ if (float_targets_ < 0) {
+ // Rendering INTO RGBA16F needs EXT_color_buffer_float on WebGL2 (sampling
+ // half-float textures is core; only attachment renderability is gated).
+ float_targets_ = (glExtensionPresent("GL_EXT_color_buffer_float") || glExtensionPresent("EXT_color_buffer_float")) ? 1 : 0;
+ }
+ return float_targets_ == 1;
}
} // namespace esengine
diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hpp
index df45e77eb..3d9b72ae8 100644
--- a/src/esengine/renderer/rhi/GLDevice.hpp
+++ b/src/esengine/renderer/rhi/GLDevice.hpp
@@ -271,6 +271,7 @@ private:
bool surface_blend_off_ = false;
void applySurfaceBlend(bool off);
int scissor_test_ = -1; // tri-state: -1 unknown, 0 disabled, 1 enabled
+ int float_targets_ = -1; // supportsFloatTargets(), answered once per context: -1 not asked yet
struct VaoCache {
u32 vao = 0;
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 1705f8adf..3bbe90bec 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3028,4 +3028,6 @@ export const NOTED = {
{"note":"The engine's wasm is 239KB smaller, with no change to what it does."},
"perf(render): a mesh draw finds its cached program without searching shader source":
{"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"},
};