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
feat(ecs): a disabled entity is actually skipped
esengine370d2be198e8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eb2399312..76dd0dc92 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,18 @@ published separately; it ships inside the editor.### Added+- **A disabled entity is actually skipped.** `Disabled`'s doc promised that "the+ engine's systems skip it" and nothing read the tag: `setEntityActive` returned,+ every query went on answering with the entity, and the only record of this was+ a comment in the UI builtins explaining that a verb built on it "would look+ right in the inspector and change nothing on screen". Queries now exclude+ disabled entities — the one place every system, including the AOT-compiled+ ones, meets the world — and the query cache watches the tag, so switching one+ invalidates what was already found. A query that names `Disabled` still sees+ them, because managing the switch means reaching what is switched off, and+ `setEntityActive` takes the whole subtree with it: a character switched off+ with its sword still swinging is not switched off.+- **A sorting group in the sprite demo.** The component that makes a subtreesort as one unit — the fix for a character whose sword draws behind the wrongprop — had a pixel criterion of its own and no instance in any shipped scene.diff --git a/sdk/src/ecs/aot/AotDispatch.ts b/sdk/src/ecs/aot/AotDispatch.tsindex 3d242ef31..6c39c4e5f 100644--- a/sdk/src/ecs/aot/AotDispatch.ts+++ b/sdk/src/ecs/aot/AotDispatch.ts@@ -38,7 +38,7 @@*/import type { AnyComponentDef } from '../component';-import { computeQueryCacheKey, type World } from '../world';+import { computeQueryCacheKey, type World, queryDepIds } from '../world';import type { Entity } from '../../types';import { CMD_DESPAWN } from './AotContext';import type { AotRuntime } from './AotRuntime';@@ -293,7 +293,7 @@ export class AotDispatch {resolvers: comps.map((c) => resolverFor(this.world, c)),mutated: [...(twin.mutated[k] ?? [])],key: computeQueryCacheKey(comps),- depIds: comps.map((c) => c._id as symbol),+ depIds: queryDepIds(comps, NO_FILTERS, NO_FILTERS),width: 1 + comps.length,resolved,reader: null,diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.tsindex 5600f5c4d..ae057dbd6 100644--- a/sdk/src/ecs/component.ts+++ b/sdk/src/ecs/component.ts@@ -1156,7 +1156,9 @@ export const ParticleEmitter = defineBuiltin<ParticleEmitterData>('ParticleEmitt/*** Marks an entity inactive: it keeps its components and its place in the tree,- * and the engine's systems skip it. A tag, so it carries no data.+ * and every query skips it — which is how the systems skip it. A query that+ * NAMES this one sees them, since managing the switch means reaching what is+ * switched off; `setEntityActive` sets it, and takes the subtree with it.*/export const Disabled = defineTag('Disabled');diff --git a/sdk/src/ecs/entityUtils.ts b/sdk/src/ecs/entityUtils.tsindex a66224cf5..8fa5320ff 100644--- a/sdk/src/ecs/entityUtils.ts+++ b/sdk/src/ecs/entityUtils.ts@@ -16,7 +16,7 @@*/import type { Entity } from '../types';import type { World } from './world';-import { Disabled, renderableComponents, Transform } from './component';+import { Children, Disabled, renderableComponents, Transform, type ChildrenData } from './component';import { UINode, UIDisplay, type UINodeData } from '../ui/core/ui-node';/**@@ -65,18 +65,28 @@ export function isEntityVisible(world: World, entity: Entity): boolean {return true;}+/**+ * Switch `entity` and everything under it off, or back on — a character switched+ * off with its sword still swinging is not switched off.+ *+ * Tagged per entity rather than derived from an ancestor, so a query costs one+ * lookup: a subtree RE-PARENTED under a disabled entity needs this called again.+ */export function setEntityActive(world: World, entity: Entity, active: boolean): void {- if (active) {- if (world.has(entity, Disabled)) {- world.remove(entity, Disabled);+ const apply = (e: Entity): void => {+ if (!world.valid(e)) return;+ if (active) {+ if (world.has(e, Disabled)) world.remove(e, Disabled);+ } else if (!world.has(e, Disabled)) {+ world.insert(e, Disabled, {});}- } else {- if (!world.has(entity, Disabled)) {- world.insert(entity, Disabled, {});- }- }+ if (!world.has(e, Children)) return;+ for (const child of (world.get(e, Children) as ChildrenData).entities) apply(child as Entity);+ };+ apply(entity);}+/** Whether this entity itself is switched on — see {@link setEntityActive}. */export function isEntityActive(world: World, entity: Entity): boolean {return !world.has(entity, Disabled);}diff --git a/sdk/src/ecs/query.ts b/sdk/src/ecs/query.tsindex 560ede913..16f0f70a7 100644--- a/sdk/src/ecs/query.ts+++ b/sdk/src/ecs/query.ts@@ -8,7 +8,7 @@import { Entity } from '../types';import { AnyComponentDef, ComponentData, isBuiltinComponent } from './component';import type { World, QueryFilter } from './world';-import { computeQueryCacheKey } from './world';+import { computeQueryCacheKey, queryDepIds } from './world';// =============================================================================// Mutable Component Wrapper@@ -440,12 +440,10 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu// Same set the cache validity check reads; order is irrelevant (it maps// each id to its version). Must match what getEntitiesWithComponents would// otherwise build per call.- this.depIds_ = [- ...this.allRequired_.map(c => c._id),- ...descriptor._with.map(c => c._id),- ...descriptor._without.map(c => c._id),- ...(this.compiledFilter_?.deps.map(c => c._id) ?? []),- ];+ this.depIds_ = queryDepIds(+ this.allRequired_, descriptor._with, descriptor._without,+ this.compiledFilter_?.deps ?? [],+ );this.getters_ = this.actualComponents_.map(comp => world.resolveGetter(comp, 'borrowed'));this.gettersRetained_ = this.actualComponents_.map(comp => world.resolveGetter(comp, 'retained'));this.mutSetters_ = descriptor._mutIndices.map(idx =>diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 135f133db..bd2513fff 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -6,7 +6,7 @@*/import { Entity, entityGeneration, entityIndex, makeEntity, INVALID_ENTITY } from '../types';-import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getComponentRegistry, getUserComponents, getComponent, Name, Parent, Children, type ParentData, type ChildrenData } from './component';+import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getComponentRegistry, getUserComponents, getComponent, Disabled, Name, Parent, Children, type ParentData, type ChildrenData } from './component';import type { CppRegistry, ESEngineModule } from '../wasm';import { handleWasmError } from '../wasm/wasmError';import { BuiltinBridge, convertFromWasm, convertForWasm, type BridgeConnectOptions, type BuiltinMethods, type CompositionDelta } from './bridge/BuiltinBridge';@@ -119,6 +119,26 @@ export interface QueryFilter {* in here too: a reparent moves a subtree without touching its transforms. */const COMPOSITION_INPUTS = new Set(['Transform', 'Parent', 'Children']);++/**+ * The cache dependencies of a query, Disabled included: switching one entity off+ * changes what EVERY query answers. Shared because QueryInstance and the AOT+ * plan precompute this set once and would each have to remember.+ */+export function queryDepIds(+ components: readonly AnyComponentDef[],+ withFilters: readonly AnyComponentDef[],+ withoutFilters: readonly AnyComponentDef[],+ filterDeps: readonly AnyComponentDef[] = [],+): symbol[] {+ const ids: symbol[] = [Disabled._id];+ for (const c of components) ids.push(c._id);+ for (const c of withFilters) ids.push(c._id);+ for (const c of withoutFilters) ids.push(c._id);+ for (const c of filterDeps) ids.push(c._id);+ return ids;+}+/*** The entity store, as `GetWorld()` hands it to a system — the escape hatch for* work the declared parameters cannot express. Prefer `Query`/`Res`/`Commands`:@@ -1012,11 +1032,7 @@ export class World {withFilters: AnyComponentDef[],withoutFilters: AnyComponentDef[],): symbol[] {- const ids: symbol[] = [];- for (const c of components) ids.push(c._id);- for (const c of withFilters) ids.push(c._id);- for (const c of withoutFilters) ids.push(c._id);- return ids;+ return queryDepIds(components, withFilters, withoutFilters);}/**@@ -1069,8 +1085,15 @@ export class World {}}+ // `Disabled`'s whole contract is that the systems skip it, answered once+ // here rather than remembered at 78 call sites. A query that NAMES the+ // tag is the exception: managing the switch means seeing it.+ const namesDisabled = components.includes(Disabled)+ || withFilters.includes(Disabled) || withoutFilters.includes(Disabled);+return this.queries_.getOrCompute(cacheKey, depIds, () => {const entities: Entity[] = [];+ const off = namesDisabled ? null : this.scripts_.getStorageById(Disabled._id);const reqScript: Map<Entity, unknown>[] = [];const reqBuiltin: BuiltinMethods[] = [];@@ -1120,6 +1143,7 @@ export class World {const rbLen = reqBuiltin.length;for (const entity of candidates) {+ if (off?.has(entity)) continue;let match = true;for (let i = 0; i < rsLen; i++) {if (!reqScript[i].has(entity)) { match = false; break; }diff --git a/sdk/tests/disabled-entities.test.ts b/sdk/tests/disabled-entities.test.tsnew file mode 100644index 000000000..943e9be0b--- /dev/null+++ b/sdk/tests/disabled-entities.test.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file disabled-entities.test.ts+ * @brief A switched-off entity is out of the frame, not just marked.+ *+ * `Disabled`'s doc promised that "the engine's systems skip it" and+ * nothing read the tag: `setEntityActive(world, e, false)` returned,+ * every query went on answering with the entity, and the only sign was+ * a comment in ui/controller/ai-builtins admitting it. A query is where+ * a system meets the world, so that is where the promise is kept.+ */+import { describe, it, expect } from 'vitest';+import { World } from '../src/ecs/world';+import { defineComponent, defineTag, Disabled, Children } from '../src/ecs/component';+import { setEntityActive, isEntityActive } from '../src/ecs/entityUtils';+import type { Entity } from '../src/types';++const Health = defineComponent('TestHealth', { hp: 10 });+const Hostile = defineTag('TestHostile');++function worldWith(n: number): { world: World; entities: Entity[] } {+ const world = new World();+ const entities = Array.from({ length: n }, () => {+ const e = world.spawn();+ world.insert(e, Health, { hp: 10 });+ return e;+ });+ return { world, entities };+}++describe('a disabled entity', () => {+ it('is not answered by a query', () => {+ const { world, entities } = worldWith(3);+ expect(world.getEntitiesWithComponents([Health])).toHaveLength(3);++ setEntityActive(world, entities[1]!, false);+ const live = world.getEntitiesWithComponents([Health]);+ expect(live).toHaveLength(2);+ expect(live).not.toContain(entities[1]);++ setEntityActive(world, entities[1]!, true);+ expect(world.getEntitiesWithComponents([Health])).toHaveLength(3);+ });++ it('is seen by a query that asks for the tag', () => {+ const { world, entities } = worldWith(2);+ setEntityActive(world, entities[0]!, false);+ // Something has to be able to manage the switch — a query naming Disabled+ // is that something, and excluding them there would make it unanswerable.+ expect(world.getEntitiesWithComponents([Health, Disabled])).toEqual([entities[0]]);+ });++ it('takes its subtree with it', () => {+ // `Children` is written by the engine's hierarchy, which a unit test has+ // no wasm for — so the TREE is modelled and the walk over it is what runs.+ // That a real setParent produces this shape is the engine's own contract.+ const tags = new Map<Entity, Set<symbol>>();+ const kids = new Map<Entity, Entity[]>([[1 as Entity, [2 as Entity]], [2 as Entity, [3 as Entity]]]);+ const tree = {+ valid: () => true,+ has: (e: Entity, c: { _id: symbol }) =>+ c === Children ? kids.has(e) : (tags.get(e)?.has(c._id) ?? false),+ get: (e: Entity) => ({ entities: kids.get(e) ?? [] }),+ insert: (e: Entity, c: { _id: symbol }) => {+ if (!tags.has(e)) tags.set(e, new Set());+ tags.get(e)!.add(c._id);+ },+ remove: (e: Entity, c: { _id: symbol }) => { tags.get(e)?.delete(c._id); },+ } as unknown as World;++ setEntityActive(tree, 1 as Entity, false);+ // A character switched off with its sword still swinging is not off.+ for (const e of [1, 2, 3]) expect(isEntityActive(tree, e as Entity), `entity ${e}`).toBe(false);++ setEntityActive(tree, 1 as Entity, true);+ for (const e of [1, 2, 3]) expect(isEntityActive(tree, e as Entity), `entity ${e}`).toBe(true);+ });++ it('leaves the cached answer behind when it is switched', () => {+ const { world, entities } = worldWith(2);+ world.insert(entities[0]!, Hostile, {});+ world.insert(entities[1]!, Hostile, {});+ // Warm the cache, then switch: a query cache that does not depend on the+ // tag hands back the entity it already found.+ expect(world.getEntitiesWithComponents([Health], [Hostile])).toHaveLength(2);+ setEntityActive(world, entities[0]!, false);+ expect(world.getEntitiesWithComponents([Health], [Hostile])).toHaveLength(1);+ });++ it('is still a real entity — its components are readable', () => {+ const { world, entities } = worldWith(1);+ setEntityActive(world, entities[0]!, false);+ // Off is not gone: the scene still holds it, and switching it back on has+ // to find what it had. (Children is how the subtree walk reaches it.)+ expect(world.valid(entities[0]!)).toBe(true);+ expect((world.get(entities[0]!, Health) as { hp: number }).hp).toBe(10);+ expect(world.has(entities[0]!, Children)).toBe(false);+ });+});diff --git a/sdk/tests/entity-visibility.test.ts b/sdk/tests/entity-visibility.test.tsindex 1d7ad69e9..c2aa5fa3b 100644--- a/sdk/tests/entity-visibility.test.ts+++ b/sdk/tests/entity-visibility.test.ts@@ -17,6 +17,9 @@ describe('Entity visibility helpers', () => {const components = new Map<string, any>();const key = (comp: any) => comp._name ?? comp.name;return {+ // One entity, no tree: switching off walks the subtree, and an+ // entity with no Children is where that walk stops.+ valid: () => true,has: (_e: number, comp: any) => components.has(key(comp)),get: (_e: number, comp: any) => components.get(key(comp)),set: (_e: number, comp: any, data: any) => {diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjsindex 63065a030..c2833f4da 100644--- a/tools/check-corpus-authoring.mjs+++ b/tools/check-corpus-authoring.mjs@@ -125,7 +125,7 @@ const DISPOSITION = {ParticleForceField: ['owed', 'particle-demo adds force fields from code, and the field has a radius gizmo the Inspector already draws'],NavArea: ['owed', 'cost-modifying nav regions (mud, road) never appear; enemy-ai-3d authors NavVolume, NavLink and NavObstacle but no area'],Marker: ['owed', 'Create > Marker and Create > Trigger Area are one click each, and not one project places either — the converged target for .tmj object groups has no hand-authored instance'],- Disabled: ['owed', 'the engine can deactivate an entity and the editor has no switch for it (the Outliner eye toggles visibility, a different thing), so no scene ships one'],+ Disabled: ['owed', 'queries skip it now, but the editor still has no switch for it — the Outliner eye toggles visibility, which is a different thing — so no scene ships one'],Velocity: ['owed', 'motion without a physics body — the cheapest thing in the engine, authored nowhere'],};