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(webgpu): engine boots on WebGPU — full-scene pixel parity with GL (WGSL phase 2 slice 5b, phase 2 complete)

yhha049b71aca9b
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 00930799b..7b7316b17 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -71,7 +71,8 @@ jobs:
test_ecs test_events test_particle test_tilemap test_sparse_set \
test_resource_pool test_shader_variant test_log_format test_registry_safety \
test_shader_device test_draw_params test_texture_fb test_buffer_device \
- test_compressed_format test_batch_builder test_boundary_span test_webgpu_device
+ test_compressed_format test_batch_builder test_boundary_span test_webgpu_device \
+ webgpu_engine_bringup
# The root package.json is ESM, so the emscripten-emitted .js must run as .cjs.
- name: Run C++ test harnesses
diff --git a/desktop/scripts/engine-parity.mjs b/desktop/scripts/engine-parity.mjs
new file mode 100644
index 000000000..c06550c3a
--- /dev/null
+++ b/desktop/scripts/engine-parity.mjs
@@ -0,0 +1,185 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Engine-level backend parity runner (REARCH_WGSL Phase 2).
+ *
+ * Loads tests' webgpu_engine_bringup.wasm twice — once per backend
+ * (?backend=webgpu / ?backend=gl) — in a real browser context. The wasm boots
+ * the FULL engine (EstellaContext) on the selected backend and renders the
+ * same ECS scene through the production RenderFrame path. This runner asserts
+ * the SAME pixel expectations on both runs AND diffs the two captures against
+ * each other: the backends are each other's gold.
+ *
+ * Run: node desktop/scripts/engine-parity.mjs (electron resolved from desktop/)
+ * Prereq: cmake --build build/wasm/web-tests --target webgpu_engine_bringup
+ */
+import { app, BrowserWindow } from 'electron';
+import http from 'node:http';
+import os from 'node:os';
+import { readFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+try {
+ os.setPriority(os.constants.priority.PRIORITY_BELOW_NORMAL);
+} catch { /* not fatal */ }
+
+const BIN = path.resolve(path.dirname(fileURLToPath(import.meta.url)),
+ '..', '..', 'build', 'wasm', 'web-tests', 'bin');
+
+const PAGE = `<!doctype html>
+<html><body style="margin:0">
+<canvas id="canvas" width="256" height="256"></canvas>
+<script>
+(async () => {
+ try {
+ const useGL = location.search.indexOf('backend=gl') >= 0;
+ window.Module = {};
+ if (!useGL) {
+ if (!navigator.gpu) { console.error('PARITY_FAIL no navigator.gpu'); return; }
+ const adapter = await navigator.gpu.requestAdapter();
+ if (!adapter) { console.error('PARITY_FAIL no adapter'); return; }
+ const device = await adapter.requestDevice();
+ device.addEventListener('uncapturederror', (e) => {
+ console.error('PARITY_VALIDATION ' + e.error.message);
+ });
+ window.Module.preinitializedWebGPUDevice = device;
+ }
+ const s = document.createElement('script');
+ s.src = '/webgpu_engine_bringup.js';
+ document.body.appendChild(s);
+ } catch (e) {
+ console.error('PARITY_FAIL ' + e.message);
+ }
+})();
+</script></body></html>`;
+
+function serve() {
+ const server = http.createServer(async (req, res) => {
+ try {
+ const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname).replace(/^\/+/, '');
+ if (rel === '' || rel === 'index.html') {
+ res.writeHead(200, { 'content-type': 'text/html' }).end(PAGE);
+ return;
+ }
+ const abs = path.join(BIN, rel);
+ if (!abs.startsWith(BIN)) { res.writeHead(403).end(); return; }
+ const bytes = await readFile(abs);
+ const mime = rel.endsWith('.wasm') ? 'application/wasm' : 'text/javascript';
+ res.writeHead(200, { 'content-type': mime }).end(bytes);
+ } catch {
+ res.writeHead(404).end();
+ }
+ });
+ return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server)));
+}
+
+/** Navigates the shared window to one backend, waits for completion, and
+ * captures the 256x256 page pixels. One window navigated twice — a second
+ * BrowserWindow after a GPU-heavy first run fails navigation on some
+ * platforms. */
+async function runBackend(win, baseUrl, backend) {
+ let framesOk = false;
+ const errors = [];
+ const onMessage = (...args) => {
+ const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');
+ if (/PARITY|error|warn/i.test(msg)) console.log(`[${backend}]`, msg.slice(0, 220));
+ if (msg.includes('PARITY_FRAMES_OK')) framesOk = true;
+ if (msg.includes('PARITY_FAIL') || msg.includes('PARITY_VALIDATION')) errors.push(msg);
+ };
+ win.webContents.on('console-message', onMessage);
+ try {
+ await win.loadURL(`${baseUrl}?backend=${backend}`);
+
+ const deadline = Date.now() + 20000;
+ while (!framesOk && errors.length === 0 && Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ await new Promise((r) => setTimeout(r, 500));
+
+ const image = await win.webContents.capturePage({ x: 0, y: 0, width: 256, height: 256 });
+ const bitmap = image.toBitmap(); // BGRA rows
+ const width = image.getSize().width;
+ return { framesOk, errors, bitmap, width };
+ } catch (e) {
+ errors.push(`run failed: ${e.message}`);
+ return { framesOk, errors, bitmap: Buffer.alloc(256 * 256 * 4), width: 256 };
+ } finally {
+ win.webContents.removeListener('console-message', onMessage);
+ }
+}
+
+app.whenReady().then(async () => {
+ const server = await serve();
+ const url = `http://127.0.0.1:${server.address().port}/index.html`;
+
+ // Sequential on purpose: two GPU-heavy runs at once is the kind of load
+ // this machine must not take.
+ const win = new BrowserWindow({ show: false, width: 256, height: 256, useContentSize: true });
+ const webgpu = await runBackend(win, url, 'webgpu');
+ const gl = await runBackend(win, url, 'gl');
+ win.destroy();
+
+ const px = (run, x, y) => {
+ const i = (y * run.width + x) * 4;
+ return { b: run.bitmap[i], g: run.bitmap[i + 1], r: run.bitmap[i + 2] };
+ };
+ const near = (v, want, tol = 40) => Math.abs(v - want) <= tol;
+
+ // Shared expectations (screen space, y down). World y up: screen_y = 256 - world_y.
+ // - checker sprite: world center (64,176) size 64 → screen x 32..96, y 48..112
+ // texel-center probes: quarter centers of the quad
+ // - green sprite: world center (192,176) size 48 → screen (192, 80)
+ // - magenta circle: world center (128,80) r 32 → screen (128, 176)
+ // - clear color corner (8, 8)
+ const POINTS = {
+ checkerA: { x: 48, y: 96 }, // lower-left quarter center
+ checkerB: { x: 48, y: 64 }, // upper-left quarter center (opposite texel)
+ green: { x: 192, y: 80 },
+ circle: { x: 128, y: 176 },
+ corner: { x: 8, y: 8 },
+ };
+
+ const report = {};
+ let ok = true;
+ for (const run of [{ name: 'webgpu', data: webgpu }, { name: 'gl', data: gl }]) {
+ const p = Object.fromEntries(
+ Object.entries(POINTS).map(([k, v]) => [k, px(run.data, v.x, v.y)]));
+ report[run.name] = p;
+ // One checker probe must be pure red and the vertically opposite one pure
+ // blue — same orientation on both backends (which one is which is pinned
+ // by the cross-backend diff below plus the red/blue split here).
+ const checkerOk =
+ (near(p.checkerA.r, 255) && near(p.checkerA.b, 0) && near(p.checkerB.r, 0) && near(p.checkerB.b, 255)) ||
+ (near(p.checkerA.r, 0) && near(p.checkerA.b, 255) && near(p.checkerB.r, 255) && near(p.checkerB.b, 0));
+ const greenOk = near(p.green.r, 0) && near(p.green.g, 255) && near(p.green.b, 0);
+ const circleOk = near(p.circle.r, 255) && near(p.circle.g, 0) && near(p.circle.b, 255);
+ const cornerOk = near(p.corner.r, 13) && near(p.corner.g, 13) && near(p.corner.b, 77, 60);
+ const runOk = run.data.framesOk && run.data.errors.length === 0 &&
+ checkerOk && greenOk && circleOk && cornerOk;
+ console.log(`[${run.name}] frames=${run.data.framesOk} errors=${run.data.errors.length} ` +
+ `checker=${checkerOk} green=${greenOk} circle=${circleOk} corner=${cornerOk}`);
+ ok = ok && runOk;
+ }
+
+ // Cross-backend diff at the probe points: the two runs must agree closely —
+ // this is the parity gold, independent of the absolute expectations.
+ let maxDiff = 0;
+ for (const [k, v] of Object.entries(POINTS)) {
+ const a = px(webgpu, v.x, v.y);
+ const b = px(gl, v.x, v.y);
+ const d = Math.max(Math.abs(a.r - b.r), Math.abs(a.g - b.g), Math.abs(a.b - b.b));
+ maxDiff = Math.max(maxDiff, d);
+ if (d > 8) {
+ console.log(`[parity] MISMATCH at ${k}: webgpu=${JSON.stringify(a)} gl=${JSON.stringify(b)}`);
+ ok = false;
+ }
+ }
+
+ console.log(`RESULT ${JSON.stringify(report)}`);
+ console.log(`[parity] max cross-backend diff at probes: ${maxDiff}`);
+ console.log(`\n[engine-parity] ${ok ? 'PASS' : 'FAIL'}`);
+ process.exitCode = ok ? 0 : 1;
+ try { server.close(); } catch { /* ignore */ }
+ app.quit();
+});
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 267335518..8eab72e3b 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -376,7 +376,9 @@ EMSCRIPTEN_BINDINGS(esengine_ptr_access) {
EMSCRIPTEN_BINDINGS(esengine_context) {
emscripten::class_<esengine::EstellaContext>("EstellaContext")
.constructor<>()
- .function("init", &esengine::EstellaContext::init)
+ // The WebGL overload — JS hands over a context handle. The
+ // device-injection overload is C++-side only (harnesses/backends).
+ .function("init", emscripten::select_overload<bool(int)>(&esengine::EstellaContext::init))
.function("shutdown", &esengine::EstellaContext::shutdown)
.function("isInitialized", &esengine::EstellaContext::isInitialized);
// Pointer (not reference) so JS can pass null to clear the active context.
diff --git a/src/esengine/core/EstellaContext.cpp b/src/esengine/core/EstellaContext.cpp
index bfeff992c..657700a6c 100644
--- a/src/esengine/core/EstellaContext.cpp
+++ b/src/esengine/core/EstellaContext.cpp
@@ -88,14 +88,27 @@ bool EstellaContext::init(int webglContextHandle) {
}
#endif
- initSubsystems();
+ initSubsystems(makeUnique<GLDevice>());
return true;
}
-void EstellaContext::initSubsystems() {
- // GLDevice is created first: ResourceManager (the GPU-resource factory) and
- // every other renderer subsystem borrow this single device.
- auto gfxDevice = makeUnique<GLDevice>();
+bool EstellaContext::init(Unique<GfxDevice> device) {
+ if (state_.initialized) {
+ ES_LOG_WARN("EstellaContext already initialized");
+ return true;
+ }
+ if (!device) {
+ ES_LOG_ERROR("EstellaContext::init: no device");
+ return false;
+ }
+ initSubsystems(std::move(device));
+ return true;
+}
+
+void EstellaContext::initSubsystems(Unique<GfxDevice> gfxDevice) {
+ // The device arrives first: ResourceManager (the GPU-resource factory) and
+ // every other renderer subsystem borrow this single device. Which backend
+ // it is was decided at the platform edge (init overloads).
auto* gfxDevicePtr = gfxDevice.get();
services_.registerOwned<GfxDevice>(std::move(gfxDevice));
@@ -179,6 +192,7 @@ void EstellaContext::initSubsystems() {
initPass.clearColorValue[2] = state_.clear_color.b;
initPass.clearColorValue[3] = state_.clear_color.a;
gfxDevicePtr->beginRenderPass(initPass);
+ gfxDevicePtr->endRenderPass(); // a pass never outlives its task (WebGPU submits here)
ES_LOG_INFO("EstellaContext initialized");
}
diff --git a/src/esengine/core/EstellaContext.hpp b/src/esengine/core/EstellaContext.hpp
index f0e376293..433b1d1d2 100644
--- a/src/esengine/core/EstellaContext.hpp
+++ b/src/esengine/core/EstellaContext.hpp
@@ -32,9 +32,21 @@ public:
* @brief Initialize with an existing WebGL context handle
* @param webglContextHandle Valid WebGL context (from emscripten_webgl_create_context)
* @return True on success
+ * @details Convenience for the GL backend: makes the context current and
+ * delegates to init(UniquePtr<GfxDevice>) with a GLDevice.
*/
bool init(int webglContextHandle);
+ /**
+ * @brief Initialize with an injected render backend.
+ * @param device A ready-to-use GfxDevice (e.g. a WebGPUDevice whose surface
+ * is already configured). The platform edge owns backend selection —
+ * exactly as the WebGL overload receives an externally created
+ * context handle — so this class needs no backend-specific code.
+ * @return True on success
+ */
+ bool init(Unique<GfxDevice> device);
+
/**
* @brief Shut down all subsystems and release resources
*/
@@ -55,7 +67,7 @@ public:
const EngineState& state() const { return state_; }
private:
- void initSubsystems();
+ void initSubsystems(Unique<GfxDevice> gfxDevice);
/**
* Register the GPU-independent ECS logic systems (Transform/UI/Tween).
* Called from the constructor *and* initSubsystems so they exist even for
diff --git a/src/esengine/renderer/ImmediateDraw.cpp b/src/esengine/renderer/ImmediateDraw.cpp
index c8416209f..029d71aaf 100644
--- a/src/esengine/renderer/ImmediateDraw.cpp
+++ b/src/esengine/renderer/ImmediateDraw.cpp
@@ -19,6 +19,7 @@
#include "RenderContext.hpp"
#include "Shader.hpp"
#include "ShaderEmbeds.generated.hpp"
+#include "webgpu/WGSLTwins.hpp"
#include "BatchVertex.hpp"
#include "../resource/ShaderParser.hpp"
#include "../resource/ResourceManager.hpp"
@@ -63,12 +64,19 @@ void ImmediateDraw::init() {
pool_.init();
white_texture_id_ = context_.getWhiteTextureId();
- auto parsed = resource::ShaderParser::parse(ShaderEmbeds::BATCH);
- auto handle = resource_manager_.createShaderWithBindings(
- resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex),
- resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment),
- {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}}
- );
+ resource::ShaderHandle handle;
+ if (resource_manager_.preferredShaderLanguage() == GfxShaderLanguage::GLSL_ES300) {
+ auto parsed = resource::ShaderParser::parse(ShaderEmbeds::BATCH);
+ handle = resource_manager_.createShaderWithBindings(
+ resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex),
+ resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment),
+ {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}}
+ );
+ } else {
+ handle = resource_manager_.createShaderWithBindings(
+ webgpu::kBatchWGSL_Vertex, webgpu::kBatchWGSL_Fragment,
+ {}, GfxShaderLanguage::WGSL);
+ }
Shader* shader = resource_manager_.getShader(handle);
if (shader && shader->isValid()) {
batch_shader_ = shader->handle();
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index 3004ba08e..1cf240600 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -15,6 +15,7 @@
#include "RenderContext.hpp"
#include "GfxDevice.hpp"
#include "Shader.hpp"
+#include "webgpu/WGSLTwins.hpp"
#include "../resource/ResourceManager.hpp"
#include "../core/Log.hpp"
#include <algorithm>
@@ -69,7 +70,14 @@ void PostProcessPipeline::init(u32 width, u32 height) {
width_ = width;
height_ = height;
- blitShader_ = resourceManager_.createShader(BLIT_VERTEX, BLIT_FRAGMENT);
+ if (resourceManager_.preferredShaderLanguage() == GfxShaderLanguage::GLSL_ES300) {
+ blitShader_ = resourceManager_.createShader(BLIT_VERTEX, BLIT_FRAGMENT);
+ } else {
+ blitShader_ = resourceManager_.createShader(webgpu::kBlitWGSL_Vertex,
+ webgpu::kBlitWGSL_Fragment,
+ /*rewriteLoose=*/false,
+ GfxShaderLanguage::WGSL);
+ }
if (!blitShader_.isValid()) {
ES_LOG_ERROR("PostProcessPipeline: Failed to create blit shader");
return;
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index 1ed27c75e..514bbc015 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -3,6 +3,7 @@
#include "RenderFrame.hpp"
#include "Shader.hpp"
#include "ShaderEmbeds.generated.hpp"
+#include "webgpu/WGSLTwins.hpp"
#include "LightStore.hpp"
#include "../ecs/components/Transform.hpp"
#include "../ecs/components/Light2D.hpp"
@@ -349,6 +350,12 @@ void RenderFrame::end() {
const f32 ppMs = usePostProcess ? gpu_timer_pp_.lastMs() : 0.0f;
stats_.gpu_time_ms = submitMs < 0.0f ? -1.0f : submitMs + (ppMs > 0.0f ? ppMs : 0.0f);
+ // The frame's pass closes HERE, not at the next begin: a WebGPU backend
+ // submits on endRenderPass, and a surface texture acquired this task must
+ // not ride into the next one (the swapchain recycles it at task end). On
+ // GL this is just the default-framebuffer rebind.
+ device_.endRenderPass();
+
frame_capture_.endCapture();
in_frame_ = false;
flushed_ = false;
@@ -618,20 +625,34 @@ u32 RenderFrame::batchProgram(const std::vector<std::string>& features) {
}
u32 RenderFrame::compileBatchVariant(const std::vector<std::string>& features) {
- // The batch shader is authored as a single .esshader, embedded for the web build.
- // Parse it and assemble the two GLSL ES 3.00 stages (single source of truth),
- // injecting the requested feature #defines (e.g. SDF).
- auto parsed = resource::ShaderParser::parse(ShaderEmbeds::BATCH);
- // LIT is a Lit2D-domain variant: the domain drives the lighting injection,
- // same path as Lit2D material shaders.
- if (std::find(features.begin(), features.end(), "LIT") != features.end()) {
- parsed.domain = "Lit2D";
+ resource::ShaderHandle handle;
+ if (resource_manager_.preferredShaderLanguage() == GfxShaderLanguage::WGSL) {
+ // Only the default variant has a hand-written twin; the SDF/LIT feature
+ // variants arrive with the Phase 3 dual-language emitter.
+ if (!features.empty()) {
+ const std::string vk = resource::ShaderParser::variantKey(features);
+ ES_LOG_ERROR("Batch shader variant '{}' has no WGSL twin yet", vk.c_str());
+ return 0;
+ }
+ handle = resource_manager_.createShaderWithBindings(
+ webgpu::kBatchWGSL_Vertex, webgpu::kBatchWGSL_Fragment,
+ {}, GfxShaderLanguage::WGSL);
+ } else {
+ // The batch shader is authored as a single .esshader, embedded for the web build.
+ // Parse it and assemble the two GLSL ES 3.00 stages (single source of truth),
+ // injecting the requested feature #defines (e.g. SDF).
+ auto parsed = resource::ShaderParser::parse(ShaderEmbeds::BATCH);
+ // LIT is a Lit2D-domain variant: the domain drives the lighting injection,
+ // same path as Lit2D material shaders.
+ if (std::find(features.begin(), features.end(), "LIT") != features.end()) {
+ parsed.domain = "Lit2D";
+ }
+ handle = resource_manager_.createShaderWithBindings(
+ resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features),
+ resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features),
+ {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}}
+ );
}
- resource::ShaderHandle handle = resource_manager_.createShaderWithBindings(
- resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features),
- resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features),
- {{0, "a_position"}, {1, "a_color"}, {2, "a_texCoord"}}
- );
Shader* shader = resource_manager_.getShader(handle);
if (shader && shader->isValid()) {
diff --git a/src/esengine/renderer/plugins/ParticlePlugin.cpp b/src/esengine/renderer/plugins/ParticlePlugin.cpp
index da755c9b0..cfb7eff4f 100644
--- a/src/esengine/renderer/plugins/ParticlePlugin.cpp
+++ b/src/esengine/renderer/plugins/ParticlePlugin.cpp
@@ -6,6 +6,7 @@
#include "../RenderFrame.hpp"
#include "../Shader.hpp"
#include "../ShaderEmbeds.generated.hpp"
+#include "../webgpu/WGSLTwins.hpp"
#include "../Texture.hpp"
#include "../BatchVertex.hpp" // packColor
#include "../../resource/ShaderParser.hpp"
@@ -36,17 +37,28 @@ static_assert(sizeof(ParticleInstanceData) == 40, "instance stride must match th
void ParticlePlugin::init(RenderFrameContext& ctx) {
// Particle instancing shader, authored as particle.esshader (single source) and
// embedded for the web build. Attribute locations are explicit, so no name bindings.
- auto parsed = resource::ShaderParser::parse(ShaderEmbeds::PARTICLE);
- auto handle = ctx.resources.createShaderWithBindings(
- resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex),
- resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment),
- {});
+ resource::ShaderHandle handle;
+ if (ctx.resources.preferredShaderLanguage() == GfxShaderLanguage::GLSL_ES300) {
+ auto parsed = resource::ShaderParser::parse(ShaderEmbeds::PARTICLE);
+ handle = ctx.resources.createShaderWithBindings(
+ resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex),
+ resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment),
+ {});
+ } else {
+ handle = ctx.resources.createShaderWithBindings(
+ webgpu::kParticleWGSL_Vertex, webgpu::kParticleWGSL_Fragment,
+ {}, GfxShaderLanguage::WGSL);
+ }
Shader* shader = ctx.resources.getShader(handle);
if (shader && shader->isValid()) {
particle_shader_id_ = shader->getProgramId();
- shader->bind();
- shader->setUniform("u_texture", 0); // sampler unit 0
- shader->unbind();
+ if (shader->language() == GfxShaderLanguage::GLSL_ES300) {
+ // Sampler seeding is a GLSL concept; on WGSL the texture rides the
+ // bind group.
+ shader->bind();
+ shader->setUniform("u_texture", 0); // sampler unit 0
+ shader->unbind();
+ }
}
}
diff --git a/src/esengine/renderer/plugins/ShapePlugin.cpp b/src/esengine/renderer/plugins/ShapePlugin.cpp
index 19ded3398..604e03216 100644
--- a/src/esengine/renderer/plugins/ShapePlugin.cpp
+++ b/src/esengine/renderer/plugins/ShapePlugin.cpp
@@ -6,6 +6,7 @@
#include "../RenderFrame.hpp"
#include "../Shader.hpp"
#include "../ShaderEmbeds.generated.hpp"
+#include "../webgpu/WGSLTwins.hpp"
#include "../../ecs/components/Transform.hpp"
#include "../../ecs/components/ShapeRenderer.hpp"
#include "../../resource/ShaderParser.hpp"
@@ -15,12 +16,20 @@
namespace esengine {
void ShapePlugin::init(RenderFrameContext& ctx) {
- auto shapeParsed = resource::ShaderParser::parse(ShaderEmbeds::SHAPE);
- shape_shader_handle_ = ctx.resources.createShaderWithBindings(
- resource::ShaderParser::assembleStage(shapeParsed, resource::ShaderStage::Vertex),
- resource::ShaderParser::assembleStage(shapeParsed, resource::ShaderStage::Fragment),
- {{0, "a_position"}, {1, "a_texCoord"}, {2, "a_color"}, {3, "a_shapeInfo"}}
- );
+ if (ctx.resources.preferredShaderLanguage() == GfxShaderLanguage::GLSL_ES300) {
+ auto shapeParsed = resource::ShaderParser::parse(ShaderEmbeds::SHAPE);
+ shape_shader_handle_ = ctx.resources.createShaderWithBindings(
+ resource::ShaderParser::assembleStage(shapeParsed, resource::ShaderStage::Vertex),
+ resource::ShaderParser::assembleStage(shapeParsed, resource::ShaderStage::Fragment),
+ {{0, "a_position"}, {1, "a_texCoord"}, {2, "a_color"}, {3, "a_shapeInfo"}}
+ );
+ } else {
+ // The WGSL twin fixes its attribute locations in-source; name bindings
+ // are a GL link-time concept.
+ shape_shader_handle_ = ctx.resources.createShaderWithBindings(
+ webgpu::kShapeWGSL_Vertex, webgpu::kShapeWGSL_Fragment,
+ {}, GfxShaderLanguage::WGSL);
+ }
Shader* shader = ctx.resources.getShader(shape_shader_handle_);
shape_shader_id_ = shader ? shader->getProgramId() : 0;
diff --git a/src/esengine/renderer/webgpu/WGSLTwins.hpp b/src/esengine/renderer/webgpu/WGSLTwins.hpp
index c30a6a554..029312c8b 100644
--- a/src/esengine/renderer/webgpu/WGSLTwins.hpp
+++ b/src/esengine/renderer/webgpu/WGSLTwins.hpp
@@ -8,11 +8,15 @@
* the multi-texture set as bind group 1 — 8 texture_2d at bindings 0..7
* paired with 8 samplers at bindings 8..15 (GL's combined
* texture+sampler state arrives de-combined; sampler i carries texture
- * i's filter/wrap params). Consumed by the WebGPU bring-up today and by
- * the engine's WGSL program selection when the backend reports WGSL;
- * Phase 3's dual-language emitter replaces the hand-written pairs.
+ * i's filter/wrap params). Consumed by the embedded-pipeline creation
+ * sites when ResourceManager::preferredShaderLanguage() reports WGSL,
+ * and by the WebGPU bring-up harnesses; Phase 3's dual-language
+ * emitter replaces the hand-written pairs.
*
- * Compiled only under ES_ENABLE_WEBGPU; never part of the GL build.
+ * Twin discipline: declare exactly the bindings you use — the WebGPU
+ * device reflects bind-group contents by scanning these declarations.
+ *
+ * Plain string constants — safe in every build; no WebGPU headers.
*
* @author ESEngine Team
* @date 2026
@@ -168,4 +172,107 @@ struct VSOut {
}
)";
+// =============================================================================
+// particle.esshader — the instanced particle quad: quad corner + uv per vertex
+// (locations 0..1), instance stream at locations 2..7, FrameConstants at
+// group 0. u_texture is single-texture, so the twin declares just the t0/s0
+// pair of the group-1 convention (declare-exactly-what-you-use — the binding
+// masks are scanned from the source).
+// =============================================================================
+
+inline constexpr const char* kParticleWGSL_Vertex = R"(
+struct FrameConstants { projection : mat4x4f };
+@group(0) @binding(0) var<uniform> frame : FrameConstants;
+
+struct VSIn {
+ @location(0) position : vec2f,
+ @location(1) uv : vec2f,
+ @location(2) instPosition : vec2f,
+ @location(3) instSize : vec2f,
+ @location(4) instRotation : f32,
+ @location(5) instColor : vec4f,
+ @location(6) instUvOffset : vec2f,
+ @location(7) instUvScale : vec2f,
+};
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+ @location(1) color : vec4f,
+};
+
+@vertex fn vs_main(v : VSIn) -> VSOut {
+ let scaled = v.position * v.instSize;
+
+ let cosR = cos(v.instRotation);
+ let sinR = sin(v.instRotation);
+ let rotated = vec2f(
+ scaled.x * cosR - scaled.y * sinR,
+ scaled.x * sinR + scaled.y * cosR
+ );
+
+ let worldPos = rotated + v.instPosition;
+
+ var out : VSOut;
+ out.pos = frame.projection * vec4f(worldPos, 0.0, 1.0);
+ out.uv = v.uv * v.instUvScale + v.instUvOffset;
+ out.color = v.instColor;
+ return out;
+}
+)";
+
+inline constexpr const char* kParticleWGSL_Fragment = R"(
+@group(1) @binding(0) var t0 : texture_2d<f32>;
+@group(1) @binding(8) var s0 : sampler;
+
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+ @location(1) color : vec4f,
+};
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ let texColor = textureSampleLevel(t0, s0, v.uv, 0.0);
+ return texColor * v.color;
+}
+)";
+
+// =============================================================================
+// The post-process blit (PostProcessPipeline's inline GLSL pair) — a clip-space
+// quad passing uv through, sampling the captured target as t0/s0. Effect
+// shaders are Phase 3; the blit keeps the pipeline initialized and its
+// passthrough path working.
+// =============================================================================
+
+inline constexpr const char* kBlitWGSL_Vertex = R"(
+struct VSIn {
+ @location(0) position : vec2f,
+ @location(1) uv : vec2f,
+};
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+};
+
+@vertex fn vs_main(v : VSIn) -> VSOut {
+ var out : VSOut;
+ out.pos = vec4f(v.position, 0.0, 1.0);
+ out.uv = v.uv;
+ return out;
+}
+)";
+
+inline constexpr const char* kBlitWGSL_Fragment = R"(
+@group(1) @binding(0) var t0 : texture_2d<f32>;
+@group(1) @binding(8) var s0 : sampler;
+
+struct VSOut {
+ @builtin(position) pos : vec4f,
+ @location(0) uv : vec2f,
+};
+
+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
+ return textureSampleLevel(t0, s0, v.uv, 0.0);
+}
+)";
+
} // namespace esengine::webgpu
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index 8f1450384..05f8a13eb 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -483,10 +483,13 @@ ShaderHandle WebGPUDevice::createProgram(const GfxShaderSource& source,
ProgramRec rec{};
rec.vertex = makeModule(source.vertexSrc);
rec.fragment = makeModule(source.fragmentSrc);
- // Group 1 is the texture set by engine convention; a program that never
- // spells it must never have the group bound (auto layouts omit it).
- rec.usesTextureGroup = (source.fragmentSrc && std::strstr(source.fragmentSrc, "@group(1)")) ||
- (source.vertexSrc && std::strstr(source.vertexSrc, "@group(1)"));
+ // Reflection-by-scan: bind groups must match the pipeline's auto layout
+ // exactly, so record which group-0 UBO slots and group-1 texture/sampler
+ // bindings the program declares (twin discipline: declare = use).
+ rec.group0Mask = scanWGSLBindingMask(source.vertexSrc, 0) |
+ scanWGSLBindingMask(source.fragmentSrc, 0);
+ rec.group1Mask = scanWGSLBindingMask(source.vertexSrc, 1) |
+ scanWGSLBindingMask(source.fragmentSrc, 1);
if (!rec.vertex || !rec.fragment) {
if (rec.vertex) wgpuShaderModuleRelease(rec.vertex);
if (rec.fragment) wgpuShaderModuleRelease(rec.fragment);
@@ -825,14 +828,22 @@ void WebGPUDevice::flushBindGroup() {
WGPURenderPipeline p = ensurePipeline(current_pipeline_);
if (!p) return;
+ const ProgramRec* prog = nullptr;
+ if (auto pipeIt = pipelines_.find(current_pipeline_); pipeIt != pipelines_.end()) {
+ auto progIt = programs_.find(static_cast<u32>(pipeIt->second.desc.program));
+ if (progIt != programs_.end()) prog = &progIt->second;
+ }
+ if (!prog) return;
+
// Group 0 = the engine's UBO bindings (0..4). Entries must match the
- // pipeline's layout exactly, so only slots the shader declares may appear;
- // bring-up shaders declare exactly the slots the scene sets. Full slot-mask
- // reflection ships with the WGSL emitter metadata (Phase 3).
+ // pipeline's auto layout exactly — the layout contains only the bindings
+ // the shader declares — so the bound slots filter through the program's
+ // scanned mask. (The engine keeps Frame/Time/DrawParams armed on 0/3/4;
+ // a shader that only declares FrameConstants gets a one-entry group.)
WGPUBindGroupEntry entries[kUniformSlots];
u32 count = 0;
for (u32 slot = 0; slot < kUniformSlots; ++slot) {
- if (uniform_slots_[slot] == 0) continue;
+ if (uniform_slots_[slot] == 0 || (prog->group0Mask & (1u << slot)) == 0) continue;
auto it = buffers_.find(uniform_slots_[slot]);
if (it == buffers_.end()) continue;
WGPUBindGroupEntry e{};
@@ -844,50 +855,55 @@ void WebGPUDevice::flushBindGroup() {
}
if (bind_group_) { wgpuBindGroupRelease(bind_group_); bind_group_ = nullptr; }
- if (count == 0) { bind_group_dirty_ = false; return; }
-
- WGPUBindGroupDescriptor bgd{};
- bgd.layout = wgpuRenderPipelineGetBindGroupLayout(p, 0);
- bgd.entryCount = count;
- bgd.entries = entries;
- bind_group_ = wgpuDeviceCreateBindGroup(device_, &bgd);
- if (bgd.layout) wgpuBindGroupLayoutRelease(bgd.layout);
- if (bind_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 0, bind_group_, 0, nullptr);
-
- // Group 1: the texture units. The WGSL twin convention is 8 texture_2d at
- // bindings 0..7 paired with 8 samplers at bindings 8..15 (the batch shader's
- // u_textures[8], de-combined: sampler i carries texture i's filter/wrap
- // params via the sampler cache). Unused slots repeat slot 0's view/sampler —
- // the same trick DrawList::execute uses for WebGL2's complete-texture rule.
- // Only set when the pass bound textures AND the current program declares the
- // group — a sampler-less shader (shape) drawn after textured ones must keep
- // its group-0-only layout.
- bool wantsTextures = false;
- if (auto pipeIt = pipelines_.find(current_pipeline_); pipeIt != pipelines_.end()) {
- auto progIt = programs_.find(static_cast<u32>(pipeIt->second.desc.program));
- wantsTextures = progIt != programs_.end() && progIt->second.usesTextureGroup;
+ if (count > 0) {
+ WGPUBindGroupDescriptor bgd{};
+ bgd.layout = wgpuRenderPipelineGetBindGroupLayout(p, 0);
+ bgd.entryCount = count;
+ bgd.entries = entries;
+ bind_group_ = wgpuDeviceCreateBindGroup(device_, &bgd);
+ if (bgd.layout) wgpuBindGroupLayoutRelease(bgd.layout);
+ if (bind_group_) wgpuRenderPassEncoderSetBindGroup(pass_, 0, bind_group_, 0, nullptr);
}
- if (any_texture_bound_ && wantsTextures) {
+
+ // Group 1: the texture units. The WGSL twin convention is texture_2d at
+ // bindings 0..7 paired with samplers at bindings 8..15 (u_textures[8]
+ // de-combined: sampler i carries texture i's filter/wrap params via the
+ // sampler cache); a single-texture shader declares just t0/s0. Entries
+ // filter through the program's group-1 mask; missing units repeat slot 0's
+ // view/sampler — the same trick DrawList::execute uses for WebGL2's
+ // complete-texture rule. Only set when the pass bound textures AND the
+ // program declares the group — a sampler-less shader (shape) drawn after
+ // textured ones must keep its group-0-only layout.
+ if (any_texture_bound_ && prog->group1Mask != 0) {
const TextureRec* slot0 = nullptr;
for (u32 slot = 0; slot < kTextureSlots && !slot0; ++slot) {
auto it = textures_.find(texture_slots_[slot]);
if (it != textures_.end()) slot0 = &it->second;
}
if (slot0) {
- WGPUBindGroupEntry texEntries[kTextureSlots * 2] = {};
+ WGPUBindGroupEntry texEntries[kTextureSlots * 2];
+ u32 texCount = 0;
for (u32 slot = 0; slot < kTextureSlots; ++slot) {
auto it = textures_.find(texture_slots_[slot]);
const TextureRec& rec = (it != textures_.end()) ? it->second : *slot0;
- texEntries[slot].binding = slot;
- texEntries[slot].textureView = rec.view;
- texEntries[kTextureSlots + slot].binding = kTextureSlots + slot;
- texEntries[kTextureSlots + slot].sampler = samplerFor(rec.samplerKey);
+ if (prog->group1Mask & (1u << slot)) {
+ WGPUBindGroupEntry e{};
+ e.binding = slot;
+ e.textureView = rec.view;
+ texEntries[texCount++] = e;
+ }
+ if (prog->group1Mask & (1u << (kTextureSlots + slot))) {
+ WGPUBindGroupEntry e{};
+ e.binding = kTextureSlots + slot;
+ e.sampler = samplerFor(rec.samplerKey);
+ texEntries[texCount++] = e;
+ }
}
if (texture_group_) { wgpuBindGroupRelease(texture_group_); texture_group_ = nullptr; }
WGPUBindGroupDescriptor tgd{};
tgd.layout = wgpuRenderPipelineGetBindGroupLayout(p, 1);
- tgd.entryCount = kTextureSlots * 2;
+ tgd.entryCount = texCount;
tgd.entries = texEntries;
texture_group_ = wgpuDeviceCreateBindGroup(device_, &tgd);
if (tgd.layout) wgpuBindGroupLayoutRelease(tgd.layout);
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index c58c62a87..7d5dd3575 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -167,10 +167,14 @@ private:
struct ProgramRec {
WGPUShaderModule vertex = nullptr;
WGPUShaderModule fragment = nullptr;
- /** @brief Whether the WGSL declares the group-1 texture set. A pipeline
- * without it must never have group 1 set (its auto layout has no
- * such group), even when the pass bound textures for other draws. */
- bool usesTextureGroup = false;
+ /** @brief `@group(0/1) @binding(i)` masks scanned from the WGSL (both
+ * stages). Bind groups must match a pipeline's auto layout
+ * exactly, so the device filters its bound state through these:
+ * group 0 = which UBO slots the program declares, group 1 =
+ * which texture/sampler bindings. Zero group-1 mask means the
+ * program must never have the texture group set at all. */
+ u32 group0Mask = 0;
+ u32 group1Mask = 0;
};
struct PipelineRec {
PipelineDesc desc;
diff --git a/src/esengine/renderer/webgpu/WebGPUMappings.hpp b/src/esengine/renderer/webgpu/WebGPUMappings.hpp
index ba7a3dd38..0f0cfb508 100644
--- a/src/esengine/renderer/webgpu/WebGPUMappings.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUMappings.hpp
@@ -26,6 +26,9 @@
#include <webgpu/webgpu.h>
+#include <cstdlib>
+#include <cstring>
+
namespace esengine::webgpu {
// =============================================================================
@@ -311,4 +314,40 @@ inline WGPUCullMode toWGPUCullMode(bool enabled, bool front) {
return front ? WGPUCullMode_Front : WGPUCullMode_Back;
}
+// =============================================================================
+// WGSL binding reflection (source scan)
+// =============================================================================
+
+/**
+ * @brief Bit mask of the `@group(N) @binding(i)` indices a WGSL source declares.
+ * @details Bind-group entries must match a pipeline's auto layout EXACTLY, and
+ * auto layouts contain only the bindings the shader uses — so the
+ * device filters its bound state (UBO slots, texture units) through
+ * this mask per program. A source scan stands in for real reflection
+ * until the Phase 3 emitter carries binding metadata; the twins'
+ * discipline is declare-exactly-what-you-use, which makes the two
+ * equivalent. Bindings ≥ 32 are ignored (the engine's conventions top
+ * out at 16).
+ */
+inline u32 scanWGSLBindingMask(const char* source, u32 group) {
+ if (!source) return 0;
+ u32 mask = 0;
+ for (const char* p = source; (p = std::strstr(p, "@group(")) != nullptr;) {
+ p += 7;
+ char* end = nullptr;
+ const unsigned long g = std::strtoul(p, &end, 10);
+ if (end == p) continue;
+ p = end;
+ if (g != group) continue;
+ const char* b = std::strstr(p, "@binding(");
+ if (!b) break;
+ b += 9;
+ const unsigned long idx = std::strtoul(b, &end, 10);
+ if (end == b) continue;
+ p = end;
+ if (idx < 32) mask |= (1u << idx);
+ }
+ return mask;
+}
+
} // namespace esengine::webgpu
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index fa00064dc..bc57d293e 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -64,6 +64,12 @@ void ResourceManager::update() {
// Shader Resources
// =============================================================================
+GfxShaderLanguage ResourceManager::preferredShaderLanguage() const {
+ return (device_ && !device_->supportsShaderLanguage(GfxShaderLanguage::GLSL_ES300))
+ ? GfxShaderLanguage::WGSL
+ : GfxShaderLanguage::GLSL_ES300;
+}
+
ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const std::string& fragSrc,
bool rewriteLoose, GfxShaderLanguage language) {
if (!device_) return {};
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index 5506838fa..251668ed0 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -127,6 +127,15 @@ public:
// Shader Resources
// =========================================================================
+ /**
+ * @brief The language embedded pipelines must author their sources in.
+ * @details GLSL when the backend compiles it (the GL device); otherwise the
+ * backend's own language (WGSL). Embedded shader creation sites
+ * branch on this to pick the .esshader assembly or its WGSL twin —
+ * the one seam that keeps plugins backend-agnostic.
+ */
+ GfxShaderLanguage preferredShaderLanguage() const;
+
/**
* @brief Creates a shader from source strings
* @param vertSrc Vertex shader GLSL source
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 2929bcfe5..46585b0bb 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -148,6 +148,27 @@ if(EMSCRIPTEN)
target_link_options(webgpu_bringup PRIVATE --use-port=emdawnwebgpu)
endif()
+# Engine-level backend parity harness (REARCH_WGSL Phase 2): the FULL engine —
+# EstellaContext with every subsystem — booted on an injected backend (WebGPU
+# via emdawnwebgpu, or the stock WebGL2 path, chosen by URL) rendering one ECS
+# scene. Driven by desktop/scripts/engine-parity.mjs, which asserts the SAME
+# pixels on both backends. WebGL2 link flags are required because the GL run
+# uses the production GLES3 path.
+if(EMSCRIPTEN)
+ add_executable(webgpu_engine_bringup
+ renderer/webgpu_engine_bringup.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+ )
+ target_link_libraries(webgpu_engine_bringup PRIVATE esengine)
+ target_compile_options(webgpu_engine_bringup PRIVATE --use-port=emdawnwebgpu)
+ target_link_options(webgpu_engine_bringup PRIVATE
+ --use-port=emdawnwebgpu
+ -sUSE_WEBGL2=1
+ -sFULL_ES3=1
+ -sALLOW_MEMORY_GROWTH=1
+ )
+endif()
+
# Boundary-span validation (RC3): JS-supplied pointer+length pairs are null-,
# overflow-, and heap-range-checked ALWAYS ON. Header-only + Log.cpp; under
# emscripten the heap-range cases exercise the real linear-memory bound.
diff --git a/tests/renderer/test_webgpu_device.cpp b/tests/renderer/test_webgpu_device.cpp
index 645b5b621..efbca7ce5 100644
--- a/tests/renderer/test_webgpu_device.cpp
+++ b/tests/renderer/test_webgpu_device.cpp
@@ -102,6 +102,30 @@ TEST_CASE("pipeline depth-stencil state carries GL semantics exactly") {
CHECK(!hasStencilPlanes(WGPUTextureFormat_Undefined));
}
+TEST_CASE("binding-mask scan mirrors what a WGSL auto layout will contain") {
+ // A batch-like fragment: the full group-1 texture/sampler set.
+ const char* batchish = R"(
+@group(1) @binding(0) var t0 : texture_2d<f32>;
+@group(1) @binding(7) var t7 : texture_2d<f32>;
+@group(1) @binding(8) var s0 : sampler;
+@group(1) @binding(15) var s7 : sampler;
+)";
+ CHECK(scanWGSLBindingMask(batchish, 1) == ((1u << 0) | (1u << 7) | (1u << 8) | (1u << 15)));
+ CHECK(scanWGSLBindingMask(batchish, 0) == 0u);
+
+ // A shader over several UBO slots — the engine's 0..4 binding map.
+ const char* ubos = R"(
+@group(0) @binding(0) var<uniform> frame : FrameConstants;
+@group(0) @binding(3) var<uniform> time : TimeConstants;
+@group(0) @binding(4) var<uniform> params : DrawParams;
+)";
+ CHECK(scanWGSLBindingMask(ubos, 0) == ((1u << 0) | (1u << 3) | (1u << 4)));
+ CHECK(scanWGSLBindingMask(ubos, 1) == 0u);
+
+ CHECK(scanWGSLBindingMask(nullptr, 0) == 0u);
+ CHECK(scanWGSLBindingMask("no bindings here", 0) == 0u);
+}
+
TEST_CASE("pass load-ops: full-target clear is a real load-op, a scoped clear is not") {
CHECK(toWGPULoadOp(/*clear*/ true, /*scoped*/ false) == WGPULoadOp_Clear);
CHECK(toWGPULoadOp(true, true) == WGPULoadOp_Load); // region clear → emulate, load first
diff --git a/tests/renderer/webgpu_engine_bringup.cpp b/tests/renderer/webgpu_engine_bringup.cpp
new file mode 100644
index 000000000..92d0d2844
--- /dev/null
+++ b/tests/renderer/webgpu_engine_bringup.cpp
@@ -0,0 +1,185 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Engine-level backend parity harness (REARCH_WGSL Phase 2) — NOT a
+ * doctest harness.
+ *
+ * Boots the REAL engine — EstellaContext with every subsystem — on either
+ * backend, selected by the page URL (?backend=gl or ?backend=webgpu), and
+ * renders one ECS scene through the production path: TransformSystem →
+ * RenderFrame begin/collectAll/flush/end. The WebGPU run receives an injected
+ * WebGPUDevice with a configured surface; the GL run creates a WebGL2 context —
+ * both through the same EstellaContext::init seams the SDK uses.
+ *
+ * The scene exercises the embedded pipelines that have WGSL twins: sprites
+ * (batch, multi-texture: a 2x2 checker + a solid texture) and an SDF shape
+ * circle. The electron runner (desktop/scripts/engine-parity.mjs) loads the
+ * page once per backend and asserts the SAME pixel expectations on both — the
+ * two backends' outputs are each other's gold.
+ */
+#include "esengine/core/EstellaContext.hpp"
+#include "esengine/core/World.hpp"
+#include "esengine/ecs/Registry.hpp"
+#include "esengine/ecs/TransformSystem.hpp"
+#include "esengine/ecs/components/Transform.hpp"
+#include "esengine/ecs/components/Sprite.hpp"
+#include "esengine/ecs/components/ShapeRenderer.hpp"
+#include "esengine/renderer/RenderContext.hpp"
+#include "esengine/renderer/RenderFrame.hpp"
+#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
+#include "esengine/resource/ResourceManager.hpp"
+
+#include <emscripten.h>
+#include <emscripten/html5.h>
+
+#include <glm/gtc/matrix_transform.hpp>
+
+#include <cstdio>
+
+using namespace esengine;
+
+namespace {
+
+constexpr u32 kSize = 256;
+
+EstellaContext* g_context = nullptr;
+ecs::Registry* g_registry = nullptr;
+int g_frames = 0;
+f32 g_elapsed = 0.0f;
+
+void renderFrame() {
+ auto& ctx = *g_context;
+ auto& registry = *g_registry;
+
+ g_elapsed += 1.0f / 60.0f;
+ ctx.require<RenderContext>().setFrameTime(g_elapsed, kSize, kSize);
+
+ World world{registry, ctx.services(), 1.0f / 60.0f};
+ ctx.require<ecs::TransformSystem>().update(world);
+
+ // World units are pixels, y up — the same ortho the SDK's default camera
+ // derives for a 256x256 view centered on (128,128).
+ const glm::mat4 viewProjection =
+ glm::ortho(0.0f, static_cast<f32>(kSize), 0.0f, static_cast<f32>(kSize));
+
+ auto& renderFrame = ctx.require<RenderFrame>();
+ renderFrame.begin(viewProjection, 0,
+ RenderFrame::PassClear{true, true, glm::vec4(0.05f, 0.05f, 0.30f, 1.0f)});
+ renderFrame.collectAll(registry);
+ renderFrame.flush();
+ renderFrame.end();
+
+ if (++g_frames == 3) {
+ std::printf("PARITY_FRAMES_OK\n");
+ emscripten_cancel_main_loop();
+ }
+}
+
+bool buildScene(EstellaContext& ctx, ecs::Registry& registry) {
+ auto& rm = ctx.require<resource::ResourceManager>();
+
+ // 2x2 red/blue checker; asserted at texel centers, so the expectation is
+ // filter-independent and purely about UV orientation parity.
+ const u8 checker[16] = {
+ 255, 0, 0, 255, 0, 0, 255, 255, // row 0: red, blue
+ 0, 0, 255, 255, 255, 0, 0, 255, // row 1: blue, red
+ };
+ auto checkerTex = rm.createTexture(2, 2, ConstSpan<u8>(checker, sizeof(checker)),
+ TextureFormat::RGBA8);
+ const u8 green[4] = {0, 255, 0, 255};
+ auto greenTex = rm.createTexture(1, 1, ConstSpan<u8>(green, sizeof(green)),
+ TextureFormat::RGBA8);
+ if (!checkerTex.isValid() || !greenTex.isValid()) return false;
+
+ // Sprite A: the checker, left-top area (world center 64,176, size 64).
+ {
+ auto e = registry.create();
+ auto& t = registry.emplace<ecs::Transform>(e);
+ t.position = {64.0f, 176.0f, 0.0f};
+ auto& s = registry.emplace<ecs::Sprite>(e);
+ s.texture = checkerTex;
+ s.size = {64.0f, 64.0f};
+ }
+
+ // Sprite B: solid green (world center 192,176, size 48).
+ {
+ auto e = registry.create();
+ auto& t = registry.emplace<ecs::Transform>(e);
+ t.position = {192.0f, 176.0f, 0.0f};
+ auto& s = registry.emplace<ecs::Sprite>(e);
+ s.texture = greenTex;
+ s.size = {48.0f, 48.0f};
+ }
+
+ // Shape: a magenta SDF circle, bottom-center (world center 128,80, size 64).
+ {
+ auto e = registry.create();
+ auto& t = registry.emplace<ecs::Transform>(e);
+ t.position = {128.0f, 80.0f, 0.0f};
+ auto& s = registry.emplace<ecs::ShapeRenderer>(e);
+ s.shapeType = 0; // circle
+ s.color = {1.0f, 0.0f, 1.0f, 1.0f};
+ s.size = {64.0f, 64.0f};
+ }
+ return true;
+}
+
+} // namespace
+
+int main() {
+ const bool useGL =
+ EM_ASM_INT({ return location.search.indexOf('backend=gl') >= 0 ? 1 : 0; }) != 0;
+
+ static EstellaContext context;
+ g_context = &context;
+ context.state().viewport_width = kSize;
+ context.state().viewport_height = kSize;
+
+ if (useGL) {
+ EmscriptenWebGLContextAttributes attrs;
+ emscripten_webgl_init_context_attributes(&attrs);
+ attrs.majorVersion = 2;
+ attrs.minorVersion = 0;
+ attrs.alpha = false;
+ attrs.depth = true;
+ attrs.stencil = true;
+ attrs.antialias = false;
+ const auto handle = emscripten_webgl_create_context("#canvas", &attrs);
+ if (handle <= 0) {
+ std::printf("PARITY_FAIL webgl context\n");
+ return 1;
+ }
+ if (!context.init(static_cast<int>(handle))) {
+ std::printf("PARITY_FAIL gl init\n");
+ return 1;
+ }
+ std::printf("PARITY_BACKEND gl\n");
+ } else {
+ WGPUDevice raw = emscripten_webgpu_get_device();
+ if (!raw) {
+ std::printf("PARITY_FAIL no preinitialized device\n");
+ return 1;
+ }
+ auto device = makeUnique<WebGPUDevice>(raw);
+ if (!device->configureSurface("#canvas", kSize, kSize)) {
+ std::printf("PARITY_FAIL surface\n");
+ return 1;
+ }
+ if (!context.init(std::move(device))) {
+ std::printf("PARITY_FAIL webgpu init\n");
+ return 1;
+ }
+ std::printf("PARITY_BACKEND webgpu\n");
+ }
+
+ static ecs::Registry registry;
+ g_registry = &registry;
+ if (!buildScene(context, registry)) {
+ std::printf("PARITY_FAIL scene\n");
+ return 1;
+ }
+
+ std::printf("PARITY_INIT_OK\n");
+ emscripten_set_main_loop(renderFrame, 0, /*simulate_infinite_loop=*/false);
+ return 0;
+}