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.

fix: synchronize rendering with scaled game time

yhh44960e3b1c50
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 5c879cea8..360a3a139 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -101,6 +101,15 @@ jobs:
node tools/render-host/build.mjs
node tools/tests/planar-reflection.e2e.mjs --webgl-only
node tools/tests/planar-reflection.e2e.mjs --webgl-only --prepass
+ - name: Check paused and scaled render clocks with genuine headless Chromium
+ run: node tools/tests/render-clock.e2e.mjs --webgl-only
+ - name: Upload render clock runtime observations
+ if: always()
+ uses: actions/upload-artifact@v7
+ with:
+ name: render-clock-runtime
+ path: output/render-clock/
+ retention-days: 3
- name: Upload planar reflection runtime observations
if: always()
uses: actions/upload-artifact@v7
diff --git a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx
index d34fb83ac..1bc713db0 100644
--- a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx
+++ b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx
@@ -231,7 +231,7 @@ from there; if you are writing a game, you should never need to name them.
| `app.setFixedTimestep(s)` / `app.getFixedTimestep()` | The `FixedUpdate` cadence. Default `1/60`. |
| `app.setMaxDeltaTime(s)` | Clamp on a single frame's delta. Default `0.25`. |
| `app.setMaxFixedSteps(n)` | Cap on fixed-step catch-up per frame. Default `8`. A time budget additionally caps catch-up so a too-heavy sim degrades to slow motion instead of freezing. |
-| `app.setPaused(v)` / `app.isPaused()` | User pause. While paused only `Schedule.Last` runs. |
+| `app.setPaused(v)` / `app.isPaused()` | User pause. `Schedule.Last` and variable-phase systems marked `runWhenPaused` still prepare and draw the frame. |
| `app.holdExecution()` | Returns an idempotent release function. While any owner holds execution, automatic frames, tick, stepping and native game input are held. Audio and video plugins cooperate. |
| `app.isExecutionHeld()` / `app.onExecutionChange(fn)` | Query the hold, or observe it with an initial notification and disposer. Observers are withdrawn on quit. |
| `app.stepFrame()` | Queue exactly one full frame while paused (editor "step"). |
@@ -243,6 +243,13 @@ Within one frame the schedules run: `First` → the fixed trio
the accumulator) → `PreUpdate` → `Update` → `PostUpdate` → `Last`. `Startup`
systems are flushed before the first frame.
+The renderer, material and post-process `u_time.x`, and camera blends and shakes
+use `Time.elapsed`: accumulated scaled game time. Pause freezes that clock;
+an explicit frame step advances it by the scaled step duration. `Time.scale = 0`
+also freezes it. Rendering and paused presentation can still respond to viewport
+or property changes. The editor's unpaused edit view continues to animate its
+preview, while `renderCameraFrame()` redraws the most recently sampled time.
+
### Execution holds
Use an execution hold when a host requires the game to stop rendering and interacting:
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx
index 85db7c7b1..44a6ac586 100644
--- a/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx
@@ -210,7 +210,7 @@ export const scorePlugin: Plugin = {
| `app.setFixedTimestep(s)` / `app.getFixedTimestep()` | `FixedUpdate` 节奏。默认 `1/60`。 |
| `app.setMaxDeltaTime(s)` | 单帧 delta 的钳制上限。默认 `0.25`。 |
| `app.setMaxFixedSteps(n)` | 每帧固定步追赶的上限。默认 `8`。此外还有时间预算封顶追赶,过重的模拟会退化为慢动作而不是卡死。 |
-| `app.setPaused(v)` / `app.isPaused()` | 用户暂停。暂停期间只有 `Schedule.Last` 运行。 |
+| `app.setPaused(v)` / `app.isPaused()` | 用户暂停。`Schedule.Last` 和标记了 `runWhenPaused` 的可变步长系统仍会准备并绘制画面。 |
| `app.holdExecution()` | 返回幂等的释放函数。任一持有者挂起时,自动帧、tick、步进及原生游戏输入均停止,音频与视频插件配合挂起。 |
| `app.isExecutionHeld()` / `app.onExecutionChange(fn)` | 查询挂起状态,或订阅状态变化(含初始通知,返回取消订阅函数)。退出时移除订阅。 |
| `app.stepFrame()` | 在暂停时排入恰好一整帧(编辑器"步进")。 |
@@ -221,6 +221,11 @@ export const scorePlugin: Plugin = {
`FixedUpdate` / `FixedPostUpdate`,由累加器决定跑零到多次)→ `PreUpdate` →
`Update` → `PostUpdate` → `Last`。`Startup` 系统在首帧之前冲刷。
+渲染器、材质与后处理的 `u_time.x`、镜头过渡和震动共同使用 `Time.elapsed`,
+即累计的缩放后游戏时间。暂停会冻结这个时钟;显式单帧步进按缩放后的步长推进它。
+`Time.scale = 0` 也会冻结它。暂停时仍能更新窗口尺寸和属性编辑对应的画面。
+编辑器中未暂停的编辑视图继续播放动态预览,`renderCameraFrame()` 则重绘最近采样的时刻。
+
### 执行挂起
当宿主要求游戏停止渲染和交互时,可以取得执行挂起:
diff --git a/fixtures/scenes/mat-clock/clock.esmaterial b/fixtures/scenes/mat-clock/clock.esmaterial
new file mode 100644
index 000000000..ebaed3fb3
--- /dev/null
+++ b/fixtures/scenes/mat-clock/clock.esmaterial
@@ -0,0 +1,8 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "clock.esshader",
+ "blendMode": 0,
+ "depthTest": true,
+ "properties": {}
+}
diff --git a/fixtures/scenes/mat-clock/clock.esshader b/fixtures/scenes/mat-clock/clock.esshader
new file mode 100644
index 000000000..f6fb0eade
--- /dev/null
+++ b/fixtures/scenes/mat-clock/clock.esshader
@@ -0,0 +1,19 @@
+#pragma shader "RenderClock"
+#pragma version 300 es
+#pragma domain Unlit
+
+#pragma fragment
+precision highp float;
+out vec4 fragColor;
+void main() {
+ float phase = fract(u_time.x);
+ fragColor = vec4(phase, 1.0 - phase, 0.0, 1.0);
+}
+#pragma end
+
+#pragma fragment wgsl
+@fragment fn fs_main(v: VSOut) -> @location(0) vec4f {
+ let phase = fract(tc.u_time.x);
+ return vec4f(phase, 1.0 - phase, 0.0, 1.0);
+}
+#pragma end
diff --git a/fixtures/scenes/render-clock.esscene b/fixtures/scenes/render-clock.esscene
new file mode 100644
index 000000000..0816da06f
--- /dev/null
+++ b/fixtures/scenes/render-clock.esscene
@@ -0,0 +1,27 @@
+{
+ "version": 4,
+ "name": "Sprite and Mesh Render Clock",
+ "entities": [
+ {
+ "id": 0, "name": "Camera", "parent": null, "children": [], "visible": true,
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 3 } } },
+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 1, "fov": 45, "nearPlane": 0.1, "farPlane": 100, "isActive": true, "clearFlags": 3 } }
+ ]
+ },
+ {
+ "id": 1, "name": "Clock Sprite", "parent": null, "children": [], "visible": true,
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": -0.5, "y": 0, "z": 0 } } },
+ { "type": "Sprite", "data": { "size": { "x": 0.7, "y": 0.7 }, "material": "/scenes/mat-clock/clock.esmaterial" } }
+ ]
+ },
+ {
+ "id": 2, "name": "Clock Mesh", "parent": null, "children": [], "visible": true,
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0.5, "y": 0, "z": 0 }, "scale": { "x": 0.006, "y": 0.006, "z": 0.006 } } },
+ { "type": "MeshRenderer", "data": { "mesh": "builtin:cube", "material": "/scenes/mat-clock/clock.esmaterial", "opaque": true, "lit": false, "enabled": true } }
+ ]
+ }
+ ]
+}
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index 0aaf5f77c..f3340c4ec 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -37,7 +37,7 @@ import { renderTargetSize } from '../render/renderTexture';
import { cameraClearColor } from './cameraClear';
import { Renderer } from '../render/renderer';
import { followRenderOrigin, pushRenderOrigin, renderOrigin } from '../render/renderOrigin';
-import { platformNow, platformDevicePixelRatio } from '../platform';
+import { platformDevicePixelRatio } from '../platform';
import { SceneManager } from '../scene/sceneManager';
import {
ortho, perspective, invertViewZ, invertViewOrbit, invertViewQuat, multiply,
@@ -816,7 +816,6 @@ export function cameraPlugin(
const module = app.wasmModule;
const cppRegistry = app.world.getCppRegistry()!;
const pipeline = app.pipeline!;
- const startTime = platformNow();
// Per-App scratch pool for collectCameras — one per plugin instance,
// so two Apps running at once never clobber each other's CameraInfo.
const cameraInfoPool: CameraInfo[] = [];
@@ -864,7 +863,7 @@ export function cameraPlugin(
_params: [],
_fn: () => {
const { width, height } = viewport();
- const now = (platformNow() - startTime) / 1000;
+ const now = app.getResource(Time).elapsed;
// Peek (advance=false): this early sync must not tick the director's
// blend — the render system (end of frame) is the authoritative tick.
const cameras = resolveCameras(app, module, cppRegistry, width, height, undefined, undefined, cameraInfoPool, now, false);
@@ -893,7 +892,8 @@ export function cameraPlugin(
const canvas = cppRegistry.getCanvas(canvasEntity);
clearColor = canvas.backgroundColor;
}
- const elapsed = (platformNow() - startTime) / 1000;
+ // Materials and camera motion share gameplay's clock, including pause, time scale and explicit stepping.
+ const elapsed = app.getResource(Time).elapsed;
if (width !== lastResizeW || height !== lastResizeH) {
app.measureFrameScope('render.resize', () => Renderer.resize(width, height));
diff --git a/sdk/src/ecs/resource.ts b/sdk/src/ecs/resource.ts
index 243b8542d..e8b6a82bb 100644
--- a/sdk/src/ecs/resource.ts
+++ b/sdk/src/ecs/resource.ts
@@ -308,7 +308,7 @@ export class ResourceStorage {
export interface TimeData {
/** Seconds since the previous frame, scaled by `scale`. */
delta: number;
- /** Seconds since the app started. */
+ /** Accumulated scaled game seconds; frozen while paused except for explicit frame steps. */
elapsed: number;
/** Render frames completed — machine-dependent; see `fixedTick`. */
frameCount: number;
diff --git a/sdk/tests/camera-render-order.test.ts b/sdk/tests/camera-render-order.test.ts
index d752615ee..bf3a66e98 100644
--- a/sdk/tests/camera-render-order.test.ts
+++ b/sdk/tests/camera-render-order.test.ts
@@ -23,6 +23,9 @@ import { Query, Mut } from '../src/ecs/query';
import type { Entity } from '../src/types';
import type { CppRegistry } from '../src/wasm';
import { ScreenScaling } from '../src/camera/ScreenScaling';
+import { Time } from '../src/ecs/resource';
+import { setAppHostPaused } from '../src/app/app';
+import { setViewTarget, BlendCurve, shakeCamera } from '../src/camera/CameraDirector';
/** Where a world point lands in clip space under a view-projection. */
const ndcX = (vp: Float32Array, x: number, y: number): number =>
@@ -32,6 +35,8 @@ describe('render order: transforms resolve before cameras are read', () => {
const calls: string[] = [];
let lastViewProjection: Float32Array | null = null;
let beginFrames = 0;
+ let wallTime = 0;
+ const drawnTimes: number[] = [];
/**
* Stands in for the C++ renderer: `beginFrame` clears the transform pass's
@@ -42,7 +47,7 @@ describe('render order: transforms resolve before cameras are read', () => {
let transformsUpdated = false;
return {
init: () => {}, resize: () => {},
- beginFrame: () => { transformsUpdated = false; beginFrames++; calls.push('beginFrame'); },
+ beginFrame: elapsed => { transformsUpdated = false; beginFrames++; drawnTimes.push(elapsed); calls.push('beginFrame'); },
updateTransforms: () => {
calls.push('updateTransforms');
if (transformsUpdated) return;
@@ -71,12 +76,93 @@ describe('render order: transforms resolve before cameras are read', () => {
}
beforeEach(() => {
- calls.length = 0; lastViewProjection = null; beginFrames = 0;
- // The plugin reads the clock at build time; nothing here needs a real one.
- setPlatform({ now: () => 0, devicePixelRatio: () => 1 } as unknown as PlatformAdapter);
+ calls.length = 0; drawnTimes.length = 0; lastViewProjection = null; beginFrames = 0; wallTime = 0;
+ setPlatform({ now: () => wallTime, devicePixelRatio: () => 1 } as unknown as PlatformAdapter);
});
afterEach(() => { setRendererBackend(null); });
+ it.each([
+ { dimension: '2D', projection: ProjectionType.Orthographic, owner: 'user' },
+ { dimension: '3D', projection: ProjectionType.Perspective, owner: 'user' },
+ { dimension: '2D', projection: ProjectionType.Orthographic, owner: 'host' },
+ { dimension: '3D', projection: ProjectionType.Perspective, owner: 'host' },
+ ] as const)('$dimension rendering shares scaled time through $owner pause, stepping and resume', async ({ projection, owner }) => {
+ const { app, module } = bootMockApp();
+ const registry = module.getRegistry() as unknown as Record<string, unknown> & CppRegistry;
+ const cam = app.world.spawn('camera');
+ app.world.insert(cam, Transform, { position: { x: 0, y: 0, z: 5 } });
+ app.world.insert(cam, Camera, { isActive: true, projectionType: projection, orthoSize: 300 });
+ registry.getCameraEntities = () => [cam];
+ registry.getCanvasEntities = () => [];
+ const pipeline = new RenderPipeline();
+ app.setPipeline(pipeline);
+ setRendererBackend(fakeBackend(registry, [cam]));
+ app.addPlugin(cameraPlugin(() => ({ width: 800, height: 600 })));
+ const host = {};
+ const pause = (on: boolean) => owner === 'host' ? setAppHostPaused(app, host, on) : app.setPaused(on);
+ wallTime = 10_000;
+ await app.tick(0.1);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.1);
+ app.getResource(Time).scale = 0.5;
+ wallTime += 5000;
+ await app.tick(0.2);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.2);
+ pause(true);
+ wallTime += 60_000;
+ await app.tick(0.2);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.2);
+ expect(beginFrames).toBe(3);
+ await app.stepFrames(1, 0.1);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.25);
+ expect(app.isPaused()).toBe(true);
+ expect(renderCameraFrame(app, 800, 600)).toBe(true);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.25);
+ pause(false);
+ app.getResource(Time).scale = 0;
+ wallTime += 5000;
+ await app.tick(0.2);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.25);
+ app.getResource(Time).scale = 1;
+ await app.tick(0.1);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.35);
+ expect(drawnTimes).toHaveLength(7);
+ for (const [i, expected] of [0.1, 0.2, 0.2, 0.25, 0.25, 0.25, 0.35].entries()) {
+ expect(drawnTimes[i]).toBeCloseTo(expected);
+ }
+ app.quit();
+ });
+
+ it('camera blends and shakes freeze at the same frame as material time', async () => {
+ const { app, module } = bootMockApp();
+ const registry = module.getRegistry() as unknown as Record<string, unknown> & CppRegistry;
+ const cameras = [app.world.spawn('from'), app.world.spawn('to')];
+ for (const [i, cam] of cameras.entries()) {
+ app.world.insert(cam, Transform, { position: { x: i * 100, y: 0, z: 0 } });
+ app.world.insert(cam, Camera, { isActive: i === 0, orthoSize: 300 });
+ }
+ registry.getCameraEntities = () => cameras;
+ registry.getCanvasEntities = () => [];
+ const pipeline = new RenderPipeline();
+ app.setPipeline(pipeline);
+ setRendererBackend(fakeBackend(registry, cameras));
+ app.addPlugin(cameraPlugin(() => ({ width: 800, height: 600 })));
+ await app.tick(0.1);
+ setViewTarget(app, cameras[1], { time: 0.8, curve: BlendCurve.Linear });
+ shakeCamera(app, { amplitude: 4, frequency: 3, duration: 1 });
+ await app.tick(0.1);
+ await app.tick(0.2);
+ const held = Array.from(lastViewProjection!);
+ app.setPaused(true);
+ wallTime = 60_000;
+ await app.tick(0.2);
+ expect(Array.from(lastViewProjection!)).toEqual(held);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.4);
+ await app.stepFrames(1, 0.2);
+ expect(Array.from(lastViewProjection!)).not.toEqual(held);
+ expect(pipeline.frameElapsed).toBeCloseTo(0.6);
+ app.quit();
+ });
+
it('previews an inactive camera at its latest placement without running Update', async () => {
const { app, module } = bootMockApp();
const registry = module.getRegistry() as unknown as Record<string, unknown> & CppRegistry;
diff --git a/tools/render-host/host.ts b/tools/render-host/host.ts
index 95d9ee0a6..317ca5031 100644
--- a/tools/render-host/host.ts
+++ b/tools/render-host/host.ts
@@ -21,11 +21,11 @@ import {
loadSceneData, discoverSceneAssets, Renderer, instantiatePrefab, writeFieldPath, Transform, Name,
getComponent, DeviceStatus, getDeviceStatus, getDeviceLostReport, recoverDevice,
getContextLossGuardInfo, decodeImagePixels, captureFramePixels, captureFrame, replayDraw, BatchBreak,
- RenderTexture, Camera, Sprite,
+ RenderTexture, Camera, Sprite, Time,
planarReflectionStatus,
EditorViewLighting, EditorViewShading, EditorView, EditorGrid, installEditorGrid, editorViewHalfHeight, setEditorViewHalfHeight,
ProfileRecorder, AnimatorController, Timeline, onDeviceRestored, Schedule, defineSystem,
- textureImportSettingsFrom,
+ textureImportSettingsFrom, shadersCompiled,
} from 'esengine';
import type { App, SceneData, SceneEntityData, PrefabData, RenderSurfaceSource } from 'esengine';
import type { ESEngineModule } from 'esengine/wasm';
@@ -452,6 +452,9 @@ const api = {
return { world: 'engine', frames, dt };
},
+ /** Waits for submitted shader variants without advancing the simulation clock. */
+ waitForShaders: () => shadersCompiled(module),
+
/**
* The frame as the ENGINE holds it, whichever backend drew it. captureViewport
* reads the page instead, which on WebGPU is a compositor copy — blank in a
@@ -822,6 +825,15 @@ declare global {
window.__estellaHeadless = {
ready: boot(),
api,
+ clock: {
+ state: () => ({ ...app!.getResource(Time), paused: app!.isPaused(), renderElapsed: app!.pipeline!.frameElapsed }),
+ pause: (on: boolean) => app!.setPaused(on),
+ scale: (value: number) => {
+ if (!Number.isFinite(value) || value < 0) throw new Error('Clock scale must be finite and non-negative');
+ app!.getResource(Time).scale = value;
+ },
+ step: (dt = 1 / 60) => app!.stepFrames(1, dt),
+ },
device: {
status: () => getDeviceStatus(),
report: () => getDeviceLostReport(),
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index 846affe23..7171dda70 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -56,6 +56,23 @@ export function sceneWatchdogMs(backend, host) {
* verbatim — an empty one is the default sprite scene.
*/
export const SCENES = [
+ {
+ id: 'render-clock', tier: 'pr',
+ // WebGPU captures the next frame; GL reads the already completed frame.
+ webgpu: { ESTELLA_VERIFY_EXPECT: JSON.stringify([
+ { x: 0.25, y: 0.5, rgb: [21, 234, 0], tol: 2 },
+ { x: 0.75, y: 0.5, rgb: [21, 234, 0], tol: 2 },
+ ]) },
+ env: {
+ ESTELLA_VERIFY_SCENE: '/scenes/render-clock.esscene',
+ ESTELLA_VERIFY_W: '256', ESTELLA_VERIFY_H: '256', ESTELLA_VERIFY_STEPS: '3',
+ // The second GL readback observes the fourth completed frame (4/60 s).
+ ESTELLA_VERIFY_EXPECT: JSON.stringify([
+ { x: 0.25, y: 0.5, rgb: [17, 238, 0], tol: 2 },
+ { x: 0.75, y: 0.5, rgb: [17, 238, 0], tol: 2 },
+ ]),
+ },
+ },
{
id: 'planar-tiled-lights', tier: 'pr', webgpu: true,
env: {
diff --git a/tools/tests/render-clock.e2e.mjs b/tools/tests/render-clock.e2e.mjs
new file mode 100644
index 000000000..366f2913f
--- /dev/null
+++ b/tools/tests/render-clock.e2e.mjs
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file render-clock.e2e.mjs
+ * @brief Verify scaled and paused shader time across sprite and mesh rendering.
+ */
+import { chromium } from 'playwright';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import assert from 'node:assert/strict';
+import { serveHost } from '../lib/staticServer.mjs';
+import { requireCurrentEngine } from '../lib/engineBuild.mjs';
+const { PNG } = createRequire(new URL('../../pipeline/package.json', import.meta.url))('pngjs');
+const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const out = path.join(repo, 'output/render-clock');
+const host = path.join(repo, 'build/render-host');
+requireCurrentEngine(repo, path.join(host, 'wasm'));
+await mkdir(out, { recursive: true });
+const server = await serveHost(host);
+const browser = await chromium.launch({
+ channel: 'chromium', headless: true,
+ args: ['--enable-unsafe-webgpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--mute-audio'],
+});
+const report = { status: 'failed', checks: [] };
+try {
+ const backends = process.argv.includes('--webgl-only') ? ['webgl2'] : ['webgl2', 'webgpu'];
+ for (const backend of backends) {
+ const page = await browser.newPage({ viewport: { width: 256, height: 256 } });
+ const errors = [];
+ report.activeBackend = backend;
+ report.errors = errors;
+ page.on('pageerror', error => errors.push(String(error)));
+ page.on('console', message => {
+ if (message.type() === 'error') errors.push(message.text());
+ });
+ await page.route('**/favicon.ico', route => route.fulfill({ status: 204 }));
+ await page.goto(`http://127.0.0.1:${server.address().port}/?w=256&h=256&backend=${backend}`);
+ await page.evaluate(async () => { await window.__estellaHeadless.ready; });
+ const loaded = await page.evaluate(() => window.__estellaHeadless.api.loadScene('/scenes/render-clock.esscene'));
+ assert.deepEqual(loaded.missing, []);
+ const frames = [];
+ const capture = async (label, expected) => {
+ const raw = await page.evaluate(async () => {
+ const { api, clock } = window.__estellaHeadless;
+ const state = clock.state();
+ clock.pause(true);
+ try {
+ const image = await api.captureViewportPixels();
+ return { state, width: image.width, height: image.height, rgba: Array.from(image.rgba) };
+ } finally {
+ clock.pause(state.paused);
+ }
+ });
+ assert.ok(Math.abs(raw.state.elapsed - expected) < 1e-6, `${label}: simulation clock`);
+ assert.ok(Math.abs(raw.state.renderElapsed - expected) < 1e-6, `${label}: render clock`);
+ const image = new PNG({ width: raw.width, height: raw.height });
+ const bytes = Buffer.from(raw.rgba), stride = raw.width * 4;
+ for (let y = 0; y < raw.height; y++) {
+ bytes.copy(image.data, y * stride, (raw.height - 1 - y) * stride, (raw.height - y) * stride);
+ }
+ await writeFile(path.join(out, `${backend}-${label}.png`), PNG.sync.write(image));
+ const want = [Math.round((expected % 1) * 255), Math.round((1 - expected % 1) * 255), 0];
+ const pixels = [64, 192].map(x => Array.from(image.data.subarray((128 * 256 + x) * 4, (128 * 256 + x) * 4 + 3)));
+ for (const pixel of pixels) {
+ for (let c = 0; c < 3; c++) {
+ assert.ok(Math.abs(pixel[c] - want[c]) <= 2, `${label}: sprite/mesh ${pixel}, expected ${want}`);
+ }
+ }
+ frames.push({ label, ...raw.state, pixels });
+ return image;
+ };
+ await page.evaluate(async () => {
+ const { api, clock } = window.__estellaHeadless;
+ clock.pause(true);
+ await api.step(3, 0.2);
+ });
+ assert.equal(await page.evaluate(() => window.__estellaHeadless.api.waitForShaders()), true,
+ 'scene shader variants must finish compiling');
+ await page.evaluate(() => window.__estellaHeadless.api.step(1, 0.2));
+ await capture('cold-paused', 0);
+ await page.evaluate(() => window.__estellaHeadless.clock.step(0.25));
+ const held = await capture('stepped', 0.25);
+ await page.waitForTimeout(200);
+ await page.evaluate(() => window.__estellaHeadless.api.step(3, 0.2));
+ const later = await capture('paused-later', 0.25);
+ assert.deepEqual(later.data, held.data, 'paused redraws must preserve the entire picture');
+ await page.evaluate(async () => {
+ const { clock } = window.__estellaHeadless;
+ clock.scale(0.5);
+ await clock.step(0.2);
+ });
+ await capture('half-speed-step', 0.35);
+ await page.evaluate(async () => {
+ const { api, clock } = window.__estellaHeadless;
+ clock.pause(false);
+ await api.step(1, 0.2);
+ });
+ const scaled = await capture('half-speed-running', 0.45);
+ await page.evaluate(async () => {
+ const { api, clock } = window.__estellaHeadless;
+ clock.scale(0);
+ await api.step(2, 0.2);
+ });
+ const zero = await capture('zero-scale', 0.45);
+ assert.deepEqual(zero.data, scaled.data, 'zero scale must freeze both rendering paths');
+ await page.evaluate(async () => {
+ const { api, clock } = window.__estellaHeadless;
+ clock.scale(1);
+ await api.step(1, 0.1);
+ });
+ await capture('resumed', 0.55);
+ await page.evaluate(async () => {
+ const { api, clock } = window.__estellaHeadless;
+ clock.pause(true);
+ await api.setField(0, 'Camera', 'projectionType', '', 0);
+ await api.step(1, 0.1);
+ });
+ await capture('perspective-paused', 0.55);
+ await page.evaluate(async () => {
+ const { api, clock } = window.__estellaHeadless;
+ api.useEditorView(true);
+ clock.pause(false);
+ await api.step(1, 0.1);
+ });
+ await capture('editor-preview', 0.65);
+ assert.deepEqual(errors, []);
+ report.checks.push({ backend, frames, errors });
+ await page.close();
+ }
+ report.status = 'checks-passed';
+ delete report.activeBackend;
+ console.log(JSON.stringify(report));
+} catch (error) {
+ report.error = String(error);
+ throw error;
+} finally {
+ await writeFile(path.join(out, 'report.json'), JSON.stringify(report, null, 2));
+ await browser.close();
+ await new Promise(resolve => server.close(resolve));
+}