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(sdk): a live entity can say which document row it came from
yhhd200b5f7017e
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 1081ef42e..c369d2c7d 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 112,"beta": 60,- "experimental": 1486,+ "experimental": 1496,"deprecated": 3},- "total": 1658,+ "total": 1668,"subsystems": [{"id": "ecs",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 0b5c6410b..65212aa51 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1371 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1381 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2665,6 +2665,20 @@ NativeEngineApi & Partial<NativeHeap>number```+## EntityBox — interface @experimental+```+cx: number+cy: number+hh: number+hw: number+rot: number+```++## EntityBoxOptions — interface @experimental+```+iconHalf: number | undefined+```+## EntityCommands — class @public```childOf: (parent: Entity) => EntityCommands@@ -5651,6 +5665,11 @@ ReadonlySet<string>position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined```+## ReadableWorld — type @experimental+```+Pick<World, 'valid' | 'has' | 'get'>+```+## ReadonlySignal — interface @experimental```get: () => T@@ -6264,6 +6283,11 @@ migrated: booleantoVersion: number```+## SceneOrigins — const @experimental+```+ResourceDef<Map<number, number>>+```+## SceneOwner — const @experimental```ComponentDef<SceneOwnerData>@@ -9456,6 +9480,11 @@ DragPlugin(): FsmDefinition```+## enableSceneOrigins — function @experimental+```+(app: App): void+```+## encodeTile — function @experimental```(id: number, flags?: TileFlags): number@@ -9471,6 +9500,16 @@ DragPlugin(scope: AnimatorScope, name: string): string[]```+## entityBoxCorners — function @experimental+```+(b: EntityBox): Array<{ x: number; y: number; }>+```++## entityWorldBox — function @experimental+```+(world: ReadableWorld, entity: Entity, opts?: EntityBoxOptions): EntityBox | null+```+## enumOptions — function @experimental```(obj: Record<string, unknown>, only?: readonly string[]): ReadonlyArray<{ label: string; value: number; }>@@ -10511,6 +10550,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## recordSceneOrigins — function @experimental+```+(app: App, entityMap: ReadonlyMap<number, Entity>): void+```+## recoverDevice — function @experimental```(): boolean@@ -10771,6 +10815,16 @@ SafeAreaPluginPlugin```+## sceneOriginOf — function @experimental+```+(app: App, entity: Entity): number | undefined+```++## sceneOriginsEnabled — function @experimental+```+(app: App): boolean+```+## sceneUsesI18n — function @experimental```(sceneData: SceneData): booleandiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 85098ec17..cbab95820 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 58 beta · 1390 experimental · 3 deprecated+Symbols: 112 public · 58 beta · 1400 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -2673,6 +2673,20 @@ NativeEngineApi & Partial<NativeHeap>number```+## EntityBox — interface @experimental+```+cx: number+cy: number+hh: number+hw: number+rot: number+```++## EntityBoxOptions — interface @experimental+```+iconHalf: number | undefined+```+## EntityCommands — class @public```childOf: (parent: Entity) => EntityCommands@@ -5844,6 +5858,11 @@ ReadonlySet<string>position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined```+## ReadableWorld — type @experimental+```+Pick<World, 'valid' | 'has' | 'get'>+```+## ReadonlySignal — interface @experimental```get: () => T@@ -6457,6 +6476,11 @@ migrated: booleantoVersion: number```+## SceneOrigins — const @experimental+```+ResourceDef<Map<number, number>>+```+## SceneOwner — const @experimental```ComponentDef<SceneOwnerData>@@ -9689,6 +9713,11 @@ DragPlugin(): FsmDefinition```+## enableSceneOrigins — function @experimental+```+(app: App): void+```+## encodeTile — function @experimental```(id: number, flags?: TileFlags): number@@ -9704,6 +9733,16 @@ DragPlugin(scope: AnimatorScope, name: string): string[]```+## entityBoxCorners — function @experimental+```+(b: EntityBox): Array<{ x: number; y: number; }>+```++## entityWorldBox — function @experimental+```+(world: ReadableWorld, entity: Entity, opts?: EntityBoxOptions): EntityBox | null+```+## enumOptions — function @experimental```(obj: Record<string, unknown>, only?: readonly string[]): ReadonlyArray<{ label: string; value: number; }>@@ -10754,6 +10793,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## recordSceneOrigins — function @experimental+```+(app: App, entityMap: ReadonlyMap<number, Entity>): void+```+## recoverDevice — function @experimental```(): boolean@@ -11014,6 +11058,16 @@ SafeAreaPluginPlugin```+## sceneOriginOf — function @experimental+```+(app: App, entity: Entity): number | undefined+```++## sceneOriginsEnabled — function @experimental+```+(app: App): boolean+```+## sceneUsesI18n — function @experimental```(sceneData: SceneData): booleandiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 1d1085616..1d7094fb3 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 55 beta · 1370 experimental · 3 deprecated+Symbols: 112 public · 55 beta · 1380 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2660,6 +2660,20 @@ NativeEngineApi & Partial<NativeHeap>number```+## EntityBox — interface @experimental+```+cx: number+cy: number+hh: number+hw: number+rot: number+```++## EntityBoxOptions — interface @experimental+```+iconHalf: number | undefined+```+## EntityCommands — class @public```childOf: (parent: Entity) => EntityCommands@@ -5646,6 +5660,11 @@ ReadonlySet<string>position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined```+## ReadableWorld — type @experimental+```+Pick<World, 'valid' | 'has' | 'get'>+```+## ReadonlySignal — interface @experimental```get: () => T@@ -6259,6 +6278,11 @@ migrated: booleantoVersion: number```+## SceneOrigins — const @experimental+```+ResourceDef<Map<number, number>>+```+## SceneOwner — const @experimental```ComponentDef<SceneOwnerData>@@ -9451,6 +9475,11 @@ DragPlugin(): FsmDefinition```+## enableSceneOrigins — function @experimental+```+(app: App): void+```+## encodeTile — function @experimental```(id: number, flags?: TileFlags): number@@ -9466,6 +9495,16 @@ DragPlugin(scope: AnimatorScope, name: string): string[]```+## entityBoxCorners — function @experimental+```+(b: EntityBox): Array<{ x: number; y: number; }>+```++## entityWorldBox — function @experimental+```+(world: ReadableWorld, entity: Entity, opts?: EntityBoxOptions): EntityBox | null+```+## enumOptions — function @experimental```(obj: Record<string, unknown>, only?: readonly string[]): ReadonlyArray<{ label: string; value: number; }>@@ -10516,6 +10555,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## recordSceneOrigins — function @experimental+```+(app: App, entityMap: ReadonlyMap<number, Entity>): void+```+## recoverDevice — function @experimental```(): boolean@@ -10776,6 +10820,16 @@ SafeAreaPluginPlugin```+## sceneOriginOf — function @experimental+```+(app: App, entity: Entity): number | undefined+```++## sceneOriginsEnabled — function @experimental+```+(app: App): boolean+```+## sceneUsesI18n — function @experimental```(sceneData: SceneData): booleandiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex cbb5acb1b..d4bba907c 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1391 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1401 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2660,6 +2660,20 @@ NativeEngineApi & Partial<NativeHeap>number```+## EntityBox — interface @experimental+```+cx: number+cy: number+hh: number+hw: number+rot: number+```++## EntityBoxOptions — interface @experimental+```+iconHalf: number | undefined+```+## EntityCommands — class @public```childOf: (parent: Entity) => EntityCommands@@ -5891,6 +5905,11 @@ ReadonlySet<string>position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined```+## ReadableWorld — type @experimental+```+Pick<World, 'valid' | 'has' | 'get'>+```+## ReadonlySignal — interface @experimental```get: () => T@@ -6504,6 +6523,11 @@ migrated: booleantoVersion: number```+## SceneOrigins — const @experimental+```+ResourceDef<Map<number, number>>+```+## SceneOwner — const @experimental```ComponentDef<SceneOwnerData>@@ -9701,6 +9725,11 @@ DragPlugin(): FsmDefinition```+## enableSceneOrigins — function @experimental+```+(app: App): void+```+## encodeTile — function @experimental```(id: number, flags?: TileFlags): number@@ -9716,6 +9745,16 @@ DragPlugin(scope: AnimatorScope, name: string): string[]```+## entityBoxCorners — function @experimental+```+(b: EntityBox): Array<{ x: number; y: number; }>+```++## entityWorldBox — function @experimental+```+(world: ReadableWorld, entity: Entity, opts?: EntityBoxOptions): EntityBox | null+```+## enumOptions — function @experimental```(obj: Record<string, unknown>, only?: readonly string[]): ReadonlyArray<{ label: string; value: number; }>@@ -10766,6 +10805,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## recordSceneOrigins — function @experimental+```+(app: App, entityMap: ReadonlyMap<number, Entity>): void+```+## recoverDevice — function @experimental```(): boolean@@ -11026,6 +11070,16 @@ SafeAreaPluginPlugin```+## sceneOriginOf — function @experimental+```+(app: App, entity: Entity): number | undefined+```++## sceneOriginsEnabled — function @experimental+```+(app: App): boolean+```+## sceneUsesI18n — function @experimental```(sceneData: SceneData): booleandiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 11b4fe874..6c284db7d 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 112 public · 53 beta · 1381 experimental · 3 deprecated+Symbols: 112 public · 53 beta · 1391 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -2660,6 +2660,20 @@ NativeEngineApi & Partial<NativeHeap>number```+## EntityBox — interface @experimental+```+cx: number+cy: number+hh: number+hw: number+rot: number+```++## EntityBoxOptions — interface @experimental+```+iconHalf: number | undefined+```+## EntityCommands — class @public```childOf: (parent: Entity) => EntityCommands@@ -5653,6 +5667,11 @@ ReadonlySet<string>position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined```+## ReadableWorld — type @experimental+```+Pick<World, 'valid' | 'has' | 'get'>+```+## ReadonlySignal — interface @experimental```get: () => T@@ -6266,6 +6285,11 @@ migrated: booleantoVersion: number```+## SceneOrigins — const @experimental+```+ResourceDef<Map<number, number>>+```+## SceneOwner — const @experimental```ComponentDef<SceneOwnerData>@@ -9478,6 +9502,11 @@ DragPlugin(): FsmDefinition```+## enableSceneOrigins — function @experimental+```+(app: App): void+```+## encodeTile — function @experimental```(id: number, flags?: TileFlags): number@@ -9493,6 +9522,16 @@ DragPlugin(scope: AnimatorScope, name: string): string[]```+## entityBoxCorners — function @experimental+```+(b: EntityBox): Array<{ x: number; y: number; }>+```++## entityWorldBox — function @experimental+```+(world: ReadableWorld, entity: Entity, opts?: EntityBoxOptions): EntityBox | null+```+## enumOptions — function @experimental```(obj: Record<string, unknown>, only?: readonly string[]): ReadonlyArray<{ label: string; value: number; }>@@ -10538,6 +10577,11 @@ PrefabsPlugin(entities: ProcessedEntity[]): void```+## recordSceneOrigins — function @experimental+```+(app: App, entityMap: ReadonlyMap<number, Entity>): void+```+## recoverDevice — function @experimental```(): boolean@@ -10798,6 +10842,16 @@ SafeAreaPluginPlugin```+## sceneOriginOf — function @experimental+```+(app: App, entity: Entity): number | undefined+```++## sceneOriginsEnabled — function @experimental+```+(app: App): boolean+```+## sceneUsesI18n — function @experimental```(sceneData: SceneData): booleandiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 30e4e1641..e648554ce 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -172,6 +172,14 @@ export {export { sceneManagerPlugin } from './scene/scenePlugin';+export {+ SceneOrigins,+ enableSceneOrigins,+ sceneOriginsEnabled,+ recordSceneOrigins,+ sceneOriginOf,+} from './scene/sceneOrigins';+export {transitionTo,type TransitionConfig,diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex a0ffc0abe..b4ab3a670 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -60,6 +60,8 @@ export {// =============================================================================export { setEntityVisible, isEntityVisible, hasVisibility, setEntityActive, isEntityActive } from './ecs/entityUtils';++export { entityWorldBox, entityBoxCorners, type EntityBox, type EntityBoxOptions, type ReadableWorld } from './ecs/entityBox';export { CacheBitmap, type BitmapCache } from './render/cacheBitmap';export {CacheAsBitmap,diff --git a/sdk/src/ecs/entityBox.ts b/sdk/src/ecs/entityBox.tsnew file mode 100644index 000000000..fd7863d92--- /dev/null+++ b/sdk/src/ecs/entityBox.ts@@ -0,0 +1,109 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file entityBox.ts+ * @brief How much room an entity takes up in the world, and where.+ *+ * The box an editor outlines, hit-tests and drags is the box the renderer+ * draws, so both have to be derived from one description of it. Two of them+ * agree until a pivot or a parent scale is involved, and then a selection+ * outline sits beside the sprite it claims to be around.+ */+import type { Entity } from '../types';+import type { World } from './world';+import { Transform, Sprite } from './component';+import { UINode } from '../ui/core/ui-node';+import { quaternionToAngle2D } from '../ui/util/math';++/**+ * The three reads a box derivation needs — so an editor's read-only projection+ * of a World satisfies it without being handed the mutators.+ *+ * @experimental+ */+export type ReadableWorld = Pick<World, 'valid' | 'has' | 'get'>;++/**+ * An oriented box in world units: centre, half-extents, and rotation in radians.+ *+ * @experimental+ */+export interface EntityBox {+ cx: number;+ cy: number;+ hw: number;+ hh: number;+ rot: number;+}++/** @experimental */+export interface EntityBoxOptions {+ /**+ * World half-size for an entity that draws nothing of its own — a camera, a+ * light, an empty. Zero (the default) reports no box for those; an editor+ * that wants them clickable passes the size of the icon it drew.+ */+ iconHalf?: number;+}++/**+ * The world box of `entity`, or null when it has none.+ *+ * Size scaled by the WORLD scale, centred by the pivot, turned by the world+ * rotation — the three fields the renderer composes. UI nodes get null: they+ * live in the layout's own screen space and are hit-tested there.+ *+ * @experimental+ */+export function entityWorldBox(world: ReadableWorld, entity: Entity, opts?: EntityBoxOptions): EntityBox | null {+ if (!world.valid(entity) || !world.has(entity, Transform)) return null;+ if (world.has(entity, UINode)) return null;++ const t = world.get(entity, Transform);+ const r = t.worldRotation as { z: number; w: number };+ const rot = quaternionToAngle2D(r.z, r.w);++ const iconHalf = opts?.iconHalf ?? 0;+ let w = iconHalf * 2;+ let h = iconHalf * 2;+ let px = 0.5;+ let py = 0.5;+ if (world.has(entity, Sprite)) {+ const sp = world.get(entity, Sprite);+ w = sp.size.x * t.worldScale.x;+ h = sp.size.y * t.worldScale.y;+ px = sp.pivot?.x ?? 0.5;+ py = sp.pivot?.y ?? 0.5;+ } else if (iconHalf === 0) {+ return null;+ }++ // The centre orbits the transform position when the pivot is off-centre —+ // the position is what rotation turns around, not the middle of the sprite.+ const ox = w * (0.5 - px);+ const oy = h * (0.5 - py);+ const c = Math.cos(rot);+ const s = Math.sin(rot);+ return {+ cx: t.worldPosition.x + ox * c - oy * s,+ cy: t.worldPosition.y + ox * s + oy * c,+ hw: Math.abs(w) / 2,+ hh: Math.abs(h) / 2,+ rot,+ };+}++/**+ * The box's four corners in world units, counter-clockwise from its local+ * -x,-y — what an outline is drawn through.+ *+ * @experimental+ */+export function entityBoxCorners(b: EntityBox): Array<{ x: number; y: number }> {+ const c = Math.cos(b.rot);+ const s = Math.sin(b.rot);+ return ([[-b.hw, -b.hh], [b.hw, -b.hh], [b.hw, b.hh], [-b.hw, b.hh]] as const).map(([lx, ly]) => ({+ x: b.cx + lx * c - ly * s,+ y: b.cy + lx * s + ly * c,+ }));+}diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex b1687ad0b..25c9b6cd9 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -7,6 +7,7 @@import { SceneOwner } from '../ecs/component';import { loadSceneData, updateCameraAspectRatio, sceneHasPrefabEntries, expandScenePrefabs, type SceneData } from '../scene/scene';+import { recordSceneOrigins } from '../scene/sceneOrigins';import type { PrefabData } from '../prefab/types';import { switchTheme, resolveThemeTokens, type ThemeOverrides } from '../ui';import { discoverSceneAssets } from '../asset/discoverAssets';@@ -406,6 +407,9 @@ export async function loadRuntimeScene(options: LoadRuntimeSceneOptions): Promis}const entityMap = loadSceneData(app.world, sceneData);+ // Which document row each entity came from, when someone is keeping track+ // (an editor inspecting its own running game). No-op otherwise.+ recordSceneOrigins(app, entityMap);// Apply the project theme over the freshly instantiated scene: prefabs bake// the default dark palette, so a light base or any token override re-resolvesdiff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.tsindex b3fbed088..d608bc8d2 100644--- a/sdk/src/scene/sceneManager.ts+++ b/sdk/src/scene/sceneManager.ts@@ -14,6 +14,7 @@ import { Material } from '../render/material';import type { DrawCallback } from '../render/customDraw';import { Schedule } from '../ecs/system';import { loadSceneWithAssets } from './scene';+import { recordSceneOrigins } from './sceneOrigins';import { registerDrawCallback, unregisterDrawCallback } from '../render/customDraw';import { PostProcess, PostProcessStack } from '../postprocess';import { defineResource } from '../ecs/resource';@@ -601,6 +602,7 @@ export class SceneManagerState {persistent: false,});}+ recordSceneOrigins(this.app_, entityMap);}// Same token check for the data-less path (systems/setup only) and to faildiff --git a/sdk/src/scene/sceneOrigins.ts b/sdk/src/scene/sceneOrigins.tsnew file mode 100644index 000000000..d3a38a64e--- /dev/null+++ b/sdk/src/scene/sceneOrigins.ts@@ -0,0 +1,64 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file sceneOrigins.ts — which authored entity a live entity was loaded from.+ *+ * A resource rather than a module table, because the answer belongs to one App:+ * an editor runs its own world beside the game's, and a module-scoped map is one+ * bundle chunk away from being two maps that never meet.+ */+import type { App } from '../app/app';+import type { Entity } from '../types';+import { defineResource } from '../ecs/resource';++/**+ * Per loaded entity, the id it carried in the scene document.+ *+ * Absent unless something asked for it: a running game never needs to know which+ * document row an entity came from, and the table would be the editor's cost+ * charged to every player.+ *+ * @experimental+ */+export const SceneOrigins = defineResource<Map<Entity, number>>(new Map(), 'SceneOrigins');++/**+ * Start recording origins on `app`. Call before the first scene loads — what is+ * already spawned was not recorded.+ *+ * @experimental+ */+export function enableSceneOrigins(app: App): void {+ if (!app.hasResource(SceneOrigins)) app.insertResource(SceneOrigins, new Map());+}++/** @experimental */+export function sceneOriginsEnabled(app: App): boolean {+ return app.hasResource(SceneOrigins);+}++/**+ * Record a scene load's document-id → entity map. No-op unless enabled.+ *+ * @experimental+ */+export function recordSceneOrigins(app: App, entityMap: ReadonlyMap<number, Entity>): void {+ if (!app.hasResource(SceneOrigins)) return;+ const table = app.getResource(SceneOrigins);+ // A scene reloaded on every death would otherwise grow one dead row per+ // entity per restart, forever.+ for (const entity of table.keys()) {+ if (!app.world.valid(entity)) table.delete(entity);+ }+ for (const [src, entity] of entityMap) table.set(entity, src);+}++/**+ * The document id `entity` was loaded from; undefined if the game spawned it (or+ * nothing is recording).+ *+ * @experimental+ */+export function sceneOriginOf(app: App, entity: Entity): number | undefined {+ return app.hasResource(SceneOrigins) ? app.getResource(SceneOrigins).get(entity) : undefined;+}diff --git a/sdk/tests/entity-box.test.ts b/sdk/tests/entity-box.test.tsnew file mode 100644index 000000000..f7f7da363--- /dev/null+++ b/sdk/tests/entity-box.test.ts@@ -0,0 +1,93 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The box an editor outlines is the box the renderer draws.+ *+ * Two derivations of it agree on a plain sprite and part company the moment a+ * pivot or a parent scale is involved — which is the case a selection outline+ * sitting beside its sprite is made of. One definition, these claims.+ */+import { describe, expect, it } from 'vitest';+import { entityWorldBox, entityBoxCorners } from '../src/ecs/entityBox';+import { Transform, Sprite } from '../src/ecs/component';+import { UINode } from '../src/ui/core/ui-node';+import type { Entity } from '../src/types';++interface Comp { name: string }++/** A world of hand-written component values — the three reads the box takes. */+function fakeWorld(rows: Record<number, Record<string, unknown>>) {+ const nameOf = (c: unknown): string => (c as Comp & { _name?: string })._name ?? (c as { name?: string }).name ?? '';+ return {+ valid: (e: Entity) => rows[e as unknown as number] !== undefined,+ has: (e: Entity, c: unknown) => rows[e as unknown as number]?.[nameOf(c)] !== undefined,+ get: (e: Entity, c: unknown) => rows[e as unknown as number]?.[nameOf(c)],+ } as never;+}++const T = (x: number, y: number, sx = 1, sy = 1, angle = 0) => ({+ worldPosition: { x, y, z: 0 },+ worldScale: { x: sx, y: sy, z: 1 },+ worldRotation: { x: 0, y: 0, z: Math.sin(angle / 2), w: Math.cos(angle / 2) },+});++const name = (c: unknown): string => (c as { _name?: string })._name ?? (c as { name: string }).name;+const ent = (n: number) => n as unknown as Entity;++describe('an entity world box', () => {+ it('is the sprite size taken through the WORLD scale', () => {+ // A parent scale reaches the drawn size, so it has to reach the box: this+ // is the case where "size alone" and "size × world scale" diverge.+ const world = fakeWorld({+ 1: { [name(Transform)]: T(10, 20, 2, 3), [name(Sprite)]: { size: { x: 100, y: 50 }, pivot: { x: 0.5, y: 0.5 } } },+ });+ const box = entityWorldBox(world, ent(1));+ expect(box).toEqual({ cx: 10, cy: 20, hw: 100, hh: 75, rot: 0 });+ });++ it('puts the centre off the transform when the pivot is off-centre', () => {+ // A bottom-left pivot means the position is the sprite's CORNER; a box+ // centred on the position would sit a half-sprite down and left of it.+ const world = fakeWorld({+ 1: { [name(Transform)]: T(0, 0), [name(Sprite)]: { size: { x: 100, y: 40 }, pivot: { x: 0, y: 0 } } },+ });+ const box = entityWorldBox(world, ent(1))!;+ expect(box.cx).toBeCloseTo(50);+ expect(box.cy).toBeCloseTo(20);+ });++ it('orbits that off-centre box around the position when rotated', () => {+ const world = fakeWorld({+ 1: { [name(Transform)]: T(0, 0, 1, 1, Math.PI / 2), [name(Sprite)]: { size: { x: 100, y: 40 }, pivot: { x: 0, y: 0 } } },+ });+ const box = entityWorldBox(world, ent(1))!;+ // The +50,+20 offset turned a quarter-turn about the transform position.+ expect(box.cx).toBeCloseTo(-20);+ expect(box.cy).toBeCloseTo(50);+ });++ it('has no box for a UI node, which is hit-tested in its own space', () => {+ const world = fakeWorld({ 1: { [name(Transform)]: T(0, 0), [name(UINode)]: {} } });+ expect(entityWorldBox(world, ent(1))).toBeNull();+ });++ it('reports nothing for an entity that draws nothing, unless given an icon size', () => {+ const world = fakeWorld({ 1: { [name(Transform)]: T(5, 5) } });+ expect(entityWorldBox(world, ent(1))).toBeNull();+ expect(entityWorldBox(world, ent(1), { iconHalf: 24 })).toEqual({ cx: 5, cy: 5, hw: 24, hh: 24, rot: 0 });+ });++ it('has no box for an entity that is not there', () => {+ expect(entityWorldBox(fakeWorld({}), ent(9))).toBeNull();+ });++ it('walks its corners counter-clockwise from the local -x,-y', () => {+ const corners = entityBoxCorners({ cx: 0, cy: 0, hw: 2, hh: 1, rot: 0 });+ expect(corners).toEqual([+ { x: -2, y: -1 },+ { x: 2, y: -1 },+ { x: 2, y: 1 },+ { x: -2, y: 1 },+ ]);+ });+});diff --git a/sdk/tests/scene-origins.test.ts b/sdk/tests/scene-origins.test.tsnew file mode 100644index 000000000..b2b49e622--- /dev/null+++ b/sdk/tests/scene-origins.test.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A live entity can name the document row it was loaded from.+ *+ * The editor's tree and the running world's are the same tree only if this+ * mapping exists. It hangs off the App on purpose: an editor runs its own world+ * beside the game's, and a module-scoped table is one bundle chunk away from+ * being two tables that never meet.+ */+import { describe, expect, it } from 'vitest';+import type { Entity } from '../src';+import {+ SceneOrigins,+ enableSceneOrigins,+ sceneOriginsEnabled,+ recordSceneOrigins,+ sceneOriginOf,+} from '../src/scene/sceneOrigins';++type App = Parameters<typeof enableSceneOrigins>[0];++/** The four members the origins table asks of an App. */+function fakeApp(alive: Set<number>): App {+ const resources = new Map<symbol, unknown>();+ return {+ world: { valid: (e: Entity) => alive.has(e as unknown as number) },+ hasResource: (def: { _id: symbol }) => resources.has(def._id),+ getResource: (def: { _id: symbol }) => resources.get(def._id),+ insertResource: (def: { _id: symbol }, v: unknown) => resources.set(def._id, v),+ } as unknown as App;+}++const ent = (n: number): Entity => n as unknown as Entity;++describe('scene origins', () => {+ it('records nothing until an App asks for it', () => {+ const app = fakeApp(new Set([10]));+ recordSceneOrigins(app, new Map([[1, ent(10)]]));+ expect(sceneOriginOf(app, ent(10))).toBeUndefined();+ expect(sceneOriginsEnabled(app)).toBe(false);+ });++ it('maps a live entity back to its document id once enabled', () => {+ const app = fakeApp(new Set([10, 11]));+ enableSceneOrigins(app);+ recordSceneOrigins(app, new Map([[1, ent(10)], [7, ent(11)]]));+ expect(sceneOriginOf(app, ent(10))).toBe(1);+ expect(sceneOriginOf(app, ent(11))).toBe(7);+ });++ it('has no answer for an entity the game spawned', () => {+ const app = fakeApp(new Set([10, 99]));+ enableSceneOrigins(app);+ recordSceneOrigins(app, new Map([[1, ent(10)]]));+ expect(sceneOriginOf(app, ent(99))).toBeUndefined();+ });++ it('drops dead rows on the next load rather than growing per restart', () => {+ const alive = new Set([10]);+ const app = fakeApp(alive);+ enableSceneOrigins(app);+ recordSceneOrigins(app, new Map([[1, ent(10)]]));++ alive.delete(10); // the scene unloaded; its entities are gone+ alive.add(20);+ recordSceneOrigins(app, new Map([[1, ent(20)]]));++ expect(sceneOriginOf(app, ent(20))).toBe(1);+ expect(sceneOriginOf(app, ent(10))).toBeUndefined();+ });++ it('keeps two Apps apart', () => {+ const a = fakeApp(new Set([10]));+ const b = fakeApp(new Set([10]));+ enableSceneOrigins(a);+ enableSceneOrigins(b);+ recordSceneOrigins(a, new Map([[3, ent(10)]]));+ expect(sceneOriginOf(a, ent(10))).toBe(3);+ expect(sceneOriginOf(b, ent(10))).toBeUndefined();+ });++ it('enabling twice keeps what is already recorded', () => {+ const app = fakeApp(new Set([10]));+ enableSceneOrigins(app);+ recordSceneOrigins(app, new Map([[5, ent(10)]]));+ enableSceneOrigins(app);+ expect(sceneOriginOf(app, ent(10))).toBe(5);+ expect(app.getResource(SceneOrigins).size).toBe(1);+ });+});