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(sdk): builtin templates + sprite filters gain WGSL twins; compileEsshader assembles per backend (WGSL phase 3 slice 4)

yhhdabff4105792
diff --git a/sdk/src/builtinShaders.ts b/sdk/src/builtinShaders.ts
index 6aea401c2..0fd4a44e1 100644
--- a/sdk/src/builtinShaders.ts
+++ b/sdk/src/builtinShaders.ts
@@ -3,6 +3,12 @@
/**
* @file builtinShaders.ts
* @brief Built-in .esshader templates — the engine's stock material starting points.
+ * @details Each template carries a `#pragma fragment wgsl` twin so it compiles
+ * on the WebGPU backend. Twins run under the canonical fragment-only
+ * contract: `fs_main(v : VSOut)` with v.v_color / v.v_texCoord
+ * (+ v.v_worldPos on Lit2D), the batch textures as t0..t7 / s0..s7,
+ * params as mc.<name>, texture params as <name> + <name>_s, and the
+ * frame clock as tc.u_time / tc.u_viewport.
*/
export interface BuiltinShaderTemplate {
@@ -34,6 +40,12 @@ void main() {
fragColor = texture(u_textures[0], v_texCoord) * v_color * u_tint;
}
#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ return textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color * mc.u_tint;
+}
+#pragma end
`;
const SPRITE_LIT = `#pragma shader "Sprite Lit"
@@ -60,6 +72,14 @@ void main() {
fragColor = vec4(applyLighting2D(base.rgb, N, v_worldPos), base.a);
}
#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color * mc.u_tint;
+ let N = sampleNormal(u_normalMap, u_normalMap_s, v.v_texCoord);
+ return vec4f(applyLighting2D(base.rgb, N, v.v_worldPos), base.a);
+}
+#pragma end
`;
const SPRITE_HIT_FLASH = `#pragma shader "Hit Flash"
@@ -84,6 +104,13 @@ void main() {
fragColor = vec4(mix(base.rgb, u_flashColor.rgb, u_flash), base.a);
}
#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ return vec4f(mix(base.rgb, mc.u_flashColor.rgb, mc.u_flash), base.a);
+}
+#pragma end
`;
const SPRITE_OUTLINE = `#pragma shader "Outline"
@@ -117,6 +144,23 @@ void main() {
fragColor = mix(vec4(u_outlineColor.rgb, edge * u_outlineColor.a), base, base.a);
}
#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ let texel = mc.u_outlineWidth / vec2f(textureDimensions(t0, 0));
+ var edge = 0.0;
+ edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f( texel.x, 0.0), 0.0).a);
+ edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(-texel.x, 0.0), 0.0).a);
+ edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(0.0, texel.y), 0.0).a);
+ edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(0.0, -texel.y), 0.0).a);
+ edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f( texel.x, texel.y), 0.0).a);
+ edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f( texel.x, -texel.y), 0.0).a);
+ edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(-texel.x, texel.y), 0.0).a);
+ edge = max(edge, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(-texel.x, -texel.y), 0.0).a);
+ return mix(vec4f(mc.u_outlineColor.rgb, edge * mc.u_outlineColor.a), base, base.a);
+}
+#pragma end
`;
const SPRITE_DISSOLVE = `#pragma shader "Dissolve"
@@ -156,6 +200,26 @@ void main() {
fragColor = vec4(rgb, base.a);
}
#pragma end
+
+#pragma fragment wgsl
+fn hash2d(p : vec2f) -> f32 { return fract(sin(dot(p, vec2f(127.1, 311.7))) * 43758.5453123); }
+fn noise2d(p : vec2f) -> f32 {
+ let i = floor(p);
+ var f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hash2d(i), hash2d(i + vec2f(1.0, 0.0)), f.x),
+ mix(hash2d(i + vec2f(0.0, 1.0)), hash2d(i + vec2f(1.0, 1.0)), f.x), f.y);
+}
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ let n = noise2d(v.v_texCoord * mc.u_noiseScale);
+ let cut = mc.u_progress * (1.0 + mc.u_edgeWidth);
+ if (n < cut - mc.u_edgeWidth) { discard; }
+ let rgb = select(base.rgb, mc.u_edgeColor.rgb, n < cut);
+ return vec4f(rgb, base.a);
+}
+#pragma end
`;
const SPRITE_PIXELATE = `#pragma shader "Pixelate"
@@ -178,6 +242,13 @@ void main() {
fragColor = texture(u_textures[0], uv) * v_color;
}
#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let uv = (floor(v.v_texCoord * mc.u_pixels) + 0.5) / mc.u_pixels;
+ return textureSampleLevel(t0, s0, uv, 0.0) * v.v_color;
+}
+#pragma end
`;
const SPRITE_UV_SCROLL = `#pragma shader "UV Scroll"
@@ -201,6 +272,13 @@ void main() {
fragColor = texture(u_textures[0], uv) * v_color;
}
#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let uv = fract(v.v_texCoord + tc.u_time.x * mc.u_scrollSpeed);
+ return textureSampleLevel(t0, s0, uv, 0.0) * v.v_color;
+}
+#pragma end
`;
export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [
diff --git a/sdk/src/filters.ts b/sdk/src/filters.ts
index 3a97b2a91..ed0bd8085 100644
--- a/sdk/src/filters.ts
+++ b/sdk/src/filters.ts
@@ -34,6 +34,19 @@ void main() {
dot(u_cmRow3, texColor)) + u_colorOffset;
fragColor = clamp(result, 0.0, 1.0);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let texColor = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ let result = vec4f(
+ dot(mc.u_cmRow0, texColor),
+ dot(mc.u_cmRow1, texColor),
+ dot(mc.u_cmRow2, texColor),
+ dot(mc.u_cmRow3, texColor)) + mc.u_colorOffset;
+ return clamp(result, vec4f(0.0), vec4f(1.0));
+}
+#pragma end
`;
let colorMatrixShader_: ShaderHandle | null = null;
diff --git a/sdk/src/spriteFilter.ts b/sdk/src/spriteFilter.ts
index 1d42dc2e6..4e51fa73f 100644
--- a/sdk/src/spriteFilter.ts
+++ b/sdk/src/spriteFilter.ts
@@ -46,6 +46,23 @@ void main() {
vec4 outline = u_outlineColor * maxAlpha * (1.0 - texColor.a);
fragColor = texColor + outline;
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let texColor = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ var maxAlpha = 0.0;
+ for (var x = -1.0; x <= 1.0; x += 1.0) {
+ for (var y = -1.0; y <= 1.0; y += 1.0) {
+ if (x == 0.0 && y == 0.0) { continue; }
+ let offset = vec2f(x, y) * mc.u_texelSize * mc.u_outlineWidth;
+ maxAlpha = max(maxAlpha, textureSampleLevel(t0, s0, v.v_texCoord + offset, 0.0).a);
+ }
+ }
+ let outline = mc.u_outlineColor * maxAlpha * (1.0 - texColor.a);
+ return texColor + outline;
+}
+#pragma end
`;
// =============================================================================
@@ -87,6 +104,27 @@ void main() {
vec4 texColor = texture(u_textures[0], v_texCoord) * v_color;
fragColor = texColor + shadow * (1.0 - texColor.a);
}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let shadowUV = v.v_texCoord - mc.u_shadowOffset * mc.u_texelSize;
+ var shadowAlpha = 0.0;
+ var total = 0.0;
+ let radius = max(1.0, mc.u_shadowBlur);
+ for (var x = -2.0; x <= 2.0; x += 1.0) {
+ for (var y = -2.0; y <= 2.0; y += 1.0) {
+ let offset = vec2f(x, y) * mc.u_texelSize * radius;
+ shadowAlpha += textureSampleLevel(t0, s0, shadowUV + offset, 0.0).a;
+ total += 1.0;
+ }
+ }
+ shadowAlpha /= total;
+ let shadow = mc.u_shadowColor * shadowAlpha;
+ let texColor = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+ return texColor + shadow * (1.0 - texColor.a);
+}
+#pragma end
`;
// =============================================================================
diff --git a/sdk/tests/shader-twins.test.ts b/sdk/tests/shader-twins.test.ts
new file mode 100644
index 000000000..b86fc69d6
--- /dev/null
+++ b/sdk/tests/shader-twins.test.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+// Structural guard for the SDK's embedded .esshader strings: every stage
+// section must close with `#pragma end` (an unterminated section fails
+// ShaderParser.parse at runtime — the sprite-filter shaders shipped broken
+// this way once, lazily compiled and never exercised), and every material
+// source must carry its `#pragma fragment wgsl` twin so it compiles on the
+// WebGPU backend.
+import { describe, expect, it } from 'vitest';
+
+import { BUILTIN_SHADER_TEMPLATES } from '../src/builtinShaders';
+
+// The filter modules export functions, not their sources — read the sources
+// from disk so the guard sees exactly what ships.
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const SRC = join(dirname(fileURLToPath(import.meta.url)), '..', 'src');
+
+function embeddedEsshaders(file: string): string[] {
+ const text = readFileSync(join(SRC, file), 'utf-8');
+ // Template literals that start with a #pragma shader header.
+ return [...text.matchAll(/`(#pragma shader[\s\S]*?)`/g)].map((m) => m[1]);
+}
+
+function sectionsBalance(source: string): boolean {
+ let open = 0;
+ for (const line of source.split('\n')) {
+ const t = line.trim();
+ if (/^#pragma (vertex|fragment|properties|variant)\b/.test(t)) {
+ if (open !== 0) return false;
+ open = 1;
+ } else if (t === '#pragma end') {
+ if (open !== 1) return false;
+ open = 0;
+ }
+ }
+ return open === 0;
+}
+
+const CASES: Array<{ name: string; source: string }> = [
+ ...BUILTIN_SHADER_TEMPLATES.map((t) => ({ name: `template:${t.id}`, source: t.source })),
+ ...embeddedEsshaders('filters.ts').map((source, i) => ({ name: `filters.ts[${i}]`, source })),
+ ...embeddedEsshaders('spriteFilter.ts').map((source, i) => ({ name: `spriteFilter.ts[${i}]`, source })),
+];
+
+describe('embedded .esshader structure', () => {
+ it('found the filter sources', () => {
+ expect(CASES.filter((c) => c.name.startsWith('filters.ts')).length).toBe(1);
+ expect(CASES.filter((c) => c.name.startsWith('spriteFilter.ts')).length).toBe(2);
+ });
+
+ for (const { name, source } of CASES) {
+ it(`${name}: every section closes with #pragma end`, () => {
+ expect(sectionsBalance(source)).toBe(true);
+ });
+
+ it(`${name}: carries a WGSL fragment twin with the fs_main entry point`, () => {
+ expect(source).toContain('#pragma fragment wgsl');
+ const wgsl = source.slice(source.indexOf('#pragma fragment wgsl'));
+ expect(wgsl).toContain('fn fs_main(');
+ });
+ }
+});
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 8eab72e3b..0f89d3738 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -147,24 +147,36 @@ u32 compileEsshader(const std::string& source, const std::string& featuresCsv) {
if (comma == std::string::npos) break;
start = comma + 1;
}
- const std::string vert = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features);
- const std::string frag = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features);
+ // Assemble both stages for the backend's language — a material .esshader
+ // carries its WGSL twin in-file, and a missing twin surfaces here as a
+ // descriptive assembly error rather than a backend compile failure.
+ const auto target = rm->preferredShaderTarget();
+ const std::string vert = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features, target);
+ const std::string frag = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features, target);
+ if (vert.empty() || frag.empty()) {
+ ES_LOG_ERROR("compileEsshader: stage assembly failed for '{}'", parsed.name);
+ return 0;
+ }
// No DrawParams rewrite: assembled material sources already carry their
// params in MaterialConstants; only sampler uniforms remain loose.
- resource::ShaderHandle handle = rm->createShader(vert, frag, /*rewriteLoose=*/false);
+ resource::ShaderHandle handle = rm->createShader(vert, frag, /*rewriteLoose=*/false,
+ rm->preferredShaderLanguage());
if (!handle.isValid()) return 0;
if (auto* rc = g_renderContext) {
if (Shader* s = rm->getShader(handle)) {
rc->materials().registerLayout(s->getProgramId(), buildMaterialLayout(parsed, *rc));
// Point each texture param's sampler at its unit, once per program (GLSL ES 300 has
// no layout(binding=); mirrors the batch path's u_textures setup in RenderFrame).
- s->bind();
- for (const auto& p : parsed.properties) {
- if (p.fromParam && p.type == resource::ShaderPropertyType::Texture && p.textureUnit >= 0) {
- s->setUniform(p.name, static_cast<i32>(p.textureUnit));
+ // Sampler seeding is a GLSL concept; on WGSL the unit rides the bind group.
+ if (s->language() == GfxShaderLanguage::GLSL_ES300) {
+ s->bind();
+ for (const auto& p : parsed.properties) {
+ if (p.fromParam && p.type == resource::ShaderPropertyType::Texture && p.textureUnit >= 0) {
+ s->setUniform(p.name, static_cast<i32>(p.textureUnit));
+ }
}
+ s->unbind();
}
- s->unbind();
}
}
return handle.id();
diff --git a/tests/renderer/webgpu_engine_bringup.cpp b/tests/renderer/webgpu_engine_bringup.cpp
index 745545107..9865ce90d 100644
--- a/tests/renderer/webgpu_engine_bringup.cpp
+++ b/tests/renderer/webgpu_engine_bringup.cpp
@@ -82,7 +82,9 @@ void renderFrame() {
// compiled in each backend's language. It exercises every WGSL injection the
// emitter owns (canonical vertex, VSOut, batch texture contract, Time/
// Material constants, material texture bindings, the Lit2D header, and the
-// assembly-time feature preprocessor) against the REAL compiler: a WGSL error
+// assembly-time feature preprocessor) plus the language constructs the SDK's
+// template/filter twins rely on (sampleNormal, textureDimensions, nested
+// loops with continue, select) against the REAL compiler: a WGSL error
// surfaces as a device validation error (the runner counts those); a GLSL
// error fails shader creation here.
const char* kEmitterProbe = R"(#pragma shader "EmitterProbe"
@@ -102,12 +104,21 @@ uniform sampler2D u_textures[8];
out vec4 fragColor;
void main() {
vec4 c = texture(u_textures[0], v_texCoord) * v_color * u_tint;
- vec4 m = texture(u_mask, v_texCoord);
- vec3 litRgb = applyLighting2D(c.rgb * m.rgb, vec3(0.0, 0.0, 1.0), v_worldPos);
+ vec3 N = sampleNormal(u_mask, v_texCoord);
+ highp vec2 texel = 1.0 / vec2(textureSize(u_textures[0], 0));
+ float acc = 0.0;
+ for (float x = -1.0; x <= 1.0; x += 1.0) {
+ for (float y = -1.0; y <= 1.0; y += 1.0) {
+ if (x == 0.0 && y == 0.0) continue;
+ acc = max(acc, texture(u_textures[0], v_texCoord + vec2(x, y) * texel).a);
+ }
+ }
+ vec3 litRgb = applyLighting2D(c.rgb, N, v_worldPos);
+ vec3 edged = (acc > 1.5) ? u_tint.rgb : litRgb;
#ifdef GLOW
- fragColor = vec4(litRgb * u_progress, c.a);
+ fragColor = vec4(edged * u_progress, c.a);
#else
- fragColor = vec4(litRgb, c.a);
+ fragColor = vec4(edged, c.a);
#endif
}
#pragma end
@@ -115,12 +126,21 @@ void main() {
#pragma fragment wgsl
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
var c = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color * mc.u_tint;
- let m = textureSampleLevel(u_mask, u_mask_s, v.v_texCoord, 0.0);
- let litRgb = applyLighting2D(c.rgb * m.rgb, vec3f(0.0, 0.0, 1.0), v.v_worldPos);
+ let N = sampleNormal(u_mask, u_mask_s, v.v_texCoord);
+ let texel = 1.0 / vec2f(textureDimensions(t0, 0));
+ var acc = 0.0;
+ for (var x = -1.0; x <= 1.0; x += 1.0) {
+ for (var y = -1.0; y <= 1.0; y += 1.0) {
+ if (x == 0.0 && y == 0.0) { continue; }
+ acc = max(acc, textureSampleLevel(t0, s0, v.v_texCoord + vec2f(x, y) * texel, 0.0).a);
+ }
+ }
+ let litRgb = applyLighting2D(c.rgb, N, v.v_worldPos);
+ let edged = select(litRgb, mc.u_tint.rgb, acc > 1.5);
#ifdef GLOW
- return vec4f(litRgb * mc.u_progress, c.a);
+ return vec4f(edged * mc.u_progress, c.a);
#else
- return vec4f(litRgb, c.a);
+ return vec4f(edged, c.a);
#endif
}
#pragma end