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(query): four places answered "which entities match", and two of them were wrong

esengine67079e37d10e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5878af82b..170f91666 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,19 @@ published separately; it ships inside the editor.
### Fixed
+- **Asking a query a question gave a different answer than iterating it.**
+ `Added()`/`Changed()` are per-entity tick checks applied while iterating, not
+ part of the entity set the query cache returns — and `count()` read that set
+ directly. `Query(Changed(Position)).count()` therefore reported every entity
+ that has a Position, while `[...Query(Changed(Position))].length` reported the
+ ones that actually changed; a system deciding whether to run by `count()` ran
+ every frame. `isEmpty()` had the mirror-image problem: it ran the iterator, and
+ one step of a `Mut()` query writes that entity back and records a `Changed` tick
+ for it — so asking whether a query was empty marked an entity as changed and
+ fed a false positive to the next frame's `Changed()`. `single()` also handed
+ back the iterator's shared row buffer, so holding one watched it get overwritten
+ by the next call. Four places answered "which entities match" and now one does.
+
- **`registry.eachLive<A, B>` did not compile.** `Registry::each`/`eachLive` are
variadic, so both read as available at any arity — but `eachLive` existed only on
the single-component `View<T>`, and the multi-component `View<Components...>` had
diff --git a/sdk/src/ecs/query.ts b/sdk/src/ecs/query.ts
index 6c4237640..e69e7c3ee 100644
--- a/sdk/src/ecs/query.ts
+++ b/sdk/src/ecs/query.ts
@@ -347,6 +347,26 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
this.lastRunTick_ = tick;
}
+ /**
+ * The entity set before change filters — what the query cache can answer on
+ * its own. Every caller that asks "which entities match" goes through here,
+ * so none of them can disagree about the cache key or the dep set.
+ */
+ private candidates_(): Entity[] {
+ return this.world_.getEntitiesWithComponents(
+ this.allRequired_,
+ this.descriptor_._with,
+ this.descriptor_._without,
+ this.cacheKey_,
+ this.compiledFilter_ ?? undefined,
+ this.depIds_,
+ );
+ }
+
+ private hasChangeFilters_(): boolean {
+ return this.descriptor_._addedFilters.length > 0 || this.descriptor_._changedFilters.length > 0;
+ }
+
private passesChangeFilters_(entity: Entity): boolean {
const { _addedFilters, _changedFilters } = this.descriptor_;
if (_addedFilters.length === 0 && _changedFilters.length === 0) return true;
@@ -398,17 +418,10 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
[Symbol.iterator](): Iterator<QueryResult<C>> {
const { _mutIndices } = this.descriptor_;
const actualComponents = this.actualComponents_;
- const entities = this.world_.getEntitiesWithComponents(
- this.allRequired_,
- this.descriptor_._with,
- this.descriptor_._without,
- this.cacheKey_,
- this.compiledFilter_ ?? undefined,
- this.depIds_,
- );
+ const entities = this.candidates_();
const compCount = actualComponents.length;
const hasMut = _mutIndices.length > 0;
- const hasChangeFilters = this.descriptor_._addedFilters.length > 0 || this.descriptor_._changedFilters.length > 0;
+ const hasChangeFilters = this.hasChangeFilters_();
const result = this.result_;
const mutData = this.mutData_;
const mutCount = mutData.length;
@@ -481,17 +494,10 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
forEach(callback: (entity: Entity, ...components: ComponentsData<C>) => void): void {
const { _mutIndices } = this.descriptor_;
- const entities = this.world_.getEntitiesWithComponents(
- this.allRequired_,
- this.descriptor_._with,
- this.descriptor_._without,
- this.cacheKey_,
- this.compiledFilter_ ?? undefined,
- this.depIds_,
- );
+ const entities = this.candidates_();
const compCount = this.actualComponents_.length;
const hasMut = _mutIndices.length > 0;
- const hasChangeFilters = this.descriptor_._addedFilters.length > 0 || this.descriptor_._changedFilters.length > 0;
+ const hasChangeFilters = this.hasChangeFilters_();
const result = this.result_;
const mutData = this.mutData_;
const mutCount = mutData.length;
@@ -540,25 +546,47 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu
world.endIteration();
}
+ /**
+ * The one result, or null. Copied off the iterator's shared row buffer, which
+ * the next iteration overwrites — a caller that holds this would otherwise
+ * watch it change under them.
+ */
single(): QueryResult<C> | null {
for (const result of this) {
- return result;
+ return [...result] as QueryResult<C>;
}
return null;
}
+ /**
+ * Whether iterating would yield nothing. Asks the entity set rather than
+ * running the iterator: taking one step of a Mut() query writes that entity
+ * back and records a Changed tick for it, and asking whether a query is empty
+ * must not mark anything as having changed.
+ */
isEmpty(): boolean {
- return this.single() === null;
+ const entities = this.candidates_();
+ if (!this.hasChangeFilters_()) return entities.length === 0;
+ for (const entity of entities) {
+ if (this.passesChangeFilters_(entity)) return false;
+ }
+ return true;
}
+ /**
+ * How many results iterating would yield. Added()/Changed() are per-entity
+ * tick checks rather than part of the entity set the cache returns, so
+ * counting has to apply them too — the same pass the iterator makes.
+ */
count(): number {
- return this.world_.getEntitiesWithComponents(
- this.allRequired_,
- this.descriptor_._with,
- this.descriptor_._without,
- this.cacheKey_,
- this.compiledFilter_ ?? undefined,
- ).length;
+ const entities = this.candidates_();
+ if (!this.hasChangeFilters_()) return entities.length;
+
+ let n = 0;
+ for (const entity of entities) {
+ if (this.passesChangeFilters_(entity)) n++;
+ }
+ return n;
}
toArray(): QueryResult<C>[] {
diff --git a/sdk/tests/query-count-invariant.test.ts b/sdk/tests/query-count-invariant.test.ts
new file mode 100644
index 000000000..c831d3a89
--- /dev/null
+++ b/sdk/tests/query-count-invariant.test.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file query-count-invariant.test.ts
+ * @brief Asking a query a question must not give a different answer than
+ * iterating it, and must not change the world.
+ *
+ * Added()/Changed() are per-entity tick checks applied while iterating,
+ * not part of the entity set the query cache returns. count() read that
+ * set directly, so `Query(Changed(P)).count()` reported every entity
+ * holding P while `[...Query(Changed(P))].length` reported the changed
+ * ones. isEmpty() had the opposite problem: it ran the iterator, and one
+ * step of a Mut() query writes that entity back and records a Changed
+ * tick — so asking whether a query was empty marked an entity changed.
+ * The matrix crosses the filter kinds so no one of them can be fixed
+ * while another silently drifts.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { World } from '../src/ecs/world';
+import { Query, QueryInstance, Added, Changed, Mut, Not, Or, With } from '../src/ecs/query';
+import { defineComponent } from '../src/ecs/component';
+import type { Entity } from '../src/types';
+
+const P = defineComponent('CIPosition', { x: 0, y: 0 });
+const V = defineComponent('CIVelocity', { dx: 0, dy: 0 });
+const Tag = defineComponent('CITag', {});
+
+/** Every query shape, built fresh per case so no cache state carries between them. */
+const SHAPES: { name: string; build: () => ReturnType<typeof Query> }[] = [
+ { name: 'plain', build: () => Query(P) },
+ { name: 'two components', build: () => Query(P, V) },
+ { name: 'with', build: () => Query(P).with(V) },
+ { name: 'without', build: () => Query(P).without(Tag) },
+ { name: 'Added', build: () => Query(Added(P)) },
+ { name: 'Changed', build: () => Query(Changed(P)) },
+ { name: 'Changed + Added', build: () => Query(Changed(P), Added(V)) },
+ { name: 'Changed + without', build: () => Query(Changed(P)).without(Tag) },
+ { name: 'Changed + with', build: () => Query(Changed(P)).with(V) },
+ { name: 'Changed + filter tree', build: () => Query(Changed(P)).filter(Or(With(V), Not(With(Tag)))) },
+ { name: 'filter tree alone', build: () => Query(P).filter(Or(With(V), Not(With(Tag)))) },
+];
+
+describe('count() equals what iterating yields', () => {
+ let world: World;
+ let entities: Entity[];
+
+ beforeEach(() => {
+ world = new World();
+ entities = [];
+ // Tracking has to be on before the writes below, or nothing records a tick
+ // for Added()/Changed() to find. A QueryInstance enables it in its ctor,
+ // which is too late for anything already written.
+ world.enableChangeTracking(P);
+ world.enableChangeTracking(V);
+ // A spread of component combinations so every shape has both matches and
+ // non-matches to tell apart.
+ for (let i = 0; i < 12; i++) {
+ const e = world.spawn();
+ world.insert(e, P, { x: i, y: 0 });
+ if (i % 2 === 0) world.insert(e, V, { dx: 1, dy: 0 });
+ if (i % 3 === 0) world.insert(e, Tag, {});
+ entities.push(e);
+ }
+ });
+
+ /**
+ * sinceTick moves what Added()/Changed() consider recent: -1 sees the seeding
+ * writes, a tick past them sees nothing until something writes again.
+ */
+ for (const sinceTick of [-1, 0, 1]) {
+ for (const shape of SHAPES) {
+ it(`${shape.name} @ tick ${sinceTick}`, () => {
+ world.advanceTick();
+ const counted = new QueryInstance(world, shape.build(), sinceTick).count();
+ const iterated = new QueryInstance(world, shape.build(), sinceTick).toArray().length;
+ expect(counted).toBe(iterated);
+ });
+ }
+ }
+
+ it('a fresh write moves both count() and iteration together', () => {
+ world.advanceTick();
+ const tick = world.getWorldTick();
+ world.advanceTick();
+
+ const before = new QueryInstance(world, Query(Changed(P)), tick);
+ expect(before.count()).toBe(0);
+ expect(before.toArray()).toHaveLength(0);
+
+ world.set(entities[0], P, { x: 99, y: 0 });
+ world.set(entities[5], P, { x: 98, y: 0 });
+
+ const after = new QueryInstance(world, Query(Changed(P)), tick);
+ expect(after.count()).toBe(2);
+ expect(after.count()).toBe(after.toArray().length);
+ });
+
+ it('count() with a change filter does not just report everything holding it', () => {
+ world.advanceTick();
+ const tick = world.getWorldTick();
+ world.advanceTick();
+ world.set(entities[3], P, { x: 1, y: 1 });
+
+ const q = new QueryInstance(world, Query(Changed(P)), tick);
+ expect(q.count()).toBe(1);
+ // The pre-fix answer: every entity that has P at all.
+ expect(q.count()).not.toBe(entities.length);
+ });
+
+ it('isEmpty() on a Mut query does not mark anything Changed', () => {
+ world.advanceTick();
+ const tick = world.getWorldTick();
+ world.advanceTick();
+
+ expect(new QueryInstance(world, Query(Mut(P)), -1).isEmpty()).toBe(false);
+
+ // Taking one iterator step writes that entity back and records a tick for
+ // it; asking whether the query is empty must not do that.
+ expect(new QueryInstance(world, Query(Changed(P)), tick).toArray()).toHaveLength(0);
+ });
+
+ it('single() hands back its own row, not the buffer the next one overwrites', () => {
+ const q = new QueryInstance(world, Query(P), -1);
+ const first = q.single();
+ const second = q.single();
+ expect(first).not.toBe(second);
+ expect(first).toEqual(second);
+ });
+
+ it('isEmpty() agrees with count() === 0 under a change filter', () => {
+ world.advanceTick();
+ const tick = world.getWorldTick();
+ world.advanceTick();
+
+ const quiet = new QueryInstance(world, Query(Changed(P)), tick);
+ expect(quiet.count()).toBe(0);
+ expect(quiet.isEmpty()).toBe(true);
+
+ world.set(entities[1], P, { x: 7, y: 7 });
+ const busy = new QueryInstance(world, Query(Changed(P)), tick);
+ expect(busy.count()).toBeGreaterThan(0);
+ expect(busy.isEmpty()).toBe(false);
+ });
+});