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
perf(ui): GearApplySystem does not run in a frame where nothing it reads changed
yhhb6f277d5e25d
diff --git a/sdk/src/ui/controller/gear-apply.ts b/sdk/src/ui/controller/gear-apply.tsindex 6cca04c56..2614f56fa 100644--- a/sdk/src/ui/controller/gear-apply.ts+++ b/sdk/src/ui/controller/gear-apply.ts@@ -18,7 +18,7 @@* editor preview path) can exercise the value logic without a World.*/import { defineSystem, type SystemDef } from '../../ecs/system';-import { getComponent } from '../../ecs/component';+import { getComponent, Parent } from '../../ecs/component';import { Res, Time, type TimeData } from '../../ecs/resource';import { applyEasing } from '../../animation/Easing';import { EntityStateMap } from '../util/helpers';@@ -188,7 +188,25 @@ interface BindingTx {export function createGearApplySystem(world: World): SystemDef {const tracker = new EntityStateMap<{ ref: unknown; txs: Array<BindingTx | null> }>();+ // A frame in which nothing a gear reads has changed does the same nothing as the last one, so it is not run. Everything the+ // pass depends on is tracked: the controllers' pages (UIController), the bindings (UIGear), where each node hangs (Parent, which+ // is how a controller is found), and what exists and carries which component (the world's structural version, which covers a+ // target component arriving later). A tween in flight is the one thing that moves without any of those changing, so it keeps+ // the pass running until it settles. A world without change tracking (a test double) runs every frame as it always did.+ const canSkip = typeof world.enableChangeTracking === 'function' && typeof world.anyChangedSince === 'function'+ && typeof world.getWorldTick === 'function' && typeof world.getWorldVersion === 'function';+ if (canSkip) {+ world.enableChangeTracking(UIController);+ world.enableChangeTracking(UIGear);+ world.enableChangeTracking(Parent);+ }+ let settledTick = -1, settledVersion = -1, inFlight = true;+return defineSystem([Res(Time)], (time: TimeData) => {+ if (canSkip && !inFlight && settledVersion === world.getWorldVersion()+ && !world.anyChangedSince(UIController, settledTick) && !world.anyChangedSince(UIGear, settledTick)+ && !world.anyChangedSince(Parent, settledTick)) return;+ let moving = false;const dt = time.delta;const seen = new Set<Entity>();@@ -216,7 +234,8 @@ export function createGearApplySystem(world: World): SystemDef {if (target === undefined) continue; // page not authored → leave field aloneconst comp = getComponent(b.component);- if (!comp || !world.has(e, comp)) continue;+ if (!comp) { moving = true; continue; } // not registered yet: look again next frame+ if (!world.has(e, comp)) continue;const fade = Math.max(0, b.tween?.duration ?? 0);const lerpable = fade > 0 && isLerpable(target);@@ -241,9 +260,15 @@ export function createGearApplySystem(world: World): SystemDef {if (writeFieldPath(data, b.property, value)) {world.insert(e, comp, data);}- if (t >= 1) tx.done = true;+ if (t >= 1) tx.done = true; else moving = true;}}+ if (canSkip) {+ inFlight = moving;+ // Strictly-after, like the layout pass: a write that lands later in this same tick is seen next frame.+ settledTick = world.getWorldTick() - 1;+ settledVersion = world.getWorldVersion();+ }// Purge trackers for entities that no longer carry UIGear (the query only// yields live UIGear entities, so anything unseen is gone or stripped).diff --git a/sdk/tests/ui-controller-gear.test.ts b/sdk/tests/ui-controller-gear.test.tsindex ff6af2f26..114e5d129 100644--- a/sdk/tests/ui-controller-gear.test.ts+++ b/sdk/tests/ui-controller-gear.test.ts@@ -339,3 +339,110 @@ describe('InteractionControllerDriverSystem — button states through gears', ()expect(getControllerPage(world as never, e, '$interaction')).toBe('hover');});});++// ─── Skipping the frames in which nothing changed ────────────────────────++/** The mock world with the change tracking the real one has: a tick per frame, a structural version, and when each component last changed. */+function makeTrackedWorld() {+ const base = makeMockWorld();+ let tick = 0, version = 0;+ const changedAt = new Map<AnyComponentDef, number>();+ const reads = { get: 0, has: 0 };+ const note = (c: AnyComponentDef) => changedAt.set(c, tick);+ const world = {+ ...base,+ get: (e: Entity, c: AnyComponentDef) => { reads.get++; return base.get(e, c); },+ has: (e: Entity, c: AnyComponentDef) => { reads.has++; return base.has(e, c); },+ insert: (e: Entity, c: AnyComponentDef, d: unknown) => { if (!base.has(e, c)) version++; base.insert(e, c, d); note(c); },+ update: (e: Entity, c: AnyComponentDef, edit: (d: unknown) => void) => { base.update(e, c, edit); note(c); },+ remove: (e: Entity, c: AnyComponentDef) => { version++; return base.remove(e, c); },+ enableChangeTracking: () => {},+ getWorldTick: () => tick,+ getWorldVersion: () => version,+ anyChangedSince: (c: AnyComponentDef, since: number) => (changedAt.get(c) ?? -1) > since,+ nextFrame: () => { tick++; },+ reads,+ };+ return world;+}++describe('GearApplySystem — idle frames are skipped', () => {+ let world: ReturnType<typeof makeTrackedWorld>;+ let e: Entity;+ const red = { r: 1, g: 0, b: 0, a: 1 }, blue = { r: 0, g: 0, b: 1, a: 1 };+ const frame = (sys: SystemDef, dt = 1 / 60) => { world.nextFrame(); runSystem(sys, dt); };+ beforeEach(() => {+ world = makeTrackedWorld();+ e = world.spawn();+ world.insert(e, UIVisual, makeVisual());+ world.insert(e, UIController, { controllers: [controllerState('tab', ['a', 'b'], 'a')] });+ world.insert(e, UIGear, { bindings: [gearBinding('tab', 'UIVisual', 'color', { a: red, b: blue })] } as UIGearData);+ });++ it('reads nothing from the world in a frame where nothing changed, once the gears have settled', () => {+ const sys = createGearApplySystem(world as never);+ frame(sys); frame(sys); frame(sys); // the first pass applies, the next ones settle+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual(red);+ world.reads.get = 0; world.reads.has = 0;+ for (let i = 0; i < 20; i++) frame(sys);+ expect(world.reads.get + world.reads.has).toBe(0);+ });++ it('wakes for a controller page change and applies it', () => {+ const sys = createGearApplySystem(world as never);+ frame(sys); frame(sys); frame(sys);+ setControllerPage(world as never, e, 'tab', 'b');+ world.update(e, UIController, () => {}); // what setControllerPage's own write records+ frame(sys);+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual(blue);+ });++ it('keeps running while a tween is in flight, with nothing else changing, until it settles', () => {+ world.insert(e, UIGear, { bindings: [gearBinding('tab', 'UIVisual', 'color', { a: red, b: blue }, { duration: 0.5, easing: 0 })] } as UIGearData);+ const sys = createGearApplySystem(world as never);+ frame(sys); frame(sys);+ world.update(e, UIController, (d) => { (d as UIControllerData).controllers[0].current = 'b'; });+ frame(sys, 0.1);+ const early = (world.get(e, UIVisual) as UIVisualData).color.b;+ expect(early).toBeGreaterThan(0); expect(early).toBeLessThan(1);+ for (let i = 0; i < 10; i++) frame(sys, 0.1); // no write to anything a gear reads: only the tween moves it+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual(blue);+ world.reads.get = 0; world.reads.has = 0;+ for (let i = 0; i < 5; i++) frame(sys, 0.1);+ expect(world.reads.get + world.reads.has).toBe(0); // and once it has settled it sleeps again+ });++ it('wakes when the component a gear writes to arrives after the gear', () => {+ const other = world.spawn();+ world.insert(other, UIController, { controllers: [controllerState('tab', ['a', 'b'], 'b')] });+ world.insert(other, UIGear, { bindings: [gearBinding('tab', 'UIVisual', 'color', { a: red, b: blue })] } as UIGearData);+ const sys = createGearApplySystem(world as never);+ frame(sys); frame(sys); frame(sys); // `other` has no UIVisual yet: nothing to write to+ expect(world.has(other, UIVisual)).toBe(false);+ world.insert(other, UIVisual, makeVisual());+ frame(sys);+ expect((world.get(other, UIVisual) as UIVisualData).color).toEqual(blue);+ });++ it('wakes when a node is hung under a different parent, so its controller is found again', () => {+ const bare = world.spawn(), root = world.spawn(), leaf = world.spawn();+ world.insert(root, UIController, { controllers: [controllerState('tab', ['a', 'b'], 'b')] });+ world.insert(leaf, UIVisual, makeVisual());+ world.insert(leaf, Parent, { entity: bare }); // it already hangs somewhere, so moving it adds no component+ world.insert(leaf, UIGear, { bindings: [gearBinding('tab', 'UIVisual', 'color', { a: red, b: blue })] } as UIGearData);+ const sys = createGearApplySystem(world as never);+ frame(sys); frame(sys); frame(sys); // no controller above it yet: left alone+ expect((world.get(leaf, UIVisual) as UIVisualData).color).toEqual({ r: 1, g: 1, b: 1, a: 1 });+ world.update(leaf, Parent, (d) => { (d as { entity: Entity }).entity = root; });+ frame(sys);+ expect((world.get(leaf, UIVisual) as UIVisualData).color).toEqual(blue);+ });++ it('wakes when the bindings themselves are rewritten', () => {+ const sys = createGearApplySystem(world as never);+ frame(sys); frame(sys); frame(sys);+ world.update(e, UIGear, (d) => { (d as UIGearData).bindings = [gearBinding('tab', 'UIVisual', 'color', { a: blue, b: red })]; });+ frame(sys);+ expect((world.get(e, UIVisual) as UIVisualData).color).toEqual(blue);+ });+});