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.

feat(render): a shader with switches runs on WebGPU

esenginee9a5f0685250
diff --git a/desktop/electron/shaderTwins.ts b/desktop/electron/shaderTwins.ts
index a5e6a8aff..4f850339c 100644
--- a/desktop/electron/shaderTwins.ts
+++ b/desktop/electron/shaderTwins.ts
@@ -96,7 +96,7 @@ export async function ensureProjectShaderTwins(
try {
const r = await gen.processFile(module, f, {});
if (r.status === 'generated') result.generated.push(f);
- else if (r.status === 'skipped-switches') result.skipped.push(f);
+ else if (r.status.startsWith('skipped-')) result.skipped.push(f);
} catch (err) {
result.failed.push(f);
console.warn(`[shader-twins] generation failed for ${path.relative(root, f)} —`,
diff --git a/desktop/public/scenes/mat-sw/switched.esshader b/desktop/public/scenes/mat-sw/switched.esshader
index fdb9607f7..403d8d68c 100644
--- a/desktop/public/scenes/mat-sw/switched.esshader
+++ b/desktop/public/scenes/mat-sw/switched.esshader
@@ -37,3 +37,167 @@ void main() {
#endif
}
#pragma end
+
+#pragma vertex wgsl full
+// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
+// Regenerate after changing the GLSL stages above.
+// source-hash: 707645015287f4ca
+#ifdef USE_GREEN
+struct gl_PerVertex {
+ @builtin(position) gl_Position: vec4<f32>,
+ gl_PointSize: f32,
+}
+
+struct FrameConstants {
+ u_projection: mat4x4<f32>,
+}
+
+struct TimeConstants {
+ u_time: vec4<f32>,
+ u_viewport: vec4<f32>,
+}
+
+struct VertexOutput {
+ @builtin(position) gl_Position: vec4<f32>,
+ @location(0) member: vec4<f32>,
+}
+
+var<private> unnamed: gl_PerVertex = gl_PerVertex(vec4<f32>(0f, 0f, 0f, 1f), 1f);
+@group(0) @binding(0)
+var<uniform> unnamed_1: FrameConstants;
+var<private> a_position_1: vec3<f32>;
+var<private> v_color: vec4<f32>;
+var<private> a_color_1: vec4<f32>;
+@group(0) @binding(3)
+var<uniform> unnamed_2: TimeConstants;
+var<private> a_texCoord_1: vec2<f32>;
+var<private> a_texIndex_1: f32;
+
+fn main_1() {
+ let _e11 = unnamed_1.u_projection;
+ let _e12 = a_position_1;
+ unnamed.gl_Position = (_e11 * vec4<f32>(_e12.x, _e12.y, _e12.z, 1f));
+ let _e19 = a_color_1;
+ v_color = _e19;
+ return;
+}
+
+@vertex
+fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>, @location(2) a_texCoord: vec2<f32>, @location(3) a_texIndex: f32) -> VertexOutput {
+ a_position_1 = a_position;
+ a_color_1 = a_color;
+ a_texCoord_1 = a_texCoord;
+ a_texIndex_1 = a_texIndex;
+ main_1();
+ let _e11 = unnamed.gl_Position;
+ let _e12 = v_color;
+ return VertexOutput(_e11, _e12);
+}
+#else
+struct gl_PerVertex {
+ @builtin(position) gl_Position: vec4<f32>,
+ gl_PointSize: f32,
+}
+
+struct FrameConstants {
+ u_projection: mat4x4<f32>,
+}
+
+struct TimeConstants {
+ u_time: vec4<f32>,
+ u_viewport: vec4<f32>,
+}
+
+struct VertexOutput {
+ @builtin(position) gl_Position: vec4<f32>,
+ @location(0) member: vec4<f32>,
+}
+
+var<private> unnamed: gl_PerVertex = gl_PerVertex(vec4<f32>(0f, 0f, 0f, 1f), 1f);
+@group(0) @binding(0)
+var<uniform> unnamed_1: FrameConstants;
+var<private> a_position_1: vec3<f32>;
+var<private> v_color: vec4<f32>;
+var<private> a_color_1: vec4<f32>;
+@group(0) @binding(3)
+var<uniform> unnamed_2: TimeConstants;
+var<private> a_texCoord_1: vec2<f32>;
+var<private> a_texIndex_1: f32;
+
+fn main_1() {
+ let _e11 = unnamed_1.u_projection;
+ let _e12 = a_position_1;
+ unnamed.gl_Position = (_e11 * vec4<f32>(_e12.x, _e12.y, _e12.z, 1f));
+ let _e19 = a_color_1;
+ v_color = _e19;
+ return;
+}
+
+@vertex
+fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>, @location(2) a_texCoord: vec2<f32>, @location(3) a_texIndex: f32) -> VertexOutput {
+ a_position_1 = a_position;
+ a_color_1 = a_color;
+ a_texCoord_1 = a_texCoord;
+ a_texIndex_1 = a_texIndex;
+ main_1();
+ let _e11 = unnamed.gl_Position;
+ let _e12 = v_color;
+ return VertexOutput(_e11, _e12);
+}
+#endif
+#pragma end
+
+#pragma fragment wgsl full
+// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
+// Regenerate after changing the GLSL stages above.
+// source-hash: 707645015287f4ca
+#ifdef USE_GREEN
+struct TimeConstants {
+ u_time: vec4<f32>,
+ u_viewport: vec4<f32>,
+}
+
+var<private> fragColor: vec4<f32>;
+var<private> v_color_1: vec4<f32>;
+@group(0) @binding(3)
+var<uniform> unnamed: TimeConstants;
+
+fn main_1() {
+ let _e6 = v_color_1;
+ fragColor = (vec4<f32>(0f, 1f, 0f, 1f) * _e6);
+ return;
+}
+
+@fragment
+fn fs_main(@location(0) v_color: vec4<f32>) -> @location(0) vec4<f32> {
+ v_color_1 = v_color;
+ main_1();
+ let _e3 = fragColor;
+ return _e3;
+}
+#else
+struct TimeConstants {
+ u_time: vec4<f32>,
+ u_viewport: vec4<f32>,
+}
+
+var<private> fragColor: vec4<f32>;
+var<private> v_color_1: vec4<f32>;
+@group(0) @binding(3)
+var<uniform> unnamed: TimeConstants;
+
+fn main_1() {
+ let _e6 = v_color_1;
+ fragColor = (vec4<f32>(1f, 0f, 0f, 1f) * _e6);
+ return;
+}
+
+@fragment
+fn fs_main(@location(0) v_color: vec4<f32>) -> @location(0) vec4<f32> {
+ v_color_1 = v_color;
+ main_1();
+ let _e3 = fragColor;
+ return _e3;
+}
+#endif
+#pragma end
diff --git a/desktop/tests/shader-twin-permutations.test.ts b/desktop/tests/shader-twin-permutations.test.ts
new file mode 100644
index 000000000..68aa77d28
--- /dev/null
+++ b/desktop/tests/shader-twin-permutations.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Twin generation for a shader with toggles. WGSL has no preprocessor, so
+ * every permutation has to be in the body and selected at assembly by the
+ * same `#ifdef` the GLSL side gets from a real define.
+ */
+import { describe, it, expect } from 'vitest';
+// @ts-expect-error — a repo tool, shipped as .mjs with no declarations
+import { needsTwin, permutationsOf, composePermutations } from '../../tools/gen-shader-twins.mjs';
+
+const GLSL_ONLY = '#pragma shader "X"\n#pragma switch USE_GREEN default(off)\n#pragma fragment\nvoid main() {}\n#pragma end\n';
+
+describe('needsTwin', () => {
+ it('asks for a twin for a shader with switches', () => {
+ expect(needsTwin(GLSL_ONLY)).toBe(true);
+ });
+
+ it('leaves a hand-authored twin alone', () => {
+ expect(needsTwin('#pragma fragment wgsl\n@fragment fn fs_main() {}\n#pragma end\n')).toBe(false);
+ });
+});
+
+describe('permutationsOf', () => {
+ it('is the empty combination when there is nothing to toggle', () => {
+ expect(permutationsOf([])).toEqual([[]]);
+ });
+
+ it('covers every on/off combination', () => {
+ const got = permutationsOf(['A', 'B']).map((c: string[]) => c.join('') || '-');
+ expect(new Set(got)).toEqual(new Set(['-', 'A', 'B', 'AB']));
+ });
+});
+
+describe('composePermutations', () => {
+ it('emits the single body verbatim when nothing toggles', () => {
+ expect(composePermutations([], new Map([['', 'BODY']]))).toBe('BODY');
+ });
+
+ it('selects one toggle with #ifdef/#else', () => {
+ const bodies = new Map([['', 'OFF'], ['A', 'ON']]);
+ expect(composePermutations(['A'], bodies)).toBe('#ifdef A\nON\n#else\nOFF\n#endif');
+ });
+
+ it('nests two toggles so every combination is reachable', () => {
+ const bodies = new Map([['', 'oo'], ['A', 'Ao'], ['B', 'oB'], ['A,B', 'AB']]);
+ const out = composePermutations(['A', 'B'], bodies);
+ for (const body of ['oo', 'Ao', 'oB', 'AB']) expect(out).toContain(body);
+ expect(out.startsWith('#ifdef A')).toBe(true);
+ // Balanced: one #endif per #ifdef, or the assembly-time preprocessor
+ // silently swallows the rest of the stage.
+ expect((out.match(/#ifdef/g) ?? []).length).toBe((out.match(/#endif/g) ?? []).length);
+ });
+});
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 8f0202798..08933d02b 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -123,6 +123,17 @@ emscripten::val esshader_cookInfo(const std::string& source, const std::string&
out.set("hasWgslVertex", parsed.wgslStages.count(resource::ShaderStage::Vertex) != 0);
out.set("hasWgslFragment", parsed.wgslStages.count(resource::ShaderStage::Fragment) != 0);
out.set("hasSwitches", !parsed.switches.empty());
+ // The switch/feature NAMES, so a cook can enumerate the permutations it has
+ // to emit a twin for — WGSL resolves them at assembly time (preprocessWGSL),
+ // which needs every branch present in the body.
+ emscripten::val switches = emscripten::val::array();
+ u32 switchCount = 0;
+ for (const auto& s : parsed.switches) switches.set(switchCount++, s.name);
+ out.set("switches", switches);
+ emscripten::val featureNames = emscripten::val::array();
+ u32 featureCount = 0;
+ for (const auto& f : parsed.features) featureNames.set(featureCount++, f);
+ out.set("features", featureNames);
out.set("vertGlsl", vert);
out.set("fragGlsl", frag);
emscripten::val textures = emscripten::val::array();
diff --git a/tools/gen-shader-twins.mjs b/tools/gen-shader-twins.mjs
index 36bf39c19..f2ed4cc2d 100644
--- a/tools/gen-shader-twins.mjs
+++ b/tools/gen-shader-twins.mjs
@@ -287,12 +287,10 @@ export function sourceHash(source) {
/** Whether `source` needs a (re)generated WGSL twin: it has no twin, or its
* GENERATED twin's stored source-hash no longer matches the authored GLSL
- * (stale). A hand-authored `wgsl` twin (builtins) and a `#pragma switch` shader
- * are left alone — the former is authored not derived, the latter needs
- * per-permutation twins the generator can't emit. Pure + cheap (no engine), so
- * the editor's on-open scan and CI --check share one definition of "stale". */
+ * (stale). A hand-authored `wgsl` twin (builtins) is left alone — it is
+ * authored, not derived. Pure + cheap (no engine), so the editor's on-open scan
+ * and CI --check share one definition of "stale". */
export function needsTwin(source) {
- if (/#pragma switch\b/.test(source)) return false;
const hasGenerated = /#pragma (?:vertex|fragment) wgsl[ \t]+full\b/.test(source);
const hasHandwritten = /#pragma (?:vertex|fragment) wgsl(?![ \t]+full)/.test(source);
if (hasHandwritten && !hasGenerated) return false;
@@ -310,36 +308,87 @@ export async function loadTwinModule() {
return createModule();
}
+/** An emscripten val array as a JS array of strings. */
+function valStrings(v) {
+ const out = [];
+ for (let i = 0; i < (v?.length ?? 0); i++) out.push(v[i]);
+ return out;
+}
+
+/**
+ * How many toggles a twin may carry. Each one doubles the emitted programs, and
+ * WGSL has no preprocessor to share between them — at four the body is sixteen
+ * copies of the shader, which is a size nobody asked for silently.
+ */
+const MAX_TOGGLES = 3;
+
+/** Every on/off combination of `toggles`, as arrays of the ones that are ON. */
+export function permutationsOf(toggles) {
+ const out = [];
+ for (let mask = 0; mask < (1 << toggles.length); mask++) {
+ out.push(toggles.filter((_, i) => (mask & (1 << i)) !== 0));
+ }
+ return out;
+}
+
+const permutationKey = (on) => [...on].sort().join(',');
+
+/**
+ * One body carrying every permutation, selected by the same `#ifdef` the GLSL
+ * side gets from real defines — `preprocessWGSL` resolves it at assembly, so
+ * both targets see identical variant logic.
+ */
+export function composePermutations(toggles, bodies, remaining = toggles, on = []) {
+ if (remaining.length === 0) return bodies.get(permutationKey(on)).trimEnd();
+ const [head, ...rest] = remaining;
+ const whenOn = composePermutations(toggles, bodies, rest, [...on, head]);
+ const whenOff = composePermutations(toggles, bodies, rest, on);
+ return `#ifdef ${head}\n${whenOn}\n#else\n${whenOff}\n#endif`;
+}
+
export async function processFile(module, file, opts) {
let source = await readFile(file, 'utf8');
- if (!opts.force && !needsTwin(source)) {
- return { file, status: /#pragma switch\b/.test(source) ? 'skipped-switches' : 'has-twin' };
- }
+ if (!opts.force && !needsTwin(source)) return { file, status: 'has-twin' };
// Regenerating (missing, stale, or --force): drop any old generated twin so the
// new one — and its source-hash — replaces it cleanly.
if (/#pragma (?:vertex|fragment) wgsl full/.test(source)) source = stripGeneratedTwins(source);
const info = module.esshader_cookInfo(source, '');
if (!info.valid) throw new Error(`parse failed: ${info.error}`);
- if (info.hasSwitches) return { file, status: 'skipped-switches' };
-
- const textures = [];
- for (let i = 0; i < info.textures.length; i++) textures.push(info.textures[i]);
- const adapted = assignVaryingLocations(
- adaptGlsl(info.vertGlsl, textures),
- adaptGlsl(info.fragGlsl, textures),
- );
+ // 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` };
+ }
const workDir = await mkdtemp(path.join(tmpdir(), 'esshader-twin-'));
try {
- const vertWgsl = await glslToWgsl(adapted.vert, 'vert', 'vs_main', workDir);
- const fragWgsl = await glslToWgsl(adapted.frag, 'frag', 'fs_main', workDir);
+ const vert = new Map();
+ const frag = new Map();
+ for (const on of permutationsOf(toggles)) {
+ const key = permutationKey(on);
+ const cooked = toggles.length === 0 ? info : module.esshader_cookInfo(source, key);
+ if (!cooked.valid) throw new Error(`parse failed for [${key}]: ${cooked.error}`);
+ const textures = [];
+ for (let i = 0; i < cooked.textures.length; i++) textures.push(cooked.textures[i]);
+ const adapted = assignVaryingLocations(
+ adaptGlsl(cooked.vertGlsl, textures),
+ adaptGlsl(cooked.fragGlsl, textures),
+ );
+ // The stage tag is what glslang reads the shader stage from; the
+ // permutations reuse it in turn rather than each taking a name of its own.
+ vert.set(key, await glslToWgsl(adapted.vert, 'vert', 'vs_main', workDir));
+ frag.set(key, await glslToWgsl(adapted.frag, 'frag', 'fs_main', workDir));
+ }
const banner = bannerFor(sourceHash(source));
+ const vertBody = composePermutations(toggles, vert);
+ const fragBody = composePermutations(toggles, frag);
const twin =
- `\n#pragma vertex wgsl full\n${banner}\n${vertWgsl.trimEnd()}\n#pragma end\n` +
- `\n#pragma fragment wgsl full\n${banner}\n${fragWgsl.trimEnd()}\n#pragma end\n`;
+ `\n#pragma vertex wgsl full\n${banner}\n${vertBody}\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');
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index bb0c2b726..f0e9d1d5f 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -23,13 +23,11 @@
export const TIERS = ['pr', 'nightly'];
/**
- * What still separates the second backend from the first. Measured where an
- * adapter exists, 51 of the 52 agree with their GL frames. The one that does not
- * uses a `#pragma switch` shader, and twin generation skips those: a permutation
- * has no WGSL to run, so the material never compiles on this backend.
+ * What still separates the second backend from the first: a CI runner has no
+ * Dawn adapter, so nothing here runs it. Where an adapter exists every scene
+ * passes — both backends read the frame the same way, off the engine's buffer.
*/
-export const WEBGPU_GAP = 'no adapter on a CI runner; with one, 51/52 pass — material-switch '
- + 'needs WGSL twins for shader permutations, which gen-shader-twins does not emit';
+export const WEBGPU_GAP = 'no adapter on a CI runner; with one, all 52 pass (`--backend webgpu`)';
/**
* Every pixel gate. `env` is handed to desktop/scripts/headless-verify.mjs
@@ -101,7 +99,7 @@ export const SCENES = [
{ id: "ktx2", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/ktx2-sprite.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/ktx2-sprite.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,180,0],\"tol\":50}]" } },
{ id: "material-instance", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-instance.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-instance.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":40}]" } },
{ id: "material-texture", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-tex.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-tex.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50}]" } },
- { id: "material-switch", tier: "nightly", env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-sw.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-sw.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":50},{\"x\":0.75,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50}]" } },
+ { id: "material-switch", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-sw.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-sw.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":50},{\"x\":0.75,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50}]" } },
{ id: "material-lit", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-lit.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-lit.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50}]" } },
{ id: "material-lit-point", tier: "pr", webgpu: { ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,253,0],\"tol\":25},{\"x\":0.75,\"y\":0.5,\"rgb\":[0,52,0],\"tol\":25}]" }, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-lit-point.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-lit-point.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":50},{\"x\":0.75,\"y\":0.5,\"rgb\":[0,64,0],\"tol\":60}]" } },
{ id: "material-lit-normal", tier: "nightly", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mat-lit-normal.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/mat-lit-normal.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.333,\"y\":0.5,\"rgb\":[0,252,0],\"tol\":45},{\"x\":0.667,\"y\":0.5,\"rgb\":[0,36,0],\"tol\":50}]" } },