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(tools): the engine's own shaders derive their WebGPU twin when read instead of committing it

yhha6e2c98e7c80
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 622279759..d572f5c98 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -587,12 +587,13 @@ jobs:
- uses: ./.github/actions/render-host
- # Twin coverage guard: every fixture AND example .esshader must carry its
- # WGSL twin (hand-written, generated, or switch-skipped) — a twin-less shader
- # is WebGPU-dead by design and gen-shader-twins --check exits 1 on it. Covers
- # examples/ too so a shipped user shader can never regress to WebGL-only.
+ # Twin coverage guard: every fixture AND example .esshader must have a WGSL twin
+ # (hand-written, or derived from its GLSL when read) — one that cannot be translated
+ # is WebGPU-dead, and one that COMMITS a generated twin brings back the churn of every
+ # engine header edit touching dozens of files; --derived exits 1 on either. Covers
+ # examples/ too so a shipped shader can never regress to WebGL-only.
- name: Check shader twins
- run: node tools/gen-shader-twins.mjs --check fixtures/scenes examples
+ run: node tools/gen-shader-twins.mjs --check --derived fixtures/scenes examples
# Pipeline smoke: strip a fixture's twins into a temp copy and require the
# vendored converters (glslang wasm + naga WASI wasm) to produce one —
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7256232dc..62420c6bf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,6 +47,7 @@ published separately; it ships inside the editor.
### Changed
+- **The engine's own examples and fixtures no longer commit a generated WebGPU shader twin.** The `wgsl full` section of a `.esshader` is a translation of its GLSL joined to the engine's headers, so every edit to an engine header (the render origin in `FrameConstants`, a lighting function) changed it in dozens of files nobody had touched: 83% of that text is the engine's own lighting code, 2% the author's. It is now derived when the shader is read: by the export (`cookAssets`), by the fixture server the render checks use, and by the editor when it serves a project of the repo. Deriving all 44 shaders takes 2.3 s. `gen-shader-twins --derived` checks that each one still translates and that none commits a twin again; a project of your own keeps its twin in the file as before, because the converters are not in a packaged editor. 18 files lose about 11,000 lines; the 248 WebGPU render scenes draw the same.
- **The web module is 144 KB smaller (50 KB gzipped) because it no longer carries a C++ stream library.** `Log`, the shader parser, the font and material parsers, file reads and one JSON status string used `ostringstream`, `istringstream` and `ifstream`, which link libc++'s whole iostream and locale machinery (money, number and time facets, global locale setup at start-up) into every build. They now use `std::string`, a small line reader and stdio, with output kept the same: all 69 shaders parse and assemble to byte-identical text for both targets, a log line prints as before, and the 262 WebGL2 render scenes still draw what they claim. 2,202,592 to 2,058,299 bytes.
- **Instanced meshes that share a material now draw together, so a scene makes a tenth of the draw calls.** An opaque draw sorted by shader, then material, then depth, so two meshes sharing a material alternated by depth and no two neighbours were the same mesh: every instanced draw broke the merge (610 of 612 in the terrain-water example). An instanced mesh draw now puts a hash of its geometry in the top bits of the depth field, so one mesh's draws sit together and merge into one instanced call, in the scene, the depth prepass and the shadow pass alike. The example goes from 612 scene, 610 prepass and 385 shadow draws to 57, 55 and 45, from 10,709 GL calls a frame to 1,977, and from about 6.2 ms to 4.1 ms of CPU a frame. Only the order among opaque draws of one material changes, and they are order-independent (they write depth); the 262 WebGL2 render scenes still draw what they claim.
- **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.
diff --git a/desktop b/desktop
index 28128a5ac..140e58823 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 28128a5ace789bee81d39d4c17e6346d7a28f9ff
+Subproject commit 140e58823fea919abe3ab297a22b976a884a34b9
diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.ts
index 1991cc449..215c32d57 100644
--- a/pipeline/src/assets/cookAssets.ts
+++ b/pipeline/src/assets/cookAssets.ts
@@ -448,6 +448,24 @@ export interface CookResult {
failed: string[];
}
+/**
+ * The function that gives a `.esshader` its derived WGSL twin, or null when the converters are not here (anywhere but a checkout of the engine).
+ * Loaded by a path it holds in a variable: the bundlers must leave the module and its wasm alone, and the cook runs from the same depth in
+ * the package whether it is bundled or not, which is what lets one relative specifier name it.
+ */
+let twinDeriver: Promise<((source: string) => Promise<string>) | null> | undefined;
+function shaderTwinDeriver(): Promise<((source: string) => Promise<string>) | null> {
+ twinDeriver ??= (async () => {
+ try {
+ const specifier = '../../../tools/lib/derivedTwin.mjs';
+ return ((await import(/* @vite-ignore */ specifier)) as { withDerivedTwin: (source: string) => Promise<string> }).withDerivedTwin;
+ } catch {
+ return null;
+ }
+ })();
+ return twinDeriver;
+}
+
/**
* Cook assets reachable from `entryScenes` (project-relative scene paths) into
* `outDir` (project-relative or absolute). Returns what was included vs culled.
@@ -848,11 +866,15 @@ export async function cookAssets(
warnings.push(`${entry.path}: tilemap ref rewrite failed — ${err instanceof Error ? err.message : String(err)}`);
}
}
- // Shaders ship as-authored; a WGSL twin is what makes one run on the
- // WebGPU backend, so a twin-less shader is worth a cook-time warning
- // (generation is a dev-time step — tools/gen-shader-twins.mjs writes the
- // twins into the source file, keeping the cook deterministic and free of
- // converter-toolchain dependencies).
+ // A WGSL twin is what makes a shader run on the WebGPU backend. The repo's own
+ // sources carry none, so one is derived here from the GLSL when the converters
+ // are at hand (a checkout of the engine); a project that ships its own twin has it
+ // already, and one with neither is worth a cook-time warning.
+ if (ext.toLowerCase() === '.esshader' &&
+ !Buffer.from(data).toString('utf8').includes('#pragma fragment wgsl')) {
+ const derive = await shaderTwinDeriver();
+ if (derive) data = Buffer.from(await derive(Buffer.from(data).toString('utf8')), 'utf8');
+ }
if (ext.toLowerCase() === '.esshader' &&
!Buffer.from(data).toString('utf8').includes('#pragma fragment wgsl')) {
warnings.push(
diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.ts
index a196c9e56..f816813ff 100644
--- a/sdk/tests/shader-twins.test.ts
+++ b/sdk/tests/shader-twins.test.ts
@@ -88,6 +88,7 @@ describe('embedded .esshader structure', () => {
const gen = (await import('../../tools/gen-shader-twins.mjs')) as unknown as {
needsTwin(s: string): boolean;
sourceHash(s: string): string;
+ deriveTwin(module: unknown, source: string, opts?: object): Promise<{ status: string; text?: string }>;
};
describe('gen-shader-twins needsTwin / sourceHash (staleness)', () => {
const glsl = '#pragma shader "T"\n#pragma fragment\nvoid main() { }\n#pragma end\n';
@@ -116,3 +117,11 @@ describe('gen-shader-twins needsTwin / sourceHash (staleness)', () => {
expect(gen.needsTwin(fresh.replace('void main() { }', 'void main() { discard; }'))).toBe(true);
});
});
+
+describe('gen-shader-twins deriveTwin (reads and writes no file)', () => {
+ const glsl = '#pragma shader "T"\n#pragma fragment\nvoid main() { }\n#pragma end\n';
+ it('a hand-authored twin is left as it is, without touching the engine', async () => {
+ const authored = `${glsl}\n#pragma fragment wgsl\n@fragment fn fs_main() { }\n#pragma end\n`;
+ expect(await gen.deriveTwin(null, authored)).toEqual({ status: 'has-twin' });
+ });
+});
diff --git a/tools/gates.mjs b/tools/gates.mjs
index 1cf77aa77..2e75f3982 100644
--- a/tools/gates.mjs
+++ b/tools/gates.mjs
@@ -235,7 +235,7 @@ export const GATES = [
// master carrying a stamp older than their own GLSL.
id: 'wgsl-twin-fresh',
run: "if [ -f build/wasm/web/esengine.js ]; then "
- + "node tools/gen-shader-twins.mjs --check fixtures/scenes examples; "
+ + "node tools/gen-shader-twins.mjs --check --derived fixtures/scenes examples; "
+ "else echo 'wgsl-twin-fresh: skipped — no built engine in build/wasm/web'; fi",
where: 'local',
why: 'the check cooks each shader to hash the ASSEMBLED GLSL, so it needs the built engine and skips a machine without one; the render CI job runs it where the binary is',
diff --git a/tools/gen-shader-twins.mjs b/tools/gen-shader-twins.mjs
index 9ffc76f11..d49dee0b0 100644
--- a/tools/gen-shader-twins.mjs
+++ b/tools/gen-shader-twins.mjs
@@ -29,9 +29,12 @@
* TimeConstants 3; group 1 = texture unit u at binding (u<8 ? u : u+8) with its
* sampler at (u<8 ? u+8 : u+16) — mirrors WebGPUMappings.
*
- * Usage: node tools/gen-shader-twins.mjs [--check] [--force] <file.esshader ...>
+ * Usage: node tools/gen-shader-twins.mjs [--check] [--force] [--derived | --strip] <file.esshader ...>
* --check report what would change, write nothing (exit 1 if any)
* --force regenerate even when a twin exists (replaces generated sections)
+ * --derived for sources that carry NO generated twin and have it derived when read (the repo's own examples,
+ * fixtures and games): each must still translate, and one that commits a generated twin is reported
+ * --strip remove the committed generated twin from a source that can derive it (the one-time migration)
*
* Requires: a built engine (pnpm build:web). A `#pragma switch` or feature is a
* toggle: every combination is emitted into one body behind the same `#ifdef`
@@ -440,9 +443,12 @@ export function composePermutations(toggles, bodies, remaining = toggles, on = [
return `#ifdef ${head}\n${whenOn}\n#else\n${whenOff}\n#endif`;
}
-export async function processFile(module, file, opts) {
- const original = await readFile(file, 'utf8');
- if (isAuthoredTwin(original)) return { file, status: 'has-twin' };
+/**
+ * The file text with its WGSL twin derived from the authored GLSL, or a status saying why there is nothing to add. Pure in its inputs: it reads and
+ * writes no file, so whatever serves a shader (the cook, a dev server, the editor) can ask for the same text the CLI would have written.
+ */
+export async function deriveTwin(module, original, opts = {}) {
+ if (isAuthoredTwin(original)) return { status: 'has-twin' };
// The twin is generated FROM the authored stages, so an old one is dropped
// before anything is cooked — its hashes and its body are replaced together.
let source = stripGeneratedTwins(original);
@@ -457,14 +463,14 @@ export async function processFile(module, file, opts) {
const staleVertex = engineVertex && /#pragma vertex wgsl full\b/.test(original);
if (!opts.force && !needsTwin(original) && !staleVertex
&& original.match(STORED_ASSEMBLED_RE)?.[1] === assembled) {
- return { file, status: 'has-twin' };
+ return { status: 'has-twin' };
}
// A switch or a feature changes the assembled GLSL, so each combination is its
// own program to translate.
const toggles = [...valStrings(info.switches), ...valStrings(info.features)];
if (toggles.length > MAX_TOGGLES) {
- return { file, status: `skipped-${toggles.length}-toggles` };
+ return { status: `skipped-${toggles.length}-toggles` };
}
const workDir = await mkdtemp(path.join(tmpdir(), 'esshader-twin-'));
@@ -500,14 +506,45 @@ export async function processFile(module, file, opts) {
(engineVertex ? '' : `\n#pragma vertex wgsl full\n${banner}\n${composePermutations(toggles, vert)}\n#pragma end\n`) +
`\n#pragma fragment wgsl full\n${banner}\n${fragBody}\n#pragma end\n`;
- if (opts.check) return { file, status: 'would-generate' };
- await writeFile(file, source.trimEnd() + '\n' + twin, 'utf8');
- return { file, status: 'generated' };
+ return { status: 'generated', text: source.trimEnd() + '\n' + twin };
} finally {
await rm(workDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
}
}
+/** `source` with a fresh generated twin when it needs one; `source` itself when it has one, wants none, or cannot be translated (the caller sees the throw). */
+export async function withGeneratedTwin(module, source) {
+ const r = await deriveTwin(module, source, {});
+ return r.status === 'generated' ? r.text : source;
+}
+
+export async function processFile(module, file, opts) {
+ const original = await readFile(file, 'utf8');
+ // A source that derives its twin (the repo's own examples and fixtures) carries none: a committed one is what made every engine header edit a
+ // diff across dozens of files. It must still TRANSLATE, which is what deriving it here proves. A file that keeps a hand-written twin beside a
+ // generated one has nothing to derive once the generated one is gone, so it is left as it is.
+ if (opts.derived || opts.strip) {
+ const committed = /#pragma (?:vertex|fragment) wgsl[ \t]+full\b/.test(original);
+ const bare = committed ? stripGeneratedTwins(original).trimEnd() + '\n' : original;
+ const d = await deriveTwin(module, bare, {});
+ if (d.status !== 'generated') {
+ // A hand-written twin beside a generated one: the generated one stays, so it has to be current like any committed twin.
+ const kept = committed ? await deriveTwin(module, original, {}) : d;
+ return { file, status: kept.status === 'generated' ? 'would-generate' : kept.status };
+ }
+ if (opts.strip && committed) {
+ await writeFile(file, bare, 'utf8');
+ return { file, status: 'stripped' };
+ }
+ return { file, status: committed ? 'committed-twin' : 'derivable' };
+ }
+ const r = await deriveTwin(module, original, opts);
+ if (r.status !== 'generated') return { file, status: r.status };
+ if (opts.check) return { file, status: 'would-generate' };
+ await writeFile(file, r.text, 'utf8');
+ return { file, status: 'generated' };
+}
+
/** Every .esshader under a directory, or the file itself. A caller that had to
* list them needed a shell to do it, and `find` on Windows is a text search that
* answers "File not found" and exits 0 -- so the gate ran on an empty list. */
@@ -522,7 +559,7 @@ async function expand(arg) {
async function main() {
const args = process.argv.slice(2);
- const opts = { check: args.includes('--check'), force: args.includes('--force') };
+ const opts = { check: args.includes('--check'), force: args.includes('--force'), derived: args.includes('--derived'), strip: args.includes('--strip') };
const roots = args.filter((a) => !a.startsWith('--'));
if (roots.length === 0) {
console.error('usage: node tools/gen-shader-twins.mjs [--check] [--force] <file.esshader | dir ...>');
@@ -542,7 +579,7 @@ async function main() {
try {
const r = await processFile(module, file, opts);
console.log(`[twin] ${r.status}: ${file}`);
- if (r.status === 'would-generate') pending++;
+ if (r.status === 'would-generate' || r.status === 'committed-twin') pending++;
} catch (e) {
failed++;
console.error(`[twin] FAIL: ${file}\n ${e.message.replace(/\n/g, '\n ')}`);
diff --git a/tools/lib/derivedTwin.mjs b/tools/lib/derivedTwin.mjs
new file mode 100644
index 000000000..ac3fc339d
--- /dev/null
+++ b/tools/lib/derivedTwin.mjs
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file derivedTwin.mjs — a `.esshader` as the WebGPU backend needs it, with the WGSL twin derived from its GLSL when it carries none.
+ *
+ * The repo's own fixtures, examples and games keep only the GLSL they author. The generated twin is a translation of that GLSL joined to the
+ * engine's own headers, so committing it meant every edit to an engine header changed dozens of files that no author had touched. Whatever hands
+ * such a shader to the engine asks here instead, and gets the text the generator would have written.
+ *
+ * Needs a built engine (the translation assembles through it). Without one, or for a shader that cannot be translated, the text comes back as it
+ * was and the shader runs where it ran before: on WebGL.
+ */
+import { pathToFileURL } from 'node:url';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const GENERATOR = pathToFileURL(path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'gen-shader-twins.mjs')).href;
+
+let generator = null;
+let chain = Promise.resolve();
+const memo = new Map();
+
+/** `source`, plus its derived WGSL twin when it has none. Never throws. */
+export function withDerivedTwin(source) {
+ if (memo.has(source)) return memo.get(source);
+ // One translation at a time: the engine module is shared and each translation owns a scratch directory.
+ const done = chain.then(async () => {
+ try {
+ generator ??= await import(GENERATOR).then(async (gen) => ({ gen, module: await gen.loadTwinModule() }));
+ return await generator.gen.withGeneratedTwin(generator.module, source);
+ } catch (err) {
+ console.warn('[derived-twin] left as authored:', err instanceof Error ? err.message.split('\n')[0] : String(err));
+ return source;
+ }
+ });
+ chain = done.then(() => undefined, () => undefined);
+ memo.set(source, done);
+ return done;
+}
diff --git a/tools/lib/staticServer.mjs b/tools/lib/staticServer.mjs
index e8398e38c..ef32e8211 100644
--- a/tools/lib/staticServer.mjs
+++ b/tools/lib/staticServer.mjs
@@ -17,6 +17,7 @@ import http from 'node:http';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
+import { withDerivedTwin } from './derivedTwin.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const FIXTURES = path.join(ROOT, 'fixtures');
@@ -49,9 +50,11 @@ async function readUnder(root, rel) {
export function serveHost(dist) {
const server = http.createServer(async (req, res) => {
const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '') || 'index.html';
- const bytes = (await readUnder(dist, rel)) ?? (await readUnder(FIXTURES, rel))
+ let bytes = (await readUnder(dist, rel)) ?? (await readUnder(FIXTURES, rel))
?? (rel.startsWith('corpora/') ? await readUnder(CORPORA_ROOT, rel) : null);
if (!bytes) return void res.writeHead(404).end('not found');
+ // A shader the fixtures keep as GLSL only gets its WGSL twin here, derived when asked for, not read from a committed copy.
+ if (rel.endsWith('.esshader')) bytes = Buffer.from(await withDerivedTwin(bytes.toString('utf8')), 'utf8');
res.writeHead(200, { 'content-type': MIME[path.extname(rel).toLowerCase()] ?? 'application/octet-stream' });
res.end(bytes);
});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 3fbb995a1..46a0e875d 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3060,4 +3060,14 @@ export const NOTED = {
{"note":"Instanced meshes that share a material now draw together"},
"perf(wasm): the module no longer carries a C++ stream library":
{"note":"The web module is 144 KB smaller"},
+ "feat(tools): a Configuration tables page to switch Luban on, install it with consent, and keep the generated files current":
+ {"note":"Optional tools a project switches on, fetched and checked by the engine."},
+ "feat(tools): a Protobuf block beside Luban on the Configuration tables page":
+ {"note":"Protobuf as a second optional tool: .proto files become TypeScript types and a binary codec."},
+ "fix(export): an export of a project that uses Luban builds its tables first":
+ {"internal":"A fix inside the optional tools feature, which has not shipped yet."},
+ "fix(tests): the Offset test types its unit as a number, and a temp-dir delete retries on Windows":
+ {"internal":"A type annotation and a retry in tests; nothing a creator can observe."},
+ "perf(tools): the engine's own shaders derive their WebGPU twin when read instead of committing it":
+ {"note":"The engine's own shaders derive their WebGPU twin when read"},
};