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(engine): the eye hides a skeleton, because enabled is a field somebody reads
yhh65d6a39bea6e
diff --git a/.gitignore b/.gitignoreindex 3f3c97f71..8da2414f4 100644--- a/.gitignore+++ b/.gitignore@@ -125,6 +125,9 @@ docs/REARCH_*.md**/.esengine/play/**/.esengine/sdk/**/.esengine/editor/+# Crash-recovery snapshots (electron/autosave.ts): a copy of unsaved edits, so a+# committed one is somebody's interrupted session, never the scene of record.+**/.esengine/autosave/# Plugin API typings: written by the editor on project open, always matching the# running version. A committed copy would go stale against a different editor.**/.esengine/plugins/.types/diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex d162a6924..36cb46167 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -39,18 +39,40 @@ export type AnyComp = Parameters<WorldT['has']>[1];// plus UIController/UIGear, whose authoring surface is the Controllers panel and// the Details gear dots (their array-of-object data has no generic field control).const HIDDEN_COMPONENTS = new Set(['Parent', 'Children', 'Name', 'UIController', 'UIGear', 'EventBinding']);-// Components whose enable flag drives the entity's RENDER visibility (the Outliner-// eye + hidden state). Disabling a non-render component (physics, audio, a script)-// turns that behaviour off without hiding the entity. Light2D/ShadowCaster2D belong-// here too: a hidden entity must stop lighting and shadowing the scene, not just-// stop drawing its own pixels.-const RENDER_COMPONENTS = new Set([- 'Sprite', 'ShapeRenderer', 'SpineAnimation', 'BitmapText', 'TilemapLayer', 'ParticleEmitter',- 'UIVisual', 'Text', 'Light2D', 'ShadowCaster2D',-]);+// Which components the Outliner's eye reaches: hiding an entity forces the enable+// flag off on each of them (see Reconciler.foldHidden). Disabling a NON-render+// component (physics, audio, a script) turns that behaviour off without hiding+// anything, so those must stay out.+//+// The scene-space renderables are DERIVED, not listed: a component that names a+// sorting layer is a thing the renderer draws in scene order, which is exactly the+// set the eye has to reach. That derivation is what a hand-kept list kept getting+// wrong — DragonBonesAnimation, Mesh2D and TrailRenderer were all renderables the+// eye silently skipped, and every future one would have joined them.+const SORTING_LAYER_SOURCE = 'sortingLayers';+// The rest, which the registry gives no such marker for and so are named here:+// BitmapText — draws in a sorting layer, but its `layer` field predates the+// named-layer dropdown, so it carries no enumSource.+// UIVisual — UI draws in tree order, not a sorting layer.+// Text — same, and it has no enable flag of its own (a no-op fold, kept+// so adding one later doesn't quietly change what the eye covers).+// Light2D / ShadowCaster2D — not drawn, but a hidden entity must stop LIGHTING+// and shadowing the scene too, not just stop drawing its own pixels.+const EXTRA_RENDER_COMPONENTS = new Set(['BitmapText', 'UIVisual', 'Text', 'Light2D', 'ShadowCaster2D']);+const renderComponentCache = new Map<string, boolean>();+/** Whether a component's enable flag participates in the entity's render visibility. */export function isRenderComponent(name: string): boolean {- return RENDER_COMPONENTS.has(name);+ const cached = renderComponentCache.get(name);+ if (cached !== undefined) return cached;+ const def = registryDef(name);+ const meta = def ? getComponentFieldMeta(name) : {};+ const drawsInLayer = Object.values(meta).some((f) => f.enumSource === SORTING_LAYER_SOURCE);+ const result = drawsInLayer || EXTRA_RENDER_COMPONENTS.has(name);+ // A name the registry doesn't know yet (a project component registered later)+ // isn't memoised — its answer would be a guess made before it existed.+ if (def) renderComponentCache.set(name, result);+ return result;}// Computed world-space mirrors on Transform — never editable.const DERIVED_FIELDS = new Set(['worldPosition', 'worldRotation', 'worldScale']);diff --git a/desktop/tests/schema.test.ts b/desktop/tests/schema.test.tsindex 55aa6305d..e9dc92c33 100644--- a/desktop/tests/schema.test.ts+++ b/desktop/tests/schema.test.ts@@ -6,7 +6,7 @@* the JSON-first rewrite (REARCH_SERIALIZATION.md) will lean on.*/import { describe, it, expect } from 'vitest';-import { prettyLabel, hexToRgba, angleZToQuat, inferField, assetFieldType, spineSlotType } from '@/engine/schema';+import { prettyLabel, hexToRgba, angleZToQuat, inferField, assetFieldType, spineSlotType, isRenderComponent } from '@/engine/schema';describe('prettyLabel', () => {it('splits camelCase and capitalizes', () => {@@ -88,3 +88,30 @@ describe('spineSlotType', () => {expect(assetFieldType('SpineAnimation', 'material')).toBe('material');});});++describe('isRenderComponent', () => {+ // The eye's reach used to be a hand-kept list, and three renderables were+ // missing from it — so the set is derived from the engine schema (a component+ // that names a sorting layer is drawn) with only the unmarked ones listed.+ it('covers every component that names a sorting layer', () => {+ for (const name of [+ 'Sprite', 'ShapeRenderer', 'SpineAnimation', 'DragonBonesAnimation',+ 'TilemapLayer', 'ParticleEmitter', 'Mesh2D', 'TrailRenderer',+ ]) {+ expect(isRenderComponent(name), name).toBe(true);+ }+ });+ it('covers the ones the registry marks no layer on: UI text/visuals and lighting', () => {+ for (const name of ['BitmapText', 'UIVisual', 'Text', 'Light2D', 'ShadowCaster2D']) {+ expect(isRenderComponent(name), name).toBe(true);+ }+ });+ it('excludes behaviour components — disabling those is not hiding', () => {+ for (const name of [+ 'Transform', 'Camera', 'RigidBody', 'BoxCollider', 'CircleCollider',+ 'Interactable', 'UIScroll', 'UIMask', 'ParticleForceField', 'NotAComponent',+ ]) {+ expect(isRenderComponent(name), name).toBe(false);+ }+ });+});diff --git a/docs/astro/src/content/docs/guides/dragonbones.mdx b/docs/astro/src/content/docs/guides/dragonbones.mdxindex 1d530952f..c63b162d5 100644--- a/docs/astro/src/content/docs/guides/dragonbones.mdx+++ b/docs/astro/src/content/docs/guides/dragonbones.mdx@@ -137,6 +137,12 @@ const control = defineSystem(`playing: false` freezes the pose but keeps drawing it; `setEnabled(false)` takesthe armature out of the frame. They are different things and both are useful.+`setEnabled` and the component's own `enabled` field drive the same switch: writing+the field (in the inspector, or via `world.set`) wins at the moment it is written,+and `setEnabled` holds between such writes. The editor's Outliner eye rides the+same channel, which is why hiding a skeletal entity hides it in the viewport+without touching the `enabled` you authored.+## Query an armature```typescriptdiff --git a/docs/astro/src/content/docs/guides/spine.mdx b/docs/astro/src/content/docs/guides/spine.mdxindex 9d9cd9553..c26f9162c 100644--- a/docs/astro/src/content/docs/guides/spine.mdx+++ b/docs/astro/src/content/docs/guides/spine.mdx@@ -29,7 +29,7 @@ main `esengine` package.| `color` | Color | `{1,1,1,1}` | Tint (RGBA, 0..1). || `layer` | number | `0` | Sorting layer for draw order. || `material` | asset | none | Optional custom material. |-| `enabled` | boolean | `true` | Disable to freeze and hide. |+| `enabled` | boolean | `true` | Disable to freeze and hide (the same switch `Spine.setEnabled` throws; the Outliner eye rides it too). |**Skeleton and atlas are asset slots** in the Details panel: pick from the popover,drag a file in from the Content Browser, or use the slot's locate / clear actions.diff --git a/docs/astro/src/content/docs/zh-cn/guides/dragonbones.mdx b/docs/astro/src/content/docs/zh-cn/guides/dragonbones.mdxindex 47aeb130e..35afbffd3 100644--- a/docs/astro/src/content/docs/zh-cn/guides/dragonbones.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/dragonbones.mdx@@ -121,6 +121,10 @@ const control = defineSystem(`playing: false` 是冻住姿势但继续画;`setEnabled(false)` 是把骨架从这一帧里拿掉。这是两件事,而且两个都有用。+`setEnabled` 和组件自身的 `enabled` 字段驱动的是同一个开关:写字段(在检视器里,或+`world.set`)在写下的那一刻生效,两次写之间由 `setEnabled` 说话。编辑器世界大纲里的眼睛+走的也是这条通道——所以隐藏一个骨架实体会在视口里真的隐藏,而不会动你写好的 `enabled`。+## 查询骨架```typescriptdiff --git a/docs/astro/src/content/docs/zh-cn/guides/spine.mdx b/docs/astro/src/content/docs/zh-cn/guides/spine.mdxindex c4dff43bc..23646bc5b 100644--- a/docs/astro/src/content/docs/zh-cn/guides/spine.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/spine.mdx@@ -27,7 +27,7 @@ Estella 内置 [Spine](https://esotericsoftware.com/) 骨骼动画:骨骼、网| `color` | Color | `{1,1,1,1}` | 着色(RGBA,0..1)。 || `layer` | number | `0` | 决定绘制顺序的排序层。 || `material` | asset | 无 | 可选的自定义材质。 |-| `enabled` | boolean | `true` | 关掉即冻结并隐藏。 |+| `enabled` | boolean | `true` | 关掉即冻结并隐藏(与 `Spine.setEnabled` 是同一个开关;世界大纲的眼睛也走这条通道)。 |**骨骼与图集是 Details 面板里的资产槽位**:从弹出选择器里挑,从内容浏览器拖进来,或用槽位的定位 / 清除操作。场景把它们序列化为可移植的 `@uuid:` 引用,移动或重命名diff --git a/sdk/etc/dragonbones.api.md b/sdk/etc/dragonbones.api.mdindex ef0b599cb..34901f545 100644--- a/sdk/etc/dragonbones.api.md+++ b/sdk/etc/dragonbones.api.md@@ -36,6 +36,7 @@ skeletonScale: number | undefined## DragonBonesManager — class```addEntity: (entity: Entity, skeletonHandle: number, options: DragonBonesEntityOptions) => boolean+boundEntities: () => Iterable<Entity>controller: DragonBonesModuleControllerdispose: () => voidfadeIn: (entity: Entity, animation: string, fadeSeconds: number, loop?: boolean) => booleandiff --git a/sdk/etc/spine.api.md b/sdk/etc/spine.api.mdindex e869ba470..83fef0853 100644--- a/sdk/etc/spine.api.md+++ b/sdk/etc/spine.api.md@@ -101,6 +101,7 @@ events: readonly SpineEvent[]## SpineManager — class```+boundEntities: () => Iterable<Entity>collectAllEvents: () => { entity: Entity; raw: RawSpineEvent; }[]dispose: () => voidenableEvents: (entity: Entity) => voiddiff --git a/sdk/src/dragonbones/DragonBonesManager.ts b/sdk/src/dragonbones/DragonBonesManager.tsindex f1cde0d46..2bdb2412a 100644--- a/sdk/src/dragonbones/DragonBonesManager.ts+++ b/sdk/src/dragonbones/DragonBonesManager.ts@@ -139,7 +139,19 @@ export class DragonBonesManager {return this.entities_.has(entity);}- /** A disabled entity keeps its instance but stops advancing and drawing. */+ /** The entities that currently have an armature bound — what a per-frame pass+ * over "everything DragonBones draws" iterates, without asking the World. */+ boundEntities(): Iterable<Entity> {+ return this.entities_.keys();+ }++ /**+ * A disabled entity keeps its instance but stops advancing and drawing.+ *+ * Also driven by `DragonBonesAnimation.enabled` — the plugin carries that field+ * across on its edges (skeletal/enableSync), so writing the component wins at+ * the moment it is written and this call holds between such writes.+ */setEnabled(entity: Entity, enabled: boolean): void {if (enabled) this.disabled_.delete(entity);else this.disabled_.add(entity);diff --git a/sdk/src/dragonbones/DragonBonesPlugin.ts b/sdk/src/dragonbones/DragonBonesPlugin.tsindex 93bf454c4..c225f651f 100644--- a/sdk/src/dragonbones/DragonBonesPlugin.ts+++ b/sdk/src/dragonbones/DragonBonesPlugin.ts@@ -16,6 +16,8 @@ import type { SystemDef } from '../ecs/system';import type { Entity } from '../types';import { defineResource, Time } from '../ecs/resource';import { engineApi } from '../ecs/bridge/engineApi';+import { DragonBonesAnimation } from '../ecs/component';+import { SkeletalEnableMirror } from '../skeletal/enableSync';import { DragonBonesManager } from './DragonBonesManager';import { DragonBonesModuleController } from './DragonBonesController';import { wrapDragonBonesModule, type DragonBonesWasmModule } from './DragonBonesModuleLoader';@@ -31,6 +33,8 @@ export class DragonBonesPlugin implements Plugin {private despawnUnsub_: (() => void) | null = null;private acquiring_: Promise<DragonBonesManager | null> | null = null;private submitWired_ = false;+ /** Carries DragonBonesAnimation.enabled into the manager (skeletal/enableSync). */+ private readonly enableMirror_ = new SkeletalEnableMirror(DragonBonesAnimation);/** Pass a manager for headless use or tests; otherwise it is built on demand. */constructor(manager?: DragonBonesManager) {@@ -98,13 +102,19 @@ export class DragonBonesPlugin implements Plugin {});}+ // Carries DragonBonesAnimation.enabled across before advancing — the flag+ // lives on the component, and nothing else reads it into the manager+ // (see skeletal/enableSync).const updateSystem: SystemDef = {_id: Symbol('DragonBonesUpdateSystem'),_name: 'DragonBonesUpdateSystem',_params: [],_fn: () => {const time = app.getResource(Time);- this.manager_?.updateAnimations(time?.delta ?? 0);+ const manager = this.manager_;+ if (!manager) return;+ this.enableMirror_.sync(app.world, manager);+ manager.updateAnimations(time?.delta ?? 0);},};// PreUpdate, like Spine: poses have to be current before anything thatdiff --git a/sdk/src/dragonbones/loadDragonBonesScene.ts b/sdk/src/dragonbones/loadDragonBonesScene.tsindex 49ec51140..d9d94815b 100644--- a/sdk/src/dragonbones/loadDragonBonesScene.ts+++ b/sdk/src/dragonbones/loadDragonBonesScene.ts@@ -235,7 +235,6 @@ export function applyDragonBonesEntities(opts: {if (!added) continue;manager.setEntityProps(entity, props);- if (data.enabled === false) manager.setEnabled(entity, false);const animation = typeof data.animation === 'string' ? data.animation : '';if (animation) {diff --git a/sdk/src/skeletal/enableSync.ts b/sdk/src/skeletal/enableSync.tsnew file mode 100644index 000000000..27ea8f635--- /dev/null+++ b/sdk/src/skeletal/enableSync.ts@@ -0,0 +1,84 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file skeletal/enableSync.ts+ * @brief Making a skeletal component's `enabled` field mean what it says.+ *+ * @details Every other renderable is drawn straight from its component, so+ * clearing `enabled` stops it: the renderer walks the World and the flag+ * is right there. A skeleton is not. Its instance lives in a side+ * module's heap, keyed by entity in a manager the renderer knows nothing+ * about, and the manager submits from ITS table — so the World's copy of+ * the flag was read by nobody. The editor's eye toggle, the inspector's+ * checkbox and a gameplay `world.set(e, SpineAnimation, {enabled:false})`+ * all wrote a value that changed nothing.+ *+ * This is the one place that closes the loop, and it closes it for both+ * runtimes: once a frame, each bound entity's flag is carried from the+ * World into the manager that draws it.+ *+ * EDGE-TRIGGERED, deliberately. A flag has two writers — the component+ * (authoring, editor visibility, gameplay writes) and the manager's own+ * `setEnabled` (the imperative API) — and a mirror that pushed every+ * frame would make the second one useless, undoing it on the next tick.+ * Pushing only when the component's value actually MOVES leaves both+ * honest: writing the field wins at the moment it is written, and+ * between writes the imperative switch is free to override. It also+ * means an entity whose binding lands after the field was written still+ * picks it up (the first sync it appears in has nothing memoised for it),+ * so no writer of the field needs to know when a skeleton finished+ * loading.+ */+import type { Entity } from '../types';+import type { AnyComponentDef, ComponentData } from '../ecs/component';++/** The slice of the World this reads: one component's data, or null if absent. */+export interface SkeletalEnableWorld {+ tryGet<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> | null;+}++/** A skeletal runtime's manager, seen as "which entities it holds, and the switch". */+export interface SkeletalEnableTarget {+ /** The entities this manager currently has an instance for. */+ boundEntities(): Iterable<Entity>;+ /** Take an entity out of / put it back into the frame. */+ setEnabled(entity: Entity, enabled: boolean): void;+}++/**+ * Carries `<component>.enabled` from the World into one skeletal manager, on the+ * edges of that field. Hold one per manager (the memo of what it last pushed is+ * what makes it edge-triggered) and call {@link sync} once per frame, before the+ * manager advances and submits.+ */+export class SkeletalEnableMirror {+ /** entity → the flag value this mirror last pushed for it. */+ private readonly mirrored_ = new Map<Entity, boolean>();++ constructor(private readonly component_: AnyComponentDef) {}++ sync(world: SkeletalEnableWorld, target: SkeletalEnableTarget): void {+ let bound = 0;+ for (const entity of target.boundEntities()) {+ bound++;+ const data = world.tryGet(entity, this.component_) as { enabled?: boolean } | null;+ // No component (an entity bound by something other than a scene —+ // a test, a tool) has no flag to obey, so it is left alone.+ if (!data) continue;+ const enabled = data.enabled !== false;+ if (this.mirrored_.get(entity) === enabled) continue;+ this.mirrored_.set(entity, enabled);+ target.setEnabled(entity, enabled);+ }+ // Entities have unbound (a despawn, a scene reload) — drop their memos, or+ // a long editor session accumulates one entry per skeleton it ever showed.+ if (this.mirrored_.size > bound) this.prune_(target);+ }++ private prune_(target: SkeletalEnableTarget): void {+ const live = new Set(target.boundEntities());+ for (const entity of this.mirrored_.keys()) {+ if (!live.has(entity)) this.mirrored_.delete(entity);+ }+ }+}diff --git a/sdk/src/skeletal/index.ts b/sdk/src/skeletal/index.tsindex 07b0775d1..07d24a996 100644--- a/sdk/src/skeletal/index.ts+++ b/sdk/src/skeletal/index.ts@@ -3,3 +3,5 @@export { forEachMeshBatch } from './meshBatches';export type { MeshBatchSource, MeshBatchVisitor, SkeletalHeap } from './meshBatches';export type { SkeletalBounds, SkeletalController } from './types';+export { SkeletalEnableMirror } from './enableSync';+export type { SkeletalEnableTarget, SkeletalEnableWorld } from './enableSync';diff --git a/sdk/src/spine/ModuleBackend.ts b/sdk/src/spine/ModuleBackend.tsindex b2a9b6549..bbd390c3c 100644--- a/sdk/src/spine/ModuleBackend.ts+++ b/sdk/src/spine/ModuleBackend.ts@@ -224,7 +224,10 @@ export class ModuleBackend {}updateAll(dt: number): void {- for (const info of this.entities_.values()) {+ for (const [entity, info] of this.entities_) {+ // Disabled means out of the frame entirely, so it costs no posing+ // either — the same meaning the DragonBones manager gives it.+ if (this.disabledEntities_.has(entity)) continue;// playing=false freezes the pose (skip advance, still submitted);// timeScale scales the advance (update() takes an arbitrary dt).if (info.playing) this.controller_.update(info.instanceId, dt * info.timeScale);diff --git a/sdk/src/spine/SpineManager.ts b/sdk/src/spine/SpineManager.tsindex cae1e0a2d..b3fbee20c 100644--- a/sdk/src/spine/SpineManager.ts+++ b/sdk/src/spine/SpineManager.ts@@ -107,6 +107,12 @@ export class SpineManager {}}+ /** The entities that currently have a skeleton bound — what a per-frame pass+ * over "everything spine draws" iterates, without asking the World. */+ boundEntities(): Iterable<Entity> {+ return this.entityVersions_.keys();+ }+removeEntity(entity: Entity): void {const version = this.entityVersions_.get(entity);if (!version) {@@ -258,6 +264,15 @@ export class SpineManager {return false;}+ /**+ * Take an entity out of the frame, or put it back: a disabled entity keeps its+ * instance but stops posing and drawing. Distinct from `playing: false`, which+ * freezes the pose and keeps showing it.+ *+ * Also driven by `SpineAnimation.enabled` — the plugin carries that field+ * across on its edges (skeletal/enableSync), so writing the component wins at+ * the moment it is written and this call holds between such writes.+ */setEnabled(entity: Entity, enabled: boolean): void {const backend = this.getEntityBackend_(entity);if (backend) backend.setEnabled(entity, enabled);diff --git a/sdk/src/spine/SpinePlugin.ts b/sdk/src/spine/SpinePlugin.tsindex c29a43d82..089f06278 100644--- a/sdk/src/spine/SpinePlugin.ts+++ b/sdk/src/spine/SpinePlugin.ts@@ -11,6 +11,8 @@ import type { SpineModuleFactory, SpineWasmModule } from './SpineModuleLoader';import { SPINE_VERSIONS, spineModuleId } from '../sideModules';import { engineApi } from '../ecs/bridge/engineApi';import { AnimatorController } from '../animation/Animator';+import { SpineAnimation } from '../ecs/component';+import { SkeletalEnableMirror } from '../skeletal/enableSync';export type SpineEventType = 'start' | 'interrupt' | 'end' | 'complete' | 'event';@@ -57,6 +59,8 @@ export class SpinePlugin implements Plugin {private app_: App | null = null;private despawnUnsub_: (() => void) | null = null;private submitWired_ = false;+ /** Carries SpineAnimation.enabled into the manager (see skeletal/enableSync). */+ private readonly enableMirror_ = new SkeletalEnableMirror(SpineAnimation);/** Pass an explicit manager for headless/tests; otherwise the plugin builds* one in {@link build} from the app's {@link App.sideModules} host (the realm@@ -119,16 +123,21 @@ export class SpinePlugin implements Plugin {this.spineManager_?.removeEntity(entity);});- // Per-frame spine tick: advance every loaded side-module backend (one- // per version) and publish their events. Each backend advances only its- // own entities; there is no native runtime to tick.+ // Per-frame spine tick: carry SpineAnimation.enabled across into the+ // manager (see skeletal/enableSync), advance every loaded side-module+ // backend (one per version), and publish their events. Each backend+ // advances only its own entities; there is no native runtime to tick.const spineUpdateSystem: SystemDef = {_id: Symbol('SpineUpdateSystem'),_name: 'SpineUpdateSystem',_params: [],_fn: () => {const time = app.getResource(Time);- this.spineManager_?.updateAnimations(time.delta);+ const manager = this.spineManager_;+ if (manager) {+ this.enableMirror_.sync(app.world, manager);+ manager.updateAnimations(time.delta);+ }this.collectAndPublishEvents_(app);},};diff --git a/sdk/tests/skeletal-enable-sync.test.ts b/sdk/tests/skeletal-enable-sync.test.tsnew file mode 100644index 000000000..b2712683e--- /dev/null+++ b/sdk/tests/skeletal-enable-sync.test.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The seam that makes a skeletal component's `enabled` field mean+ * something: skeletons live in a side module's table, not in the render+ * walk, so the flag has to be carried across. What matters here is that+ * it is carried on the field's EDGES — a mirror that pushed every frame+ * would silently undo the imperative `setEnabled` API next tick.+ */+import { describe, it, expect } from 'vitest';+import { SkeletalEnableMirror } from '../src/skeletal/enableSync';+import { SpineAnimation } from '../src/ecs/component';+import type { AnyComponentDef } from '../src/ecs/component';+import type { Entity } from '../src/types';++/** A World that holds one component's data per entity, and nothing else. */+function fakeWorld(data: Map<number, { enabled?: boolean } | null>) {+ return {+ tryGet<C extends AnyComponentDef>(entity: Entity, _c: C) {+ return (data.get(entity as number) ?? null) as never;+ },+ };+}++/** A manager that records every setEnabled it is told. */+function fakeManager(entities: number[]) {+ const bound = new Set(entities);+ const pushed: Array<[number, boolean]> = [];+ return {+ bound,+ pushed,+ boundEntities: () => bound as unknown as Iterable<Entity>,+ setEnabled: (e: Entity, on: boolean) => { pushed.push([e as number, on]); },+ };+}++describe('SkeletalEnableMirror', () => {+ it('pushes the field on the first sync an entity appears in', () => {+ const m = new SkeletalEnableMirror(SpineAnimation);+ const mgr = fakeManager([1, 2]);+ m.sync(fakeWorld(new Map([[1, { enabled: false }], [2, { enabled: true }]])), mgr);+ expect(mgr.pushed).toEqual([[1, false], [2, true]]);+ });++ it('treats a missing flag as enabled, and skips entities with no component', () => {+ const m = new SkeletalEnableMirror(SpineAnimation);+ const mgr = fakeManager([1, 2]);+ m.sync(fakeWorld(new Map([[1, {}], [2, null]])), mgr);+ expect(mgr.pushed).toEqual([[1, true]]);+ });++ it('pushes nothing while the field holds still', () => {+ const m = new SkeletalEnableMirror(SpineAnimation);+ const mgr = fakeManager([1]);+ const world = fakeWorld(new Map([[1, { enabled: true }]]));+ m.sync(world, mgr);+ m.sync(world, mgr);+ m.sync(world, mgr);+ expect(mgr.pushed).toEqual([[1, true]]);+ });++ it('pushes on every edge the field moves through', () => {+ const m = new SkeletalEnableMirror(SpineAnimation);+ const mgr = fakeManager([1]);+ const data = new Map<number, { enabled?: boolean }>([[1, { enabled: true }]]);+ const world = fakeWorld(data);+ m.sync(world, mgr);+ data.set(1, { enabled: false }); // the editor's eye / an inspector write+ m.sync(world, mgr);+ data.set(1, { enabled: true });+ m.sync(world, mgr);+ expect(mgr.pushed).toEqual([[1, true], [1, false], [1, true]]);+ });++ it('leaves an imperative setEnabled standing — the whole point of edge-triggering', () => {+ const m = new SkeletalEnableMirror(SpineAnimation);+ const mgr = fakeManager([1]);+ const world = fakeWorld(new Map([[1, { enabled: true }]]));+ m.sync(world, mgr);+ mgr.pushed.length = 0;+ // Gameplay calls Spine.setEnabled(e, false); the component still says true.+ // A per-frame mirror would flip it back on the next tick.+ m.sync(world, mgr);+ m.sync(world, mgr);+ expect(mgr.pushed).toEqual([]);+ });++ it('forgets an entity that unbound, so a rebound one is pushed again', () => {+ const m = new SkeletalEnableMirror(SpineAnimation);+ const mgr = fakeManager([1]);+ const world = fakeWorld(new Map([[1, { enabled: false }]]));+ m.sync(world, mgr);+ mgr.bound.delete(1);+ m.sync(world, mgr); // prunes the memo+ mgr.bound.add(1);+ mgr.pushed.length = 0;+ m.sync(world, mgr);+ expect(mgr.pushed).toEqual([[1, false]]);+ });+});