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.

feat(editor): click-through selection cycling for overlapping entities

esengine025b222b3b82
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index 34705bb9e..c1116d0c0 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -135,31 +135,37 @@ export const ViewportController = {
return hit;
},
- /** Topmost entity under the pointer — UI (screen-space) first, then a world OBB. */
- pickEntity(clientX: number, clientY: number): EntityId | null {
+ /** Selectable entities under the pointer, topmost-first (UI, then world by
+ * descending layer, later-drawn winning ties). `pickEntity` is its head;
+ * click-through cycling walks the rest. */
+ pickEntitiesAt(clientX: number, clientY: number): EntityId[] {
+ const out: EntityId[] = [];
const ui = this.pickUIEntity(clientX, clientY);
- if (ui != null) return ui;
+ if (ui != null) out.push(ui);
const world = EngineHost.world;
const wp = this.canvasToWorld(clientX, clientY);
- if (!world || !wp) return null;
-
- let best: EntityId | null = null;
- let bestLayer = -Infinity;
- for (const e of world.getAllEntities()) {
- if (!world.has(e, Transform)) continue;
- // Locked / editor-hidden entities aren't click-selectable in the viewport.
- const src = SceneModel.sourceFor(e);
- if (src != null && (SceneModel.isLocked(src) || SceneModel.isHidden(src))) continue;
- const b = this.entityBounds(e);
- if (!b || !pointInOBB(wp.x, wp.y, b)) continue;
- const layer = world.has(e, Sprite) ? world.get(e, Sprite).layer : ICON_PICK_LAYER;
- if (layer >= bestLayer) {
- bestLayer = layer;
- best = e;
+ if (world && wp) {
+ const hits: { e: EntityId; layer: number; i: number }[] = [];
+ for (const e of world.getAllEntities()) {
+ if (!world.has(e, Transform)) continue;
+ // Locked / editor-hidden entities aren't click-selectable in the viewport.
+ const src = SceneModel.sourceFor(e);
+ if (src != null && (SceneModel.isLocked(src) || SceneModel.isHidden(src))) continue;
+ const b = this.entityBounds(e);
+ if (!b || !pointInOBB(wp.x, wp.y, b)) continue;
+ const layer = world.has(e, Sprite) ? world.get(e, Sprite).layer : ICON_PICK_LAYER;
+ hits.push({ e, layer, i: hits.length });
}
+ hits.sort((a, b) => b.layer - a.layer || b.i - a.i);
+ for (const h of hits) out.push(h.e);
}
- return best;
+ return out;
+ },
+
+ /** Topmost entity under the pointer — UI (screen-space) first, then a world OBB. */
+ pickEntity(clientX: number, clientY: number): EntityId | null {
+ return this.pickEntitiesAt(clientX, clientY)[0] ?? null;
},
/** Entities whose screen bounds intersect a client-space rect (marquee box-select). */
diff --git a/desktop/src/tools/transformTools.ts b/desktop/src/tools/transformTools.ts
index 40212206e..f3431d9b3 100644
--- a/desktop/src/tools/transformTools.ts
+++ b/desktop/src/tools/transformTools.ts
@@ -10,7 +10,7 @@
* (Alt duplicates first);
* 3. empty space → a marquee box-select.
* A stroke is one undo transaction; group rotate/scale orbit the selection's
- * shared pivot, so multi-select transforms behave like UE's.
+ * shared pivot, so a multi-selection transforms as one rigid group.
*/
import { ViewportController } from '@/engine/ViewportController';
import { SceneCommands, type EditorTransaction } from '@/engine/SceneCommands';
@@ -193,7 +193,7 @@ function applyMove(d: Drag, curWorld: Pt): void {
const ed = useEditorStore.getState();
if (ed.snapping && d.targets.length) {
// Snap the primary's resulting position to the grid, apply that delta to all,
- // so the group keeps its relative layout (UE-style group grid snap).
+ // so the group keeps its relative layout.
const p0 = d.targets[0].start;
if (d.axis !== 'y') dx = snapTo(p0.x + dx, ed.snapStep) - p0.x;
if (d.axis !== 'x') dy = snapTo(p0.y + dy, ed.snapStep) - p0.y;
@@ -231,9 +231,38 @@ function applyScale(d: Drag, cur: Pt): void {
}
}
+/** Repeated clicks within this pixel radius count as the same spot; a press that
+ * travels farther is a drag, not a click. */
+const CLICK_SLOP = 4;
+
+export interface CycleState {
+ x: number;
+ y: number;
+ key: string;
+ idx: number;
+}
+
+const stackKey = (stack: readonly EntityId[]) => stack.join(',');
+
+/** True when a click at (x,y) continues the click-through walk stored in `c`. */
+export function sameCycleSpot(c: CycleState | null, key: string, x: number, y: number): boolean {
+ return c != null && c.key === key && Math.abs(c.x - x) <= CLICK_SLOP && Math.abs(c.y - y) <= CLICK_SLOP;
+}
+
+/** Next click-through pick: the topmost, or the next one down when the same spot on
+ * the same stack is re-clicked (wrapping). Null when there's nothing to cycle. */
+export function stepCycle(stack: readonly EntityId[], c: CycleState | null, x: number, y: number): { pick: EntityId; cycle: CycleState } | null {
+ if (stack.length < 2) return null;
+ const key = stackKey(stack);
+ const idx = sameCycleSpot(c, key, x, y) ? (c!.idx + 1) % stack.length : 0;
+ return { pick: stack[idx], cycle: { x, y, key, idx } };
+}
+
function makeTransformTool(mode: ToolMode): EditorTool {
let drag: Drag | null = null;
let marquee: MarqueeState | null = null;
+ let pendingClick: { downX: number; downY: number; stack: EntityId[] } | null = null;
+ let cycle: CycleState | null = null;
// The select tool shares the move drag (click selects, drag moves) but shows no
// transform gizmo; move/rotate/scale do. kind === the tool's transform.
const kind: Kind = mode === 'rotate' ? 'rotate' : mode === 'scale' ? 'scale' : 'move';
@@ -266,16 +295,22 @@ function makeTransformTool(mode: ToolMode): EditorTool {
}
// 2) Pick an entity → select + free transform (Shift toggles, Alt duplicates).
- const rtId = ViewportController.pickEntity(p.clientX, p.clientY);
- const hitSource = rtId != null ? SceneModel.sourceFor(rtId) ?? null : null;
+ const stack = ViewportController.pickEntitiesAt(p.clientX, p.clientY)
+ .map((rt) => SceneModel.sourceFor(rt))
+ .filter((s): s is EntityId => s != null);
+ const hitSource = stack[0] ?? null;
if (hitSource != null) {
if (p.shift) {
- sel.toggleSelect(hitSource); // selection edit only; no drag
+ sel.toggleSelect(hitSource);
+ cycle = null;
return false;
}
- const inSel = sel.selectedIds.has(hitSource);
- if (!inSel) sel.select(hitSource);
- const ids = inSel ? [...sel.selectedIds] : [hitSource];
+ // Fresh click selects the topmost; mid-cycle keeps the current pick so
+ // pointer-up can advance it (and a drag still grabs the selected object).
+ const cycling = sameCycleSpot(cycle, stack.join(','), p.clientX, p.clientY);
+ if (!cycling && !sel.selectedIds.has(hitSource)) sel.select(hitSource);
+ pendingClick = { downX: p.clientX, downY: p.clientY, stack };
+ const ids = [...useSelection.getState().selectedIds];
let targets: Target[];
let pivotWorld: Pt | null;
@@ -295,12 +330,19 @@ function makeTransformTool(mode: ToolMode): EditorTool {
}
// 3) Empty space → marquee box-select (Shift = additive).
+ cycle = null;
marquee = { downX: p.clientX, downY: p.clientY, additive: p.shift, base: new Set(sel.selectedIds) };
ctx.capture(p.pointerId);
return true;
},
onPointerMove(p) {
+ // A press that travels past the slop is a drag, not a click — disarm the
+ // click-through cycle so releasing won't advance the selection.
+ if (pendingClick && (Math.abs(p.clientX - pendingClick.downX) > CLICK_SLOP || Math.abs(p.clientY - pendingClick.downY) > CLICK_SLOP)) {
+ pendingClick = null;
+ cycle = null;
+ }
if (drag) {
const origin = canvasOrigin();
const cur: Pt = origin
@@ -332,6 +374,15 @@ function makeTransformTool(mode: ToolMode): EditorTool {
drag.tx.commit();
drag = null;
useEditorStore.getState().setActiveGizmoAxis(null);
+ // A bare click (no drag) on overlapping entities walks to the next one down.
+ const stepped = pendingClick && stepCycle(pendingClick.stack, cycle, p.clientX, p.clientY);
+ pendingClick = null;
+ if (stepped) {
+ useSelection.getState().select(stepped.pick);
+ cycle = stepped.cycle;
+ } else {
+ cycle = null;
+ }
return;
}
if (marquee) {
@@ -368,6 +419,8 @@ function makeTransformTool(mode: ToolMode): EditorTool {
}
Marquee.set(null);
marquee = null;
+ pendingClick = null;
+ cycle = null;
},
};
}
diff --git a/desktop/tests/transform-cycle.test.ts b/desktop/tests/transform-cycle.test.ts
new file mode 100644
index 000000000..0f364106f
--- /dev/null
+++ b/desktop/tests/transform-cycle.test.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Click-through selection cycling: clicking the same spot on a stack of
+ * overlapping entities walks down to the next one, wrapping.
+ */
+import { describe, it, expect } from 'vitest';
+import { stepCycle, sameCycleSpot, type CycleState } from '@/tools/transformTools';
+
+const STACK = [10, 20, 30]; // topmost-first
+
+describe('stepCycle', () => {
+ it('first click selects the topmost and seeds the cycle', () => {
+ const r = stepCycle(STACK, null, 100, 100)!;
+ expect(r.pick).toBe(10);
+ expect(r.cycle).toEqual({ x: 100, y: 100, key: '10,20,30', idx: 0 });
+ });
+
+ it('repeated clicks at the same spot walk down and wrap', () => {
+ let c: CycleState | null = null;
+ const picks: number[] = [];
+ for (let i = 0; i < 4; i++) {
+ const r = stepCycle(STACK, c, 100, 100)!;
+ picks.push(r.pick);
+ c = r.cycle;
+ }
+ expect(picks).toEqual([10, 20, 30, 10]);
+ });
+
+ it('a click within the slop still counts as the same spot', () => {
+ const first = stepCycle(STACK, null, 100, 100)!;
+ expect(stepCycle(STACK, first.cycle, 103, 97)!.pick).toBe(20); // advanced
+ });
+
+ it('a click beyond the slop restarts at the topmost', () => {
+ const first = stepCycle(STACK, null, 100, 100)!;
+ expect(stepCycle(STACK, first.cycle, 200, 200)!.pick).toBe(10); // reset
+ });
+
+ it('a different stack at the same spot restarts', () => {
+ const first = stepCycle(STACK, null, 100, 100)!;
+ expect(stepCycle([40, 50], first.cycle, 100, 100)!.pick).toBe(40);
+ });
+
+ it('a single-entity (or empty) stack has nothing to cycle', () => {
+ expect(stepCycle([10], null, 100, 100)).toBeNull();
+ expect(stepCycle([], null, 100, 100)).toBeNull();
+ });
+});
+
+describe('sameCycleSpot', () => {
+ const c: CycleState = { x: 100, y: 100, key: '10,20,30', idx: 1 };
+ it('matches within the slop on the same stack', () => {
+ expect(sameCycleSpot(c, '10,20,30', 104, 96)).toBe(true);
+ });
+ it('rejects a far click, a different stack, or no prior cycle', () => {
+ expect(sameCycleSpot(c, '10,20,30', 120, 100)).toBe(false);
+ expect(sameCycleSpot(c, '10,20', 100, 100)).toBe(false);
+ expect(sameCycleSpot(null, '10,20,30', 100, 100)).toBe(false);
+ });
+});
diff --git a/desktop/tests/transform-tool.test.ts b/desktop/tests/transform-tool.test.ts
index 197a2d4da..160fde224 100644
--- a/desktop/tests/transform-tool.test.ts
+++ b/desktop/tests/transform-tool.test.ts
@@ -11,7 +11,7 @@ import { GIZMO } from '@/tools/gizmo';
// Shared mutable test state the module mocks read (hoisted above the vi.mock calls).
const h = vi.hoisted(() => ({
- pick: { entity: null as number | null, rect: [] as number[] },
+ pick: { entity: null as number | null, rect: [] as number[], stack: undefined as number[] | undefined },
pos: new Map<number, { x: number; y: number }>(),
calls: { setXY: [] as Array<[number, number, number]>, dup: [] as number[], commit: 0, abort: 0 },
}));
@@ -25,6 +25,7 @@ vi.mock('@/engine/ViewportController', () => ({
worldToClient: (x: number, y: number) => ({ x, y }),
getEntityXY: (rt: number) => h.pos.get(rt) ?? { x: 0, y: 0 },
pickEntity: () => h.pick.entity,
+ pickEntitiesAt: () => (h.pick.stack ?? (h.pick.entity != null ? [h.pick.entity] : [])),
pickInRect: () => h.pick.rect,
},
}));
@@ -58,6 +59,7 @@ const ev = (x: number, y: number, mod: Partial<{ shift: boolean; alt: boolean }>
beforeEach(() => {
h.pick.entity = null;
h.pick.rect = [];
+ h.pick.stack = undefined;
h.pos.clear();
h.calls.setXY = [];
h.calls.dup = [];
@@ -123,6 +125,31 @@ describe('entity pick → select + move', () => {
t.onPointerUp(ev(140, 100), ctx);
expect(h.calls.setXY.at(-1)).toEqual([107, 140, 100]); // copy tracks the cursor from the original's start
});
+
+ it('repeated clicks at the same spot cycle through the overlapping stack', () => {
+ h.pick.stack = [7, 8, 9]; // topmost-first, all under (100,100)
+ for (const id of [7, 8, 9]) h.pos.set(id, { x: 100, y: 100 });
+ const t = TRANSFORM_TOOLS.select;
+ const click = () => {
+ t.onPointerDown(ev(100, 100), ctx);
+ t.onPointerUp(ev(100, 100), ctx);
+ return useSelection.getState().selectedId;
+ };
+ expect([click(), click(), click(), click()]).toEqual([7, 8, 9, 7]);
+ });
+
+ it('a drag grabs the selected object instead of cycling', () => {
+ h.pick.stack = [7, 8];
+ h.pos.set(7, { x: 100, y: 100 });
+ const t = TRANSFORM_TOOLS.move;
+ t.onPointerDown(ev(100, 100), ctx);
+ t.onPointerUp(ev(100, 100), ctx); // click 1 → 7
+ t.onPointerDown(ev(100, 100), ctx);
+ t.onPointerMove(ev(140, 100), ctx); // drag past the slop
+ t.onPointerUp(ev(140, 100), ctx);
+ expect(useSelection.getState().selectedId).toBe(7); // stayed on 7, moved it
+ expect(h.calls.setXY.at(-1)).toEqual([7, 140, 100]);
+ });
});
describe('gizmo handle → axis-constrained group transform', () => {