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(editor): an outliner drag reorders the live viewport, not just the saved scene

yhhf4ade82dc600
diff --git a/desktop/src/engine/Reconciler.ts b/desktop/src/engine/Reconciler.ts
index f7bba09ca..ad81678cd 100644
--- a/desktop/src/engine/Reconciler.ts
+++ b/desktop/src/engine/Reconciler.ts
@@ -218,9 +218,31 @@ export class ReconcilerImpl {
return this.projectName(ev.sourceId);
case 'hiddenChanged':
return this.projectHidden(ev.sourceId);
+ case 'orderChanged':
+ return this.projectOrder();
}
}
+ /**
+ * Project scene order onto the World. Painter order within a sorting layer is
+ * the order the renderer walks the ECS, which a load establishes by spawning in
+ * `data.entities` order — so without this an outliner drag changed the saved
+ * scene (and Play, and the exported game) while the viewport kept drawing the
+ * old order until the next reload. Storage is permuted in place, so entity ids,
+ * component values, and everything keyed on them (spine runtimes, live particle
+ * state, tilemap chunks) survive the drag untouched.
+ */
+ private projectOrder(): void {
+ const world = EngineHost.mutableWorld();
+ if (!world) return;
+ const order: EntityId[] = [];
+ for (const sourceId of this.model.entityOrder()) {
+ const rt = this.model.runtimeFor(sourceId);
+ if (rt != null) order.push(rt);
+ }
+ if (order.length > 0) world.applyEntityOrder(order);
+ }
+
private spawnEntity(sourceId: number): void {
const world = EngineHost.mutableWorld();
const entity = this.model.entityBySource(sourceId);
diff --git a/desktop/src/engine/SceneModel.ts b/desktop/src/engine/SceneModel.ts
index b08cc527f..50eca482d 100644
--- a/desktop/src/engine/SceneModel.ts
+++ b/desktop/src/engine/SceneModel.ts
@@ -373,8 +373,10 @@ export class SceneModelImpl {
// ── Sibling order (outliner drag-reorder; render order = `data.entities` order) ──
// The outliner derives sibling order from each entity's position in
// `data.entities` (buildSceneTree's parent index preserves it), so reordering is
- // reordering this array. The World is order-agnostic (ECS), so these never reach
- // the Reconciler.
+ // reordering this array. That order is also PAINTER order — the engine draws in
+ // the order it walks its pools, which a load establishes by spawning in this
+ // order — so `orderChanged` reaches the Reconciler like any other model change
+ // and is projected onto the live World (World.applyEntityOrder).
/** The scene's entity ids in current (render) order. */
entityOrder(): number[] {
@@ -389,20 +391,32 @@ export class SceneModelImpl {
this.emit({ kind: 'orderChanged' });
}
- /** Move an entity immediately before/after a target in scene order (drag-reorder). */
+ /**
+ * Move an entity immediately before/after a target in scene order (drag-reorder).
+ *
+ * The whole SUBTREE travels with it, keeping its internal order: the outliner
+ * shows children nested under their parent, so dragging a parent's row has to
+ * carry them or scene order would stop matching what the outliner draws — and
+ * scene order is render order, so the children would keep drawing where the
+ * parent used to be.
+ */
moveEntityAdjacent(sourceId: number, targetId: number, before: boolean): void {
if (!this.data || sourceId === targetId) return;
+ const block = new Set(this.collectSubtree(sourceId));
+ if (block.size === 0 || block.has(targetId)) return; // nothing to move, or into itself
+
const arr = this.data.entities;
- const si = arr.findIndex((e) => e.id === sourceId);
- if (si < 0) return;
- const [moved] = arr.splice(si, 1);
- let ti = arr.findIndex((e) => e.id === targetId);
- if (ti < 0) {
- arr.splice(si, 0, moved); // target vanished — put it back
- return;
- }
+ const moved = arr.filter((e) => block.has(e.id));
+ const rest = arr.filter((e) => !block.has(e.id));
+ let ti = rest.findIndex((e) => e.id === targetId);
+ if (ti < 0) return; // target vanished — leave the order untouched
if (!before) ti += 1;
- arr.splice(ti, 0, moved);
+
+ // Rewrite in place (no spread: a big scene would blow the argument limit).
+ arr.length = 0;
+ for (let i = 0; i < ti; i++) arr.push(rest[i]);
+ for (const e of moved) arr.push(e);
+ for (let i = ti; i < rest.length; i++) arr.push(rest[i]);
this.emit({ kind: 'orderChanged' });
}
diff --git a/desktop/tests/outliner-reorder.test.ts b/desktop/tests/outliner-reorder.test.ts
index 3358f817f..6e8dd1a84 100644
--- a/desktop/tests/outliner-reorder.test.ts
+++ b/desktop/tests/outliner-reorder.test.ts
@@ -53,4 +53,23 @@ describe('SceneCommands.reorderEntity', () => {
S.commands.reorderEntity(2, 2, true); // onto self → no-op
expect(S.history.canUndo()).toBe(before);
});
+
+ it('carries the whole subtree with a dragged parent', () => {
+ // 1 owns 2; dropping 1 after 3 must take 2 along, or 2 would keep drawing
+ // where 1 used to be (scene order is render order).
+ S.model.adopt({ version: '1.0', name: 'o', entities: [ent(1, null, [2]), ent(2, 1, []), ent(3, null, [])] } as unknown as SceneData, new Map());
+ S.commands.reorderEntity(1, 3, false);
+ expect(S.model.entityOrder()).toEqual([3, 1, 2]);
+ S.history.undo();
+ expect(S.model.entityOrder()).toEqual([1, 2, 3]);
+ });
+
+ it('keeps a moved subtree contiguous and internally ordered', () => {
+ S.model.adopt({
+ version: '1.0', name: 'o',
+ entities: [ent(1, null, [2, 3]), ent(2, 1, []), ent(3, 1, [4]), ent(4, 3, []), ent(5, null, [])],
+ } as unknown as SceneData, new Map());
+ S.commands.reorderEntity(1, 5, false);
+ expect(S.model.entityOrder()).toEqual([5, 1, 2, 3, 4]);
+ });
});
diff --git a/desktop/tests/scene-order-projection.test.ts b/desktop/tests/scene-order-projection.test.ts
new file mode 100644
index 000000000..e7a6b1eb8
--- /dev/null
+++ b/desktop/tests/scene-order-projection.test.ts
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Scene order is render order, and the World is a projection of the model —
+ * so an outliner drag has to reach the live World, not just the saved file.
+ * The engine draws in the order it walks its pools, which a load establishes
+ * by spawning in `data.entities` order; `orderChanged` re-establishes it on
+ * the already-populated World (Reconciler.projectOrder → applyEntityOrder).
+ */
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
+import { App, Sprite } from 'esengine';
+import type { ESEngineModule, SceneData } from 'esengine';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+
+const host = vi.hoisted(() => ({ world: null as unknown as App['world'] }));
+vi.mock('@/engine/EngineHost', () => ({
+ EngineHost: {
+ mutableWorld: () => host.world,
+ get world() {
+ return host.world;
+ },
+ getResource: () => undefined,
+ },
+}));
+
+import { EditorSession } from '@/engine/EditorSession';
+
+const sprite = (id: number, parent: number | null, children: number[]) => ({
+ id,
+ name: `E${id}`,
+ parent,
+ children,
+ components: [
+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } },
+ { type: 'Sprite', data: { size: { x: 10, y: 10 } } },
+ ],
+});
+
+const scene = (entities: unknown[]): SceneData =>
+ ({ version: '1.0', name: 'order', entities }) as unknown as SceneData;
+
+describe.skipIf(!HAS_WASM)('scene order → World draw order', () => {
+ let module: ESEngineModule;
+ let S: EditorSession;
+
+ beforeAll(async () => {
+ module = await loadWasmModule();
+ });
+
+ beforeEach(() => {
+ const app = App.new();
+ app.connectCpp(new module.Registry() as never, module);
+ host.world = app.world;
+ S = EditorSession.create();
+ });
+
+ afterEach(() => S.dispose());
+
+ /** The World's sprite iteration order, back in SOURCE ids. */
+ const worldOrder = (): number[] =>
+ host.world
+ .getEntitiesWithComponents([Sprite])
+ .map((rt) => S.model.sourceFor(rt))
+ .filter((id): id is number => id != null);
+
+ it('a load projects scene order onto the World', () => {
+ const data = scene([sprite(1, null, []), sprite(2, null, []), sprite(3, null, [])]);
+ S.reconciler.adopt(data, scene([sprite(1, null, []), sprite(2, null, []), sprite(3, null, [])]));
+ expect(worldOrder()).toEqual([1, 2, 3]);
+ });
+
+ it('a drag-reorder reaches the live World immediately', () => {
+ S.reconciler.adopt(
+ scene([sprite(1, null, []), sprite(2, null, []), sprite(3, null, [])]),
+ scene([sprite(1, null, []), sprite(2, null, []), sprite(3, null, [])]),
+ );
+
+ S.commands.reorderEntity(1, 3, false); // drop E1 after E3 → E1 draws last (on top)
+
+ expect(S.model.entityOrder()).toEqual([2, 3, 1]);
+ expect(worldOrder()).toEqual([2, 3, 1]);
+ });
+
+ it('undo restores the World order too', () => {
+ S.reconciler.adopt(
+ scene([sprite(1, null, []), sprite(2, null, []), sprite(3, null, [])]),
+ scene([sprite(1, null, []), sprite(2, null, []), sprite(3, null, [])]),
+ );
+
+ S.commands.reorderEntity(3, 1, true);
+ expect(worldOrder()).toEqual([3, 1, 2]);
+
+ S.history.undo();
+ expect(worldOrder()).toEqual([1, 2, 3]);
+ });
+
+ it('a dragged parent takes its children with it in the World', () => {
+ const entities = [sprite(1, null, [2]), sprite(2, 1, []), sprite(3, null, [])];
+ S.reconciler.adopt(scene(entities), scene([sprite(1, null, [2]), sprite(2, 1, []), sprite(3, null, [])]));
+
+ S.commands.reorderEntity(1, 3, false);
+
+ expect(worldOrder()).toEqual([3, 1, 2]);
+ });
+
+ it("reorders the parent's child list too (UI draws in child order)", () => {
+ // A UI subtree draws in child-list order, not pool order, so the same drag
+ // has to move the child list or a Canvas child would ignore the outliner.
+ const entities = () => [sprite(1, null, [2, 3, 4]), sprite(2, 1, []), sprite(3, 1, []), sprite(4, 1, [])];
+ S.reconciler.adopt(scene(entities()), scene(entities()));
+ const childOrder = (): number[] => {
+ // The wasm Children.entities is an embind vector (snapshot, then free).
+ const vec = host.world.getCppRegistry()!.getChildren(S.model.runtimeFor(1)!).entities;
+ const out: number[] = [];
+ for (let i = 0; i < vec.size(); i++) out.push(S.model.sourceFor(vec.get(i) as never)!);
+ vec.delete();
+ return out;
+ };
+ expect(childOrder()).toEqual([2, 3, 4]);
+
+ S.commands.reorderEntity(4, 2, true); // drop E4 before E2 → first child, drawn behind
+
+ expect(childOrder()).toEqual([4, 2, 3]);
+ });
+
+ it('a newly added entity draws last, ahead of nothing', () => {
+ S.reconciler.adopt(scene([sprite(1, null, [])]), scene([sprite(1, null, [])]));
+ const added = S.model.addEntity('New', [
+ { type: 'Transform', data: {} },
+ { type: 'Sprite', data: {} },
+ ] as never);
+ expect(worldOrder()).toEqual([1, added]);
+ });
+});
diff --git a/docs/astro/src/content/docs/guides/sprites.mdx b/docs/astro/src/content/docs/guides/sprites.mdx
index 32262f22b..892391f17 100644
--- a/docs/astro/src/content/docs/guides/sprites.mdx
+++ b/docs/astro/src/content/docs/guides/sprites.mdx
@@ -108,6 +108,22 @@ sprite.layer = 2; // e.g. "Foreground" — drawn on top
fine ordering *within* a layer, use the entity's `Transform` z position.
</Aside>
+### Scene order breaks the tie
+
+Same layer, same z? Then **scene order** decides: the engine draws entities in the
+order the scene lists them, so the one further **down** the Outliner lands on top.
+Dragging a row in the Outliner therefore changes what covers what — and the viewport
+updates as you drop it, exactly as the running game will draw it. A dragged parent
+takes its children along, so a child always keeps its position relative to its parent.
+
+At runtime the same order is available without touching layers — useful for "bring
+this card to the front":
+
+```typescript
+// Draw `card` last (on top) among these three, leaving everything else alone.
+world.applyEntityOrder([other, another, card]);
+```
+
### Y-sort (top-down occlusion)
For top-down games, check a layer under **Project Settings → Rendering → Y-sorted
diff --git a/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx b/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
index 3ef9a1fc7..106f4d88a 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
@@ -97,6 +97,19 @@ sprite.layer = 2; // 例如 "Foreground" —— 画在上面
排序层做粗粒度分组(背景 vs 玩法 vs 世界内 UI)。层**内**的精细排序,用实体 `Transform` 的 z 位置。
</Aside>
+### 场景顺序决定平局
+
+同一层、同一 z 怎么办?那就由**场景顺序**决定:引擎按场景列出实体的顺序绘制,所以在大纲
+里越**靠下**的越画在上面。因此在大纲里拖动一行就会改变谁盖住谁——而且松手当下视口就更新,
+和运行时的画面完全一致。拖动父实体会带上它的子实体,所以子实体相对父实体的位置始终不变。
+
+运行时也能用同一套顺序,不必动排序层——比如「把这张牌提到最前」:
+
+```typescript
+// 让 card 在这三者中最后绘制(在最上面),其余实体不受影响。
+world.applyEntityOrder([other, another, card]);
+```
+
### Y 排序(俯视遮挡)
俯视视角游戏在 **Project Settings → Rendering → Y-sorted layers** 勾选某个层后,该层上的
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 149101371..c91f59c3d 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1136,6 +1136,7 @@ has: (entity: Entity, component: BuiltinComponentDef<any>) => boolean
hasCpp: boolean
insert: <T>(entity: Entity, component: BuiltinComponentDef<T>, data?: Partial<T>) => { merged: T; isNew: boolean; }
remove: (entity: Entity, component: BuiltinComponentDef<any>) => void
+reorderEntitySets: (rankOf: RankOf) => void
resolvePtrFn: (cppName: string) => ((entity: Entity) => number) | null
resolvePtrGetter: (cppName: string) => ((entity: Entity) => unknown) | null
resolvePtrSetter: (cppName: string) => ((entity: Entity, data: unknown) => void) | null
@@ -2373,6 +2374,7 @@ renderer_resize: (width: number, height: number) => void
renderer_setClearColor: (r: number, g: number, b: number, a: number) => void
renderer_setColorSpace: ((linear: number) => void) | undefined
renderer_setEntityClipRect: (entity: number, x: number, y: number, w: number, h: number) => void
+renderer_setEntityDrawOrder: ((registry: CppRegistry, entitiesPtr: number, count: number) => void) | undefined
renderer_setEntityStencilMask: (entity: number, refValue: number) => void
renderer_setEntityStencilTest: (entity: number, refValue: number) => void
renderer_setStage: (stage: number) => void
@@ -7998,6 +8000,7 @@ tabIndex: number | undefined
```
advanceTick: () => void
anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+applyEntityOrder: (entities: readonly Entity[]) => void
beginIteration: () => void
builtin: BuiltinBridge
changes_: ChangeTracker
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 2cd8887da..f42cc8a20 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1136,6 +1136,7 @@ has: (entity: Entity, component: BuiltinComponentDef<any>) => boolean
hasCpp: boolean
insert: <T>(entity: Entity, component: BuiltinComponentDef<T>, data?: Partial<T>) => { merged: T; isNew: boolean; }
remove: (entity: Entity, component: BuiltinComponentDef<any>) => void
+reorderEntitySets: (rankOf: RankOf) => void
resolvePtrFn: (cppName: string) => ((entity: Entity) => number) | null
resolvePtrGetter: (cppName: string) => ((entity: Entity) => unknown) | null
resolvePtrSetter: (cppName: string) => ((entity: Entity, data: unknown) => void) | null
@@ -2381,6 +2382,7 @@ renderer_resize: (width: number, height: number) => void
renderer_setClearColor: (r: number, g: number, b: number, a: number) => void
renderer_setColorSpace: ((linear: number) => void) | undefined
renderer_setEntityClipRect: (entity: number, x: number, y: number, w: number, h: number) => void
+renderer_setEntityDrawOrder: ((registry: CppRegistry, entitiesPtr: number, count: number) => void) | undefined
renderer_setEntityStencilMask: (entity: number, refValue: number) => void
renderer_setEntityStencilTest: (entity: number, refValue: number) => void
renderer_setStage: (stage: number) => void
@@ -8162,6 +8164,7 @@ tabIndex: number | undefined
```
advanceTick: () => void
anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+applyEntityOrder: (entities: readonly Entity[]) => void
beginIteration: () => void
builtin: BuiltinBridge
changes_: ChangeTracker
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index bd4791203..1a9370f97 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1131,6 +1131,7 @@ has: (entity: Entity, component: BuiltinComponentDef<any>) => boolean
hasCpp: boolean
insert: <T>(entity: Entity, component: BuiltinComponentDef<T>, data?: Partial<T>) => { merged: T; isNew: boolean; }
remove: (entity: Entity, component: BuiltinComponentDef<any>) => void
+reorderEntitySets: (rankOf: RankOf) => void
resolvePtrFn: (cppName: string) => ((entity: Entity) => number) | null
resolvePtrGetter: (cppName: string) => ((entity: Entity) => unknown) | null
resolvePtrSetter: (cppName: string) => ((entity: Entity, data: unknown) => void) | null
@@ -2368,6 +2369,7 @@ renderer_resize: (width: number, height: number) => void
renderer_setClearColor: (r: number, g: number, b: number, a: number) => void
renderer_setColorSpace: ((linear: number) => void) | undefined
renderer_setEntityClipRect: (entity: number, x: number, y: number, w: number, h: number) => void
+renderer_setEntityDrawOrder: ((registry: CppRegistry, entitiesPtr: number, count: number) => void) | undefined
renderer_setEntityStencilMask: (entity: number, refValue: number) => void
renderer_setEntityStencilTest: (entity: number, refValue: number) => void
renderer_setStage: (stage: number) => void
@@ -7993,6 +7995,7 @@ tabIndex: number | undefined
```
advanceTick: () => void
anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+applyEntityOrder: (entities: readonly Entity[]) => void
beginIteration: () => void
builtin: BuiltinBridge
changes_: ChangeTracker
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index aa0bc87e8..22d252efe 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1131,6 +1131,7 @@ has: (entity: Entity, component: BuiltinComponentDef<any>) => boolean
hasCpp: boolean
insert: <T>(entity: Entity, component: BuiltinComponentDef<T>, data?: Partial<T>) => { merged: T; isNew: boolean; }
remove: (entity: Entity, component: BuiltinComponentDef<any>) => void
+reorderEntitySets: (rankOf: RankOf) => void
resolvePtrFn: (cppName: string) => ((entity: Entity) => number) | null
resolvePtrGetter: (cppName: string) => ((entity: Entity) => unknown) | null
resolvePtrSetter: (cppName: string) => ((entity: Entity, data: unknown) => void) | null
@@ -2368,6 +2369,7 @@ renderer_resize: (width: number, height: number) => void
renderer_setClearColor: (r: number, g: number, b: number, a: number) => void
renderer_setColorSpace: ((linear: number) => void) | undefined
renderer_setEntityClipRect: (entity: number, x: number, y: number, w: number, h: number) => void
+renderer_setEntityDrawOrder: ((registry: CppRegistry, entitiesPtr: number, count: number) => void) | undefined
renderer_setEntityStencilMask: (entity: number, refValue: number) => void
renderer_setEntityStencilTest: (entity: number, refValue: number) => void
renderer_setStage: (stage: number) => void
@@ -8208,6 +8210,7 @@ tabIndex: number | undefined
```
advanceTick: () => void
anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+applyEntityOrder: (entities: readonly Entity[]) => void
beginIteration: () => void
builtin: BuiltinBridge
changes_: ChangeTracker
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index d46fdd88b..a381c4d1d 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -323,6 +323,7 @@ renderer_resize: (width: number, height: number) => void
renderer_setClearColor: (r: number, g: number, b: number, a: number) => void
renderer_setColorSpace: ((linear: number) => void) | undefined
renderer_setEntityClipRect: (entity: number, x: number, y: number, w: number, h: number) => void
+renderer_setEntityDrawOrder: ((registry: CppRegistry, entitiesPtr: number, count: number) => void) | undefined
renderer_setEntityStencilMask: (entity: number, refValue: number) => void
renderer_setEntityStencilTest: (entity: number, refValue: number) => void
renderer_setStage: (stage: number) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 1f4be764f..ffdc4d52a 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1131,6 +1131,7 @@ has: (entity: Entity, component: BuiltinComponentDef<any>) => boolean
hasCpp: boolean
insert: <T>(entity: Entity, component: BuiltinComponentDef<T>, data?: Partial<T>) => { merged: T; isNew: boolean; }
remove: (entity: Entity, component: BuiltinComponentDef<any>) => void
+reorderEntitySets: (rankOf: RankOf) => void
resolvePtrFn: (cppName: string) => ((entity: Entity) => number) | null
resolvePtrGetter: (cppName: string) => ((entity: Entity) => unknown) | null
resolvePtrSetter: (cppName: string) => ((entity: Entity, data: unknown) => void) | null
@@ -2368,6 +2369,7 @@ renderer_resize: (width: number, height: number) => void
renderer_setClearColor: (r: number, g: number, b: number, a: number) => void
renderer_setColorSpace: ((linear: number) => void) | undefined
renderer_setEntityClipRect: (entity: number, x: number, y: number, w: number, h: number) => void
+renderer_setEntityDrawOrder: ((registry: CppRegistry, entitiesPtr: number, count: number) => void) | undefined
renderer_setEntityStencilMask: (entity: number, refValue: number) => void
renderer_setEntityStencilTest: (entity: number, refValue: number) => void
renderer_setStage: (stage: number) => void
@@ -8017,6 +8019,7 @@ tabIndex: number | undefined
```
advanceTick: () => void
anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean
+applyEntityOrder: (entities: readonly Entity[]) => void
beginIteration: () => void
builtin: BuiltinBridge
changes_: ChangeTracker
diff --git a/sdk/src/ecs/BuiltinBridge.ts b/sdk/src/ecs/BuiltinBridge.ts
index f66d9c1a8..5da141765 100644
--- a/sdk/src/ecs/BuiltinBridge.ts
+++ b/sdk/src/ecs/BuiltinBridge.ts
@@ -13,6 +13,7 @@ import { handleWasmError } from '../wasmError';
import { installAbortGuard, throwIfModuleAborted, isModuleAborted, WasmModuleAborted } from '../moduleHealth';
import { COMPONENT_META, ABI_LAYOUT_HASH } from '../component.generated';
import { PTR_ACCESSORS } from './ptrAccessors.generated';
+import { reorderSetByRank, type RankOf } from './entityOrder';
import {
type MemoryProvider, type ComponentHeap,
WasmMemoryProvider, resolveWasmPtrFn,
@@ -531,6 +532,13 @@ export class BuiltinBridge {
return set;
}
+ /** Re-order every builtin entity set so queries iterate in rank order
+ * (the JS half of {@link World.applyEntityOrder}; the engine's own pools are
+ * permuted by the same call). */
+ reorderEntitySets(rankOf: RankOf): void {
+ for (const set of this.builtinEntitySets_.values()) reorderSetByRank(set, rankOf);
+ }
+
/** Removes the entity from every builtin set; returns the cppNames it was in. */
deleteFromEntitySets(entity: Entity): string[] {
const removed: string[] = [];
diff --git a/sdk/src/ecs/QueryCache.ts b/sdk/src/ecs/QueryCache.ts
index 17373d777..0e1e953f2 100644
--- a/sdk/src/ecs/QueryCache.ts
+++ b/sdk/src/ecs/QueryCache.ts
@@ -53,7 +53,13 @@ export class QueryCache {
this.componentVersions_.set(componentId, cur + 1);
}
+ /**
+ * Drop every cached result. For changes no per-component version describes —
+ * a reorder (see World.applyEntityOrder) moves entities within results that are
+ * otherwise still correct, so nothing else would recompute them.
+ */
invalidateAll(): void {
+ this.cache_.clear();
this.structuralVersion_++;
}
diff --git a/sdk/src/ecs/ScriptStorage.ts b/sdk/src/ecs/ScriptStorage.ts
index 6bf290bd7..90cd219f5 100644
--- a/sdk/src/ecs/ScriptStorage.ts
+++ b/sdk/src/ecs/ScriptStorage.ts
@@ -9,6 +9,7 @@ import { Entity } from '../types';
import { ComponentDef } from '../component';
import { validateComponentData, formatValidationErrors, assetFieldNames } from '../validation';
import { log } from '../logger';
+import { reorderMapByRank, type RankOf } from './entityOrder';
export interface InsertResult<T> {
value: T;
@@ -107,6 +108,12 @@ export class ScriptStorage {
return this.entityComponents_.get(entity);
}
+ /** Re-order every component's storage so queries iterate in rank order — the
+ * script half of {@link World.applyEntityOrder}. */
+ reorderStorages(rankOf: RankOf): void {
+ for (const storage of this.tsStorage_.values()) reorderMapByRank(storage, rankOf);
+ }
+
removeEntity(entity: Entity): symbol[] {
const ids = this.entityComponents_.get(entity);
if (!ids) return [];
diff --git a/sdk/src/ecs/engineApi.ts b/sdk/src/ecs/engineApi.ts
index ac706a08d..cb73247dd 100644
--- a/sdk/src/ecs/engineApi.ts
+++ b/sdk/src/ecs/engineApi.ts
@@ -46,3 +46,12 @@ export function setNativeEngineApi(api: EngineApi | null): void {
export function engineApi(app: App): EngineApi | null {
return (app.wasmModule as EngineApi | null) ?? native_;
}
+
+/**
+ * The native host's engine API, for the few callers that sit BELOW an App — the
+ * World, which on a device has a registry but no wasm module to reach the engine
+ * through. Null on the web (where the module is the answer) and on a logic host.
+ */
+export function nativeEngineApi(): EngineApi | null {
+ return native_;
+}
diff --git a/sdk/src/ecs/entityOrder.ts b/sdk/src/ecs/entityOrder.ts
new file mode 100644
index 000000000..b26276da4
--- /dev/null
+++ b/sdk/src/ecs/entityOrder.ts
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ecs/entityOrder.ts
+ * @brief Permute the JS-side entity containers to a caller-supplied order.
+ *
+ * @details Iteration order is painter order: the engine walks its component pools
+ * and the SDK walks these Maps/Sets, and within a sorting layer whichever
+ * entity is visited last lands on top. Both sides are insertion-ordered,
+ * so "apply this order" means re-inserting in rank order — which is what
+ * {@link World.applyEntityOrder} does through these two helpers.
+ *
+ * Ranking is stable: an entity the caller did not rank keeps its position
+ * relative to the other unranked ones, after every ranked one.
+ */
+
+import type { Entity } from '../types';
+
+/** Rank for an entity the caller did not order — sorts last, stably. */
+export const UNRANKED = Number.MAX_SAFE_INTEGER;
+
+/** `entity -> rank` for {@link reorderMapByRank}/{@link reorderSetByRank}. */
+export type RankOf = (entity: Entity) => number;
+
+/** Build a stable rank function from an ordered entity list (first = rank 0). */
+export function rankByOrder(order: readonly Entity[]): RankOf {
+ const ranks = new Map<Entity, number>();
+ for (const entity of order) {
+ if (!ranks.has(entity)) ranks.set(entity, ranks.size); // duplicate: first wins
+ }
+ return (entity: Entity) => ranks.get(entity) ?? UNRANKED;
+}
+
+/** Re-insert `map`'s entries in rank order (values untouched). */
+export function reorderMapByRank<V>(map: Map<Entity, V>, rankOf: RankOf): void {
+ if (map.size <= 1) return;
+ const entries = Array.from(map);
+ // Array.prototype.sort is stable (ES2019+), which is what keeps unranked
+ // entities in their existing relative order.
+ entries.sort((a, b) => rankOf(a[0]) - rankOf(b[0]));
+ map.clear();
+ for (const [entity, value] of entries) map.set(entity, value);
+}
+
+/** Re-insert `set`'s entities in rank order. */
+export function reorderSetByRank(set: Set<Entity>, rankOf: RankOf): void {
+ if (set.size <= 1) return;
+ const entities = Array.from(set);
+ entities.sort((a, b) => rankOf(a) - rankOf(b));
+ set.clear();
+ for (const entity of entities) set.add(entity);
+}
diff --git a/sdk/src/ecs/nativeEngineApi.generated.ts b/sdk/src/ecs/nativeEngineApi.generated.ts
index 7b14d1ea9..acd32a2c3 100644
--- a/sdk/src/ecs/nativeEngineApi.generated.ts
+++ b/sdk/src/ecs/nativeEngineApi.generated.ts
@@ -143,6 +143,7 @@ export interface NativeEngineApi {
renderer_setClearColor?(r: number, g: number, b: number, a: number): void;
renderer_setColorSpace?(linear: number): void;
renderer_setEntityClipRect?(entity: number, x: number, y: number, w: number, h: number): void;
+ renderer_setEntityDrawOrder?(registry: unknown, entitiesPtr: number, count: number): void;
renderer_setEntityStencilMask?(entity: number, refValue: number): void;
renderer_setEntityStencilTest?(entity: number, refValue: number): void;
renderer_setStage?(stage: number): void;
@@ -373,6 +374,7 @@ export function createNativeEngineApi(
bind('renderer_setClearColor', 'es_renderer_setClearColor', false);
bind('renderer_setColorSpace', 'es_renderer_setColorSpace', false);
bind('renderer_setEntityClipRect', 'es_renderer_setEntityClipRect', false);
+ bind('renderer_setEntityDrawOrder', 'es_renderer_setEntityDrawOrder', true);
bind('renderer_setEntityStencilMask', 'es_renderer_setEntityStencilMask', false);
bind('renderer_setEntityStencilTest', 'es_renderer_setEntityStencilTest', false);
bind('renderer_setStage', 'es_renderer_setStage', false);
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 52c0b9223..f52366030 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -300,6 +300,9 @@ export interface ESEngineModule {
renderer_resize(width: number, height: number): void;
renderer_beginFrame(elapsedSec: number): void;
renderer_updateTransforms(registry: CppRegistry): void;
+ /** Permute component storage to the given entity order — see World.applyEntityOrder.
+ * Optional: an older core still answers every other renderer entry point. */
+ renderer_setEntityDrawOrder?(registry: CppRegistry, entitiesPtr: number, count: number): void;
renderer_begin(matrixPtr: number, targetHandle: number, clearFlags: number,
r: number, g: number, b: number, a: number,
clearX: number, clearY: number, clearW: number, clearH: number): void;
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index 330986f4f..cdb892c0b 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -14,9 +14,22 @@ import { ScriptStorage } from './ecs/ScriptStorage';
import { NameIndex } from './ecs/NameIndex';
import { ChangeTracker } from './ecs/ChangeTracker';
import { QueryCache, type QueryCacheStats } from './ecs/QueryCache';
+import { rankByOrder, reorderMapByRank } from './ecs/entityOrder';
+import { nativeEngineApi } from './ecs/engineApi';
+import { withScratch } from './wasmScratch';
import { log } from './logger';
import { getDefaultContext, type EditorBridge } from './context';
+/** The slice of a core {@link World.applyEntityOrder} needs: the entry point plus
+ * the heap it marshals the entity list through (wasm memory on the web, the
+ * host's arena on a device — the writes are identical either way). */
+interface EntityOrderCore {
+ renderer_setEntityDrawOrder?(registry: CppRegistry, entitiesPtr: number, count: number): void;
+ _malloc?(bytes: number): number;
+ _free?(ptr: number): void;
+ HEAPU32?: Uint32Array;
+}
+
function editorBridge(): EditorBridge | null {
return getDefaultContext().editorBridge;
}
@@ -351,6 +364,63 @@ export class World {
return Array.from(this.entities_.keys());
}
+ /**
+ * Reorder the world's storage so every iteration follows `entities`.
+ *
+ * Within a sorting layer the renderer draws in the order it walks the ECS —
+ * so an entity that iterates later lands on top. That order is storage order,
+ * which a scene gets for free by spawning in its authored order and which this
+ * re-establishes on a world that is already populated: the picture a reload
+ * would give, without respawning anything (entity ids, component values and
+ * every subsystem keyed on them survive untouched).
+ *
+ * Entities left out of `entities` keep their relative order after the listed
+ * ones. Both halves of the world move together — the engine's component pools
+ * and the JS-side storages the SDK's own queries walk — so an editor's outliner
+ * drag and a game's "bring this card to the front" mean one thing.
+ *
+ * @param entities the desired iteration order (first iterates first, draws first)
+ */
+ applyEntityOrder(entities: readonly Entity[]): void {
+ if (entities.length === 0) return;
+ if (this.isIterating()) {
+ log.warn('world', 'applyEntityOrder ignored during query iteration');
+ return;
+ }
+ const rankOf = rankByOrder(entities);
+
+ // The engine's pools first: it owns the draw path, and its call is the one
+ // that can fail (no core, or a core built before this entry point existed).
+ this.pushEntityOrderToCore_(entities);
+
+ reorderMapByRank(this.entities_, rankOf);
+ this.builtin_.reorderEntitySets(rankOf);
+ this.scripts_.reorderStorages(rankOf);
+ // Cached query results are entity ARRAYS — their order is now wrong, and no
+ // component version moved, so drop them wholesale.
+ this.queries_.invalidateAll();
+ }
+
+ /** Marshal the order to whichever core is connected (see applyEntityOrder). */
+ private pushEntityOrderToCore_(entities: readonly Entity[]): void {
+ const cppRegistry = this.builtin_.getCppRegistry();
+ if (!cppRegistry) return;
+ const core = (this.builtin_.getWasmModule() ?? nativeEngineApi()) as EntityOrderCore | null;
+ const push = core?.renderer_setEntityDrawOrder;
+ if (!core || !push || !core._malloc || !core._free || !core.HEAPU32) return;
+ try {
+ withScratch({ _malloc: core._malloc, _free: core._free }, (alloc) => {
+ const ptr = alloc(entities.length * 4);
+ // HEAPU32 is re-read here (not captured above): emscripten swaps the
+ // views out when the heap grows, and _malloc can grow it.
+ core.HEAPU32!.set(entities as ArrayLike<number>, ptr >> 2);
+ push.call(core, cppRegistry, ptr, entities.length);
+ });
+ } catch (e) {
+ handleWasmError(e, `applyEntityOrder(count=${entities.length})`);
+ }
+ }
+
setParent(child: Entity, parent: Entity): void {
const cppRegistry = this.builtin_.getCppRegistry();
if (cppRegistry) {
diff --git a/sdk/tests/entity-order.test.ts b/sdk/tests/entity-order.test.ts
new file mode 100644
index 000000000..3f9456b10
--- /dev/null
+++ b/sdk/tests/entity-order.test.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, beforeEach } from 'vitest';
+import { World } from '../src/world';
+import { defineComponent, defineBuiltin } from '../src/component';
+import { rankByOrder, reorderMapByRank, reorderSetByRank, UNRANKED } from '../src/ecs/entityOrder';
+import type { Entity } from '../src/types';
+import { createMockModule } from './mocks/wasm';
+
+describe('World.applyEntityOrder', () => {
+ // Iteration order is painter order, so these assertions are draw-order assertions.
+ const Script = defineComponent('OrderScript', { v: 0 });
+ const Builtin = defineBuiltin('OrderBuiltin', { v: 0 });
+
+ let world: World;
+
+ beforeEach(() => {
+ world = new World();
+ const mod = createMockModule();
+ world.connectCpp(mod.getRegistry(), mod);
+ });
+
+ const spawnThree = (): [Entity, Entity, Entity] => {
+ const a = world.spawn('a');
+ const b = world.spawn('b');
+ const c = world.spawn('c');
+ for (const e of [a, b, c]) {
+ world.insert(e, Script, { v: e });
+ world.insert(e, Builtin, { v: e });
+ }
+ return [a, b, c];
+ };
+
+ it('reorders script-component query iteration', () => {
+ const [a, b, c] = spawnThree();
+ expect(world.getEntitiesWithComponents([Script])).toEqual([a, b, c]);
+
+ world.applyEntityOrder([c, a, b]);
+
+ expect(world.getEntitiesWithComponents([Script])).toEqual([c, a, b]);
+ });
+
+ it('reorders builtin-component query iteration', () => {
+ const [a, b, c] = spawnThree();
+ world.applyEntityOrder([b, c, a]);
+ expect(world.getEntitiesWithComponents([Builtin])).toEqual([b, c, a]);
+ });
+
+ it('reorders the world entity list itself', () => {
+ const [a, b, c] = spawnThree();
+ world.applyEntityOrder([c, b, a]);
+ expect(world.getAllEntities()).toEqual([c, b, a]);
+ });
+
+ it('leaves unlisted entities after the listed ones, in their existing order', () => {
+ const [a, b, c] = spawnThree();
+ const d = world.spawn('d');
+ world.insert(d, Script, { v: d });
+
+ world.applyEntityOrder([d, b]);
+
+ expect(world.getEntitiesWithComponents([Script])).toEqual([d, b, a, c]);
+ });
+
+ it('recomputes a query cached before the reorder', () => {
+ const [a, b, c] = spawnThree();
+ expect(world.getEntitiesWithComponents([Script])).toEqual([a, b, c]); // seeds the cache
+ world.applyEntityOrder([c, b, a]);
+ expect(world.getEntitiesWithComponents([Script])).toEqual([c, b, a]);
+ });
+
+ it('keeps component values with their entity', () => {
+ const [a, , c] = spawnThree();
+ world.applyEntityOrder([c, a]);
+ expect(world.get(a, Script).v).toBe(a);
+ expect(world.get(c, Script).v).toBe(c);
+ expect(world.has(a, Builtin)).toBe(true);
+ });
+
+ it('is a no-op for an empty order', () => {
+ const [a, b, c] = spawnThree();
+ world.applyEntityOrder([]);
+ expect(world.getEntitiesWithComponents([Script])).toEqual([a, b, c]);
+ });
+
+ it('marshals the order to the engine core', () => {
+ const mod = createMockModule() as unknown as Record<string, unknown>;
+ const heap = new Uint32Array(64);
+ const calls: Array<{ count: number; ids: number[] }> = [];
+ mod._malloc = () => 16;
+ mod._free = () => {};
+ mod.HEAPU32 = heap;
+ mod.renderer_setEntityDrawOrder = (_reg: unknown, ptr: number, count: number) => {
+ calls.push({ count, ids: Array.from(heap.subarray(ptr >> 2, (ptr >> 2) + count)) });
+ };
+ const w = new World();
+ w.connectCpp((mod.getRegistry as () => never)(), mod as never);
+ const a = w.spawn();
+ const b = w.spawn();
+
+ w.applyEntityOrder([b, a]);
+
+ expect(calls).toEqual([{ count: 2, ids: [b, a] }]);
+ });
+
+ it('is ignored during query iteration', () => {
+ const [a, b, c] = spawnThree();
+ world.beginIteration();
+ world.applyEntityOrder([c, b, a]);
+ world.endIteration();
+ expect(world.getEntitiesWithComponents([Script])).toEqual([a, b, c]);
+ });
+});
+
+describe('entityOrder helpers', () => {
+ const e = (n: number): Entity => n as Entity;
+
+ it('ranks by position, first occurrence wins', () => {
+ const rankOf = rankByOrder([e(7), e(3), e(7)]);
+ expect(rankOf(e(7))).toBe(0);
+ expect(rankOf(e(3))).toBe(1);
+ expect(rankOf(e(9))).toBe(UNRANKED);
+ });
+
+ it('reorders a map stably, unranked keys last', () => {
+ const map = new Map<Entity, string>([[e(1), 'a'], [e(2), 'b'], [e(3), 'c'], [e(4), 'd']]);
+ reorderMapByRank(map, rankByOrder([e(3)]));
+ expect([...map.keys()]).toEqual([e(3), e(1), e(2), e(4)]);
+ expect(map.get(e(3))).toBe('c');
+ });
+
+ it('reorders a set stably, unranked entities last', () => {
+ const set = new Set<Entity>([e(1), e(2), e(3)]);
+ reorderSetByRank(set, rankByOrder([e(2)]));
+ expect([...set]).toEqual([e(2), e(1), e(3)]);
+ });
+});
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 3a3e0c7f1..1a4dfe59d 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -383,6 +383,22 @@ void renderer_updateTransforms(ecs::Registry& registry) {
ensureTransformsUpdated(registry);
}
+// Painter order within a sorting layer is the order the render plugins iterate
+// the ECS pools, which is storage order — so a scene draws in its authored entity
+// order only because loading it spawns in that order. This is the entry point that
+// re-establishes the order on an ALREADY populated registry (the editor moving a
+// row in the outliner, a game bringing a card to the front): the same picture a
+// reload would produce, without respawning anything.
+void renderer_setEntityDrawOrder(ecs::Registry& registry, uintptr_t entitiesPtr, u32 count) {
+ if (entitiesPtr == 0 || count == 0) return;
+ const u32* raw = boundarySpan<u32>(entitiesPtr, count, "renderer_setEntityDrawOrder.entities");
+ if (!raw) return;
+ std::vector<Entity> order;
+ order.reserve(count);
+ for (u32 i = 0; i < count; ++i) order.push_back(Entity::fromRaw(raw[i]));
+ ecs::applySceneEntityOrder(registry, order.data(), order.size());
+}
+
void renderer_submitAll(ecs::Registry& registry, u32 skipFlags, i32 vpX, i32 vpY, i32 vpW, i32 vpH) {
if (!g_renderFrame) return;
ensureTransformsUpdated(registry);
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index ae93c4dbb..8d9f3835c 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -73,6 +73,7 @@ void mesh2d_setGeometry(
void renderer_submitParticles(ecs::Registry& registry);
#endif
void renderer_updateTransforms(ecs::Registry& registry);
+void renderer_setEntityDrawOrder(ecs::Registry& registry, uintptr_t entitiesPtr, u32 count);
void renderer_submitAll(ecs::Registry& registry, u32 skipFlags, i32 vpX, i32 vpY, i32 vpW, i32 vpH);
#ifdef ES_ENABLE_PARTICLES
void particle_update(ecs::Registry& registry, f32 dt);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 0b9d0333a..a1ee1c7d8 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -493,6 +493,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_submitParticles", &esengine::renderer_submitParticles);
#endif
emscripten::function("renderer_updateTransforms", &esengine::renderer_updateTransforms);
+ emscripten::function("renderer_setEntityDrawOrder", &esengine::renderer_setEntityDrawOrder);
emscripten::function("renderer_submitAll", &esengine::renderer_submitAll);
#ifdef ES_ENABLE_PARTICLES
emscripten::function("particle_update", &esengine::particle_update);
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index 1c0ca396a..6c174d36e 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -476,6 +476,56 @@ public:
entity_count_ = 0;
}
+ /**
+ * @brief Reorders every component pool to follow the given entity order
+ * @param order Entities in the desired iteration order (first iterates first)
+ * @param count How many entries @p order holds
+ *
+ * @details Component storage order IS iteration order, and iteration order is
+ * the renderer's painter order within a sorting layer — so a scene's
+ * authored entity order only reaches the draw list because a load
+ * happens to spawn in that order. This applies an order to a registry
+ * that is already populated: the same picture, without respawning
+ * anything (entity ids, component values, and every subsystem keyed on
+ * them survive untouched).
+ *
+ * Entities absent from @p order keep their relative order after the
+ * listed ones. Pools already in the requested order are left alone, so
+ * a redundant call costs a scan and bumps no pool version.
+ */
+ void applyEntityOrder(const Entity* order, usize count) {
+ if (!order || count == 0) return;
+ applyEntityRank(buildEntityRank(order, count));
+ }
+
+ /**
+ * @brief Rank table (by Entity::index()) for an ordered entity list
+ * @details Split out of {@link applyEntityOrder} so a caller that ranks other
+ * entity lists too — child lists, in applySceneEntityOrder — builds it
+ * once. Unlisted entities read {@link SparseSetBase::UNRANKED}.
+ */
+ std::vector<u32> buildEntityRank(const Entity* order, usize count) const {
+ // entityValid_ spans every index ever activated (activateIndex grows it),
+ // so it is the safe bound for a rank table keyed by Entity::index().
+ std::vector<u32> rank(entityValid_.size(), SparseSetBase::UNRANKED);
+ if (!order) return rank;
+ u32 nextRank = 0;
+ for (usize i = 0; i < count; ++i) {
+ const u32 idx = order[i].index();
+ if (idx >= rank.size()) continue; // never allocated here
+ if (rank[idx] != SparseSetBase::UNRANKED) continue; // duplicate: first wins
+ rank[idx] = nextRank++;
+ }
+ return rank;
+ }
+
+ /** @brief Reorders every component pool by a rank table from buildEntityRank. */
+ void applyEntityRank(const std::vector<u32>& rank) {
+ for (auto& pool : pools_) {
+ if (pool) pool->reorderBy(rank);
+ }
+ }
+
/**
* @brief Executes a function for each entity with specified components
* @tparam Components The required component types
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
index fbce346e1..fba4d0758 100644
--- a/src/esengine/ecs/SparseSet.hpp
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -95,6 +95,23 @@ public:
* parallel store and, notably, was not bumped on remove).
*/
virtual u32 version() const = 0;
+
+ /**
+ * @brief Permutes storage so iteration follows @p rank
+ * @param rank Rank per ENTITY INDEX (Entity::index()); lower ranks iterate first
+ *
+ * @details Storage order is iteration order, and iteration order is the
+ * renderer's within-layer painter order, so this is how a scene's
+ * authored entity order reaches the draw list without respawning
+ * anything. Entities with no rank (index past the end, or the
+ * UNRANKED sentinel) keep their relative order after the ranked
+ * ones — the sort is stable. A no-op reorder leaves storage (and
+ * therefore every handed-out component pointer) untouched.
+ */
+ virtual void reorderBy(const std::vector<u32>& rank) = 0;
+
+ /** @brief Rank for an entity the caller did not order — sorts last, stably. */
+ static constexpr u32 UNRANKED = 0xFFFFFFFFu;
};
// =============================================================================
@@ -369,6 +386,49 @@ public:
/** @copydoc SparseSetBase::version() */
u32 version() const override { return version_; }
+ /** @copydoc SparseSetBase::reorderBy() */
+ void reorderBy(const std::vector<u32>& rank) override {
+ const usize n = dense_.size();
+ if (n <= 1) return;
+
+ const auto rankOf = [&](usize i) {
+ const u32 idx = dense_[i].index();
+ return idx < rank.size() ? rank[idx] : UNRANKED;
+ };
+
+ // perm[i] = which current slot belongs at position i. stable_sort keeps
+ // equal-ranked (and unranked) entities in their present order.
+ std::vector<usize> perm(n);
+ for (usize i = 0; i < n; ++i) perm[i] = i;
+ std::stable_sort(perm.begin(), perm.end(),
+ [&](usize a, usize b) { return rankOf(a) < rankOf(b); });
+
+ bool moved = false;
+ for (usize i = 0; i < n; ++i) {
+ if (perm[i] != i) { moved = true; break; }
+ }
+ if (!moved) return; // already in order — no version bump, no stale pointers
+
+ // Cycle-walk the permutation in place (same idiom as Registry::sort).
+ for (usize i = 0; i < n; ++i) {
+ if (perm[i] == i) continue;
+ usize j = i;
+ Entity tmpEntity = std::move(dense_[i]);
+ T tmpComponent = std::move(components_[i]);
+ while (perm[j] != i) {
+ const usize src = perm[j];
+ dense_[j] = std::move(dense_[src]);
+ components_[j] = std::move(components_[src]);
+ perm[j] = j;
+ j = src;
+ }
+ dense_[j] = std::move(tmpEntity);
+ components_[j] = std::move(tmpComponent);
+ perm[j] = j;
+ }
+ rebuildSparse();
+ }
+
void rebuildSparse() {
// Called after Registry::sort permutes dense_/components_ in place —
// component addresses changed, so any handed-out raw pointer is stale.
diff --git a/src/esengine/ecs/TransformSystem.hpp b/src/esengine/ecs/TransformSystem.hpp
index ac987cf70..c8cd7b34d 100644
--- a/src/esengine/ecs/TransformSystem.hpp
+++ b/src/esengine/ecs/TransformSystem.hpp
@@ -221,6 +221,41 @@ inline void setParent(Registry& registry, Entity child, Entity newParent) {
}
}
+/**
+ * @brief Applies a scene's authored entity order to the whole world
+ * @param order Entities in the desired order (first draws first, i.e. behind)
+ * @param count How many entries @p order holds
+ *
+ * @details Two things read "order" when deciding what covers what, and one
+ * authored order has to reach both: component STORAGE order, which is
+ * the painter order of everything the renderer collects by pool walk,
+ * and each parent's CHILD LIST, which is the order the UI tree lays out
+ * and draws in (see UIRenderOrderSystem). A scene file gets both for
+ * free by spawning in order; this re-establishes them on a world that is
+ * already populated, so an editor drag or a runtime "bring to front"
+ * means the same thing a reload would.
+ *
+ * Entities left out of @p order keep their relative order, after the
+ * listed ones — including inside child lists, where reparenting's
+ * swap-with-back removal can otherwise leave a stale order.
+ */
+inline void applySceneEntityOrder(Registry& registry, const Entity* order, usize count) {
+ if (!order || count == 0) return;
+ const std::vector<u32> rank = registry.buildEntityRank(order, count);
+ registry.applyEntityRank(rank);
+
+ const auto rankOf = [&rank](Entity e) {
+ const u32 idx = e.index();
+ return idx < rank.size() ? rank[idx] : SparseSetBase::UNRANKED;
+ };
+ registry.eachLive<Children>([&rankOf](Entity, Children& children) {
+ auto& list = children.entities;
+ if (list.size() <= 1) return;
+ std::stable_sort(list.begin(), list.end(),
+ [&rankOf](Entity a, Entity b) { return rankOf(a) < rankOf(b); });
+ });
+}
+
inline Entity getRoot(Registry& registry, Entity entity) {
while (registry.has<Parent>(entity)) {
Entity parent = registry.get<Parent>(entity).entity;
diff --git a/tests/ecs/test_registry.cpp b/tests/ecs/test_registry.cpp
index eabc5ef09..14f5689d7 100644
--- a/tests/ecs/test_registry.cpp
+++ b/tests/ecs/test_registry.cpp
@@ -3,6 +3,7 @@
#include <esengine/ESEngine.hpp>
#include <esengine/ecs/TransformSystem.hpp>
+#include <vector>
namespace test {
@@ -536,3 +537,102 @@ TEST_CASE("setParent is idempotent on duplicate reparent") {
CHECK_EQ(children.size(), 1u);
CHECK_EQ(children[0], child);
}
+
+// Storage order is iteration order is painter order: applyEntityOrder is how an
+// already-populated registry is told the scene's authored order (see
+// Registry::applyEntityOrder).
+TEST_CASE("applyEntityOrder permutes every pool to the given order") {
+ esengine::ecs::Registry registry;
+ esengine::Entity a = registry.create();
+ esengine::Entity b = registry.create();
+ esengine::Entity c = registry.create();
+ for (auto e : {a, b, c}) {
+ registry.emplace<test::Position>(e, static_cast<float>(e.index()), 0.0f);
+ registry.emplace<test::Health>(e, static_cast<int>(e.index()));
+ }
+
+ std::vector<esengine::Entity> order{c, a, b};
+ registry.applyEntityOrder(order.data(), order.size());
+
+ std::vector<esengine::Entity> seen;
+ registry.each<test::Position>([&](esengine::Entity e, test::Position&) { seen.push_back(e); });
+ CHECK_EQ(seen, order);
+
+ // Every pool follows the same order, and the values travel with their entity.
+ seen.clear();
+ registry.each<test::Health>([&](esengine::Entity e, test::Health&) { seen.push_back(e); });
+ CHECK_EQ(seen, order);
+ CHECK_EQ(registry.get<test::Position>(c).x, static_cast<float>(c.index()));
+ CHECK_EQ(registry.get<test::Health>(a).value, static_cast<int>(a.index()));
+}
+
+TEST_CASE("applyEntityOrder leaves unlisted entities after the listed ones, in order") {
+ esengine::ecs::Registry registry;
+ esengine::Entity a = registry.create();
+ esengine::Entity b = registry.create();
+ esengine::Entity c = registry.create();
+ esengine::Entity d = registry.create();
+ for (auto e : {a, b, c, d}) registry.emplace<test::Position>(e, 0.0f, 0.0f);
+
+ std::vector<esengine::Entity> order{d, b};
+ registry.applyEntityOrder(order.data(), order.size());
+
+ std::vector<esengine::Entity> seen;
+ registry.each<test::Position>([&](esengine::Entity e, test::Position&) { seen.push_back(e); });
+ CHECK_EQ(seen, std::vector<esengine::Entity>{d, b, a, c});
+}
+
+TEST_CASE("applyEntityOrder keeps lookups intact across a partial pool") {
+ esengine::ecs::Registry registry;
+ esengine::Entity a = registry.create();
+ esengine::Entity b = registry.create();
+ esengine::Entity c = registry.create();
+ registry.emplace<test::Position>(a, 1.0f, 0.0f);
+ registry.emplace<test::Position>(c, 3.0f, 0.0f);
+
+ std::vector<esengine::Entity> order{c, b, a};
+ registry.applyEntityOrder(order.data(), order.size());
+
+ CHECK(registry.has<test::Position>(a));
+ CHECK(!registry.has<test::Position>(b));
+ CHECK_EQ(registry.get<test::Position>(a).x, 1.0f);
+ CHECK_EQ(registry.get<test::Position>(c).x, 3.0f);
+
+ std::vector<esengine::Entity> seen;
+ registry.each<test::Position>([&](esengine::Entity e, test::Position&) { seen.push_back(e); });
+ CHECK_EQ(seen, std::vector<esengine::Entity>{c, a});
+}
+
+// UI draws in child-list order while world sprites draw in storage order, so one
+// authored order has to reach both (see applySceneEntityOrder).
+TEST_CASE("applySceneEntityOrder reorders child lists as well as storage") {
+ esengine::ecs::Registry registry;
+ esengine::Entity parent = registry.create();
+ esengine::Entity a = registry.create();
+ esengine::Entity b = registry.create();
+ esengine::Entity c = registry.create();
+ for (auto child : {a, b, c}) esengine::ecs::setParent(registry, child, parent);
+ CHECK_EQ(registry.get<esengine::ecs::Children>(parent).entities,
+ std::vector<esengine::Entity>{a, b, c});
+
+ std::vector<esengine::Entity> order{parent, c, a, b};
+ esengine::ecs::applySceneEntityOrder(registry, order.data(), order.size());
+
+ CHECK_EQ(registry.get<esengine::ecs::Children>(parent).entities,
+ std::vector<esengine::Entity>{c, a, b});
+}
+
+TEST_CASE("applySceneEntityOrder keeps unlisted children after the listed ones") {
+ esengine::ecs::Registry registry;
+ esengine::Entity parent = registry.create();
+ esengine::Entity a = registry.create();
+ esengine::Entity b = registry.create();
+ esengine::Entity c = registry.create();
+ for (auto child : {a, b, c}) esengine::ecs::setParent(registry, child, parent);
+
+ std::vector<esengine::Entity> order{c};
+ esengine::ecs::applySceneEntityOrder(registry, order.data(), order.size());
+
+ CHECK_EQ(registry.get<esengine::ecs::Children>(parent).entities,
+ std::vector<esengine::Entity>{c, a, b});
+}