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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(webgpu): SDK-level WebGPU boot - the backend reaches the production path (WGSL campaign coda)
yhhf8cab9a362ce
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 36d57f714..67fee3717 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -15,6 +15,12 @@ option(ES_ENABLE_TILEMAP "Enable Tilemap support" ON)option(ES_ENABLE_PARTICLES "Enable Particle system" ON)option(ES_ENABLE_POSTPROCESS "Enable Post-processing pipeline" ON)option(ES_ENABLE_BITMAP_TEXT "Enable Bitmap text rendering" ON)+# WebGPU render backend: compiles WebGPUDevice into the engine and pulls the+# emdawnwebgpu port (Dawn's webgpu.h + JS glue) into every SDK executable.+# ON for the web build; stays OFF for WeChat/playable (no WebGPU there, and+# the port's JS glue would only cost size). The web-tests build also leaves it+# OFF — its harness targets compile WebGPUDevice.cpp into themselves.+option(ES_ENABLE_WEBGPU "Enable the WebGPU render backend (emdawnwebgpu port)" OFF)option(ES_ENABLE_BASIS "Build the Basis Universal KTX2 transcoder module" OFF)option(ES_BUILD_MAIN_MODULE "Build as MAIN_MODULE for dynamic linking" OFF)option(ES_BUILD_SIDE_MODULE "Build side modules for dynamic linking" OFF)@@ -80,6 +86,12 @@ if(ES_ENABLE_POSTPROCESS))endif()+if(ES_ENABLE_WEBGPU)+ list(APPEND ESENGINE_SOURCES+ src/esengine/renderer/webgpu/WebGPUDevice.cpp+ )+endif()+if(ES_ENABLE_TILEMAP)list(APPEND ESENGINE_SOURCESsrc/esengine/renderer/plugins/TilemapRenderPlugin.cpp@@ -270,6 +282,14 @@ if(ES_ENABLE_POSTPROCESS)target_compile_definitions(esengine PUBLIC ES_ENABLE_POSTPROCESS)endif()+if(ES_ENABLE_WEBGPU)+ target_compile_definitions(esengine PUBLIC ES_ENABLE_WEBGPU)+ # PUBLIC: the port supplies webgpu.h at compile time and its JS glue at+ # link time — every SDK executable linking the engine needs both sides.+ target_compile_options(esengine PUBLIC --use-port=emdawnwebgpu)+ target_link_options(esengine PUBLIC --use-port=emdawnwebgpu)+endif()+if(ES_ENABLE_BITMAP_TEXT)target_compile_definitions(esengine PUBLIC ES_ENABLE_BITMAP_TEXT)endif()diff --git a/build-tools/build.config.js b/build-tools/build.config.jsindex def3495c9..62e2c18fb 100644--- a/build-tools/build.config.js+++ b/build-tools/build.config.js@@ -23,7 +23,10 @@ export default {wasm: {web: {buildDir: 'build-web',- cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF'],+ // WebGPU backend ships in the web SDK only — WeChat/playable have no+ // WebGPU and skip the emdawnwebgpu glue. Variants sharing build-web+ // (spine*) must carry identical flags or configures would thrash.+ cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_WEBGPU=ON'],targets: ['esengine_sdk'],outputs: {'sdk/esengine.js': 'wasm/web/esengine.js',@@ -71,7 +74,7 @@ export default {},spine: {buildDir: 'build-web',- cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF'],+ cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_WEBGPU=ON'],targets: ['spine_module'],outputs: {'sdk/spine42.js': 'wasm/web/spine42.js',@@ -80,7 +83,7 @@ export default {},spine38: {buildDir: 'build-web',- cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF'],+ cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_WEBGPU=ON'],targets: ['spine_module_38'],outputs: {'sdk/spine38.js': 'wasm/web/spine38.js',@@ -89,7 +92,7 @@ export default {},spine41: {buildDir: 'build-web',- cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF'],+ cmakeFlags: ['-DES_BUILD_WEB=ON', '-DES_BUILD_TESTS=OFF', '-DES_ENABLE_WEBGPU=ON'],targets: ['spine_module_41'],outputs: {'sdk/spine41.js': 'wasm/web/spine41.js',diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjsindex 7dec284a9..23ccd30e1 100644--- a/desktop/scripts/headless-verify.mjs+++ b/desktop/scripts/headless-verify.mjs@@ -39,6 +39,9 @@ const MANIFEST = process.env.ESTELLA_VERIFY_MANIFEST ?? '/scenes/sprite-renderinconst W = Number(process.env.ESTELLA_VERIFY_W) || 640;const H = Number(process.env.ESTELLA_VERIFY_H) || 480;const STEPS = Number(process.env.ESTELLA_VERIFY_STEPS) || 30;+// ESTELLA_VERIFY_BACKEND=webgpu runs the same scene + assertions on the WebGPU+// backend (needs a real adapter — local runs; CI runners have none).+const BACKEND = process.env.ESTELLA_VERIFY_BACKEND === 'webgpu' ? 'webgpu' : 'webgl2';// Headless / GPU-less (CI) WebGL2 falls back to SwiftShader; harmless with a GPU.app.commandLine.appendSwitch('enable-unsafe-swiftshader');@@ -72,7 +75,7 @@ function serveDist() {function finish(result, server) {const ok = result.ok && result.capture?.rendered && (result.expect?.ok ?? true) && (result.preview?.ok ?? true);- console.log(`\n[verify:render] ${ok ? 'PASS' : 'FAIL'} — ${SCENE}`);+ console.log(`\n[verify:render] ${ok ? 'PASS' : 'FAIL'} — ${SCENE} (${BACKEND})`);console.log('DRIVE_RESULT ' + JSON.stringify(result));process.exitCode = ok ? 0 : 1;try {@@ -87,9 +90,14 @@ app.whenReady().then(async () => {let server;try {server = await serveDist();- const url = `http://127.0.0.1:${server.address().port}/headless.html?w=${W}&h=${H}`;+ const url = `http://127.0.0.1:${server.address().port}/headless.html?w=${W}&h=${H}&backend=${BACKEND}`;- const win = new BrowserWindow({ show: false, width: W, height: H, webPreferences: { offscreen: false } });+ // useContentSize: the capture rectangle must be the page area, not the+ // outer frame (the same trap the parity runner documents).+ const win = new BrowserWindow({+ show: false, width: W, height: H, useContentSize: true,+ webPreferences: { offscreen: false },+ });win.webContents.on('console-message', (...args) => {const msg = args.map((a) => (a && typeof a === 'object' ? a.message ?? '' : String(a))).join(' ');if (/error|fail|unwind|exception|webgl/i.test(msg)) console.log('[renderer]', msg.slice(0, 240));@@ -107,7 +115,49 @@ app.whenReady().then(async () => {await exec('window.__estellaHeadless.api.setRunMode(true)');}await exec(`window.__estellaHeadless.api.step(${STEPS}, 1 / 60)`);- const capture = await exec(`(() => {++ // WebGPU: the engine has no synchronous readback (buffer maps are async)+ // and a hidden window never presents, so drawImage-style page readback is+ // blank — capture the PAGE instead (capturePage forces a composite; the+ // same technique the engine-parity runner uses). The canvas sits at the+ // page origin at its backing size, so the page pixels ARE the frame.+ // Converted to the RGBA bottom-up order of ViewportCapture so both+ // backends share the assertion math below.+ const grabWebGPU = async () => {+ const image = await win.webContents.capturePage({ x: 0, y: 0, width: W, height: H });+ const bmp = image.toBitmap(); // BGRA, top-down+ const { width, height } = image.getSize();+ const rgba = Buffer.alloc(width * height * 4);+ for (let y = 0; y < height; y++) {+ const srcRow = y * width * 4;+ const dstRow = (height - 1 - y) * width * 4;+ for (let x = 0; x < width; x++) {+ const s = srcRow + x * 4;+ const d = dstRow + x * 4;+ rgba[d] = bmp[s + 2];+ rgba[d + 1] = bmp[s + 1];+ rgba[d + 2] = bmp[s];+ rgba[d + 3] = bmp[s + 3];+ }+ }+ return { rgba, width, height };+ };+ const webgpuFrame = BACKEND === 'webgpu' ? await grabWebGPU() : null;++ const captureStats = (rgba, width, height) => {+ const min = [255, 255, 255], max = [0, 0, 0];+ let nonZero = 0;+ for (let i = 0; i < rgba.length; i += 4) {+ for (let k = 0; k < 3; k++) { const v = rgba[i + k]; if (v < min[k]) min[k] = v; if (v > max[k]) max[k] = v; }+ if (rgba[i] | rgba[i + 1] | rgba[i + 2]) nonZero++;+ }+ const spread = (max[0] - min[0]) + (max[1] - min[1]) + (max[2] - min[2]);+ return { w: width, h: height, totalPixels: rgba.length / 4, nonZeroPixels: nonZero, min, max, spread, rendered: spread > 16 };+ };++ const capture = webgpuFrame+ ? captureStats(webgpuFrame.rgba, webgpuFrame.width, webgpuFrame.height)+ : await exec(`(() => {const c = window.__estellaHeadless.api.captureViewport();const px = c.rgba; const min = [255, 255, 255], max = [0, 0, 0]; let nonZero = 0;for (let i = 0; i < px.length; i += 4) {@@ -125,7 +175,21 @@ app.whenReady().then(async () => {let expect = null;if (process.env.ESTELLA_VERIFY_EXPECT) {const points = JSON.parse(process.env.ESTELLA_VERIFY_EXPECT);- expect = await exec(`(() => {+ const evaluate = (rgba, w, h) => {+ const out = points.map((p) => {+ const px = Math.round(p.x * (w - 1));+ const glRow = (h - 1) - Math.round(p.y * (h - 1)); // capture rows are bottom-up+ const i = (glRow * w + px) * 4;+ const got = [rgba[i], rgba[i + 1], rgba[i + 2]];+ const tol = p.tol ?? 24;+ const ok = got.every((g, k) => Math.abs(g - p.rgb[k]) <= tol);+ return { x: p.x, y: p.y, want: p.rgb, got, ok };+ });+ return { points: out, ok: out.every((o) => o.ok) };+ };+ expect = webgpuFrame+ ? evaluate(webgpuFrame.rgba, webgpuFrame.width, webgpuFrame.height)+ : await exec(`(() => {const pts = ${JSON.stringify(points)};const c = window.__estellaHeadless.api.captureViewport();const { width: w, height: h, rgba } = c;@@ -143,7 +207,10 @@ app.whenReady().then(async () => {}// Optional PNG dump (ESTELLA_VERIFY_OUT) of the engine framebuffer (not the// page) so the rendered frame can be eyeballed. GL readback is bottom-up → flip.- if (process.env.ESTELLA_VERIFY_OUT) {+ if (process.env.ESTELLA_VERIFY_OUT && BACKEND === 'webgpu') {+ const image = await win.webContents.capturePage({ x: 0, y: 0, width: W, height: H });+ await writeFile(process.env.ESTELLA_VERIFY_OUT, image.toPNG());+ } else if (process.env.ESTELLA_VERIFY_OUT) {const dataUrl = await exec(`(() => {const c = window.__estellaHeadless.api.captureViewport();const cv = document.createElement('canvas'); cv.width = c.width; cv.height = c.height;@@ -158,8 +225,12 @@ app.whenReady().then(async () => {// Optional offscreen material-preview assertion (ESTELLA_VERIFY_PREVIEW =// {w,h,rgb:[r,g,b],tol?}): renders a scene material to an offscreen target and checks the// center pixel — proves the render-to-texture preview primitive, not just the viewport.+ // The material preview reads back through GL — skipped on WebGPU (its+ // buffer maps are async; a readback seam is future work).let preview = null;- if (process.env.ESTELLA_VERIFY_PREVIEW) {+ if (process.env.ESTELLA_VERIFY_PREVIEW && BACKEND === 'webgpu') {+ console.log('[verify:render] preview assertion skipped on webgpu');+ } else if (process.env.ESTELLA_VERIFY_PREVIEW) {const cfg = JSON.parse(process.env.ESTELLA_VERIFY_PREVIEW);preview = await exec(`(() => {const cfg = ${JSON.stringify(cfg)};diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex 8cb421121..c86b673f4 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -288,12 +288,30 @@ export class EditorControlSurfaceImpl {'captureViewport requires a render host (no canvas) — run under the live viewport or the headless editor window',);}- const gl = canvas.getContext('webgl2') as WebGL2RenderingContext | null;- if (!gl) throw new Error('captureViewport: no WebGL2 context on the viewport canvas');const width = canvas.width;const height = canvas.height;+ const gl = canvas.getContext('webgl2') as WebGL2RenderingContext | null;+ if (gl) {+ const rgba = new Uint8Array(width * height * 4);+ gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, rgba);+ return { rgba, width, height };+ }+ // Non-GL canvas (the WebGPU backend): read the presented frame back+ // through a 2D-canvas copy — the compositor path works for any context+ // type. getImageData rows are top-down; flip to the bottom-up order the+ // GL readback established (the capture consumers all assume it).+ const copy = document.createElement('canvas');+ copy.width = width;+ copy.height = height;+ const ctx2d = copy.getContext('2d');+ if (!ctx2d) throw new Error('captureViewport: no 2d context for the readback copy');+ ctx2d.drawImage(canvas, 0, 0);+ const img = ctx2d.getImageData(0, 0, width, height);const rgba = new Uint8Array(width * height * 4);- gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, rgba);+ for (let y = 0; y < height; y++) {+ const src = (height - 1 - y) * width * 4;+ rgba.set(img.data.subarray(src, src + width * 4), y * width * 4);+ }return { rgba, width, height };}diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.tsindex 45cda46e4..62ba3b15b 100644--- a/desktop/src/engine/EngineHost.ts+++ b/desktop/src/engine/EngineHost.ts@@ -373,7 +373,11 @@ class EngineHostImpl {* advanced manually via tick() so captures are deterministic. Resolves once* the engine is ready; the driver then does loadScene → step → captureViewport.*/- async bootHeadless(size: { width: number; height: number }): Promise<void> {+ async bootHeadless(size: {+ width: number;+ height: number;+ backend?: 'webgl2' | 'webgpu';+ }): Promise<void> {if (this.booted) return;this.booted = true;this.setStatus('booting');@@ -381,7 +385,11 @@ class EngineHostImpl {const canvas = this.ensureCanvas();canvas.width = size.width;canvas.height = size.height;- await this.bootCore(canvas, { runLoop: false, loadInitialScene: false });+ await this.bootCore(canvas, {+ runLoop: false,+ loadInitialScene: false,+ backend: size.backend,+ });} catch (err) {this.swallowUnwind(err);}@@ -393,8 +401,9 @@ class EngineHostImpl {// does neither — it advances frames via tick() and loads scenes on demand.private async bootCore(canvas: HTMLCanvasElement,- opts: { runLoop: boolean; loadInitialScene: boolean },+ opts: { runLoop: boolean; loadInitialScene: boolean; backend?: 'webgl2' | 'webgpu' },) {+ const backend = opts.backend ?? 'webgl2';// Early build-consistency check: compare the wasm's stamped manifest// (variant / ABI / provenance) against this SDK before the heavy// instantiate. Advisory only — the runtime bridge handshake is the@@ -414,34 +423,68 @@ class EngineHostImpl {default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;};- const module = await createModule({+ const moduleArg: Record<string, unknown> = {canvas,// The glue resolves esengine.wasm relative to itself; pin it explicitly.locateFile: (path: string) => `/wasm/${path}`,print: (text: string) => console.log('[wasm]', text),printErr: (text: string) => console.warn('[wasm]', text),- });+ };+ if (backend === 'webgpu') {+ // The device must exist BEFORE the module instantiates — the wasm side+ // reads it synchronously (Module.preinitializedWebGPUDevice).+ const gpu = (navigator as unknown as {+ gpu?: {+ requestAdapter(): Promise<{ requestDevice(): Promise<unknown> } | null>;+ };+ }).gpu;+ if (!gpu) throw new Error('WebGPU is not available in this renderer.');+ const adapter = await gpu.requestAdapter();+ if (!adapter) throw new Error('No WebGPU adapter available.');+ moduleArg.preinitializedWebGPUDevice = await adapter.requestDevice();+ // The swapchain glue resolves the canvas by document.querySelector, so+ // it must be connected (the headless host never attaches it to a view).+ // Pin it at the page origin at its backing size: a hidden window never+ // presents for drawImage readback, so the WebGPU verify captures the+ // PAGE (capturePage forces a composite) and needs pixel-exact placement.+ if (!canvas.isConnected) {+ canvas.style.position = 'fixed';+ canvas.style.left = '0';+ canvas.style.top = '0';+ canvas.style.width = `${canvas.width}px`;+ canvas.style.height = `${canvas.height}px`;+ document.body.appendChild(canvas);+ }+ }+ const module = await createModule(moduleArg);this.module_ = module;- // Bind the renderer to a context WE create on this canvas (rather than the- // engine's default '#canvas' selector) so the viewport works embedded- // under any element id. Mirrors the wechat runtime path.- const gl = canvas.getContext('webgl2', {- alpha: false,- antialias: true,- depth: true,- stencil: true,- premultipliedAlpha: false,- }) as WebGL2RenderingContext | null;- if (!gl) throw new Error('WebGL2 is not available in this renderer.');-- const glHandle = module.GL.registerContext(gl, {- majorVersion: 2,- minorVersion: 0,- enableExtensionsByDefault: true,- });+ // WebGL2: bind the renderer to a context WE create on this canvas (rather+ // than the engine's default '#canvas' selector) so the viewport works+ // embedded under any element id. Mirrors the wechat runtime path. WebGPU+ // instead hands the engine the whole canvas swapchain via the injected+ // device ('#canvas' resolves to the moduleArg canvas).+ let glHandle: number | undefined;+ if (backend === 'webgl2') {+ const gl = canvas.getContext('webgl2', {+ alpha: false,+ antialias: true,+ depth: true,+ stencil: true,+ premultipliedAlpha: false,+ }) as WebGL2RenderingContext | null;+ if (!gl) throw new Error('WebGL2 is not available in this renderer.');++ glHandle = module.GL.registerContext(gl, {+ majorVersion: 2,+ minorVersion: 0,+ enableExtensionsByDefault: true,+ });+ }const app = createWebApp(module, {+ backend,+ canvasSelector: `#${canvas.id}`,glContextHandle: glHandle,getViewportSize: () => ({ width: canvas.width, height: canvas.height }),// The per-version spine side modules are served next to esengine.wasmdiff --git a/desktop/src/headless.ts b/desktop/src/headless.tsindex 07c89dbee..a7a7da772 100644--- a/desktop/src/headless.ts+++ b/desktop/src/headless.ts@@ -27,12 +27,15 @@ declare global {}// Viewport size is driver-controlled via the query string (?w=&h=) so captures-// are a known resolution; default to a common 16:9 frame.+// are a known resolution; default to a common 16:9 frame. ?backend=webgpu+// boots the WebGPU backend instead of WebGL2 — the same scene assertions then+// verify both backends.const params = new URLSearchParams(location.search);const width = Number(params.get('w')) || 1280;const height = Number(params.get('h')) || 720;+const backend = params.get('backend') === 'webgpu' ? 'webgpu' : 'webgl2';window.__estellaHeadless = {- ready: EngineHost.bootHeadless({ width, height }),+ ready: EngineHost.bootHeadless({ width, height, backend }),api: EditorControlSurface,};diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 20ce411a8..f35575d38 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -996,6 +996,20 @@ export class App {export interface WebAppOptions {getViewportSize?: () => { width: number; height: number };glContextHandle?: number;+ /**+ * Render backend. 'webgpu' boots the injected-device path: the host must+ * have acquired a GPUDevice (navigator.gpu) and passed it as the module+ * factory's `preinitializedWebGPUDevice` before instantiation — the engine+ * then owns the canvas swapchain, so no glContextHandle applies.+ * Default: WebGL2.+ */+ backend?: 'webgl2' | 'webgpu';+ /**+ * CSS selector of the canvas for the WebGPU swapchain. The WebGPU glue+ * resolves it with document.querySelector, so the canvas must be IN the+ * DOM and reachable by this selector. Default '#canvas'.+ */+ canvasSelector?: string;plugins?: Plugin[];/** The realm's optional-native-module acquirer; set before plugins build so* SpinePlugin (and later physics) can pull from it. See {@link App.sideModules}. */@@ -1013,7 +1027,14 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): Aapp.connectCpp(cppRegistry, module, { strict: true });- if (options?.glContextHandle) {+ if (options?.backend === 'webgpu') {+ const size = options.getViewportSize?.() ?? { width: 800, height: 600 };+ if (!module.initRendererWebGPU(options.canvasSelector ?? '#canvas', size.width, size.height)) {+ throw new Error(+ 'WebGPU renderer initialization failed — the module needs a ' ++ 'preinitializedWebGPUDevice and a WebGPU-enabled engine build.');+ }+ } else if (options?.glContextHandle) {module.initRendererWithContext(options.glContextHandle);} else {module.initRenderer();diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex d2289010c..c791f8b6c 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -113,6 +113,13 @@ export interface ESEngineModule {initRenderer(): void;initRendererWithCanvas(canvasSelector: string): boolean;initRendererWithContext(contextHandle: number): boolean;+ /**+ * Boot on the WebGPU backend. The host must acquire a GPUDevice and pass it+ * as `preinitializedWebGPUDevice` in the module factory arg BEFORE+ * instantiation; '#canvas' resolves to the module's canvas. Returns false+ * when the build carries no WebGPU backend or no device was provided.+ */+ initRendererWebGPU(canvasSelector: string, width: number, height: number): boolean;shutdownRenderer(): void;/*** Select which EstellaContext the bindings route through. Pass null to clear.diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 0f89d3738..fdefd10ef 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -34,6 +34,9 @@#include "../renderer/OpenGLHeaders.hpp"#include "../renderer/GfxDevice.hpp"+#ifdef ES_ENABLE_WEBGPU+#include "../renderer/webgpu/WebGPUDevice.hpp"+#endif#include "../renderer/RenderContext.hpp"#include "../renderer/RenderFrame.hpp"#include "../renderer/ImmediateDraw.hpp"@@ -237,6 +240,12 @@ void undefineMaterial(u32 materialId) {if (auto* rc = g_renderContext) rc->materials().undefine(materialId);}+// Build provenance signature — kept self-contained (not via the umbrella+// header) so the literal is guaranteed to land in this translation unit and+// survive in the shipped binary. Emitted once at init as an origin marker.+static constexpr const char* kEstellaBuildProvenance =+ "estella-build:9abbd5b4-06f3-47df-b968-826763c6879a";+bool initRendererInternal(const char* canvasSelector) {if (g_initialized) return true;@@ -260,18 +269,46 @@ bool initRendererInternal(const char* canvasSelector) {}ES_LOG_INFO("WebGL2 context created for '{}'", canvasSelector);-- // Build provenance signature — kept self-contained (not via the umbrella- // header) so the literal is guaranteed to land in this translation unit and- // survive in the shipped binary. Emitted once at init as an origin marker.- static constexpr const char* kEstellaBuildProvenance =- "estella-build:9abbd5b4-06f3-47df-b968-826763c6879a";ES_LOG_INFO("Estella runtime provenance {}", kEstellaBuildProvenance);g_activeContext = &legacyCtx().context();return g_activeContext->init(static_cast<int>(webglCtx));}+// The WebGPU mirror of initRendererInternal — the same platform boundary,+// injecting the backend instead of a GL context handle. The page acquires the+// GPUDevice asynchronously (navigator.gpu) BEFORE instantiating the module and+// hands it over via Module.preinitializedWebGPUDevice; the wasm side stays+// fully synchronous. @p width/@p height size the canvas swapchain (the SDK+// passes the canvas backing size it already manages).+bool initRendererWebGPU(const std::string& canvasSelector, u32 width, u32 height) {+#ifdef ES_ENABLE_WEBGPU+ if (g_initialized) return true;++ WGPUDevice raw = emscripten_webgpu_get_device();+ if (!raw) {+ ES_LOG_ERROR("initRendererWebGPU: no Module.preinitializedWebGPUDevice — the host "+ "must acquire a GPUDevice before instantiating the module");+ return false;+ }+ auto device = makeUnique<WebGPUDevice>(raw);+ if (!device->configureSurface(canvasSelector.c_str(), width, height)) {+ ES_LOG_ERROR("initRendererWebGPU: surface configuration failed for '{}'", canvasSelector);+ return false;+ }++ ES_LOG_INFO("WebGPU device injected for '{}' ({}x{})", canvasSelector, width, height);+ ES_LOG_INFO("Estella runtime provenance {}", kEstellaBuildProvenance);++ g_activeContext = &legacyCtx().context();+ return g_activeContext->init(std::move(device));+#else+ (void)canvasSelector; (void)width; (void)height;+ ES_LOG_ERROR("initRendererWebGPU: this build carries no WebGPU backend (ES_ENABLE_WEBGPU off)");+ return false;+#endif+}+void initRenderer() {initRendererInternal("#canvas");}@@ -404,6 +441,9 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("initRenderer", &esengine::initRenderer);emscripten::function("initRendererWithCanvas", &esengine::initRendererWithCanvas);emscripten::function("initRendererWithContext", &esengine::initRendererWithContext);+ // Registered in every build variant; without ES_ENABLE_WEBGPU it reports+ // and returns false, so the JS surface never drifts across variants.+ emscripten::function("initRendererWebGPU", &esengine::initRendererWebGPU);emscripten::function("shutdownRenderer", &esengine::shutdownRenderer);emscripten::function("renderFrame", &esengine::renderFrame);emscripten::function("renderFrameWithMatrix", &esengine::renderFrameWithMatrix);