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(ecs): a removal was recorded for things nothing was watching
esenginefcbc099ff985
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c2b955762..e5cb1ee1b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,18 @@ published separately; it ships inside the editor.### Fixed+- **`Removed()` reported despawns from before anything was watching.** Losing a+ component reaches the change tracker two ways — by definition for an explicit+ `remove()` and for builtins on despawn, by component id for script components on+ despawn — and only the first checked whether anything actually tracks that+ component. So an untracked script component recorded a removal on every despawn,+ and a `Removed(X)` query created later reported entities that had died before it+ existed, while the same query over a builtin, or over the same component removed+ explicitly, reported nothing. One "was it lost" gate now, at the single entry+ point both paths go through. The removal watermark that `anyChangedSince` reads+ is unchanged for anything tracked — UI layout still learns a `FlexContainer` is+ gone.+- **A system that threw inside `forEach` left the world iterating.** The worldrefuses `spawn`/`despawn`/`remove` while a query is being walked — those wouldresize the arrays under it — so `beginIteration` and `endIteration` have todiff --git a/sdk/src/ecs/ChangeTracker.ts b/sdk/src/ecs/ChangeTracker.tsindex 4aaf89940..8f2618308 100644--- a/sdk/src/ecs/ChangeTracker.ts+++ b/sdk/src/ecs/ChangeTracker.ts@@ -99,11 +99,17 @@ export class ChangeTracker {}recordRemoved(component: AnyComponentDef, entity: Entity): void {- if (!this.trackedComponents_.has(component._id)) return;this.recordRemovedById(component._id, entity);}+ /**+ * The gate lives here rather than in each caller: despawn reaches script+ * components through this id-only entry point and builtins through+ * recordRemoved, and when only the latter checked, the same despawn was+ * recorded for one kind and dropped for the other.+ */recordRemovedById(componentId: symbol, entity: Entity): void {+ if (!this.trackedComponents_.has(componentId)) return;let buffer = this.componentRemovedBuffer_.get(componentId);if (!buffer) {buffer = [];diff --git a/sdk/src/ecs/QueryCache.ts b/sdk/src/ecs/QueryCache.tsindex 0e1e953f2..51d437480 100644--- a/sdk/src/ecs/QueryCache.ts+++ b/sdk/src/ecs/QueryCache.ts@@ -18,8 +18,6 @@ export interface QueryCacheStats {readonly hits: number;/** Lookups that recomputed — either no entry or stale. */readonly misses: number;- /** Times an entry was found but rejected because structural version moved. */- readonly structuralInvalidations: number;/** Times an entry was rejected because one of its dep components changed. */readonly componentInvalidations: number;/** Current number of entries held. */@@ -33,7 +31,6 @@ export class QueryCache {private hits_ = 0;private misses_ = 0;- private structuralInvalidations_ = 0;private componentInvalidations_ = 0;get structuralVersion(): number {@@ -97,7 +94,6 @@ export class QueryCache {return {hits: this.hits_,misses: this.misses_,- structuralInvalidations: this.structuralInvalidations_,componentInvalidations: this.componentInvalidations_,size: this.cache_.size,};@@ -107,7 +103,6 @@ export class QueryCache {resetStats(): void {this.hits_ = 0;this.misses_ = 0;- this.structuralInvalidations_ = 0;this.componentInvalidations_ = 0;}diff --git a/sdk/src/ecs/query.ts b/sdk/src/ecs/query.tsindex 5ce9dcc6c..c36d8ee2e 100644--- a/sdk/src/ecs/query.ts+++ b/sdk/src/ecs/query.ts@@ -271,12 +271,6 @@ export type QueryResult<C extends readonly QueryArg[]> = [// Query Instance (Runtime)// =============================================================================-interface PendingMutation {- entity: Entity;- component: AnyComponentDef;- data: Record<string, unknown>;-}-export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<QueryResult<C>> {private readonly world_: World;private readonly descriptor_: QueryDescriptor<C>;diff --git a/sdk/tests/query-cache-stats.test.ts b/sdk/tests/query-cache-stats.test.tsindex 4e2854575..0314eba7e 100644--- a/sdk/tests/query-cache-stats.test.ts+++ b/sdk/tests/query-cache-stats.test.ts@@ -45,7 +45,6 @@ describe('QueryCache.getStats', () => {expect(computed).toBe(1);const s = cache.getStats();expect(s.hits).toBe(1);- expect(s.structuralInvalidations).toBe(0);expect(s.componentInvalidations).toBe(0);});@@ -56,7 +55,6 @@ describe('QueryCache.getStats', () => {cache.getOrCompute('q1', [comp], () => []);const s = cache.getStats();expect(s.componentInvalidations).toBe(1);- expect(s.structuralInvalidations).toBe(0);});it('resetStats zeroes counters but keeps cached entries', () => {diff --git a/sdk/tests/removed-query-symmetry.test.ts b/sdk/tests/removed-query-symmetry.test.tsnew file mode 100644index 000000000..7af63c289--- /dev/null+++ b/sdk/tests/removed-query-symmetry.test.ts@@ -0,0 +1,89 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file removed-query-symmetry.test.ts+ * @brief Losing a component has to mean one thing, whichever way it was lost+ * and whichever kind of component it is.+ *+ * Removal reaches the tracker two ways: recordRemoved(def) for an+ * explicit remove() and for builtins on despawn, recordRemovedById(id)+ * for script components on despawn. Only the first checked whether+ * anything tracks the component, so an untracked script component+ * accumulated a removal record on every despawn — and a Removed() query+ * created later reported despawns from before it existed, while the same+ * query over a builtin, or over the same component removed explicitly,+ * reported nothing.+ */+import { describe, it, expect } from 'vitest';+import { World } from '../src/ecs/world';+import { RemovedQueryInstance } from '../src/ecs/query';+import { defineComponent } from '../src/ecs/component';++const Sc = defineComponent('RQSScript', { v: 0 });++function removedSince(world: World, tick: number): number[] {+ return new RemovedQueryInstance(world, Sc, tick).toArray();+}++describe('Removed() records only what something is tracking', () => {+ it('an untracked component records nothing, however it is lost', () => {+ const despawned = new World();+ const a = despawned.spawn();+ despawned.insert(a, Sc, { v: 1 });+ despawned.despawn(a);++ const removed = new World();+ const b = removed.spawn();+ removed.insert(b, Sc, { v: 1 });+ removed.remove(b, Sc);++ expect(removedSince(despawned, -1)).toEqual([]);+ expect(removedSince(removed, -1)).toEqual([]);+ });++ it('a tracked component records both ways', () => {+ const world = new World();+ world.enableChangeTracking(Sc);++ const viaDespawn = world.spawn();+ world.insert(viaDespawn, Sc, { v: 1 });+ const viaRemove = world.spawn();+ world.insert(viaRemove, Sc, { v: 2 });++ world.despawn(viaDespawn);+ world.remove(viaRemove, Sc);++ expect(removedSince(world, -1).sort()).toEqual([viaDespawn, viaRemove].sort());+ });++ it('tracking starts when something asks, not retroactively', () => {+ const world = new World();+ const before = world.spawn();+ world.insert(before, Sc, { v: 1 });+ world.despawn(before);++ // The query's own ctor is what enables tracking.+ expect(removedSince(world, -1)).toEqual([]);++ const after = world.spawn();+ world.insert(after, Sc, { v: 2 });+ world.despawn(after);+ expect(removedSince(world, -1)).toEqual([after]);+ });++ it('losing a tracked component still moves the anyChangedSince watermark', () => {+ const world = new World();+ world.enableChangeTracking(Sc);+ const e = world.spawn();+ world.insert(e, Sc, { v: 1 });+ world.advanceTick();+ const tick = world.getWorldTick();+ world.advanceTick();++ expect(world.anyChangedSince(Sc, tick)).toBe(false);+ world.despawn(e);+ // Removal IS a change: a consumer gating work on this watermark has to+ // learn the component is gone (UI layout does exactly that).+ expect(world.anyChangedSince(Sc, tick)).toBe(true);+ });+});