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
fix(render): a moving camera looks through where it is, on the clock it is drawn to
yhh3fad3a58f821
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 7b34140ba..31abb669f 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -6300,6 +6300,7 @@ static prototype: RemovedQueryInstance<any>```clearColor: { x: number; y: number; z: number; w: number; } | undefinedelapsed: number+frameAlreadyBegun: boolean | undefinedheight: numberregistry: { _cpp: CppRegistry; }viewProjection: Float32Array<ArrayBufferLike>diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex bbfb21306..3d06285a8 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -6493,6 +6493,7 @@ static prototype: RemovedQueryInstance<any>```clearColor: { x: number; y: number; z: number; w: number; } | undefinedelapsed: number+frameAlreadyBegun: boolean | undefinedheight: numberregistry: { _cpp: CppRegistry; }viewProjection: Float32Array<ArrayBufferLike>diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 9464c9264..a7e2f5083 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -6295,6 +6295,7 @@ static prototype: RemovedQueryInstance<any>```clearColor: { x: number; y: number; z: number; w: number; } | undefinedelapsed: number+frameAlreadyBegun: boolean | undefinedheight: numberregistry: { _cpp: CppRegistry; }viewProjection: Float32Array<ArrayBufferLike>diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 7ab7f7e8b..d9ba38ba8 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -6541,6 +6541,7 @@ static prototype: RemovedQueryInstance<any>```clearColor: { x: number; y: number; z: number; w: number; } | undefinedelapsed: number+frameAlreadyBegun: boolean | undefinedheight: numberregistry: { _cpp: CppRegistry; }viewProjection: Float32Array<ArrayBufferLike>diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 71e836011..2f0cb1fd6 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -6302,6 +6302,7 @@ static prototype: RemovedQueryInstance<any>```clearColor: { x: number; y: number; z: number; w: number; } | undefinedelapsed: number+frameAlreadyBegun: boolean | undefinedheight: numberregistry: { _cpp: CppRegistry; }viewProjection: Float32Array<ArrayBufferLike>diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex 65c16c213..73d6ad2cf 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -1043,12 +1043,26 @@ export class App {this.mainLoop();}- private mainLoop = async (): Promise<void> => {+ /**+ * @param rafTime The host's animation-frame timestamp, when it passes one.+ */+ private mainLoop = async (rafTime?: number): Promise<void> => {if (!this.running_) {return;}- const currentTime = platformNow();+ // The frame's clock is the rAF timestamp, not the moment this callback got+ // to run. The timestamp names the vsync the frame is being drawn for, so+ // consecutive frames are exactly one refresh interval apart; platformNow()+ // here measures instead WHEN the browser got round to calling us, and that+ // delay's frame-to-frame variance enters delta twice — added to one frame,+ // subtracted from the next. A perfectly regular display then hands out an+ // irregular delta, and everything integrating `speed * delta` advances by+ // unequal steps: judder, worst on a camera pan, where the whole screen moves.+ // A host that passes no timestamp (a native shell driving its own loop) keeps+ // the old measurement; the clamp below absorbs the one frame where the two+ // clocks meet.+ const currentTime = typeof rafTime === 'number' && rafTime > 0 ? rafTime : platformNow();const deltaMs = currentTime - this.lastTime_;if (this.targetFrameInterval_ > 0 && deltaMs < this.targetFrameInterval_) {@@ -1058,7 +1072,10 @@ export class App {this.lastTime_ = currentTime;- const rawDelta = Math.min(deltaMs / 1000, this.maxDeltaTime_);+ // Never negative: two clocks with different origins meet on the first frame+ // after run()/stepFrames seeds lastTime_ from platformNow(), and time running+ // backwards is worse than a frame that stands still.+ const rawDelta = Math.max(0, Math.min(deltaMs / 1000, this.maxDeltaTime_));const delta = rawDelta * this.play_speed_;await this.flushStartupSystems_();diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.tsindex 20fce225d..622324efc 100644--- a/sdk/src/camera/CameraPlugin.ts+++ b/sdk/src/camera/CameraPlugin.ts@@ -689,6 +689,21 @@ export function cameraPlugin(}pipeline.setActiveScenes(activeScenes ?? null);++ // The frame opens, and the world's transforms resolve, BEFORE any+ // camera is read. A camera's view is built from its Transform's+ // worldPosition, and the transform pass is what writes it: run+ // behind the read — its old home, inside submitScene — it handed+ // every camera the PREVIOUS frame's placement while the sprites+ // drew at this frame's, so a camera moved in Update trailed the+ // world it was looking at by exactly one frame. beginFrame is what+ // clears the pass's once-per-frame memo, so it has to lead; the+ // call still inside submitScene then finds the answer and costs+ // nothing.+ pipeline.beginFrame(elapsed);+ app.measureFrameScope('render.updateTransforms', () =>+ Renderer.updateTransforms({ _cpp: cppRegistry }));+// Authoritative tick (advance=true): ticks the director's blend.const cameras = app.measureFrameScope('render.resolveCameras', () =>resolveCameras(app, module, cppRegistry, width, height, app.world, activeScenes, cameraInfoPool, elapsed, true));@@ -706,9 +721,11 @@ export function cameraPlugin(viewProjection: IDENTITY,width, height, elapsed,clearColor,+ // Already opened above. Opening it twice ages the+ // render-target pool twice in one frame.+ frameAlreadyBegun: true,});} else {- pipeline.beginFrame(elapsed);pipeline.beginScreenCapture();// One project-level choice, read once: a per-camera answer// would let two cameras present the same surface at twodiff --git a/sdk/src/render/renderPipeline.ts b/sdk/src/render/renderPipeline.tsindex ac6cf8259..d80dd7c5d 100644--- a/sdk/src/render/renderPipeline.ts+++ b/sdk/src/render/renderPipeline.ts@@ -34,6 +34,12 @@ export interface RenderParams {elapsed: number;/** Background for the pass's load-op clear (default opaque black). */clearColor?: { x: number; y: number; z: number; w: number };+ /**+ * The caller already opened the frame (`beginFrame`) — as the render system+ * does, so the transform pass can run before the cameras are read. Opening a+ * frame twice ages the render-target pool twice, so it must happen once.+ */+ frameAlreadyBegun?: boolean;}export interface CameraRenderParams {@@ -140,7 +146,7 @@ export class RenderPipeline {this.lastHeight_ = height;}- Renderer.beginFrame(elapsed);+ if (!params.frameAlreadyBegun) Renderer.beginFrame(elapsed);Renderer.setViewport(0, 0, width, height);Renderer.begin(viewProjection, 0, /*clear color+depth*/ 3, params.clearColor);// The mask is sticky in the draw list; this path has no camera to own one.diff --git a/sdk/tests/app-tick.test.ts b/sdk/tests/app-tick.test.tsindex 43fadd30a..89232aa8c 100644--- a/sdk/tests/app-tick.test.ts+++ b/sdk/tests/app-tick.test.ts@@ -162,6 +162,60 @@ describe('App.stepFrames()', () => {expect(app.isPaused()).toBe(true);});+ // A display hands out frames on a metronome; the callback that draws them does+ // not start on one. Measuring delta at callback entry puts that start delay's+ // variance into delta TWICE — added to one frame, subtracted from the next —+ // so a steady 60 Hz becomes an unsteady delta, and `speed * delta` motion moves+ // in unequal steps. The rAF timestamp is the vsync itself, which is the clock+ // the frame is actually drawn against.+ it('takes the frame clock from the animation-frame timestamp, not the callback entry time', async () => {+ const realRaf = globalThis.requestAnimationFrame;+ let pending: ((ts: number) => void) | null = null;+ globalThis.requestAnimationFrame = ((fn: FrameRequestCallback) => {+ pending = fn as unknown as (ts: number) => void;+ return 1;+ }) as unknown as typeof globalThis.requestAnimationFrame;++ // The wall clock as the callback sees it: vsync plus however long the host+ // took to get round to us this frame.+ let entryNow = 1000;+ setPlatform({ now: () => entryNow } as unknown as PlatformAdapter);++ const app = App.new();+ const deltasMs: number[] = [];+ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Res(Time)], (time: { delta: number }) => { deltasMs.push(time.delta * 1000); },+ { name: 'RecordDelta' },+ ));++ const settle = async (): Promise<void> => {+ for (let i = 0; i < 30; i++) await Promise.resolve();+ };++ try {+ await app.run(); // seeds the clock and runs one frame off platformNow()+ await settle();+ deltasMs.length = 0;++ const VSYNC = 1000 / 60;+ const startDelay = [0.2, 4.1, 0.9, 6.3, 1.7, 3.0];+ for (let i = 1; i <= startDelay.length; i++) {+ const vsync = 1000 + i * VSYNC;+ entryNow = vsync + startDelay[i - 1];+ const fire = pending!;+ pending = null;+ await fire(vsync);+ await settle();+ }++ expect(deltasMs).toHaveLength(startDelay.length);+ for (const d of deltasMs) expect(d).toBeCloseTo(VSYNC, 6);+ } finally {+ app.quit();+ globalThis.requestAnimationFrame = realRaf;+ }+ });+it('defaults to one frame', async () => {const app = App.new();await app.stepFrames();diff --git a/sdk/tests/camera-render-order.test.ts b/sdk/tests/camera-render-order.test.tsnew file mode 100644index 000000000..507a6651c--- /dev/null+++ b/sdk/tests/camera-render-order.test.ts@@ -0,0 +1,115 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The render system's frame order: the world's transforms resolve BEFORE+ * the cameras are read.+ *+ * A camera's view matrix is built from its Transform's worldPosition, and the+ * transform pass is what writes it. With the pass behind the read (its old home,+ * inside submitScene) every camera was placed at the PREVIOUS frame's position+ * while the sprites drew at this frame's — so a camera moved in Update trailed+ * the world by exactly one frame, and the two only agreed while nothing moved.+ */+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { bootMockApp } from './helpers/mockApp';+import { setPlatform } from '../src/platform/base';+import type { PlatformAdapter } from '../src/platform/types';+import { cameraPlugin } from '../src/camera/CameraPlugin';+import { RenderPipeline } from '../src/render/renderPipeline';+import { setRendererBackend, type RendererBackend } from '../src/render/renderer';+import { defineSystem, Schedule } from '../src/ecs/system';+import { Camera, Transform, ProjectionType } from '../src/ecs/component';+import { Query, Mut } from '../src/ecs/query';+import type { Entity } from '../src/types';+import type { CppRegistry } from '../src/wasm';++/** Where a world point lands in clip space under a view-projection. */+const ndcX = (vp: Float32Array, x: number, y: number): number =>+ vp[0] * x + vp[4] * y + vp[12];++describe('render order: transforms resolve before cameras are read', () => {+ const calls: string[] = [];+ let lastViewProjection: Float32Array | null = null;+ let beginFrames = 0;++ /**+ * Stands in for the C++ renderer: `beginFrame` clears the transform pass's+ * once-per-frame memo (EngineState.transforms_updated) and the pass itself+ * does what TransformSystem does to a root — world TRS := local TRS.+ */+ function fakeBackend(registry: CppRegistry, roots: Entity[]): RendererBackend {+ let transformsUpdated = false;+ return {+ init: () => {}, resize: () => {},+ beginFrame: () => { transformsUpdated = false; beginFrames++; calls.push('beginFrame'); },+ updateTransforms: () => {+ calls.push('updateTransforms');+ if (transformsUpdated) return;+ transformsUpdated = true;+ for (const e of roots) {+ const t = registry.getTransform(e) as unknown as+ { position: { x: number; y: number; z: number } } | undefined;+ if (!t) continue;+ (registry as unknown as { addTransform(e: Entity, d: unknown): void })+ .addTransform(e, { ...t, worldPosition: { ...t.position } });+ }+ },+ begin: (viewProjection) => { calls.push('begin'); lastViewProjection = viewProjection; },+ submitAll: () => { calls.push('submitAll'); },+ flush: () => {}, end: () => {},+ setStage: () => {}, setViewport: () => {},+ setYSortLayers: () => {}, setDepthLayers: () => {}, setCullingMask: () => {},+ getStats: () => ({ drawCalls: 0, triangles: 0, sprites: 0, text: 0, skeletal: 0, meshes: 0, culled: 0 }),+ };+ }++ 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);+ });+ afterEach(() => { setRendererBackend(null); });++ it('a camera moved in Update is looked through at THIS frame’s position', async () => {+ const { app, module } = bootMockApp();+ const registry = module.getRegistry() as unknown as Record<string, unknown> & CppRegistry;++ const cam = app.world.spawn('camera') as Entity;+ app.world.insert(cam, Transform, { position: { x: 0, y: 0, z: 0 } });+ app.world.insert(cam, Camera, {+ isActive: true, projectionType: ProjectionType.Orthographic, orthoSize: 300,+ });++ // The mock registry answers scene queries the C++ registry owns.+ registry.getCameraEntities = () => [cam];+ registry.getCanvasEntities = () => [];++ app.setPipeline(new RenderPipeline());+ setRendererBackend(fakeBackend(registry, [cam]));+ app.addPlugin(cameraPlugin(() => ({ width: 800, height: 600 })));++ // The user's cameraMoveSystem, in the shape the report came in.+ const SPEED = 300;+ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Query(Mut(Transform), Camera)],+ (query) => { query.forEach((_e, t) => { t.position.x += SPEED * (1 / 60); }); },+ { name: 'cameraMove' },+ ));++ await app.tick(1 / 60);++ // The order itself: the pass that writes worldPosition leads the read.+ expect(calls.indexOf('updateTransforms')).toBeGreaterThanOrEqual(0);+ expect(calls.indexOf('updateTransforms')).toBeLessThan(calls.indexOf('begin'));+ // And it is opened exactly once — a second beginFrame ages the target pool twice.+ expect(beginFrames).toBe(1);++ // What it buys: the camera's own position maps to the centre of the view.+ // A frame-late camera would put x = 0 there instead.+ const moved = SPEED / 60;+ expect(app.world.get(cam, Transform).position.x).toBeCloseTo(moved);+ expect(lastViewProjection).not.toBeNull();+ expect(ndcX(lastViewProjection!, moved, 0)).toBeCloseTo(0, 5);+ expect(Math.abs(ndcX(lastViewProjection!, 0, 0))).toBeGreaterThan(1e-3); // not still at the origin+ });+});