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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { App, Plugin } from '../../app/app';
import { registerComponent, Transform, Parent, Sprite } from '../../ecs/component';
import type { TransformData, ParentData, SpriteData } from '../../ecs/component';
import { UINode } from '../core/ui-node';
import type { UINodeData } from '../core/ui-node';
import { px } from '../core/dimension';
import { defineSystem, Schedule } from '../../ecs/system';
import { Res } from '../../ecs/resource';
import { Input } from '../../input/input';
import { primaryPointerCancellationVersion } from '../../input/pointerCancellation';
import { engineApi } from '../../ecs/bridge/engineApi';
import type { InputState } from '../../input/input';
import type { Entity } from '../../types';
import type { World } from '../../ecs/world';
import { Draggable, DragState } from './draggable';
import type { DraggableData, DragStateData } from './draggable';
import { Interactable, UIInteraction } from './interactable';
import type { UIInteractionData } from './interactable';
import { UIEvents, UIEventQueue } from '../core/events';
import { UICameraInfo } from '../core/ui-camera-info';
import { ScreenLayout, type ScreenLayoutData } from '../core/screen-layout';
import { ScreenOverlay, type ScreenOverlayData } from '../core/screen-overlay';
import { uiPointerFor } from '../util/ui-pick';
import type { UICameraData } from '../core/ui-camera-info';
import { playModeOnly } from '../../ecs/env';
import { getEntityDepth } from '../util/helpers';
import { createLiveVisibilityQuery } from '../util/live-visibility';
import { createLocalTransformReader } from '../util/local-transform';
import { SystemLabel, PluginName } from '../../ecs/systemLabels';
import { quaternionToAngle2D } from '../util/math';
function worldToLocalDelta(
world: World,
entity: Entity,
dx: number,
dy: number,
readParent?: (parent: Entity, dx: number, dy: number) => { x: number; y: number } | null | undefined,
): { x: number; y: number } | null {
if (!world.has(entity, Parent)) {
return { x: dx, y: dy };
}
const parentData = world.get(entity, Parent) as ParentData;
const parentEntity = parentData.entity;
if (!world.valid(parentEntity) || !world.has(parentEntity, Transform)) {
return { x: dx, y: dy };
}
const resolved = readParent?.(parentEntity, dx, dy);
if (resolved !== undefined) return resolved;
const parentWt = world.get(parentEntity, Transform) as TransformData;
const sx = parentWt.worldScale.x !== 0 ? parentWt.worldScale.x : 1;
const sy = parentWt.worldScale.y !== 0 ? parentWt.worldScale.y : 1;
const angle = quaternionToAngle2D(parentWt.worldRotation.z, parentWt.worldRotation.w);
const sin = Math.sin(-angle);
const cos = Math.cos(-angle);
return {
x: (dx * cos - dy * sin) / sx,
y: (dx * sin + dy * cos) / sy,
};
}
function applyConstraints(
draggable: DraggableData,
dragState: DragStateData,
newX: number,
newY: number
): { x: number; y: number } {
let x = draggable.lockX ? dragState.startWorldPos.x : newX;
let y = draggable.lockY ? dragState.startWorldPos.y : newY;
// A flag rather than a null bound: zero is a usable limit, so it cannot
// double as "no limit".
if (draggable.constrainMin) {
x = Math.max(x, draggable.constraintMin.x);
y = Math.max(y, draggable.constraintMin.y);
}
if (draggable.constrainMax) {
x = Math.min(x, draggable.constraintMax.x);
y = Math.min(y, draggable.constraintMax.y);
}
return { x, y };
}
export class DragPlugin implements Plugin {
name = PluginName.Drag;
dependencies = [PluginName.UIInteraction];
private readonly cleanups_ = new Map<App, () => void>();
cleanup(app?: App): void {
if (app) {
const cleanup = this.cleanups_.get(app);
this.cleanups_.delete(app);
cleanup?.();
} else {
const cleanups = [...this.cleanups_.values()];
this.cleanups_.clear();
for (const cleanup of cleanups) cleanup();
}
}
build(app: App): void {
this.cleanup(app);
registerComponent('Draggable', Draggable);
registerComponent('DragState', DragState);
const world = app.world;
const events = app.getResource(UIEvents) as UIEventQueue;
const engine = engineApi(app);
const registry = world.getCppRegistry();
const localTransform = createLocalTransformReader(world);
const releaseMatrix = localTransform.dispose;
const readParentDelta = localTransform.vector;
const eligible = (entity: Entity): boolean => world.valid(entity) && world.isEntityActive(entity)
&& !world.isDestructionPending(entity)
&& world.has(entity, Draggable) && world.get(entity, Draggable).enabled
&& world.has(entity, Transform)
&& (!world.has(entity, Interactable) || world.get(entity, Interactable).enabled)
// Fresh per check: drag callbacks may hide an ancestor before the
// next layout pass, invalidating an earlier visibility snapshot.
&& !createLiveVisibilityQuery(world, target => !!(world.has(target, UINode)
&& engine?.getUINodeHiddenInTree?.(registry!, target)))(entity);
let pendingEntity: Entity | null = null;
let pendingStartWorld = { x: 0, y: 0 };
let activeEntity: Entity | null = null;
let lastCancellationVersion = primaryPointerCancellationVersion(app.getResource(Input));
const stopCapture = (): void => {
const entity = activeEntity ?? pendingEntity;
const started = activeEntity !== null;
activeEntity = pendingEntity = null;
if (entity === null || !world.valid(entity) || world.isDestructionPending(entity)) return;
if (world.has(entity, DragState)) {
world.update(entity, DragState, d => { d.isDragging = false; });
}
if (started) events.emit(entity, 'drag_end');
};
this.cleanups_.set(app, () => {
try { stopCapture(); } finally { releaseMatrix(); }
});
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
[Res(Input), Res(UICameraInfo), Res(ScreenLayout), Res(ScreenOverlay)],
(input: InputState, camera: UICameraData, layout: ScreenLayoutData,
overlay: ScreenOverlayData) => {
const cancellationVersion = primaryPointerCancellationVersion(input);
const cancelled = cancellationVersion !== lastCancellationVersion;
lastCancellationVersion = cancellationVersion;
if (!camera.valid && !overlay.active) { stopCapture(); return; }
const captured = activeEntity ?? pendingEntity;
if (captured !== null && (cancelled || !eligible(captured)
|| !world.has(captured, DragState)
|| (!input.isMouseButtonDown(0) && !input.isMouseButtonReleased(0)))) stopCapture();
// Per ENTITY, not once per frame: a drag subtracts a pointer from
// a transform, and the two share coordinates only if the pointer
// was projected into the domain the entity is laid out in.
const pointerFor = (entity: Entity): { x: number; y: number } =>
uiPointerFor(world, entity, camera, overlay);
if (input.isMouseButtonPressed(0) && input.isMouseButtonDown(0)) {
const draggableEntities = world.getEntitiesWithComponents([Draggable, UIInteraction]);
let bestEntity: Entity | null = null;
let bestLayer = -Infinity;
let bestDepth = -1;
for (const entity of draggableEntities) {
const interaction = world.get(entity, UIInteraction) as UIInteractionData;
if (interaction.hovered && eligible(entity)) {
let layer = 0;
if (world.has(entity, Sprite)) {
layer = (world.get(entity, Sprite) as SpriteData).layer;
}
const depth = getEntityDepth(world, entity);
if (layer > bestLayer || (layer === bestLayer && depth >= bestDepth)) {
bestLayer = layer;
bestDepth = depth;
bestEntity = entity;
}
}
}
if (bestEntity !== null) {
pendingEntity = bestEntity;
const pointer = pointerFor(bestEntity);
pendingStartWorld = { x: pointer.x, y: pointer.y };
if (!world.has(bestEntity, DragState)) {
world.insert(bestEntity, DragState);
}
const wt = world.get(bestEntity, Transform) as TransformData;
world.update(bestEntity, DragState, (d) => {
d.startWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };
d.currentWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };
d.pointerStartWorld = { x: pointer.x, y: pointer.y };
d.deltaWorld = { x: 0, y: 0 };
d.totalDeltaWorld = { x: 0, y: 0 };
d.isDragging = false;
});
}
}
if (pendingEntity !== null && !input.isMouseButtonDown(0)) {
if (world.valid(pendingEntity) && world.has(pendingEntity, DragState)) {
world.update(pendingEntity, DragState, (d) => { d.isDragging = false; });
}
pendingEntity = null;
}
if (pendingEntity !== null && activeEntity === null) {
if (!world.valid(pendingEntity)) {
pendingEntity = null;
return;
}
const pointer = pointerFor(pendingEntity);
const dx = pointer.x - pendingStartWorld.x;
const dy = pointer.y - pendingStartWorld.y;
const dist = Math.sqrt(dx * dx + dy * dy);
const draggable = world.get(pendingEntity, Draggable) as DraggableData;
const screenDist = dist * layout.scale;
if (screenDist >= draggable.dragThreshold) {
activeEntity = pendingEntity;
pendingEntity = null;
world.update(activeEntity, DragState, (d) => { d.isDragging = true; });
events.emit(activeEntity, 'drag_start');
}
}
if (activeEntity !== null) {
if (!eligible(activeEntity) || !world.has(activeEntity, DragState)) {
stopCapture();
return;
}
const dragState = world.get(activeEntity, DragState) as DragStateData;
const draggable = world.get(activeEntity, Draggable) as DraggableData;
const pointer = pointerFor(activeEntity);
const pointerDeltaX = pointer.x - dragState.pointerStartWorld.x;
const pointerDeltaY = pointer.y - dragState.pointerStartWorld.y;
let newWorldX = dragState.startWorldPos.x + pointerDeltaX;
let newWorldY = dragState.startWorldPos.y + pointerDeltaY;
const constrained = applyConstraints(draggable, dragState, newWorldX, newWorldY);
newWorldX = constrained.x;
newWorldY = constrained.y;
const prevX = dragState.currentWorldPos.x;
const prevY = dragState.currentWorldPos.y;
const localDelta = worldToLocalDelta(world, activeEntity, newWorldX - prevX, newWorldY - prevY, readParentDelta);
if (!localDelta) { stopCapture();return; }
world.update(activeEntity, DragState, (d) => {
d.deltaWorld = { x: newWorldX - prevX, y: newWorldY - prevY };
d.currentWorldPos = { x: newWorldX, y: newWorldY };
d.totalDeltaWorld = {
x: newWorldX - d.startWorldPos.x,
y: newWorldY - d.startWorldPos.y,
};
});
if (world.has(activeEntity, UINode)) {
// Nudge the CSS-box absolute insets (the layout input), so
// the dragged position survives the next layout pass.
const node = world.get(activeEntity, UINode) as UINodeData;
const baseL = node.insetLeft.unit === 0 ? node.insetLeft.value : 0;
const baseT = node.insetTop.unit === 0 ? node.insetTop.value : 0;
node.insetLeft = px(baseL + localDelta.x);
node.insetTop = px(baseT - localDelta.y); // inset top is y-down
world.insert(activeEntity, UINode, node);
} else if (world.has(activeEntity, Transform)) {
world.update(activeEntity, Transform, (t) => {
t.position.x += localDelta.x;
t.position.y += localDelta.y;
});
}
events.emit(activeEntity, 'drag_move');
if (!eligible(activeEntity) || !world.has(activeEntity, DragState)) {
stopCapture();
return;
}
if (input.isMouseButtonReleased(0)) {
stopCapture();
}
}
},
{ name: 'DragSystem', runAfter: [SystemLabel.UIInteraction] }
), { runIf: playModeOnly });
}
}
export const dragPlugin = new DragPlugin();