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(render): a loading screen can wait for the shaders, and the lit programs link a quarter faster
yhh6283ff32e8a0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 098005441..b5d44b23c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,7 @@ published separately; it ships inside the editor.### Added-- **Shaders that compile without stopping the frame.** `quality.asyncShaderCompile` (off unless a game turns it on): a draw whose shader the browser is still compiling is left out until it is ready, and every shader asked for in the meantime compiles at once, where before each was waited for in turn. On a first visit the Terrain & Water example's shaders took 43 seconds of a frozen page on Chrome and D3D11 (the heavy lit ones 3 to 10 seconds each, the worst frame 10 seconds); with this on the page was blocked for about a second in all and the whole scene was drawn at 20 seconds, not 56. The same scene, once everything has compiled, is the same picture. `renderer_getPendingShaders()` says how many are still compiling, for a loading screen. Off, nothing changes. WebGL2 only (a WebGPU pipeline is not compiled this way).+- **Shaders that compile without stopping the frame.** `quality.asyncShaderCompile` (off unless a game turns it on): a draw whose shader the browser is still compiling is left out until it is ready, and every shader asked for in the meantime compiles at once, where before each was waited for in turn. On a first visit the Terrain & Water example's shaders took 43 seconds of a frozen page on Chrome and D3D11 (the heavy lit ones 3 to 10 seconds each, the worst frame 10 seconds); with this on the page was blocked for about a second in all and the whole scene was drawn at 20 seconds, not 56. The same scene, once everything has compiled, is the same picture. `renderer_getPendingShaders()` says how many are still compiling, for a loading screen. Off, nothing changes. WebGL2 only (a WebGPU pipeline is not compiled this way). With `quality.prewarmShaders` (and `prewarmTimeoutMs`, default 30 s) a packaged game draws its first scene out of sight behind the loading screen until nothing is compiling, and opens complete; `warmShaders(app)` does the same from code, `shadersCompiled(module)` waits for the queue, and a scene prepared ahead (`readyRenderPrograms`) now claims its programs ready only once they have compiled. The lit shaders also link about 23% faster on a first visit: a light that comes from the tiles no longer carries a second copy of the shadow lookup in the program.- **A depth prepass for the opaque scene.** A quality level can draw the opaque meshes twice, depth alone first, so a pixel is shaded for the surface that is in front of it and not for every one drawn there on the way: `QualityProfile.depthPrepass` (on for `high` and `medium`, off for `low` and with the quality system off), and `renderer_setDepthPrepass` for a host without one. Cut-out leaves take part, with the coverage their own shader writes. A surface whose material bends its vertices with a hook takes part too, unless it is also a cut-out. On the Terrain & Water example, on an RTX 3060, a frame is 4 to 39 ms shorter, most where trees stand thick.- **A third mesh for a plant.** A part of a world's plants can name `lod2Mesh` and its kind `lod2Distance`: past that distance the third mesh stands in for the cheaper one, until the kind stops being drawn as itself. The Terrain & Water example's trees have one (a tenth of the triangles, made by `tools/plant-lod2.mjs`) from 80 m, which takes 9 to 15 ms off a frame on an RTX 3060 where trees stand between 60 and 170 m. `tools/terrain-water-cost.mjs` measures what each part of that example costs a frame headless, and `docs/TERRAIN_WATER_GPU_COST.md` has the numbers.- **A generated world on worker threads.** A planet provider can give the engine its generator as `workerSource` (the text of a self-contained module), and the world's placements and the planet's pages (heights, normals, and the paint by the biomes) are then worked out by a pool of workers (`runtime/jobs.ts`), byte for byte what the main thread works out, while the main thread only puts each answer in the world as it arrives. Laying out a planet's world no longer costs the frame: 2 to 8 frames a second while it was laid out became 60.diff --git a/docs/TERRAIN_WATER_GPU_COST.md b/docs/TERRAIN_WATER_GPU_COST.mdindex a78380d83..b0ea1c67d 100644--- a/docs/TERRAIN_WATER_GPU_COST.md+++ b/docs/TERRAIN_WATER_GPU_COST.md@@ -492,3 +492,5 @@- **只做"延迟链接"不够。**材质变体是一帧一个、创建完马上要画的,没有重叠(43.5 s 对 49.8 s);要**让帧别等**:没好的程序,画它的绘制先跳过(`GfxDevice::setSkipPendingPrograms`)。材质着色器、后处理着色器、默认网格着色器、网格变体都是排队创建,第一个要用的才等(`GfxShaderSource::deferLink`、`Shader::whenLinked`)。- **试过没用的:**把阴影采样改成 `textureLod`(想让 ANGLE 不展开循环)——编译反而慢了一个数量级(单个程序 37 到 82 s),已还原。哪些代码贡献最多(剪掉实验):阴影接收约 60%(10.9 s → 4.4 s),地形 8 层混合循环约 55%(10.9 → 5.0 s);灯循环只占一成多。减小这些着色器本身还能再省,没做。- 选项默认关,和动态分辨率一样是显式开启:开了以后第一次看到的画面会有东西"长出来"。+- **预热:**`quality.prewarmShaders`(配 `asyncShaderCompile`)在启动页后面把第一个场景画到没有着色器在编译为止再打开(`warmShaders(app)`,上限 `prewarmTimeoutMs`,默认 30 s),打开时是完整画面。预备好的场景(`readyRenderPrograms`)也等编译队列清空才报告就绪。+- **编译成本再削:**平铺光源没有阴影图,`shadeLight` 加了 `shadow3D` 参数,平铺那处调用传 `false`,编译器把那份拷贝里的阴影滤波整段丢掉:受光着色器首次链接合计 −23%(模型着色器约 −40%),运行时无变化。把循环合并成动态循环能再省 40% 编译,但模型段多 ~1 ms,没要。diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.tsindex 09852a4f6..5a20eb360 100644--- a/pipeline/src/runtime/gameHost.ts+++ b/pipeline/src/runtime/gameHost.ts@@ -21,7 +21,7 @@ import {AnimatorRootMotion, Playthrough, Name,worldResidencyReport, PostProcess, Renderer, Audio, Camera,getComponentRegistry, BakesRes,- startDebugChannel, glContextAttributes,+ startDebugChannel, glContextAttributes, warmShaders,} from 'esengine';import { installDevicePreview } from './devicePreviewClient';declare const __ESTELLA_LAN_PREVIEW__: boolean;@@ -959,6 +959,16 @@ async function boot(): Promise<void> {poki?.loaded();crazyGames?.loaded();splash?.reach('assets');+ // With the shaders compiled in the background, the first scene is drawn out of sight until they are ready (the splash is still up), so the+ // game opens on a complete picture; without this it opens at once and fills in.+ if (cfg.quality?.asyncShaderCompile && cfg.quality.prewarmShaders) {+ try {+ const warmed = await warmShaders(app, { timeoutMs: cfg.quality.prewarmTimeoutMs });+ if (warmed.timedOut) console.warn(`[game] ${warmed.pending} shader(s) still compiling after ${Math.round(warmed.ms)} ms; opening anyway`);+ } catch (error) {+ console.warn('[game] shader warm-up failed', error);+ }+ }// Before run(), not after: run() may hand control to the emscripten loop and// never return, and the fade is what the first frames should arrive through.splash?.reach('ready');diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex d5ad8a627..876549652 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: 115 public · 159 beta · 1867 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1872 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -7627,6 +7627,8 @@ asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefined+prewarmShaders: boolean | undefined+prewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefinedtargetFps: number | undefined```@@ -8864,6 +8866,21 @@ params: ShaderParam[]{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }```+## ShaderWarmup — interface @experimental+```+frames: number+ms: number+pending: number+timedOut: boolean+```++## ShaderWarmupOptions — interface @experimental+```+onProgress: ((pending: number) => void) | undefined+settleFrames: number | undefined+timeoutMs: number | undefined+```+## ShadowCaster2D — const @experimental```BuiltinComponentDef<ShadowCaster2DData>@@ -14835,6 +14852,11 @@ ParticlePlugin(scene: SceneData, sceneName: string, options: PartitionOptions): WorldPartition | null```+## pendingShaders — function @experimental+```+(source: App | ESEngineModule | null): number+```+## percent — const @public```(n: number) => Dimension@@ -15715,6 +15737,11 @@ ServicesPlugin(dx: number, dy: number, dz: number, out: Float32Array): void```+## shadersCompiled — function @experimental+```+(module: ESEngineModule | null, timeoutMs?: number): Promise<boolean>+```+## shakeCamera — function @experimental```(host: CameraDirectorHost, opts?: { amplitude?: number; rotation?: number; frequency?: number; duration?: number; }): void@@ -16210,6 +16237,11 @@ SystemDefVideoPlugin```+## warmShaders — function @experimental+```+(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>+```+## warn — function @experimental```(category: string, message: string, data?: unknown): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 552ecc929..0b0ddf2ad 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: 115 public · 164 beta · 1886 experimental · 3 deprecated+Symbols: 115 public · 164 beta · 1891 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -7830,6 +7830,8 @@ asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefined+prewarmShaders: boolean | undefined+prewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefinedtargetFps: number | undefined```@@ -9077,6 +9079,21 @@ params: ShaderParam[]{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }```+## ShaderWarmup — interface @experimental+```+frames: number+ms: number+pending: number+timedOut: boolean+```++## ShaderWarmupOptions — interface @experimental+```+onProgress: ((pending: number) => void) | undefined+settleFrames: number | undefined+timeoutMs: number | undefined+```+## ShadowCaster2D — const @experimental```BuiltinComponentDef<ShadowCaster2DData>@@ -15098,6 +15115,11 @@ ParticlePlugin(scene: SceneData, sceneName: string, options: PartitionOptions): WorldPartition | null```+## pendingShaders — function @experimental+```+(source: App | ESEngineModule | null): number+```+## percent — const @public```(n: number) => Dimension@@ -15978,6 +16000,11 @@ ServicesPlugin(dx: number, dy: number, dz: number, out: Float32Array): void```+## shadersCompiled — function @experimental+```+(module: ESEngineModule | null, timeoutMs?: number): Promise<boolean>+```+## shakeCamera — function @experimental```(host: CameraDirectorHost, opts?: { amplitude?: number; rotation?: number; frequency?: number; duration?: number; }): void@@ -16473,6 +16500,11 @@ SystemDefVideoPlugin```+## warmShaders — function @experimental+```+(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>+```+## warn — function @experimental```(category: string, message: string, data?: unknown): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 966f46b72..508775ca6 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: 115 public · 161 beta · 1866 experimental · 3 deprecated+Symbols: 115 public · 161 beta · 1871 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -7622,6 +7622,8 @@ asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefined+prewarmShaders: boolean | undefined+prewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefinedtargetFps: number | undefined```@@ -8859,6 +8861,21 @@ params: ShaderParam[]{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }```+## ShaderWarmup — interface @experimental+```+frames: number+ms: number+pending: number+timedOut: boolean+```++## ShaderWarmupOptions — interface @experimental+```+onProgress: ((pending: number) => void) | undefined+settleFrames: number | undefined+timeoutMs: number | undefined+```+## ShadowCaster2D — const @experimental```BuiltinComponentDef<ShadowCaster2DData>@@ -14840,6 +14857,11 @@ ParticlePlugin(scene: SceneData, sceneName: string, options: PartitionOptions): WorldPartition | null```+## pendingShaders — function @experimental+```+(source: App | ESEngineModule | null): number+```+## percent — const @public```(n: number) => Dimension@@ -15720,6 +15742,11 @@ ServicesPlugin(dx: number, dy: number, dz: number, out: Float32Array): void```+## shadersCompiled — function @experimental+```+(module: ESEngineModule | null, timeoutMs?: number): Promise<boolean>+```+## shakeCamera — function @experimental```(host: CameraDirectorHost, opts?: { amplitude?: number; rotation?: number; frequency?: number; duration?: number; }): void@@ -16215,6 +16242,11 @@ SystemDefVideoPlugin```+## warmShaders — function @experimental+```+(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>+```+## warn — function @experimental```(category: string, message: string, data?: unknown): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex e3d6958ff..9f92cf3e5 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: 115 public · 159 beta · 1888 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1893 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -7915,6 +7915,8 @@ asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefined+prewarmShaders: boolean | undefined+prewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefinedtargetFps: number | undefined```@@ -9152,6 +9154,21 @@ params: ShaderParam[]{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }```+## ShaderWarmup — interface @experimental+```+frames: number+ms: number+pending: number+timedOut: boolean+```++## ShaderWarmupOptions — interface @experimental+```+onProgress: ((pending: number) => void) | undefined+settleFrames: number | undefined+timeoutMs: number | undefined+```+## ShadowCaster2D — const @experimental```BuiltinComponentDef<ShadowCaster2DData>@@ -15144,6 +15161,11 @@ ParticlePlugin(scene: SceneData, sceneName: string, options: PartitionOptions): WorldPartition | null```+## pendingShaders — function @experimental+```+(source: App | ESEngineModule | null): number+```+## percent — const @public```(n: number) => Dimension@@ -16024,6 +16046,11 @@ ServicesPlugin(dx: number, dy: number, dz: number, out: Float32Array): void```+## shadersCompiled — function @experimental+```+(module: ESEngineModule | null, timeoutMs?: number): Promise<boolean>+```+## shakeCamera — function @experimental```(host: CameraDirectorHost, opts?: { amplitude?: number; rotation?: number; frequency?: number; duration?: number; }): void@@ -16519,6 +16546,11 @@ SystemDefVideoPlugin```+## warmShaders — function @experimental+```+(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>+```+## warn — function @experimental```(category: string, message: string, data?: unknown): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 02df99b38..7a29b70b2 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: 115 public · 159 beta · 1879 experimental · 3 deprecated+Symbols: 115 public · 159 beta · 1884 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -7629,6 +7629,8 @@ asyncShaderCompile: boolean | undefineddeviceRules: DeviceQualityRule[] | undefineddynamicResolution: boolean | undefinedmode: QualityMode | undefined+prewarmShaders: boolean | undefined+prewarmTimeoutMs: number | undefinedprofiles: Partial<Record<QualityLevel, Partial<QualityProfile>>> | undefinedtargetFps: number | undefined```@@ -8866,6 +8868,21 @@ params: ShaderParam[]{ SPRITE_VERTEX: string; SPRITE_FRAGMENT: string; COLOR_VERTEX: string; COLOR_FRAGMENT: string; }```+## ShaderWarmup — interface @experimental+```+frames: number+ms: number+pending: number+timedOut: boolean+```++## ShaderWarmupOptions — interface @experimental+```+onProgress: ((pending: number) => void) | undefined+settleFrames: number | undefined+timeoutMs: number | undefined+```+## ShadowCaster2D — const @experimental```BuiltinComponentDef<ShadowCaster2DData>@@ -14871,6 +14888,11 @@ ParticlePlugin(scene: SceneData, sceneName: string, options: PartitionOptions): WorldPartition | null```+## pendingShaders — function @experimental+```+(source: App | ESEngineModule | null): number+```+## percent — const @public```(n: number) => Dimension@@ -15751,6 +15773,11 @@ ServicesPlugin(dx: number, dy: number, dz: number, out: Float32Array): void```+## shadersCompiled — function @experimental+```+(module: ESEngineModule | null, timeoutMs?: number): Promise<boolean>+```+## shakeCamera — function @experimental```(host: CameraDirectorHost, opts?: { amplitude?: number; rotation?: number; frequency?: number; duration?: number; }): void@@ -16246,6 +16273,11 @@ SystemDefVideoPlugin```+## warmShaders — function @experimental+```+(app: App, options?: ShaderWarmupOptions): Promise<ShaderWarmup>+```+## warn — function @experimental```(category: string, message: string, data?: unknown): voiddiff --git a/sdk/src/core-render.ts b/sdk/src/core-render.tsindex 4fb8fdbf3..c434d39b4 100644--- a/sdk/src/core-render.ts+++ b/sdk/src/core-render.ts@@ -341,3 +341,5 @@ export type {QualityReport, DeviceQualityInfo, DeviceQualityRule,} from './render/quality';export { Quality } from './render/qualityRuntime';+export { warmShaders, shadersCompiled, pendingShaders } from './render/shaderWarmup';+export type { ShaderWarmup, ShaderWarmupOptions } from './render/shaderWarmup';diff --git a/sdk/src/render/quality.ts b/sdk/src/render/quality.tsindex 7ead0a610..fdd8ecf81 100644--- a/sdk/src/render/quality.ts+++ b/sdk/src/render/quality.ts@@ -80,6 +80,13 @@ export interface QualityConfig {* (a heavy lit shader on a driver that compiles slowly). Turn it on for a game that would rather open fast and fill in.*/asyncShaderCompile?: boolean;+ /**+ * With `asyncShaderCompile`: draw the first scene's frames out of sight, behind the loading screen, until its shaders have compiled, and show it+ * complete instead of filling in (see `warmShaders`). The wait is bounded by `prewarmTimeoutMs`.+ */+ prewarmShaders?: boolean;+ /** The longest the loading screen waits for the shaders. Default 30000. */+ prewarmTimeoutMs?: number;profiles?: Partial<Record<QualityLevel, Partial<QualityProfile>>>;deviceRules?: DeviceQualityRule[];}@@ -133,6 +140,8 @@ export function parseQualityConfig(value: unknown): QualityConfig {mode, targetFps: finite(raw.targetFps, 60, 15, 120),dynamicResolution: raw.dynamicResolution === true,asyncShaderCompile: raw.asyncShaderCompile === true,+ prewarmShaders: raw.prewarmShaders === true,+ prewarmTimeoutMs: finite(raw.prewarmTimeoutMs, 30000, 1000, 600000),};if (raw.profiles) {config.profiles = {};diff --git a/sdk/src/render/shaderWarmup.ts b/sdk/src/render/shaderWarmup.tsnew file mode 100644index 000000000..a3a92f34b--- /dev/null+++ b/sdk/src/render/shaderWarmup.ts@@ -0,0 +1,89 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file shaderWarmup.ts+ * @brief Letting the shaders a scene draws with finish compiling before it is shown.+ *+ * With `quality.asyncShaderCompile` a draw whose shader the browser is still compiling is left out, so a scene that opens straight onto its first+ * frame fills in as its shaders are ready. {@link warmShaders} is the other choice: draw the scene's frames out of sight until nothing is+ * compiling any more (behind a loading screen), and open on a complete picture.+ */+import type { App } from '../app/app';+import type { ESEngineModule } from '../wasm';++/** What a warm-up did. */+export interface ShaderWarmup {+ /** Frames drawn out of sight. */+ frames: number;+ /** Milliseconds it took. */+ ms: number;+ /** Shaders still compiling when it stopped: 0 unless it gave up. */+ pending: number;+ /** It stopped because the time was up, not because everything was ready. */+ timedOut: boolean;+}++/** @experimental */+export interface ShaderWarmupOptions {+ /** How long to wait for the compiles before giving up and opening anyway. Default 30000. */+ timeoutMs?: number;+ /** Consecutive frames in which nothing was compiling before it counts as done: a frame can ask for a shader the one before did not. Default 3. */+ settleFrames?: number;+ /** Called after each frame with how many shaders are still compiling. */+ onProgress?: (pending: number) => void;+}++const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));+const now = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now());++/**+ * How many shaders are still compiling in the background (0 when shaders are not compiled that way).+ * @experimental+ */+export function pendingShaders(source: App | ESEngineModule | null): number {+ const module = source && 'wasmModule' in source ? (source as App).wasmModule : (source as ESEngineModule | null);+ return module?.renderer_getPendingShaders?.() ?? 0;+}++/**+ * Waits until no shader is compiling. For a host that asked the engine to ready programs (a scene being prepared) and wants "ready" to be true.+ * @experimental+ */+export async function shadersCompiled(module: ESEngineModule | null, timeoutMs = 30000): Promise<boolean> {+ const start = now();+ while (pendingShaders(module) > 0) {+ if (now() - start > timeoutMs) return false;+ await sleep(8);+ }+ return true;+}++/**+ * Draws the app's frames out of sight until its shaders have finished compiling, so what is shown first is complete.+ *+ * The frames advance the world by a tenth of a millisecond each: they exist to make the renderer ask for the shaders the scene needs (a variant is+ * only asked for when something first draws with it), not to play the game. Meant for a loading screen, before the first visible frame.+ * @experimental+ */+export async function warmShaders(app: App, options: ShaderWarmupOptions = {}): Promise<ShaderWarmup> {+ const timeoutMs = options.timeoutMs ?? 30000;+ const settle = Math.max(options.settleFrames ?? 3, 1);+ const module = app.wasmModule;+ const start = now();+ let frames = 0;+ let quiet = 0;+ let pending = 0;+ // A core that does not compile this way has nothing to wait for.+ if (!module?.renderer_getPendingShaders) return { frames, ms: 0, pending: 0, timedOut: false };+ while (quiet < settle) {+ if (now() - start > timeoutMs) return { frames, ms: now() - start, pending, timedOut: true };+ await app.stepFrames(1, 1e-4);+ ++frames;+ pending = module.renderer_getPendingShaders?.() ?? 0;+ options.onProgress?.(pending);+ quiet = pending === 0 ? quiet + 1 : 0;+ // The browser compiles between tasks: give it one.+ await sleep(8);+ }+ return { frames, ms: now() - start, pending: 0, timedOut: false };+}diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex 779bd9ebc..9793d227c 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -29,6 +29,7 @@ import type { BasisTranscoder } from '../asset/compressed';import type { TextureImportSettings } from '../asset/loaders/TextureLoader';import { SceneManager, type SceneConfig } from '../scene/sceneManager';import { readyMeshPrograms } from '../render/meshProgramReadiness';+import { shadersCompiled } from '../render/shaderWarmup';import type { RenderReadiness } from '../render/renderReadiness';import { WorldStreaming } from '../residency/WorldStreamer';import { persistentEntityRows } from '../residency/identity';@@ -702,7 +703,10 @@ export function createRuntimeSceneConfig(// describe requirements for geometry nothing has acquired.async readyRenderPrograms() {if (prepared === null) return { applicable: false } as RenderReadiness;- return readyMeshPrograms(options.module, prepared.sceneData);+ const readied = readyMeshPrograms(options.module, prepared.sceneData);+ // Queued compiles are not ready programs: where shaders compile in the background, the claim waits for them.+ if (readied.applicable) await shadersCompiled(options.module);+ return readied;},discardPrepared() {// Speculation is not authority: what nobody asked for is given back,diff --git a/sdk/tests/shader-warmup.test.ts b/sdk/tests/shader-warmup.test.tsnew file mode 100644index 000000000..70fb985dd--- /dev/null+++ b/sdk/tests/shader-warmup.test.ts@@ -0,0 +1,74 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it, vi } from 'vitest';+import type { App } from '../src/app/app';+import type { ESEngineModule } from '../src/wasm';+import { parseQualityConfig } from '../src/render/quality';+import { pendingShaders, shadersCompiled, warmShaders } from '../src/render/shaderWarmup';++/** A module whose compile queue drains by one on every read after `drainAfter` reads. */+function moduleWithQueue(initial: number, drainEvery = 1): ESEngineModule {+ let left = initial;+ let reads = 0;+ return {+ renderer_getPendingShaders: () => {+ const now = left;+ if (++reads % drainEvery === 0 && left > 0) --left;+ return now;+ },+ } as unknown as ESEngineModule;+}++function appOf(module: ESEngineModule | null): { app: App; stepFrames: ReturnType<typeof vi.fn> } {+ const stepFrames = vi.fn(async () => {});+ return { app: { wasmModule: module, stepFrames } as unknown as App, stepFrames };+}++describe('shader warm-up', () => {+ it('reports 0 where the core does not compile in the background', () => {+ expect(pendingShaders(null)).toBe(0);+ expect(pendingShaders({} as ESEngineModule)).toBe(0);+ expect(pendingShaders(moduleWithQueue(3))).toBe(3);+ expect(pendingShaders(appOf(moduleWithQueue(2)).app)).toBe(2);+ });++ it('draws frames until the queue is empty and stays quiet for the settle frames', async () => {+ const { app, stepFrames } = appOf(moduleWithQueue(3));+ const seen: number[] = [];+ const result = await warmShaders(app, { settleFrames: 2, onProgress: (n) => seen.push(n) });+ expect(result.timedOut).toBe(false);+ expect(result.pending).toBe(0);+ expect(result.frames).toBe(stepFrames.mock.calls.length);+ expect(seen.slice(-2)).toEqual([0, 0]);+ expect(seen.some((n) => n > 0)).toBe(true);+ });++ it('does nothing where there is nothing to wait for', async () => {+ const { app, stepFrames } = appOf({} as ESEngineModule);+ expect(await warmShaders(app)).toEqual({ frames: 0, ms: 0, pending: 0, timedOut: false });+ expect(stepFrames).not.toHaveBeenCalled();+ });++ it('gives up at the timeout instead of holding the loading screen', async () => {+ const stuck = { renderer_getPendingShaders: () => 2 } as unknown as ESEngineModule;+ const { app } = appOf(stuck);+ const result = await warmShaders(app, { timeoutMs: 40 });+ expect(result.timedOut).toBe(true);+ expect(result.pending).toBe(2);+ });++ it('shadersCompiled resolves true once drained and false on timeout', async () => {+ expect(await shadersCompiled(moduleWithQueue(2), 2000)).toBe(true);+ expect(await shadersCompiled({ renderer_getPendingShaders: () => 1 } as unknown as ESEngineModule, 30)).toBe(false);+ expect(await shadersCompiled(null)).toBe(true);+ });++ it('is configured from the package quality config', () => {+ const off = parseQualityConfig({});+ expect(off?.prewarmShaders).toBeFalsy();+ const on = parseQualityConfig({ asyncShaderCompile: true, prewarmShaders: true, prewarmTimeoutMs: 5000 });+ expect(on?.prewarmShaders).toBe(true);+ expect(on?.prewarmTimeoutMs).toBe(5000);+ expect(parseQualityConfig({ prewarmTimeoutMs: 5 })?.prewarmTimeoutMs).toBe(1000);+ });+});diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex 2af8215d7..eaa51132d 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -744,6 +744,19 @@ bool GLDevice::backendFinishProgram(u32 id) {return true;}+u32 GLDevice::backendPendingProgramCount() {+ if (pending_programs_.empty()) return 0;+ // Finishing erases from the map, so the ids are taken first.+ std::vector<u32> ids;+ ids.reserve(pending_programs_.size());+ for (const auto& entry : pending_programs_) ids.push_back(entry.first);+ u32 compiling = 0;+ for (const u32 id : ids) {+ if (!backendProgramReady(id) && !failed_programs_.count(id)) ++compiling;+ }+ return compiling;+}+bool GLDevice::backendProgramReady(u32 id) {if (failed_programs_.count(id)) return false;if (!pending_programs_.count(id)) return true;diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hppindex 5336f9800..df45e77eb 100644--- a/src/esengine/renderer/rhi/GLDevice.hpp+++ b/src/esengine/renderer/rhi/GLDevice.hpp@@ -142,7 +142,7 @@ protected:bool backendFinishProgram(u32 id) override;void endFrame() override;bool backendProgramReady(u32 id) override;- u32 backendPendingProgramCount() const override { return static_cast<u32>(pending_programs_.size()); }+ u32 backendPendingProgramCount() override;bool backendCreateFramebuffer(u32 id, const FramebufferDesc& desc) override;void backendDeleteFramebuffer(u32 id) override;diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hppindex abb84a31f..5b595de91 100644--- a/src/esengine/renderer/rhi/GfxDevice.hpp+++ b/src/esengine/renderer/rhi/GfxDevice.hpp@@ -511,8 +511,12 @@ public:*/bool programReady(ShaderHandle program) { return backendProgramReady(static_cast<u32>(program)); }- /** @brief How many programs made with deferLink nothing has waited for yet. */- u32 pendingProgramCount() const { return backendPendingProgramCount(); }+ /**+ * @brief How many programs made with deferLink are still compiling.+ * @details Asking finishes the ones that are done (their shader objects are freed, what was owed to them is done), so a program nothing ever+ * draws with does not stay on the list: a loading screen waits for this to be 0.+ */+ u32 pendingProgramCount() { return backendPendingProgramCount(); }/*** @brief Whether a draw whose program is not ready is left out, instead of waited for.@@ -883,7 +887,7 @@ protected:/** @brief True while a program created with deferLink has not been waited for. */virtual bool backendProgramPending(u32 id) const { (void)id; return false; }virtual bool backendProgramReady(u32 id) { (void)id; return true; }- virtual u32 backendPendingProgramCount() const { return 0; }+ virtual u32 backendPendingProgramCount() { return 0; }/** @brief Waits for a deferred program, runs its onLinked callback; false when it failed to link. True for a program that was not deferred. */virtual bool backendFinishProgram(u32 id) { (void)id; return true; }/** @brief For a backend finishing a deferred program: runs its onLinked callback, leaving the bound program as it was. */diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 0ceeb59de..a4473e2b0 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -1916,7 +1916,7 @@ fn applyLightingSurface(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f,var extra = vec3f(0.0);for (var i = 0; i < 16; i++) {let term = shadeLight(lc.u_lights[i].posDir, lc.u_lights[i].color, lc.u_lights[i].spot, lc.u_lights[i].shadow,- lc.u_lights[i].shadowMap, lc.u_lights[i].falloff, N, V, worldPos, a, F0, NdotV, specular, roughness, ext);+ lc.u_lights[i].shadowMap, lc.u_lights[i].falloff, N, V, worldPos, a, F0, NdotV, specular, roughness, ext, true);lit += term.lit;gloss += term.gloss;extra += term.extra;@@ -1940,7 +1940,7 @@ fn applyLightingSurface(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f,if (k >= tiledCount) { break; }let term = shadeLight(lc.tiledLights[k].posDir, lc.tiledLights[k].color, lc.tiledLights[k].spot,lc.tiledLights[k].shadow, lc.tiledLights[k].shadowMap, lc.tiledLights[k].falloff,- N, V, worldPos, a, F0, NdotV, specular, roughness, ext);+ N, V, worldPos, a, F0, NdotV, specular, roughness, ext, false);lit += term.lit;gloss += term.gloss;extra += term.extra;@@ -1999,7 +1999,7 @@ fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metastruct LightTerm { lit : vec3f, gloss : vec3f, extra : vec3f };fn shadeLight(pd : vec4f, col : vec4f, sp : vec4f, sh : vec4f, sm : vec4f, fo : vec4f, N : vec3f, V : vec3f,worldPos : vec3f, a : f32, F0 : vec3f, NdotV : f32, specular : f32, roughness : f32,- ext : SurfaceExt) -> LightTerm {+ ext : SurfaceExt, shadow3D : bool) -> LightTerm {var lit = vec3f(0.0);var gloss = vec3f(0.0);var extra = vec3f(0.0);@@ -2035,7 +2035,8 @@ fn shadeLight(pd : vec4f, col : vec4f, sp : vec4f, sh : vec4f, sm : vec4f, fo :if (castShadow && col.a > 0.0 && atten > 0.0) {atten *= mix(1.0, shadowFactor2D(sm.w, worldPos.xy), fo.z);}- if (sm.y > 0.0 && atten > 0.0) {+ // See the GLSL twin: a light the tiles carry has no shadow map, and says so.+ if (shadow3D && sm.y > 0.0 && atten > 0.0) {atten *= mix(1.0,shadowFactor3D(worldPos, N, L, vec2f(sh.x, sm.z), i32(sm.x), i32(sm.y)),fo.z);@@ -3216,7 +3217,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" in highp vec4 fo, in highp vec3 N, in highp vec3 V, in highp vec3 worldPos,\n"" in highp float a, in highp vec3 F0, in highp float NdotV, in highp float specular,\n"" in highp float roughness, in SurfaceExt ext, inout highp vec3 lit, inout highp vec3 gloss,\n"- " inout highp vec3 extra);\n"+ " inout highp vec3 extra, in bool shadow3D);\n"// The lighting model in its general form; a lit 2D surface is its zero// (metallic 0, roughness 1, specular 0 leaves albedo * NdotL, pixel for pixel// what this engine has always drawn), so there is one model and not two.@@ -3239,7 +3240,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" for (int i = 0; i < 16; ++i) {\n"" shadeLight(u_lights[i].posDir, u_lights[i].color, u_lights[i].spot, u_lights[i].shadow,\n"" u_lights[i].shadowMap, u_lights[i].falloff, N, V, worldPos, a, F0, NdotV,\n"- " specular, roughness, ext, lit, gloss, extra);\n"+ " specular, roughness, ext, lit, gloss, extra, true);\n"" }\n"// The lights past the sixteen: this pixel's tile is found from where the fragment lands through the camera it was drawn by// (normalized device coordinates, the same on every backend), and only the lights whose bit is set in its mask are shaded.@@ -3259,7 +3260,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" if (k >= tiledCount) break;\n"" shadeLight(u_tiledLights[k].posDir, u_tiledLights[k].color, u_tiledLights[k].spot,\n"" u_tiledLights[k].shadow, u_tiledLights[k].shadowMap, u_tiledLights[k].falloff,\n"- " N, V, worldPos, a, F0, NdotV, specular, roughness, ext, lit, gloss, extra);\n"+ " N, V, worldPos, a, F0, NdotV, specular, roughness, ext, lit, gloss, extra, false);\n"" }\n"" }\n"" }\n"@@ -3317,7 +3318,7 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" in highp vec4 fo, in highp vec3 N, in highp vec3 V, in highp vec3 worldPos,\n"" in highp float a, in highp vec3 F0, in highp float NdotV, in highp float specular,\n"" in highp float roughness, in SurfaceExt ext, inout highp vec3 lit, inout highp vec3 gloss,\n"- " inout highp vec3 extra) {\n"+ " inout highp vec3 extra, in bool shadow3D) {\n"// A slot nothing lights from (the block holds sixteen and a scene has one or two): every term below is its colour times// its intensity, so it adds exactly nothing, but the lobe is worked out for it all the same without this." if (col.a == 0.0) return;\n"@@ -3357,7 +3358,9 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p// The tiles this light rendered into, which are its own: a fragment// tested against every map in the atlas would be darkened by geometry// seen from somewhere no light reaching it is standing.- " if (sm.y > 0.0 && atten > 0.0) {\n"+ // A light the tiles carry has no shadow map (the sixteen are where the lights that cast are), so its call says so and the compiler+ // drops the lookup from that copy of this function: a program holds the whole shadow filter once, not twice.+ " if (shadow3D && sm.y > 0.0 && atten > 0.0) {\n"" atten *= mix(1.0, shadowFactor3D(worldPos, N, L, vec2(sh.x, sm.z),\n"" int(sm.x), int(sm.y)), fo.z);\n"" }\n"diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex aa79dc2e7..ddaace080 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2998,4 +2998,6 @@ export const NOTED = {{"note":"A small caster no longer drops out of a wide shadow map."},"feat(render): shaders can compile without stopping the frame, and a tile-based GPU is told what a pass does not keep":{"note":"Shaders that compile without stopping the frame."},+ "feat(render): a loading screen can wait for the shaders, and the lit programs link a quarter faster":+ {"note":"Shaders that compile without stopping the frame."},};