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(pipeline): a shipped web build can ask for WebGPU

esengineb89ac27477bf
diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.ts
index 591b845f6..d69e707cf 100644
--- a/desktop/src/engine/EngineHost.ts
+++ b/desktop/src/engine/EngineHost.ts
@@ -14,7 +14,7 @@ import {
installEditorGrid,
setEditorMode,
setPlayMode,
- engineWebGPUFeatures,
+ acquireWebGPUDevice,
} from 'esengine';
import type { App, ResourceDef, SubsystemStatus, SceneData, RenderSurfaceSource, FrameCosts } from 'esengine';
import type { ESEngineModule } from 'esengine/wasm';
@@ -591,33 +591,12 @@ class EngineHostImpl {
};
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<{
- features?: { has(name: string): boolean };
- requestDevice(descriptor?: { requiredFeatures?: string[] }): 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.');
- // The engine says which optional features it uses; a device created without
- // them refuses the work later, as a texture that never loaded.
- const requiredFeatures = engineWebGPUFeatures(adapter);
- console.info(`[engine] webgpu features: ${requiredFeatures.join(', ') || '(none available)'}`);
- moduleArg.preinitializedWebGPUDevice = await adapter.requestDevice(
- requiredFeatures.length ? { requiredFeatures } : undefined);
- // Surface Dawn validation failures: without a listener an invalid draw is
- // silently dropped — a black pass with no trace (exactly how the WGSL
- // bloom-chain regression hid). console.error passes the shot/verify
- // console filters, so headless runs carry the evidence.
- (moduleArg.preinitializedWebGPUDevice as {
- addEventListener?: (t: string, cb: (e: { error?: { message?: string } }) => void) => void;
- }).addEventListener?.('uncapturederror', (e) => {
- console.error('[webgpu] uncaptured error:', e.error?.message ?? e);
- });
+ // reads it synchronously (Module.preinitializedWebGPUDevice). The listener
+ // it installs is what makes an invalid draw visible: without one Dawn drops
+ // it in silence, which reads as a black pass with nothing wrong.
+ const gpu = await acquireWebGPUDevice('webgpu', (m) => console.error(m));
+ if (!gpu.device) throw new Error(`WebGPU is not available: ${gpu.reason}`);
+ moduleArg.preinitializedWebGPUDevice = gpu.device;
// 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
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index c12d784a9..6450bbabf 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -307,6 +307,13 @@ export const settingsMessages = defineMessages({
},
'set.project.rendering.colorSpace.gamma': { en: 'Gamma', zh: '伽马' },
'set.project.rendering.colorSpace.linear': { en: 'Linear', zh: '线性' },
+ 'set.project.rendering.backend': { en: 'GPU backend', zh: 'GPU 后端' },
+ 'set.project.rendering.backend.desc': {
+ en: 'Which GPU API a shipped web or desktop build asks for. WebGPU is the modern one; a browser without it falls back to WebGL2 on its own, so opting in never costs you a player. Mini-games and playables always run WebGL2 — their hosts offer nothing else. The editor viewport follows your own Editor \u2192 Renderer setting instead of this one.',
+ zh: '发布的 Web / 桌面版向哪套 GPU API 申请渲染。WebGPU 是现代后端;不支持的浏览器会自行回退到 WebGL2,所以开启它不会失去任何玩家。小游戏与 playable 始终使用 WebGL2 —— 其宿主只提供这一种。编辑器视口跟随你自己的「编辑器 → 渲染器」设置,而非此项。',
+ },
+ 'set.project.rendering.backend.webgl2': { en: 'WebGL2', zh: 'WebGL2' },
+ 'set.project.rendering.backend.webgpu': { en: 'WebGPU', zh: 'WebGPU' },
'set.project.rendering.ySortLayers': { en: 'Y-sorted layers', zh: 'Y 轴排序层' },
'set.project.rendering.ySortLayers.desc': {
en: 'Entities on a checked layer draw in world-Y order (lower on screen on top) — top-down occlusion. Within a y-sorted layer, paint order wins over material batching.',
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index b079e6190..7a1e8304b 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1683,13 +1683,14 @@ class ProjectStoreImpl {
}
/** Named render sorting layers (z-order = slot index). Default empty list. */
- renderingFeature(): { sortingLayers: string[]; ySortLayers: number[]; depthLayers: number[]; colorSpace: 'gamma' | 'linear'; cameraScaleMode: CameraScaleMode; cameraMatch: number } {
+ renderingFeature(): { sortingLayers: string[]; ySortLayers: number[]; depthLayers: number[]; colorSpace: 'gamma' | 'linear'; backend: 'webgl2' | 'webgpu'; cameraScaleMode: CameraScaleMode; cameraMatch: number } {
const r = this.state?.features?.rendering;
return {
sortingLayers: Array.from({ length: SORTING_LAYER_COUNT }, (_, i) => r?.sortingLayers?.[i] ?? ''),
ySortLayers: r?.ySortLayers ?? [],
depthLayers: r?.depthLayers ?? [],
colorSpace: r?.colorSpace === 'linear' ? 'linear' : 'gamma',
+ backend: r?.backend === 'webgpu' ? 'webgpu' : 'webgl2',
cameraScaleMode: r?.cameraScaleMode ?? 'none',
cameraMatch: r?.cameraMatch ?? 0.5,
};
@@ -1764,7 +1765,7 @@ class ProjectStoreImpl {
/** Set rendering-feature config (sorting layers, y-sort, color space) and persist
* to the manifest. Sorting/y-sort live-apply; colorSpace is boot-fixed (shaders
* compile against it) — the settings page prompts for a reload, like the backend. */
- async setRendering(patch: { sortingLayers?: string[]; ySortLayers?: number[]; depthLayers?: number[]; colorSpace?: 'gamma' | 'linear'; cameraScaleMode?: CameraScaleMode; cameraMatch?: number }): Promise<void> {
+ async setRendering(patch: { sortingLayers?: string[]; ySortLayers?: number[]; depthLayers?: number[]; colorSpace?: 'gamma' | 'linear'; backend?: 'webgl2' | 'webgpu'; cameraScaleMode?: CameraScaleMode; cameraMatch?: number }): Promise<void> {
const st = this.state;
if (!st) return;
const rendering: NonNullable<ProjectFeatures['rendering']> = { ...st.features?.rendering };
@@ -1779,6 +1780,9 @@ class ProjectStoreImpl {
// 'gamma' is the default — expressed by ABSENCE so untouched manifests stay untouched.
if (patch.colorSpace === 'linear') rendering.colorSpace = 'linear';
else if (patch.colorSpace === 'gamma') delete rendering.colorSpace;
+ // Same shape: WebGL2 is the default and persists as absence.
+ if (patch.backend === 'webgpu') rendering.backend = 'webgpu';
+ else if (patch.backend === 'webgl2') delete rendering.backend;
// 'none' (off) is the default — expressed by ABSENCE, like colorSpace 'gamma'.
if (patch.cameraScaleMode === 'none') delete rendering.cameraScaleMode;
else if (patch.cameraScaleMode !== undefined) rendering.cameraScaleMode = patch.cameraScaleMode;
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index e5598cd9e..da77689ae 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -194,6 +194,28 @@ settingsRegistry.register({
},
});
+settingsRegistry.register({
+ id: 'project.rendering.backend',
+ type: 'enum',
+ scope: 'project',
+ section: 'rendering',
+ group: t('set.group.colorSpace'),
+ label: t('set.project.rendering.backend'),
+ description: t('set.project.rendering.backend.desc'),
+ default: 'webgl2',
+ segmented: true,
+ options: [
+ { value: 'webgl2', label: t('set.project.rendering.backend.webgl2') },
+ { value: 'webgpu', label: t('set.project.rendering.backend.webgpu') },
+ ],
+ bind: {
+ get: () => ProjectStore.renderingFeature().backend,
+ // Shipped builds only: the viewport runs the developer's own renderer
+ // setting, so there is nothing live to reload here.
+ set: (v) => void ProjectStore.setRendering({ backend: v as 'webgl2' | 'webgpu' }),
+ },
+});
+
settingsRegistry.register({
id: 'project.rendering.colorSpace',
type: 'enum',
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index b28f30e4d..6d2c5062a 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -2,11 +2,11 @@
"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.",
"counts": {
"public": 113,
- "beta": 61,
- "experimental": 1513,
+ "beta": 62,
+ "experimental": 1515,
"deprecated": 3
},
- "total": 1687,
+ "total": 1690,
"subsystems": [
{
"id": "ecs",
@@ -2176,6 +2176,18 @@
"minigame"
]
},
+ {
+ "name": "acquireWebGPUDevice",
+ "kind": "function",
+ "deprecated": false,
+ "entries": [
+ "index",
+ "index.node",
+ "index.native",
+ "wechat",
+ "minigame"
+ ]
+ },
{
"name": "addNode",
"kind": "function",
diff --git a/pipeline/src/export/exportMiniGame.ts b/pipeline/src/export/exportMiniGame.ts
index ed188247b..4d857da08 100644
--- a/pipeline/src/export/exportMiniGame.ts
+++ b/pipeline/src/export/exportMiniGame.ts
@@ -316,7 +316,11 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {
// having to remember that this template exists. Theme colours are the one that
// is not a plain value — the runtime takes parsed overrides, so a call is
// emitted for them instead.
- const packaged = packagedRuntimeFields(opts.runtime ?? DEFAULT_RUNTIME_CONFIG);
+ // Every mini-game vendor gives the runtime a GL context and nothing else, so
+ // a WebGPU request cannot be honoured here — carrying it would be a config
+ // field the runtime is guaranteed to ignore.
+ const { renderBackend: _webgpuNotHere, ...packaged } =
+ packagedRuntimeFields(opts.runtime ?? DEFAULT_RUNTIME_CONFIG);
const themeColors = packaged.uiThemeColors;
const runtimeArgs = Object.entries(packaged)
.map(([k, v]) => (k === 'uiThemeColors'
diff --git a/pipeline/src/export/exportPlayable.ts b/pipeline/src/export/exportPlayable.ts
index 2b32e556a..b7920c9b3 100644
--- a/pipeline/src/export/exportPlayable.ts
+++ b/pipeline/src/export/exportPlayable.ts
@@ -172,6 +172,12 @@ async function collectSideModules(
* engine runtime (esengine.js glue + esengine.wasm) inlined — no separate
* SINGLE_FILE build. `playableHostEntry` is the host source; `wasmDir` the web wasm dir.
*/
+/** The packaged fields minus what a playable's host cannot serve. */
+function playableRuntimeFields(rc: Parameters<typeof packagedRuntimeFields>[0]) {
+ const { renderBackend: _glOnly, ...rest } = packagedRuntimeFields(rc);
+ return rest;
+}
+
export async function exportPlayable(opts: {
root: string;
entryScene: string;
@@ -319,7 +325,9 @@ export async function exportPlayable(opts: {
// ONE global for the project's settings, in the same shape game.config.json
// carries them. Five separate globals meant the host and the export had to
// agree on five names, and a sixth setting simply never got a global.
- `window.__GAME_RUNTIME__=${JSON.stringify(packagedRuntimeFields(opts.runtime ?? DEFAULT_RUNTIME_CONFIG))};`;
+ // A playable is one file on an ad network's page: it takes the GL context
+ // its host hands over, so a WebGPU request has nowhere to land.
+ `window.__GAME_RUNTIME__=${JSON.stringify(playableRuntimeFields(opts.runtime ?? DEFAULT_RUNTIME_CONFIG))};`;
const adProfile = opts.adProfile ?? genericPlayableProfile;
const network = playableAdInjection(adProfile, { title, orientation });
const outFile = path.join(absOut, 'index.html');
diff --git a/pipeline/src/project/format.ts b/pipeline/src/project/format.ts
index 84e9af9c8..a6a1709e5 100644
--- a/pipeline/src/project/format.ts
+++ b/pipeline/src/project/format.ts
@@ -136,6 +136,11 @@ export interface ProjectFeatures {
* sample, linear blending, OETF at the final blit). Fixed at engine boot —
* shaders compile against it. Absent ⇒ 'gamma'. */
colorSpace?: 'linear';
+ /** GPU backend a shipped build asks for. 'webgpu' takes it where the machine
+ * serves one and falls back to WebGL2 where it does not, so a project can
+ * opt in without giving up the browsers that have neither. Absent ⇒ WebGL2,
+ * which is also what a mini-game and a playable always get. */
+ backend?: 'webgpu';
/** How the MAIN camera fits the design resolution, INDEPENDENT of any UI Canvas
* (the runtime's ScreenScaling). Absent/'none' ⇒ the camera keeps its raw
* orthoSize (Canvas fit when present) — the zero-regression default. */
@@ -546,6 +551,8 @@ export function parseManifest(raw: unknown): ProjectManifest {
}
// Only 'linear' persists; 'gamma' (the default) is expressed by absence.
if (r.colorSpace === 'linear') rendering.colorSpace = 'linear';
+ // Same shape: only the opt-in persists, WebGL2 is absence.
+ if (r.backend === 'webgpu') rendering.backend = 'webgpu';
// Camera fit — 'none' (off) is the default, expressed by absence.
if (r.cameraScaleMode === 'fixed-width' || r.cameraScaleMode === 'fixed-height' ||
r.cameraScaleMode === 'expand' || r.cameraScaleMode === 'shrink' || r.cameraScaleMode === 'match') {
diff --git a/pipeline/src/project/runtimeConfig.ts b/pipeline/src/project/runtimeConfig.ts
index 3f5eef0f6..3f78d5483 100644
--- a/pipeline/src/project/runtimeConfig.ts
+++ b/pipeline/src/project/runtimeConfig.ts
@@ -67,6 +67,9 @@ export interface RuntimeProjectConfig {
depthLayers: number;
/** Render colour space; 'gamma' is the default. Boot-fixed (shaders compile against it). */
colorSpace: 'gamma' | 'linear';
+ /** GPU backend the build asks for; 'webgl2' is the default. Boot-fixed, and a
+ * request for 'webgpu' still falls back where the machine has none. */
+ renderBackend: 'webgl2' | 'webgpu';
/** Main-camera fit of the design resolution; `scaleMode < 0` = off. */
screenFit: RuntimeScreenFit;
}
@@ -139,6 +142,7 @@ export function runtimeConfigOf(
ySortLayers: layerMask(f?.rendering?.ySortLayers),
depthLayers: layerMask(f?.rendering?.depthLayers),
colorSpace: f?.rendering?.colorSpace === 'linear' ? 'linear' : 'gamma',
+ renderBackend: f?.rendering?.backend === 'webgpu' ? 'webgpu' : 'webgl2',
screenFit: resolveScreenFit(manifest),
};
}
@@ -146,7 +150,7 @@ export function runtimeConfigOf(
/** The settings a shipped build carries, as `game.config.json` spells them. */
export type PackagedRuntimeFields = Pick<
PackagedGameConfig,
- 'ySortLayers' | 'depthLayers' | 'colorSpace' | 'screenFit' | 'uiTheme' | 'uiThemeColors'
+ 'ySortLayers' | 'depthLayers' | 'colorSpace' | 'renderBackend' | 'screenFit' | 'uiTheme' | 'uiThemeColors'
| 'physicsEnabled' | 'physicsConfig' | 'audioConfig' | 'achievements' | 'steamAppId'
>;
@@ -164,6 +168,7 @@ export function packagedRuntimeFields(rc: RuntimeProjectConfig): PackagedRuntime
...(rc.ySortLayers ? { ySortLayers: rc.ySortLayers } : {}),
...(rc.depthLayers ? { depthLayers: rc.depthLayers } : {}),
...(rc.colorSpace === 'linear' ? { colorSpace: rc.colorSpace } : {}),
+ ...(rc.renderBackend === 'webgpu' ? { renderBackend: rc.renderBackend } : {}),
// ALWAYS, even with the fit off (`scaleMode < 0`): it carries the design
// resolution, which is what a desktop window opens at. One representation, or
// the window grows a second one that drifts.
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 5a6b56a18..31c23d5f3 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -16,8 +16,9 @@ import {
indexPackagedManifest, createPackagedAssetSource, applyAssetRefResolvers, initRuntime,
HttpBackend, fetchDecodePixels, registerPackagedSideModules,
packagedAppOptions, packagedRuntimeInit, Transform, SceneManager, Nav, UINode,
+ acquireWebGPUDevice,
} from 'esengine';
-import type { SceneData, AddressableManifest, PackagedGameConfig } from 'esengine';
+import type { SceneData, AddressableManifest, PackagedGameConfig, RenderSurfaceSource } from 'esengine';
import type { ESEngineModule } from 'esengine/wasm';
async function boot(): Promise<void> {
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
@@ -59,26 +60,45 @@ async function boot(): Promise<void> {
const { default: createModule } = (await import(/* @vite-ignore */ `${wasmBase}esengine.js`)) as {
default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;
};
+ // The device has to exist before the module reads it, and the fallback IS the
+ // contract. `?headless` pins WebGL2: a driver reads the frame back through the
+ // GL context, which is what the capture hook below has.
+ const wantsWebGPU = cfg.renderBackend === 'webgpu' && !headless;
+ const gpu = await acquireWebGPUDevice(wantsWebGPU ? 'webgpu' : 'webgl2',
+ (m) => console.error(m));
+ if (wantsWebGPU && !gpu.device) console.warn(`[estella] WebGPU unavailable (${gpu.reason}) — using WebGL2.`);
+
const module = await createModule({
canvas,
locateFile: (p: string) => `${wasmBase}${p}`,
print: (t: string) => console.log(t),
printErr: (t: string) => console.error(t),
+ ...(gpu.device ? { preinitializedWebGPUDevice: gpu.device } : {}),
});
- const gl = canvas.getContext('webgl2', {
- alpha: false,
- antialias: true,
- depth: true,
- stencil: true,
- premultipliedAlpha: false,
- preserveDrawingBuffer: headless,
- }) as WebGL2RenderingContext | null;
- if (!gl) throw new Error('WebGL2 is not available.');
- const glHandle = module.GL.registerContext(gl, { majorVersion: 2, minorVersion: 0, enableExtensionsByDefault: true });
+ let gl: WebGL2RenderingContext | null = null;
+ let renderSurface: RenderSurfaceSource;
+ if (gpu.device) {
+ canvas.id ||= 'canvas';
+ renderSurface = { kind: 'webgpu', canvasSelector: `#${canvas.id}` };
+ } else {
+ gl = canvas.getContext('webgl2', {
+ alpha: false,
+ antialias: true,
+ depth: true,
+ stencil: true,
+ premultipliedAlpha: false,
+ preserveDrawingBuffer: headless,
+ }) as WebGL2RenderingContext | null;
+ if (!gl) throw new Error('WebGL2 is not available.');
+ renderSurface = {
+ kind: 'gl-context',
+ handle: module.GL.registerContext(gl, { majorVersion: 2, minorVersion: 0, enableExtensionsByDefault: true }),
+ };
+ }
const app = createWebApp(module, {
- renderSurface: { kind: 'gl-context', handle: glHandle },
+ renderSurface,
// Everything the config says an App must be BUILT with (see packagedAppOptions).
...packagedAppOptions(cfg),
getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
@@ -91,7 +111,8 @@ async function boot(): Promise<void> {
capture(): { width: number; height: number; rgba: Uint8Array } {
const w = canvas.width, h = canvas.height;
const rgba = new Uint8Array(w * h * 4);
- gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, rgba);
+ // `?headless` pins WebGL2 above, so this is the context that drew.
+ gl!.readPixels(0, 0, w, h, gl!.RGBA, gl!.UNSIGNED_BYTE, rgba);
return { width: w, height: h, rgba };
},
/**
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2f94a4110..ebd95e61b 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 54 beta · 1398 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1400 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4562,6 +4562,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
+renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
@@ -5692,6 +5693,11 @@ static new <T extends AnyComponentDef>(world: World, component: T, lastRunTick:
static prototype: RemovedQueryInstance<any>
```
+## RenderBackendRequest — type @experimental
+```
+'webgl2' | 'webgpu' | 'auto'
+```
+
## RenderParams — interface @experimental
```
clearColor: { x: number; y: number; z: number; w: number; } | undefined
@@ -8600,6 +8606,12 @@ ySortLayers: number | undefined
features: { has(name: string): boolean; } | undefined
```
+## WebGPUBootResult — interface @experimental
+```
+device: unknown
+reason: string | undefined
+```
+
## WeldJoint — const @experimental
```
ComponentDef<WeldJointData>
@@ -8708,6 +8720,11 @@ TransformData
(typeof WrapMode)[keyof typeof WrapMode]
```
+## acquireWebGPUDevice — function @beta
+```
+(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>
+```
+
## actionRefArg — function @experimental
```
(ref: FsmActionRef | undefined): string | undefined
@@ -10335,7 +10352,7 @@ NavPlugin
## packagedAppOptions — function @experimental
```
-(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; screenFit?: PackagedGameConfig["screenFit"]; }
+(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; renderBackend?: "webgl2" | "webgpu"; screenFit?: PackagedGameConfig["screenFit"]; }
```
## packagedRuntimeInit — function @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 5e3908eb9..f92f3ec63 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 59 beta · 1417 experimental · 3 deprecated
+Symbols: 113 public · 60 beta · 1419 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -4745,6 +4745,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
+renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
@@ -5885,6 +5886,11 @@ static new <T extends AnyComponentDef>(world: World, component: T, lastRunTick:
static prototype: RemovedQueryInstance<any>
```
+## RenderBackendRequest — type @experimental
+```
+'webgl2' | 'webgpu' | 'auto'
+```
+
## RenderParams — interface @experimental
```
clearColor: { x: number; y: number; z: number; w: number; } | undefined
@@ -8793,6 +8799,12 @@ ySortLayers: number | undefined
features: { has(name: string): boolean; } | undefined
```
+## WebGPUBootResult — interface @experimental
+```
+device: unknown
+reason: string | undefined
+```
+
## WeldJoint — const @experimental
```
ComponentDef<WeldJointData>
@@ -8901,6 +8913,11 @@ TransformData
(typeof WrapMode)[keyof typeof WrapMode]
```
+## acquireWebGPUDevice — function @beta
+```
+(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>
+```
+
## actionRefArg — function @experimental
```
(ref: FsmActionRef | undefined): string | undefined
@@ -10578,7 +10595,7 @@ NavPlugin
## packagedAppOptions — function @experimental
```
-(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; screenFit?: PackagedGameConfig["screenFit"]; }
+(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; renderBackend?: "webgl2" | "webgpu"; screenFit?: PackagedGameConfig["screenFit"]; }
```
## packagedRuntimeInit — function @experimental
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 94e573a9e..7bfe8b9ed 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 56 beta · 1397 experimental · 3 deprecated
+Symbols: 113 public · 57 beta · 1399 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4557,6 +4557,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
+renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
@@ -5687,6 +5688,11 @@ static new <T extends AnyComponentDef>(world: World, component: T, lastRunTick:
static prototype: RemovedQueryInstance<any>
```
+## RenderBackendRequest — type @experimental
+```
+'webgl2' | 'webgpu' | 'auto'
+```
+
## RenderParams — interface @experimental
```
clearColor: { x: number; y: number; z: number; w: number; } | undefined
@@ -8595,6 +8601,12 @@ ySortLayers: number | undefined
features: { has(name: string): boolean; } | undefined
```
+## WebGPUBootResult — interface @experimental
+```
+device: unknown
+reason: string | undefined
+```
+
## WeldJoint — const @experimental
```
ComponentDef<WeldJointData>
@@ -8703,6 +8715,11 @@ TransformData
(typeof WrapMode)[keyof typeof WrapMode]
```
+## acquireWebGPUDevice — function @beta
+```
+(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>
+```
+
## actionRefArg — function @experimental
```
(ref: FsmActionRef | undefined): string | undefined
@@ -10340,7 +10357,7 @@ NodePlatformAdapter
## packagedAppOptions — function @experimental
```
-(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; screenFit?: PackagedGameConfig["screenFit"]; }
+(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; renderBackend?: "webgl2" | "webgpu"; screenFit?: PackagedGameConfig["screenFit"]; }
```
## packagedRuntimeInit — function @experimental
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 76349d8b3..3e7182749 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 54 beta · 1418 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1420 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4802,6 +4802,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
+renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
@@ -5932,6 +5933,11 @@ static new <T extends AnyComponentDef>(world: World, component: T, lastRunTick:
static prototype: RemovedQueryInstance<any>
```
+## RenderBackendRequest — type @experimental
+```
+'webgl2' | 'webgpu' | 'auto'
+```
+
## RenderParams — interface @experimental
```
clearColor: { x: number; y: number; z: number; w: number; } | undefined
@@ -8840,6 +8846,12 @@ ySortLayers: number | undefined
features: { has(name: string): boolean; } | undefined
```
+## WebGPUBootResult — interface @experimental
+```
+device: unknown
+reason: string | undefined
+```
+
## WeldJoint — const @experimental
```
ComponentDef<WeldJointData>
@@ -8948,6 +8960,11 @@ TransformData
(typeof WrapMode)[keyof typeof WrapMode]
```
+## acquireWebGPUDevice — function @beta
+```
+(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>
+```
+
## actionRefArg — function @experimental
```
(ref: FsmActionRef | undefined): string | undefined
@@ -10590,7 +10607,7 @@ NavPlugin
## packagedAppOptions — function @experimental
```
-(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; screenFit?: PackagedGameConfig["screenFit"]; }
+(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; renderBackend?: "webgl2" | "webgpu"; screenFit?: PackagedGameConfig["screenFit"]; }
```
## packagedRuntimeInit — function @experimental
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 776592fe4..668faf492 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 54 beta · 1408 experimental · 3 deprecated
+Symbols: 113 public · 55 beta · 1410 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -4564,6 +4564,7 @@ entryScene: string
hotUpdate: { remoteRoot?: string; persistUpdateKey?: string; } | undefined
physicsConfig: PhysicsPluginConfig | undefined
physicsEnabled: boolean | undefined
+renderBackend: "webgl2" | "webgpu" | undefined
scenes: { name: string; path: string; }[] | undefined
screenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefined
sideModules: { id: string; file: string; globalName?: string; }[] | undefined
@@ -5694,6 +5695,11 @@ static new <T extends AnyComponentDef>(world: World, component: T, lastRunTick:
static prototype: RemovedQueryInstance<any>
```
+## RenderBackendRequest — type @experimental
+```
+'webgl2' | 'webgpu' | 'auto'
+```
+
## RenderParams — interface @experimental
```
clearColor: { x: number; y: number; z: number; w: number; } | undefined
@@ -8622,6 +8628,12 @@ ySortLayers: number | undefined
features: { has(name: string): boolean; } | undefined
```
+## WebGPUBootResult — interface @experimental
+```
+device: unknown
+reason: string | undefined
+```
+
## WeldJoint — const @experimental
```
ComponentDef<WeldJointData>
@@ -8730,6 +8742,11 @@ TransformData
(typeof WrapMode)[keyof typeof WrapMode]
```
+## acquireWebGPUDevice — function @beta
+```
+(requested: RenderBackendRequest, onError?: (message: string) => void): Promise<WebGPUBootResult>
+```
+
## actionRefArg — function @experimental
```
(ref: FsmActionRef | undefined): string | undefined
@@ -10362,7 +10379,7 @@ NavPlugin
## packagedAppOptions — function @experimental
```
-(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; screenFit?: PackagedGameConfig["screenFit"]; }
+(config: Pick<PackagedGameConfig, "ySortLayers" | "depthLayers" | "colorSpace" | "screenFit">): { ySortLayers?: number; depthLayers?: number; colorSpace?: "gamma" | "linear"; renderBackend?: "webgl2" | "webgpu"; screenFit?: PackagedGameConfig["screenFit"]; }
```
## packagedRuntimeInit — function @experimental
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 140a9e78b..d27d208f6 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -198,6 +198,18 @@ export {
type WebGPUAdapterLike,
} from './render/webgpuFeatures';
+/**
+ * Acquiring the device a WebGPU boot needs, before the module that reads it
+ * exists — one answer for every host rather than one each.
+ *
+ * @beta
+ */
+export {
+ acquireWebGPUDevice,
+ type RenderBackendRequest,
+ type WebGPUBootResult,
+} from './render/webgpuBoot';
+
export {
captureFramePixels,
canCaptureFramePixels,
diff --git a/sdk/src/render/webgpuBoot.ts b/sdk/src/render/webgpuBoot.ts
new file mode 100644
index 000000000..b8281b7f1
--- /dev/null
+++ b/sdk/src/render/webgpuBoot.ts
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Getting a WebGPU device before the module exists.
+ *
+ * The wasm side reads `Module.preinitializedWebGPUDevice` synchronously,
+ * so the device has to be acquired first — and acquiring it is the same
+ * four steps wherever a host boots the engine: is it asked for, is there
+ * an adapter, which optional features does it offer, and where do its
+ * validation errors go. A host that writes those out itself gets a
+ * different subset right, and the ones it misses surface as a texture
+ * that never loaded or a pass that silently drew nothing.
+ */
+import { engineWebGPUFeatures } from './webgpuFeatures';
+
+/** What a project asks for. `auto` takes WebGPU where the machine has it. */
+export type RenderBackendRequest = 'webgl2' | 'webgpu' | 'auto';
+
+/** The device, plus what it took to get one. `device` null ⇒ boot WebGL2. */
+export interface WebGPUBootResult {
+ device: unknown | null;
+ /** Why WebGPU was not used, for a host that wants to say so. */
+ reason?: string;
+}
+
+interface GpuLike {
+ requestAdapter(): Promise<{
+ features?: { has(name: string): boolean };
+ requestDevice(descriptor?: { requiredFeatures?: string[] }): Promise<unknown>;
+ } | null>;
+}
+
+const gpuOf = (): GpuLike | undefined =>
+ (globalThis.navigator as unknown as { gpu?: GpuLike } | undefined)?.gpu;
+
+/**
+ * A device for `requested`, or null to fall back to WebGL2 — a project that asks
+ * for WebGPU still runs on a browser without it, which is the only behaviour a
+ * shipped game can have. `onError` takes Dawn's uncaptured validation messages,
+ * which are dropped in silence without a listener.
+ *
+ * @beta
+ */
+export async function acquireWebGPUDevice(
+ requested: RenderBackendRequest,
+ onError?: (message: string) => void,
+): Promise<WebGPUBootResult> {
+ if (requested === 'webgl2') return { device: null };
+
+ const gpu = gpuOf();
+ if (!gpu) return { device: null, reason: 'navigator.gpu is unavailable' };
+
+ try {
+ const adapter = await gpu.requestAdapter();
+ if (!adapter) return { device: null, reason: 'no WebGPU adapter' };
+ const requiredFeatures = engineWebGPUFeatures(adapter);
+ const device = await adapter.requestDevice(
+ requiredFeatures.length ? { requiredFeatures } : undefined);
+ if (onError) {
+ (device as { addEventListener?(t: string, fn: (e: unknown) => void): void })
+ .addEventListener?.('uncapturederror', (e) => {
+ const msg = (e as { error?: { message?: string } }).error?.message;
+ onError(`[webgpu] uncaptured error: ${msg ?? String(e)}`);
+ });
+ }
+ return { device };
+ } catch (e) {
+ return { device: null, reason: `WebGPU device request failed: ${String(e)}` };
+ }
+}
diff --git a/sdk/src/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.ts
index f00656d0e..e0be8ba38 100644
--- a/sdk/src/runtime/packagedRuntime.ts
+++ b/sdk/src/runtime/packagedRuntime.ts
@@ -44,6 +44,9 @@ export interface PackagedGameConfig {
depthLayers?: number;
/** Project color space — 'linear' boots the linear-light pipeline. */
colorSpace?: 'gamma' | 'linear';
+ /** GPU backend the build asks for; absent ⇒ WebGL2. A request for
+ * 'webgpu' falls back where the machine cannot serve one. */
+ renderBackend?: 'webgl2' | 'webgpu';
/** Project camera fit (design resolution + scale mode) — letterboxes the main
* camera without a UI Canvas; absent = no fit. */
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
@@ -142,6 +145,9 @@ export function packagedAppOptions(
ySortLayers?: number;
depthLayers?: number;
colorSpace?: 'gamma' | 'linear';
+ /** GPU backend the build asks for; absent ⇒ WebGL2. A request for
+ * 'webgpu' falls back where the machine cannot serve one. */
+ renderBackend?: 'webgl2' | 'webgpu';
screenFit?: PackagedGameConfig['screenFit'];
} {
return {
diff --git a/tools/check-project-settings.mjs b/tools/check-project-settings.mjs
index 10b08ac85..72e0b94ae 100644
--- a/tools/check-project-settings.mjs
+++ b/tools/check-project-settings.mjs
@@ -61,6 +61,13 @@ const DECLARED_GAPS = {
editor: 'boot-fixed — shaders compile against it, so the settings page asks '
+ 'for a reload rather than applying live (EngineHost.resolveColorSpace)',
},
+ renderBackend: {
+ editor: 'the viewport runs the developer\'s own `renderer.backend` setting: which '
+ + 'GPU a machine can drive is not the project\'s to decide, and a canvas cannot '
+ + 'change context type once one is acquired',
+ play: 'the play realm boots on the editor\'s own context; the two backends are held '
+ + 'equal by the pixel gates (`verify-render --backend webgpu`) rather than by Play',
+ },
screenFit: {
editor: 'the device preview reads it through projectSeams, not by applying it '
+ 'to the edit camera (the editor view is a free zoom by design)',
@@ -82,6 +89,7 @@ const PARSE_KEY = {
ySortLayers: 'r.ySortLayers',
depthLayers: 'r.depthLayers',
colorSpace: 'r.colorSpace',
+ renderBackend: 'r.backend',
screenFit: 'r.cameraScaleMode',
};