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
refactor(ui): co-locate layout/input/render concepts into modules (REARCH_GUI P0)
esengine5273719fac2b
diff --git a/sdk/src/ui/DragPlugin.ts b/sdk/src/ui/DragPlugin.tsindex 9be5aec0d..47d7d5e08 100644--- a/sdk/src/ui/DragPlugin.ts+++ b/sdk/src/ui/DragPlugin.ts@@ -1,228 +1,7 @@-import type { App, Plugin } from '../app';-import { registerComponent, Transform, Parent, Sprite } from '../component';-import type { TransformData, ParentData, SpriteData } from '../component';-import { UIRect } from './core/ui-rect';-import type { UIRectData } from './core/ui-rect';-import { defineSystem, Schedule } from '../system';-import { Res } from '../resource';-import { Input } from '../input';-import type { InputState } from '../input';-import type { Entity } from '../types';-import type { World } from '../world';-import { Draggable, DragState } from './behavior/draggable';-import type { DraggableData, DragStateData } from './behavior/draggable';-import { UIInteraction } from './behavior/interactable';-import type { UIInteractionData } from './behavior/interactable';-import { UIEvents, UIEventQueue } from './core/events';-import { UICameraInfo } from './UICameraInfo';-import type { UICameraData } from './UICameraInfo';-import { playModeOnly } from '../env';-import { getEntityDepth } from './uiHelpers';-import { SystemLabel, PluginName } from '../systemLabels';-import { quaternionToAngle2D } from './uiMath';--function worldToLocalDelta(- world: World,- entity: Entity,- dx: number,- dy: number-): { x: number; y: number } {- 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 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;-- if (draggable.constraintMin !== null) {- x = Math.max(x, draggable.constraintMin.x);- y = Math.max(y, draggable.constraintMin.y);- }- if (draggable.constraintMax !== null) {- 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];-- build(app: App): void {- registerComponent('Draggable', Draggable);- registerComponent('DragState', DragState);-- const world = app.world;- const events = app.getResource(UIEvents) as UIEventQueue;-- let pendingEntity: Entity | null = null;- let pendingStartWorld = { x: 0, y: 0 };- let activeEntity: Entity | null = null;-- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(Input), Res(UICameraInfo)],- (input: InputState, camera: UICameraData) => {- if (!camera.valid) return;-- const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };-- if (input.isMouseButtonPressed(0)) {- const draggableEntities = world.getEntitiesWithComponents([Draggable, UIInteraction]);- let bestEntity: Entity | null = null;- let bestLayer = -Infinity;- let bestDepth = -1;-- for (const entity of draggableEntities) {- const draggable = world.get(entity, Draggable) as DraggableData;- if (!draggable.enabled) continue;- const interaction = world.get(entity, UIInteraction) as UIInteractionData;- if (interaction.hovered) {- 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;- pendingStartWorld = { x: worldMouse.x, y: worldMouse.y };-- if (!world.has(bestEntity, DragState)) {- world.insert(bestEntity, DragState);- }- const dragState = world.get(bestEntity, DragState) as DragStateData;- const wt = world.get(bestEntity, Transform) as TransformData;- dragState.startWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };- dragState.currentWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };- dragState.pointerStartWorld = { x: worldMouse.x, y: worldMouse.y };- dragState.deltaWorld = { x: 0, y: 0 };- dragState.totalDeltaWorld = { x: 0, y: 0 };- dragState.isDragging = false;- }- }-- if (pendingEntity !== null && !input.isMouseButtonDown(0)) {- if (world.valid(pendingEntity) && world.has(pendingEntity, DragState)) {- const dragState = world.get(pendingEntity, DragState) as DragStateData;- dragState.isDragging = false;- }- pendingEntity = null;- }-- if (pendingEntity !== null && activeEntity === null) {- if (!world.valid(pendingEntity)) {- pendingEntity = null;- return;- }- const dx = worldMouse.x - pendingStartWorld.x;- const dy = worldMouse.y - pendingStartWorld.y;- const dist = Math.sqrt(dx * dx + dy * dy);- const draggable = world.get(pendingEntity, Draggable) as DraggableData;-- const screenDist = dist * (camera.vpW / (camera.worldRight - camera.worldLeft));- if (screenDist >= draggable.dragThreshold) {- activeEntity = pendingEntity;- pendingEntity = null;-- const dragState = world.get(activeEntity, DragState) as DragStateData;- dragState.isDragging = true;- events.emit(activeEntity, 'drag_start');- }- }-- if (activeEntity !== null) {- if (!world.valid(activeEntity) || !world.has(activeEntity, DragState)) {- activeEntity = null;- return;- }-- const dragState = world.get(activeEntity, DragState) as DragStateData;- const draggable = world.get(activeEntity, Draggable) as DraggableData;-- const pointerDeltaX = worldMouse.x - dragState.pointerStartWorld.x;- const pointerDeltaY = worldMouse.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;- dragState.deltaWorld = { x: newWorldX - prevX, y: newWorldY - prevY };- dragState.currentWorldPos = { x: newWorldX, y: newWorldY };- dragState.totalDeltaWorld = {- x: newWorldX - dragState.startWorldPos.x,- y: newWorldY - dragState.startWorldPos.y,- };-- if (world.has(activeEntity, UIRect)) {- const rect = world.get(activeEntity, UIRect) as UIRectData;- const localDelta = worldToLocalDelta(- world, activeEntity,- dragState.deltaWorld.x, dragState.deltaWorld.y- );- rect.offsetMin.x += localDelta.x;- rect.offsetMin.y += localDelta.y;- world.insert(activeEntity, UIRect, rect);- } else if (world.has(activeEntity, Transform)) {- const localDelta = worldToLocalDelta(- world, activeEntity,- dragState.deltaWorld.x, dragState.deltaWorld.y- );- const lt = world.get(activeEntity, Transform) as TransformData;- lt.position.x += localDelta.x;- lt.position.y += localDelta.y;- world.insert(activeEntity, Transform, lt);- }-- events.emit(activeEntity, 'drag_move');-- if (input.isMouseButtonReleased(0)) {- dragState.isDragging = false;- events.emit(activeEntity, 'drag_end');- activeEntity = null;- }- }- },- { name: 'DragSystem', runAfter: [SystemLabel.UIInteraction] }- ), { runIf: playModeOnly });- }-}--export const dragPlugin = new DragPlugin();+/**+ * @file ui/DragPlugin.ts+ * @brief Back-compat shim — the drag plugin moved to the input concept module+ * (REARCH_GUI P0). Re-exported here to keep the public symbol ++ * existing imports stable until REARCH_GUI P4.+ */+export { DragPlugin, dragPlugin } from './input/drag';diff --git a/sdk/src/ui/FocusPlugin.ts b/sdk/src/ui/FocusPlugin.tsindex a17df929e..9929a031d 100644--- a/sdk/src/ui/FocusPlugin.ts+++ b/sdk/src/ui/FocusPlugin.ts@@ -1,103 +1,7 @@-import type { App, Plugin } from '../app';-import { registerComponent } from '../component';-import { defineSystem, Schedule } from '../system';-import { Res } from '../resource';-import { Input } from '../input';-import type { InputState } from '../input';-import type { Entity } from '../types';-import { Focusable, FocusManager, FocusManagerState } from './behavior/focusable';-import type { FocusableData } from './behavior/focusable';-import { Interactable } from './behavior/interactable';-import type { InteractableData } from './behavior/interactable';-import { UIInteraction } from './behavior/interactable';-import type { UIInteractionData } from './behavior/interactable';-import { playModeOnly } from '../env';-import { UIEvents, UIEventQueue } from './core/events';-import { PluginName } from '../systemLabels';--export class FocusPlugin implements Plugin {- name = PluginName.Focus;- dependencies = [PluginName.UIInteraction];-- build(app: App): void {- registerComponent('Focusable', Focusable);-- const world = app.world;- const focusManager = new FocusManagerState();- app.insertResource(FocusManager, focusManager);-- app.addSystemToSchedule(Schedule.Update, defineSystem(- [Res(Input), Res(UIEvents)],- (input: InputState, events: UIEventQueue) => {- if (focusManager.focusedEntity !== null && !world.valid(focusManager.focusedEntity)) {- focusManager.focusedEntity = null;- }-- const focusableEntities = world.getEntitiesWithComponents([Focusable]);-- for (const entity of focusableEntities) {- if (!world.has(entity, UIInteraction)) continue;- const interaction = world.get(entity, UIInteraction) as UIInteractionData;- if (interaction.justPressed) {- setFocus(entity);- }- }-- if (input.isKeyPressed('Tab')) {- const sorted = getSortedFocusables();- if (sorted.length === 0) return;-- const currentIdx = focusManager.focusedEntity !== null- ? sorted.findIndex(e => e === focusManager.focusedEntity)- : -1;-- const reverse = input.isKeyDown('Shift');- let nextIdx: number;- if (currentIdx === -1) {- nextIdx = reverse ? sorted.length - 1 : 0;- } else {- nextIdx = reverse- ? (currentIdx - 1 + sorted.length) % sorted.length- : (currentIdx + 1) % sorted.length;- }-- setFocus(sorted[nextIdx]);- }-- function getSortedFocusables(): Entity[] {- const entries: { entity: Entity; tabIndex: number }[] = [];- for (const entity of focusableEntities) {- if (!world.valid(entity)) continue;- if (world.has(entity, Interactable)) {- const interactable = world.get(entity, Interactable) as InteractableData;- if (!interactable.enabled) continue;- }- const f = world.get(entity, Focusable) as FocusableData;- entries.push({ entity, tabIndex: f.tabIndex });- }- entries.sort((a, b) => a.tabIndex - b.tabIndex);- return entries.map(e => e.entity);- }-- function setFocus(entity: Entity): void {- const prev = focusManager.focusedEntity;- if (prev === entity) return;-- if (prev !== null && world.valid(prev) && world.has(prev, Focusable)) {- const prevF = world.get(prev, Focusable) as FocusableData;- prevF.isFocused = false;- events.emit(prev, 'blur');- }-- focusManager.focus(entity);- const f = world.get(entity, Focusable) as FocusableData;- f.isFocused = true;- events.emit(entity, 'focus');- }- },- { name: 'FocusSystem' }- ), { runIf: playModeOnly });- }-}--export const focusPlugin = new FocusPlugin();+/**+ * @file ui/FocusPlugin.ts+ * @brief Back-compat shim — the focus plugin moved to the input concept module+ * (REARCH_GUI P0). Re-exported here to keep the public symbol ++ * existing imports stable until REARCH_GUI P4.+ */+export { FocusPlugin, focusPlugin } from './input/focus';diff --git a/sdk/src/ui/ImagePlugin.ts b/sdk/src/ui/ImagePlugin.tsindex 4e290b579..ecfd83088 100644--- a/sdk/src/ui/ImagePlugin.ts+++ b/sdk/src/ui/ImagePlugin.ts@@ -1,114 +1,7 @@-import type { App, Plugin } from '../app';-import type { Entity } from '../types';-import { registerComponent } from '../component';-import { defineSystem, Schedule } from '../system';-import { Image, ImageType, FillMethod, FillOrigin } from './core/image';-import type { ImageData } from './core/image';-import { UIRect } from './core/ui-rect';-import type { UIRectData } from './core/ui-rect';-import { UIRenderer, UIVisualType } from './core/ui-renderer';-import type { UIRendererData } from './core/ui-renderer';-import { getEffectiveWidth, getEffectiveHeight, ensureUIRenderer } from './uiHelpers';-import { SystemLabel, PluginName } from '../systemLabels';--export class ImagePlugin implements Plugin {- name = PluginName.Image;- dependencies = [PluginName.UILayout];-- build(app: App): void {- registerComponent('Image', Image);-- const world = app.world;- const lastRenderedTick = new Map<Entity, number>();-- world.enableChangeTracking(Image);- world.enableChangeTracking(UIRect);-- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [],- () => {- for (const entity of lastRenderedTick.keys()) {- if (!world.valid(entity) || !world.has(entity, Image)) {- lastRenderedTick.delete(entity);- }- }-- const entities = world.getEntitiesWithComponents([Image]);-- for (const entity of entities) {- const image = world.get(entity, Image) as ImageData;- const uiRect = world.has(entity, UIRect)- ? world.get(entity, UIRect) as UIRectData- : null;-- const prevTick = lastRenderedTick.get(entity);- if (prevTick !== undefined && world.has(entity, UIRenderer)) {- const imageChanged = world.isChangedSince(entity, Image, prevTick);- const rectChanged = uiRect && world.isChangedSince(entity, UIRect, prevTick);- if (!imageChanged && !rectChanged) continue;- }-- ensureUIRenderer(world, entity);-- const renderer = world.get(entity, UIRenderer) as UIRendererData;-- if (!image.enabled) {- renderer.enabled = false;- world.insert(entity, UIRenderer, renderer);- lastRenderedTick.set(entity, world.getWorldTick());- continue;- }-- renderer.enabled = true;- renderer.texture = image.texture;- renderer.color = { r: image.color.r, g: image.color.g, b: image.color.b, a: image.color.a };- renderer.material = image.material;-- renderer.uvOffset = { x: 0, y: 0 };- renderer.uvScale = { x: 1, y: 1 };-- const hasTexture = !!image.texture;- if (!hasTexture) {- renderer.visualType = UIVisualType.SolidColor;- } else if (image.imageType === ImageType.Sliced) {- renderer.visualType = UIVisualType.NineSlice;- } else {- renderer.visualType = UIVisualType.Image;- }-- if (image.imageType === ImageType.Filled) {- const amount = Math.max(0, Math.min(1, image.fillAmount));-- if (image.fillMethod === FillMethod.Horizontal) {- if (image.fillOrigin === FillOrigin.Left) {- renderer.uvScale = { x: amount, y: 1 };- } else {- renderer.uvOffset = { x: 1 - amount, y: 0 };- renderer.uvScale = { x: amount, y: 1 };- }- } else {- if (image.fillOrigin === FillOrigin.Bottom) {- renderer.uvScale = { x: 1, y: amount };- } else {- renderer.uvOffset = { x: 0, y: 1 - amount };- renderer.uvScale = { x: 1, y: amount };- }- }- } else if (image.imageType === ImageType.Tiled) {- const w = uiRect ? getEffectiveWidth(uiRect, entity) : 0;- const h = uiRect ? getEffectiveHeight(uiRect, entity) : 0;- if (image.tileSize.x > 0 && image.tileSize.y > 0) {- renderer.uvScale = { x: w / image.tileSize.x, y: h / image.tileSize.y };- }- }-- world.insert(entity, UIRenderer, renderer);- lastRenderedTick.set(entity, world.getWorldTick());- }- },- { name: 'ImageSystem' }- ), { runAfter: [SystemLabel.UILayout] });- }-}--export const imagePlugin = new ImagePlugin();+/**+ * @file ui/ImagePlugin.ts+ * @brief Back-compat shim — the Image→UIRenderer system moved to the render+ * concept module (REARCH_GUI P0). Re-exported here to keep the public+ * symbol + existing imports stable until REARCH_GUI P4.+ */+export { ImagePlugin, imagePlugin } from './render/image';diff --git a/sdk/src/ui/SafeArea.ts b/sdk/src/ui/SafeArea.tsindex 3d744b54c..52775a902 100644--- a/sdk/src/ui/SafeArea.ts+++ b/sdk/src/ui/SafeArea.ts@@ -1,15 +1,7 @@-import { defineComponent } from '../component';--export interface SafeAreaData {- applyTop: boolean;- applyBottom: boolean;- applyLeft: boolean;- applyRight: boolean;-}--export const SafeArea = defineComponent<SafeAreaData>('SafeArea', {- applyTop: true,- applyBottom: true,- applyLeft: true,- applyRight: true,-});+/**+ * @file ui/SafeArea.ts+ * @brief Back-compat shim — the SafeArea component moved into the layout+ * concept module (REARCH_GUI P0). Re-exported here to keep the+ * public symbol + existing imports stable until REARCH_GUI P4.+ */+export { SafeArea, type SafeAreaData } from './layout/safe-area';diff --git a/sdk/src/ui/SafeAreaPlugin.ts b/sdk/src/ui/SafeAreaPlugin.tsindex 102f0cb30..7e0610a7a 100644--- a/sdk/src/ui/SafeAreaPlugin.ts+++ b/sdk/src/ui/SafeAreaPlugin.ts@@ -1,137 +1,11 @@-import type { App, Plugin } from '../app';-import { isWeChat, platformDevicePixelRatio } from '../platform';-import { registerComponent } from '../component';-import { Res } from '../resource';-import { defineSystem, Schedule } from '../system';-import { SafeArea } from './SafeArea';-import type { SafeAreaData } from './SafeArea';-import { UICameraInfo } from './UICameraInfo';-import type { UICameraData } from './UICameraInfo';-import { UIRect } from './core/ui-rect';-import type { UIRectData } from './core/ui-rect';-import { SystemLabel, PluginName } from '../systemLabels';--export interface SafeAreaInsets {- top: number;- bottom: number;- left: number;- right: number;-}--interface WxGlobal {- wx?: {- getSystemInfoSync?(): { safeArea: { top: number; bottom: number; left: number; right: number }; screenWidth: number; screenHeight: number } | undefined;- onWindowResize?(cb: () => void): void;- };-}--function getWeChatSafeAreaInsets(): SafeAreaInsets {- const g = globalThis as unknown as WxGlobal;- const info = g.wx?.getSystemInfoSync?.();- if (!info || !info.safeArea) {- return { top: 0, bottom: 0, left: 0, right: 0 };- }- const { safeArea, screenWidth, screenHeight } = info;- return {- top: safeArea.top,- bottom: screenHeight - safeArea.bottom,- left: safeArea.left,- right: screenWidth - safeArea.right,- };-}--function getWebSafeAreaInsets(): SafeAreaInsets {- if (typeof document === 'undefined' || typeof getComputedStyle === 'undefined') {- return { top: 0, bottom: 0, left: 0, right: 0 };- }- const style = getComputedStyle(document.documentElement);- return {- top: parseFloat(style.getPropertyValue('--sat') || '0'),- bottom: parseFloat(style.getPropertyValue('--sab') || '0'),- left: parseFloat(style.getPropertyValue('--sal') || '0'),- right: parseFloat(style.getPropertyValue('--sar') || '0'),- };-}--function getSafeAreaInsets(): SafeAreaInsets {- if (isWeChat()) {- return getWeChatSafeAreaInsets();- }- return getWebSafeAreaInsets();-}--export class SafeAreaPlugin implements Plugin {- name = PluginName.SafeArea;- dependencies = [PluginName.UILayout];-- build(app: App): void {- registerComponent('SafeArea', SafeArea);-- const world = app.world;- let cachedInsets: SafeAreaInsets = getSafeAreaInsets();- let dirty = true;- let prevScreenH = 0;- let prevWorldH = 0;-- if (isWeChat()) {- const g = globalThis as unknown as WxGlobal;- g.wx?.onWindowResize?.(() => {- cachedInsets = getSafeAreaInsets();- dirty = true;- });- } else if (typeof window !== 'undefined') {- window.addEventListener('resize', () => {- cachedInsets = getSafeAreaInsets();- dirty = true;- });- }-- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(UICameraInfo)],- (camera: UICameraData) => {- if (!camera.valid || camera.screenH === 0) return;-- const worldH = camera.worldTop - camera.worldBottom;- if (camera.screenH !== prevScreenH || worldH !== prevWorldH) {- prevScreenH = camera.screenH;- prevWorldH = worldH;- dirty = true;- }-- if (!dirty) return;- dirty = false;-- const dpr = platformDevicePixelRatio();- const insetScale = isWeChat() ? (worldH / camera.screenH) : (dpr * worldH / camera.screenH);-- const entities = world.getEntitiesWithComponents([SafeArea, UIRect]);- for (const entity of entities) {- const sa = world.get(entity, SafeArea) as SafeAreaData;- const rect = world.get(entity, UIRect) as UIRectData;-- const top = sa.applyTop ? cachedInsets.top * insetScale : 0;- const bottom = sa.applyBottom ? cachedInsets.bottom * insetScale : 0;- const left = sa.applyLeft ? cachedInsets.left * insetScale : 0;- const right = sa.applyRight ? cachedInsets.right * insetScale : 0;-- let changed = false;- if (rect.offsetMin.x !== left || rect.offsetMin.y !== bottom) {- rect.offsetMin = { x: left, y: bottom };- changed = true;- }- if (rect.offsetMax.x !== -right || rect.offsetMax.y !== -top) {- rect.offsetMax = { x: -right, y: -top };- changed = true;- }-- if (changed) {- world.insert(entity, UIRect, rect);- }- }- },- { name: 'SafeAreaSystem' }- ), { runBefore: [SystemLabel.UILayout] });- }-}--export const safeAreaPlugin = new SafeAreaPlugin();+/**+ * @file ui/SafeAreaPlugin.ts+ * @brief Back-compat shim — the SafeArea plugin moved into the layout+ * concept module (REARCH_GUI P0). Re-exported here to keep the+ * public symbol + existing imports stable until REARCH_GUI P4.+ */+export {+ SafeAreaPlugin,+ safeAreaPlugin,+ type SafeAreaInsets,+} from './layout/safe-area';diff --git a/sdk/src/ui/UIInteractionPlugin.ts b/sdk/src/ui/UIInteractionPlugin.tsindex 3e1aaf00d..1b311ec00 100644--- a/sdk/src/ui/UIInteractionPlugin.ts+++ b/sdk/src/ui/UIInteractionPlugin.ts@@ -1,175 +1,7 @@-import type { App, Plugin } from '../app';-import { registerComponent, Transform } from '../component';-import { defineSystem, Schedule } from '../system';-import { Res } from '../resource';-import { Input } from '../input';-import type { InputState } from '../input';-import type { Entity } from '../types';-import type { World } from '../world';-import { playModeOnly } from '../env';-import { Interactable } from './behavior/interactable';-import { UIInteraction } from './behavior/interactable';-import type { UIInteractionData } from './behavior/interactable';-import { UIEvents, UIEventQueue, UIEventType } from './core/events';-import { UICameraInfo } from './UICameraInfo';-import type { UICameraData } from './UICameraInfo';-import type { InteractableData } from './behavior/interactable';-import { screenToWorld, createInvVPCache } from './uiMath';-import { platformDevicePixelRatio } from '../platform';-import { ensureComponent, walkParentChain } from './uiHelpers';-import type { ESEngineModule, CppRegistry } from '../wasm';-import { UILayoutGeneration } from './UILayoutGeneration';-import { SystemLabel, PluginName } from '../systemLabels';-import type { UILayoutGenerationData } from './UILayoutGeneration';--const vpCache = createInvVPCache();-const CPP_NO_HIT_ENTITY = 0xFFFFFFFF;--function emitWithBubbling(- world: World,- events: UIEventQueue,- entity: Entity,- type: string,-): void {- const event = events.emit(entity, type);-- walkParentChain(world, entity, (ancestor) => {- if (event.propagationStopped) return true;- if (!world.has(ancestor, Interactable)) return false;- const interactable = world.get(ancestor, Interactable) as InteractableData;- if (interactable.enabled) {- events.emitBubbled(ancestor, event);- }- return interactable.blockRaycast;- });-}--export class UIInteractionPlugin implements Plugin {- name = PluginName.UIInteraction;- dependencies = [PluginName.UILayout];-- build(app: App): void {- registerComponent('Interactable', Interactable);-- const world = app.world;- const module = app.wasmModule as ESEngineModule;- const registry = world.getCppRegistry() as CppRegistry;- const events = new UIEventQueue();- app.insertResource(UIEvents, events);- // Prune handlers when an entity dies. Replaces the old- // setEntityValidator pattern; canonical UIEventQueue has no- // validator hook because it's the plugin's job to wire cleanup.- app.world.onDespawn((e) => events.removeAll(e));-- let hoveredEntity: Entity | null = null;- let pressedEntity: Entity | null = null;- let lastPointerX = NaN;- let lastPointerY = NaN;- let lastLayoutGen = -1;-- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(Input), Res(UICameraInfo), Res(UILayoutGeneration)],- (input: InputState, camera: UICameraData, layoutGen: UILayoutGenerationData) => {- events.drain();-- const interactionEntities = world.getEntitiesWithComponents([UIInteraction]);- for (const entity of interactionEntities) {- const interaction = world.get(entity, UIInteraction) as UIInteractionData;- if (interaction.justPressed || interaction.justReleased) {- interaction.justPressed = false;- interaction.justReleased = false;- world.insert(entity, UIInteraction, interaction);- }- }-- if (!camera.valid) return;-- const dpr = platformDevicePixelRatio();- const mouseGLX = input.mouseX * dpr;- const mouseGLY = camera.screenH - input.mouseY * dpr;-- vpCache.update(camera.viewProjection);- const invVP = vpCache.getInverse(camera.viewProjection);- const worldMouse = screenToWorld(- mouseGLX, mouseGLY, invVP,- camera.vpX, camera.vpY, camera.vpW, camera.vpH,- );-- camera.worldMouseX = worldMouse.x;- camera.worldMouseY = worldMouse.y;-- const mouseDown = input.isMouseButtonDown(0);- const mousePressed = input.isMouseButtonPressed(0);- const mouseReleased = input.isMouseButtonReleased(0);-- const pointerMoved = worldMouse.x !== lastPointerX || worldMouse.y !== lastPointerY;- const layoutChanged = layoutGen.generation !== lastLayoutGen;- const hasMouseEvent = mousePressed || mouseReleased;- const needsHitTest = pointerMoved || layoutChanged || hasMouseEvent;-- lastPointerX = worldMouse.x;- lastPointerY = worldMouse.y;- lastLayoutGen = layoutGen.generation;-- let hitEntity: Entity | null = hoveredEntity;- if (needsHitTest) {- module.uiHitTest_update(- registry,- worldMouse.x, worldMouse.y,- mouseDown, mousePressed, mouseReleased,- );-- const hitEntityRaw = module.uiHitTest_getHitEntity();- hitEntity = hitEntityRaw === CPP_NO_HIT_ENTITY ? null : hitEntityRaw;- }-- if (hoveredEntity !== null && !world.valid(hoveredEntity)) {- hoveredEntity = null;- }-- if (hoveredEntity !== hitEntity) {- if (hoveredEntity !== null && world.valid(hoveredEntity) && world.has(hoveredEntity, UIInteraction)) {- const prev = world.get(hoveredEntity, UIInteraction) as UIInteractionData;- prev.hovered = false;- world.insert(hoveredEntity, UIInteraction, prev);- events.emit(hoveredEntity, UIEventType.HoverExit);- }- if (hitEntity !== null) {- ensureComponent(world, hitEntity, UIInteraction);- const curr = world.get(hitEntity, UIInteraction) as UIInteractionData;- curr.hovered = true;- world.insert(hitEntity, UIInteraction, curr);- events.emit(hitEntity, UIEventType.HoverEnter);- }- hoveredEntity = hitEntity;- }-- if (mousePressed && hitEntity !== null) {- const interaction = world.get(hitEntity, UIInteraction) as UIInteractionData;- interaction.pressed = true;- interaction.justPressed = true;- world.insert(hitEntity, UIInteraction, interaction);- pressedEntity = hitEntity;- emitWithBubbling(world, events, hitEntity, UIEventType.Press);- }-- if (mouseReleased && pressedEntity !== null) {- if (world.valid(pressedEntity) && world.has(pressedEntity, UIInteraction)) {- const interaction = world.get(pressedEntity, UIInteraction) as UIInteractionData;- interaction.pressed = false;- interaction.justReleased = true;- world.insert(pressedEntity, UIInteraction, interaction);- emitWithBubbling(world, events, pressedEntity, UIEventType.Release);- if (pressedEntity === hoveredEntity) {- emitWithBubbling(world, events, pressedEntity, UIEventType.Click);- }- }- pressedEntity = null;- }- },- { name: 'UIInteractionSystem' }- ), { runAfter: [SystemLabel.UILayout], runIf: playModeOnly });- }-}--export const uiInteractionPlugin = new UIInteractionPlugin();+/**+ * @file ui/UIInteractionPlugin.ts+ * @brief Back-compat shim — the hit-test + UI event plugin moved to the input+ * concept module (REARCH_GUI P0). Re-exported here to keep the public+ * symbol + existing imports stable until REARCH_GUI P4.+ */+export { UIInteractionPlugin, uiInteractionPlugin } from './input/interaction';diff --git a/sdk/src/ui/UILayoutPlugin.ts b/sdk/src/ui/UILayoutPlugin.tsindex 27ced05fb..58191f7cc 100644--- a/sdk/src/ui/UILayoutPlugin.ts+++ b/sdk/src/ui/UILayoutPlugin.ts@@ -1,73 +1,7 @@-import type { App, Plugin } from '../app';-import { registerComponent } from '../component';-import { defineSystem, Schedule } from '../system';-import { SystemLabel } from '../systemLabels';-import { Res } from '../resource';-import { UIRect } from './core/ui-rect';-import { UIRenderer } from './core/ui-renderer';-import { UICameraInfo } from './UICameraInfo';-import type { UICameraData } from './UICameraInfo';-import { UILayoutGeneration } from './UILayoutGeneration';-import type { UILayoutGenerationData } from './UILayoutGeneration';-import type { ESEngineModule } from '../wasm';-import type { CppRegistry } from '../wasm';-import { initUIHelpers } from './uiHelpers';--export class UILayoutPlugin implements Plugin {- name = 'uiLayout';-- build(app: App): void {- registerComponent('UIRect', UIRect);- registerComponent('UIRenderer', UIRenderer);-- const world = app.world;- const module = app.wasmModule as ESEngineModule;- const registry = world.getCppRegistry() as CppRegistry;-- initUIHelpers(module, registry);-- const layoutGen: UILayoutGenerationData = { generation: 0 };- app.insertResource(UILayoutGeneration, layoutGen);-- const layoutFn = (camera: UICameraData) => {- if (!camera.valid) return;- module.uiLayout_update(- registry,- camera.worldLeft, camera.worldBottom,- camera.worldRight, camera.worldTop,- );- module.transform_update(registry);- layoutGen.generation++;- };-- const layoutOnlyFn = (camera: UICameraData) => {- if (!camera.valid) return;- module.uiLayout_update(- registry,- camera.worldLeft, camera.worldBottom,- camera.worldRight, camera.worldTop,- );- layoutGen.generation++;- };-- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(UICameraInfo)],- layoutFn,- { name: 'UILayoutSystem' }- ));-- app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(- [Res(UICameraInfo)],- layoutOnlyFn,- { name: 'UILayoutLateSystem' }- ), { runBefore: [SystemLabel.UIRenderOrder] });-- app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(- [],- () => { module.transform_update(registry); },- { name: 'UITransformFinalSystem' }- ), { runAfter: [SystemLabel.ScrollView, SystemLabel.ListView], runBefore: [SystemLabel.UIRenderOrder] });- }-}--export const uiLayoutPlugin = new UILayoutPlugin();+/**+ * @file ui/UILayoutPlugin.ts+ * @brief Back-compat shim — the Yoga layout driver moved into the layout+ * concept module (REARCH_GUI P0). Re-exported here to keep the+ * public symbol + existing imports stable until REARCH_GUI P4.+ */+export { UILayoutPlugin, uiLayoutPlugin } from './layout/layout';diff --git a/sdk/src/ui/UIMaskPlugin.ts b/sdk/src/ui/UIMaskPlugin.tsindex 78062d8ff..ebcd508f0 100644--- a/sdk/src/ui/UIMaskPlugin.ts+++ b/sdk/src/ui/UIMaskPlugin.ts@@ -1,14 +1,7 @@-import type { App, Plugin } from '../app';-import { registerComponent } from '../component';-import { UIMask } from './core/ui-mask';-import { PluginName } from '../systemLabels';--export class UIMaskPlugin implements Plugin {- name = PluginName.UIMask;-- build(app: App): void {- registerComponent('UIMask', UIMask);- }-}--export const uiMaskPlugin = new UIMaskPlugin();+/**+ * @file ui/UIMaskPlugin.ts+ * @brief Back-compat shim — the UIMask registration plugin moved to the render+ * concept module (REARCH_GUI P0). Re-exported here to keep the public+ * symbol + existing imports stable until REARCH_GUI P4.+ */+export { UIMaskPlugin, uiMaskPlugin } from './render/mask';diff --git a/sdk/src/ui/UIRenderOrderPlugin.ts b/sdk/src/ui/UIRenderOrderPlugin.tsindex e977d4d82..154730451 100644--- a/sdk/src/ui/UIRenderOrderPlugin.ts+++ b/sdk/src/ui/UIRenderOrderPlugin.ts@@ -1,27 +1,7 @@-import type { App, Plugin } from '../app';-import { defineSystem, Schedule } from '../system';-import type { ESEngineModule, CppRegistry } from '../wasm';-import { PluginName } from '../systemLabels';--export class UIRenderOrderPlugin implements Plugin {- name = PluginName.UIRenderOrder;- dependencies = [PluginName.UILayout];- after = [- PluginName.Text, PluginName.Image, PluginName.UIMask,- PluginName.UIInteraction, PluginName.ScrollView,- ];-- build(app: App): void {- const world = app.world;- const module = app.wasmModule as ESEngineModule;- const registry = world.getCppRegistry() as CppRegistry;-- app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(- [],- () => { module.uiRenderOrder_update(registry); },- { name: 'UIRenderOrderSystem' }- ));- }-}--export const uiRenderOrderPlugin = new UIRenderOrderPlugin();+/**+ * @file ui/UIRenderOrderPlugin.ts+ * @brief Back-compat shim — the UI render-order pass moved to the render+ * concept module (REARCH_GUI P0). Re-exported here to keep the public+ * symbol + existing imports stable until REARCH_GUI P4.+ */+export { UIRenderOrderPlugin, uiRenderOrderPlugin } from './render/render-order';diff --git a/sdk/src/ui/behavior/draggable.ts b/sdk/src/ui/behavior/draggable.tsindex 914d8b1ba..230fc7409 100644--- a/sdk/src/ui/behavior/draggable.ts+++ b/sdk/src/ui/behavior/draggable.ts@@ -1,37 +1,12 @@-import { defineComponent } from '../../component';--export interface DraggableData {- enabled: boolean;- dragThreshold: number;- lockX: boolean;- lockY: boolean;- constraintMin: { x: number; y: number } | null;- constraintMax: { x: number; y: number } | null;-}--export const Draggable = defineComponent<DraggableData>('Draggable', {- enabled: true,- dragThreshold: 5,- lockX: false,- lockY: false,- constraintMin: null,- constraintMax: null,-});--export interface DragStateData {- isDragging: boolean;- startWorldPos: { x: number; y: number };- currentWorldPos: { x: number; y: number };- deltaWorld: { x: number; y: number };- totalDeltaWorld: { x: number; y: number };- pointerStartWorld: { x: number; y: number };-}--export const DragState = defineComponent<DragStateData>('DragState', {- isDragging: false,- startWorldPos: { x: 0, y: 0 },- currentWorldPos: { x: 0, y: 0 },- deltaWorld: { x: 0, y: 0 },- totalDeltaWorld: { x: 0, y: 0 },- pointerStartWorld: { x: 0, y: 0 },-});+/**+ * @file ui/behavior/draggable.ts+ * @brief Back-compat shim — Draggable/DragState moved to the input concept+ * module (REARCH_GUI P0). Re-exported here to keep existing imports+ * stable until REARCH_GUI P4.+ */+export {+ Draggable,+ DragState,+ type DraggableData,+ type DragStateData,+} from '../input/draggable';diff --git a/sdk/src/ui/behavior/focusable.ts b/sdk/src/ui/behavior/focusable.tsindex fc3ed47d6..6ea220c58 100644--- a/sdk/src/ui/behavior/focusable.ts+++ b/sdk/src/ui/behavior/focusable.ts@@ -1,33 +1,12 @@-import { defineComponent } from '../../component';-import { defineResource } from '../../resource';-import type { Entity } from '../../types';--export interface FocusableData {- tabIndex: number;- isFocused: boolean;-}--export const Focusable = defineComponent<FocusableData>('Focusable', {- tabIndex: 0,- isFocused: false,-});--export class FocusManagerState {- focusedEntity: Entity | null = null;-- focus(entity: Entity): Entity | null {- const prev = this.focusedEntity;- this.focusedEntity = entity;- return prev;- }-- blur(): Entity | null {- const prev = this.focusedEntity;- this.focusedEntity = null;- return prev;- }-}--export const FocusManager = defineResource<FocusManagerState>(- new FocusManagerState(), 'FocusManager'-);+/**+ * @file ui/behavior/focusable.ts+ * @brief Back-compat shim — Focusable/FocusManager moved to the input concept+ * module (REARCH_GUI P0). Re-exported here to keep existing imports+ * stable until REARCH_GUI P4.+ */+export {+ Focusable,+ FocusManager,+ FocusManagerState,+ type FocusableData,+} from '../input/focusable';diff --git a/sdk/src/ui/behavior/interactable.ts b/sdk/src/ui/behavior/interactable.tsindex 2d1a39f4a..f8ae180ff 100644--- a/sdk/src/ui/behavior/interactable.ts+++ b/sdk/src/ui/behavior/interactable.ts@@ -1,27 +1,12 @@-import { defineBuiltin } from '../../component';--export interface InteractableData {- enabled: boolean;- blockRaycast: boolean;- raycastTarget: boolean;-}--export const Interactable = defineBuiltin<InteractableData>('Interactable', {- enabled: true,- blockRaycast: true,- raycastTarget: true,-});--export interface UIInteractionData {- hovered: boolean;- pressed: boolean;- justPressed: boolean;- justReleased: boolean;-}--export const UIInteraction = defineBuiltin<UIInteractionData>('UIInteraction', {- hovered: false,- pressed: false,- justPressed: false,- justReleased: false,-});+/**+ * @file ui/behavior/interactable.ts+ * @brief Back-compat shim — Interactable/UIInteraction moved to the input+ * concept module (REARCH_GUI P0). Re-exported here to keep existing+ * imports stable until REARCH_GUI P4.+ */+export {+ Interactable,+ UIInteraction,+ type InteractableData,+ type UIInteractionData,+} from '../input/interactable';diff --git a/sdk/src/ui/behavior/systems.ts b/sdk/src/ui/behavior/systems.tsindex 007ebe779..2da6f4f1a 100644--- a/sdk/src/ui/behavior/systems.ts+++ b/sdk/src/ui/behavior/systems.ts@@ -4,7 +4,7 @@ import { Res, Time, type TimeData } from '../../resource';import type { Entity, Color } from '../../types';import type { World } from '../../world';-import { Interactable, UIInteraction, type InteractableData, type UIInteractionData } from './interactable';+import { Interactable, UIInteraction, type InteractableData, type UIInteractionData } from '../input/interactable';import { StateMachine, type StateMachineData } from './state-machine';import {StateVisuals,diff --git a/sdk/src/ui/input/drag.ts b/sdk/src/ui/input/drag.tsnew file mode 100644index 000000000..3e6be350d--- /dev/null+++ b/sdk/src/ui/input/drag.ts@@ -0,0 +1,228 @@+import type { App, Plugin } from '../../app';+import { registerComponent, Transform, Parent, Sprite } from '../../component';+import type { TransformData, ParentData, SpriteData } from '../../component';+import { UIRect } from '../core/ui-rect';+import type { UIRectData } from '../core/ui-rect';+import { defineSystem, Schedule } from '../../system';+import { Res } from '../../resource';+import { Input } from '../../input';+import type { InputState } from '../../input';+import type { Entity } from '../../types';+import type { World } from '../../world';+import { Draggable, DragState } from './draggable';+import type { DraggableData, DragStateData } from './draggable';+import { UIInteraction } from './interactable';+import type { UIInteractionData } from './interactable';+import { UIEvents, UIEventQueue } from '../core/events';+import { UICameraInfo } from '../UICameraInfo';+import type { UICameraData } from '../UICameraInfo';+import { playModeOnly } from '../../env';+import { getEntityDepth } from '../uiHelpers';+import { SystemLabel, PluginName } from '../../systemLabels';+import { quaternionToAngle2D } from '../uiMath';++function worldToLocalDelta(+ world: World,+ entity: Entity,+ dx: number,+ dy: number+): { x: number; y: number } {+ 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 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;++ if (draggable.constraintMin !== null) {+ x = Math.max(x, draggable.constraintMin.x);+ y = Math.max(y, draggable.constraintMin.y);+ }+ if (draggable.constraintMax !== null) {+ 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];++ build(app: App): void {+ registerComponent('Draggable', Draggable);+ registerComponent('DragState', DragState);++ const world = app.world;+ const events = app.getResource(UIEvents) as UIEventQueue;++ let pendingEntity: Entity | null = null;+ let pendingStartWorld = { x: 0, y: 0 };+ let activeEntity: Entity | null = null;++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(Input), Res(UICameraInfo)],+ (input: InputState, camera: UICameraData) => {+ if (!camera.valid) return;++ const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };++ if (input.isMouseButtonPressed(0)) {+ const draggableEntities = world.getEntitiesWithComponents([Draggable, UIInteraction]);+ let bestEntity: Entity | null = null;+ let bestLayer = -Infinity;+ let bestDepth = -1;++ for (const entity of draggableEntities) {+ const draggable = world.get(entity, Draggable) as DraggableData;+ if (!draggable.enabled) continue;+ const interaction = world.get(entity, UIInteraction) as UIInteractionData;+ if (interaction.hovered) {+ 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;+ pendingStartWorld = { x: worldMouse.x, y: worldMouse.y };++ if (!world.has(bestEntity, DragState)) {+ world.insert(bestEntity, DragState);+ }+ const dragState = world.get(bestEntity, DragState) as DragStateData;+ const wt = world.get(bestEntity, Transform) as TransformData;+ dragState.startWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };+ dragState.currentWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };+ dragState.pointerStartWorld = { x: worldMouse.x, y: worldMouse.y };+ dragState.deltaWorld = { x: 0, y: 0 };+ dragState.totalDeltaWorld = { x: 0, y: 0 };+ dragState.isDragging = false;+ }+ }++ if (pendingEntity !== null && !input.isMouseButtonDown(0)) {+ if (world.valid(pendingEntity) && world.has(pendingEntity, DragState)) {+ const dragState = world.get(pendingEntity, DragState) as DragStateData;+ dragState.isDragging = false;+ }+ pendingEntity = null;+ }++ if (pendingEntity !== null && activeEntity === null) {+ if (!world.valid(pendingEntity)) {+ pendingEntity = null;+ return;+ }+ const dx = worldMouse.x - pendingStartWorld.x;+ const dy = worldMouse.y - pendingStartWorld.y;+ const dist = Math.sqrt(dx * dx + dy * dy);+ const draggable = world.get(pendingEntity, Draggable) as DraggableData;++ const screenDist = dist * (camera.vpW / (camera.worldRight - camera.worldLeft));+ if (screenDist >= draggable.dragThreshold) {+ activeEntity = pendingEntity;+ pendingEntity = null;++ const dragState = world.get(activeEntity, DragState) as DragStateData;+ dragState.isDragging = true;+ events.emit(activeEntity, 'drag_start');+ }+ }++ if (activeEntity !== null) {+ if (!world.valid(activeEntity) || !world.has(activeEntity, DragState)) {+ activeEntity = null;+ return;+ }++ const dragState = world.get(activeEntity, DragState) as DragStateData;+ const draggable = world.get(activeEntity, Draggable) as DraggableData;++ const pointerDeltaX = worldMouse.x - dragState.pointerStartWorld.x;+ const pointerDeltaY = worldMouse.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;+ dragState.deltaWorld = { x: newWorldX - prevX, y: newWorldY - prevY };+ dragState.currentWorldPos = { x: newWorldX, y: newWorldY };+ dragState.totalDeltaWorld = {+ x: newWorldX - dragState.startWorldPos.x,+ y: newWorldY - dragState.startWorldPos.y,+ };++ if (world.has(activeEntity, UIRect)) {+ const rect = world.get(activeEntity, UIRect) as UIRectData;+ const localDelta = worldToLocalDelta(+ world, activeEntity,+ dragState.deltaWorld.x, dragState.deltaWorld.y+ );+ rect.offsetMin.x += localDelta.x;+ rect.offsetMin.y += localDelta.y;+ world.insert(activeEntity, UIRect, rect);+ } else if (world.has(activeEntity, Transform)) {+ const localDelta = worldToLocalDelta(+ world, activeEntity,+ dragState.deltaWorld.x, dragState.deltaWorld.y+ );+ const lt = world.get(activeEntity, Transform) as TransformData;+ lt.position.x += localDelta.x;+ lt.position.y += localDelta.y;+ world.insert(activeEntity, Transform, lt);+ }++ events.emit(activeEntity, 'drag_move');++ if (input.isMouseButtonReleased(0)) {+ dragState.isDragging = false;+ events.emit(activeEntity, 'drag_end');+ activeEntity = null;+ }+ }+ },+ { name: 'DragSystem', runAfter: [SystemLabel.UIInteraction] }+ ), { runIf: playModeOnly });+ }+}++export const dragPlugin = new DragPlugin();diff --git a/sdk/src/ui/input/draggable.ts b/sdk/src/ui/input/draggable.tsnew file mode 100644index 000000000..5a402964d--- /dev/null+++ b/sdk/src/ui/input/draggable.ts@@ -0,0 +1,42 @@+/**+ * @file ui/input/draggable.ts+ * @brief Drag config (Draggable) + runtime drag state (DragState) components.+ * Driven by the DragPlugin system in this concept module.+ */+import { defineComponent } from '../../component';++export interface DraggableData {+ enabled: boolean;+ dragThreshold: number;+ lockX: boolean;+ lockY: boolean;+ constraintMin: { x: number; y: number } | null;+ constraintMax: { x: number; y: number } | null;+}++export const Draggable = defineComponent<DraggableData>('Draggable', {+ enabled: true,+ dragThreshold: 5,+ lockX: false,+ lockY: false,+ constraintMin: null,+ constraintMax: null,+});++export interface DragStateData {+ isDragging: boolean;+ startWorldPos: { x: number; y: number };+ currentWorldPos: { x: number; y: number };+ deltaWorld: { x: number; y: number };+ totalDeltaWorld: { x: number; y: number };+ pointerStartWorld: { x: number; y: number };+}++export const DragState = defineComponent<DragStateData>('DragState', {+ isDragging: false,+ startWorldPos: { x: 0, y: 0 },+ currentWorldPos: { x: 0, y: 0 },+ deltaWorld: { x: 0, y: 0 },+ totalDeltaWorld: { x: 0, y: 0 },+ pointerStartWorld: { x: 0, y: 0 },+});diff --git a/sdk/src/ui/input/focus.ts b/sdk/src/ui/input/focus.tsnew file mode 100644index 000000000..a6050f3c8--- /dev/null+++ b/sdk/src/ui/input/focus.ts@@ -0,0 +1,103 @@+import type { App, Plugin } from '../../app';+import { registerComponent } from '../../component';+import { defineSystem, Schedule } from '../../system';+import { Res } from '../../resource';+import { Input } from '../../input';+import type { InputState } from '../../input';+import type { Entity } from '../../types';+import { Focusable, FocusManager, FocusManagerState } from './focusable';+import type { FocusableData } from './focusable';+import { Interactable } from './interactable';+import type { InteractableData } from './interactable';+import { UIInteraction } from './interactable';+import type { UIInteractionData } from './interactable';+import { playModeOnly } from '../../env';+import { UIEvents, UIEventQueue } from '../core/events';+import { PluginName } from '../../systemLabels';++export class FocusPlugin implements Plugin {+ name = PluginName.Focus;+ dependencies = [PluginName.UIInteraction];++ build(app: App): void {+ registerComponent('Focusable', Focusable);++ const world = app.world;+ const focusManager = new FocusManagerState();+ app.insertResource(FocusManager, focusManager);++ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Res(Input), Res(UIEvents)],+ (input: InputState, events: UIEventQueue) => {+ if (focusManager.focusedEntity !== null && !world.valid(focusManager.focusedEntity)) {+ focusManager.focusedEntity = null;+ }++ const focusableEntities = world.getEntitiesWithComponents([Focusable]);++ for (const entity of focusableEntities) {+ if (!world.has(entity, UIInteraction)) continue;+ const interaction = world.get(entity, UIInteraction) as UIInteractionData;+ if (interaction.justPressed) {+ setFocus(entity);+ }+ }++ if (input.isKeyPressed('Tab')) {+ const sorted = getSortedFocusables();+ if (sorted.length === 0) return;++ const currentIdx = focusManager.focusedEntity !== null+ ? sorted.findIndex(e => e === focusManager.focusedEntity)+ : -1;++ const reverse = input.isKeyDown('Shift');+ let nextIdx: number;+ if (currentIdx === -1) {+ nextIdx = reverse ? sorted.length - 1 : 0;+ } else {+ nextIdx = reverse+ ? (currentIdx - 1 + sorted.length) % sorted.length+ : (currentIdx + 1) % sorted.length;+ }++ setFocus(sorted[nextIdx]);+ }++ function getSortedFocusables(): Entity[] {+ const entries: { entity: Entity; tabIndex: number }[] = [];+ for (const entity of focusableEntities) {+ if (!world.valid(entity)) continue;+ if (world.has(entity, Interactable)) {+ const interactable = world.get(entity, Interactable) as InteractableData;+ if (!interactable.enabled) continue;+ }+ const f = world.get(entity, Focusable) as FocusableData;+ entries.push({ entity, tabIndex: f.tabIndex });+ }+ entries.sort((a, b) => a.tabIndex - b.tabIndex);+ return entries.map(e => e.entity);+ }++ function setFocus(entity: Entity): void {+ const prev = focusManager.focusedEntity;+ if (prev === entity) return;++ if (prev !== null && world.valid(prev) && world.has(prev, Focusable)) {+ const prevF = world.get(prev, Focusable) as FocusableData;+ prevF.isFocused = false;+ events.emit(prev, 'blur');+ }++ focusManager.focus(entity);+ const f = world.get(entity, Focusable) as FocusableData;+ f.isFocused = true;+ events.emit(entity, 'focus');+ }+ },+ { name: 'FocusSystem' }+ ), { runIf: playModeOnly });+ }+}++export const focusPlugin = new FocusPlugin();diff --git a/sdk/src/ui/input/focusable.ts b/sdk/src/ui/input/focusable.tsnew file mode 100644index 000000000..c10d4ebfc--- /dev/null+++ b/sdk/src/ui/input/focusable.ts@@ -0,0 +1,39 @@+/**+ * @file ui/input/focusable.ts+ * @brief Keyboard-focus primitives: Focusable component + the FocusManager+ * resource tracking the currently-focused entity. Driven by the+ * FocusPlugin system in this concept module.+ */+import { defineComponent } from '../../component';+import { defineResource } from '../../resource';+import type { Entity } from '../../types';++export interface FocusableData {+ tabIndex: number;+ isFocused: boolean;+}++export const Focusable = defineComponent<FocusableData>('Focusable', {+ tabIndex: 0,+ isFocused: false,+});++export class FocusManagerState {+ focusedEntity: Entity | null = null;++ focus(entity: Entity): Entity | null {+ const prev = this.focusedEntity;+ this.focusedEntity = entity;+ return prev;+ }++ blur(): Entity | null {+ const prev = this.focusedEntity;+ this.focusedEntity = null;+ return prev;+ }+}++export const FocusManager = defineResource<FocusManagerState>(+ new FocusManagerState(), 'FocusManager'+);diff --git a/sdk/src/ui/input/interactable.ts b/sdk/src/ui/input/interactable.tsnew file mode 100644index 000000000..896a062f0--- /dev/null+++ b/sdk/src/ui/input/interactable.ts@@ -0,0 +1,33 @@+/**+ * @file ui/input/interactable.ts+ * @brief Input concept primitives: Interactable (hit-test gate config) and+ * UIInteraction (per-frame pointer state written by the hit-test+ * system). Foundation that the behavior FSM + drag/focus build on.+ */+import { defineBuiltin } from '../../component';++export interface InteractableData {+ enabled: boolean;+ blockRaycast: boolean;+ raycastTarget: boolean;+}++export const Interactable = defineBuiltin<InteractableData>('Interactable', {+ enabled: true,+ blockRaycast: true,+ raycastTarget: true,+});++export interface UIInteractionData {+ hovered: boolean;+ pressed: boolean;+ justPressed: boolean;+ justReleased: boolean;+}++export const UIInteraction = defineBuiltin<UIInteractionData>('UIInteraction', {+ hovered: false,+ pressed: false,+ justPressed: false,+ justReleased: false,+});diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.tsnew file mode 100644index 000000000..9d0b5d65c--- /dev/null+++ b/sdk/src/ui/input/interaction.ts@@ -0,0 +1,175 @@+import type { App, Plugin } from '../../app';+import { registerComponent, Transform } from '../../component';+import { defineSystem, Schedule } from '../../system';+import { Res } from '../../resource';+import { Input } from '../../input';+import type { InputState } from '../../input';+import type { Entity } from '../../types';+import type { World } from '../../world';+import { playModeOnly } from '../../env';+import { Interactable } from './interactable';+import { UIInteraction } from './interactable';+import type { UIInteractionData } from './interactable';+import { UIEvents, UIEventQueue, UIEventType } from '../core/events';+import { UICameraInfo } from '../UICameraInfo';+import type { UICameraData } from '../UICameraInfo';+import type { InteractableData } from './interactable';+import { screenToWorld, createInvVPCache } from '../uiMath';+import { platformDevicePixelRatio } from '../../platform';+import { ensureComponent, walkParentChain } from '../uiHelpers';+import type { ESEngineModule, CppRegistry } from '../../wasm';+import { UILayoutGeneration } from '../UILayoutGeneration';+import { SystemLabel, PluginName } from '../../systemLabels';+import type { UILayoutGenerationData } from '../UILayoutGeneration';++const vpCache = createInvVPCache();+const CPP_NO_HIT_ENTITY = 0xFFFFFFFF;++function emitWithBubbling(+ world: World,+ events: UIEventQueue,+ entity: Entity,+ type: string,+): void {+ const event = events.emit(entity, type);++ walkParentChain(world, entity, (ancestor) => {+ if (event.propagationStopped) return true;+ if (!world.has(ancestor, Interactable)) return false;+ const interactable = world.get(ancestor, Interactable) as InteractableData;+ if (interactable.enabled) {+ events.emitBubbled(ancestor, event);+ }+ return interactable.blockRaycast;+ });+}++export class UIInteractionPlugin implements Plugin {+ name = PluginName.UIInteraction;+ dependencies = [PluginName.UILayout];++ build(app: App): void {+ registerComponent('Interactable', Interactable);++ const world = app.world;+ const module = app.wasmModule as ESEngineModule;+ const registry = world.getCppRegistry() as CppRegistry;+ const events = new UIEventQueue();+ app.insertResource(UIEvents, events);+ // Prune handlers when an entity dies. Replaces the old+ // setEntityValidator pattern; canonical UIEventQueue has no+ // validator hook because it's the plugin's job to wire cleanup.+ app.world.onDespawn((e) => events.removeAll(e));++ let hoveredEntity: Entity | null = null;+ let pressedEntity: Entity | null = null;+ let lastPointerX = NaN;+ let lastPointerY = NaN;+ let lastLayoutGen = -1;++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(Input), Res(UICameraInfo), Res(UILayoutGeneration)],+ (input: InputState, camera: UICameraData, layoutGen: UILayoutGenerationData) => {+ events.drain();++ const interactionEntities = world.getEntitiesWithComponents([UIInteraction]);+ for (const entity of interactionEntities) {+ const interaction = world.get(entity, UIInteraction) as UIInteractionData;+ if (interaction.justPressed || interaction.justReleased) {+ interaction.justPressed = false;+ interaction.justReleased = false;+ world.insert(entity, UIInteraction, interaction);+ }+ }++ if (!camera.valid) return;++ const dpr = platformDevicePixelRatio();+ const mouseGLX = input.mouseX * dpr;+ const mouseGLY = camera.screenH - input.mouseY * dpr;++ vpCache.update(camera.viewProjection);+ const invVP = vpCache.getInverse(camera.viewProjection);+ const worldMouse = screenToWorld(+ mouseGLX, mouseGLY, invVP,+ camera.vpX, camera.vpY, camera.vpW, camera.vpH,+ );++ camera.worldMouseX = worldMouse.x;+ camera.worldMouseY = worldMouse.y;++ const mouseDown = input.isMouseButtonDown(0);+ const mousePressed = input.isMouseButtonPressed(0);+ const mouseReleased = input.isMouseButtonReleased(0);++ const pointerMoved = worldMouse.x !== lastPointerX || worldMouse.y !== lastPointerY;+ const layoutChanged = layoutGen.generation !== lastLayoutGen;+ const hasMouseEvent = mousePressed || mouseReleased;+ const needsHitTest = pointerMoved || layoutChanged || hasMouseEvent;++ lastPointerX = worldMouse.x;+ lastPointerY = worldMouse.y;+ lastLayoutGen = layoutGen.generation;++ let hitEntity: Entity | null = hoveredEntity;+ if (needsHitTest) {+ module.uiHitTest_update(+ registry,+ worldMouse.x, worldMouse.y,+ mouseDown, mousePressed, mouseReleased,+ );++ const hitEntityRaw = module.uiHitTest_getHitEntity();+ hitEntity = hitEntityRaw === CPP_NO_HIT_ENTITY ? null : hitEntityRaw;+ }++ if (hoveredEntity !== null && !world.valid(hoveredEntity)) {+ hoveredEntity = null;+ }++ if (hoveredEntity !== hitEntity) {+ if (hoveredEntity !== null && world.valid(hoveredEntity) && world.has(hoveredEntity, UIInteraction)) {+ const prev = world.get(hoveredEntity, UIInteraction) as UIInteractionData;+ prev.hovered = false;+ world.insert(hoveredEntity, UIInteraction, prev);+ events.emit(hoveredEntity, UIEventType.HoverExit);+ }+ if (hitEntity !== null) {+ ensureComponent(world, hitEntity, UIInteraction);+ const curr = world.get(hitEntity, UIInteraction) as UIInteractionData;+ curr.hovered = true;+ world.insert(hitEntity, UIInteraction, curr);+ events.emit(hitEntity, UIEventType.HoverEnter);+ }+ hoveredEntity = hitEntity;+ }++ if (mousePressed && hitEntity !== null) {+ const interaction = world.get(hitEntity, UIInteraction) as UIInteractionData;+ interaction.pressed = true;+ interaction.justPressed = true;+ world.insert(hitEntity, UIInteraction, interaction);+ pressedEntity = hitEntity;+ emitWithBubbling(world, events, hitEntity, UIEventType.Press);+ }++ if (mouseReleased && pressedEntity !== null) {+ if (world.valid(pressedEntity) && world.has(pressedEntity, UIInteraction)) {+ const interaction = world.get(pressedEntity, UIInteraction) as UIInteractionData;+ interaction.pressed = false;+ interaction.justReleased = true;+ world.insert(pressedEntity, UIInteraction, interaction);+ emitWithBubbling(world, events, pressedEntity, UIEventType.Release);+ if (pressedEntity === hoveredEntity) {+ emitWithBubbling(world, events, pressedEntity, UIEventType.Click);+ }+ }+ pressedEntity = null;+ }+ },+ { name: 'UIInteractionSystem' }+ ), { runAfter: [SystemLabel.UILayout], runIf: playModeOnly });+ }+}++export const uiInteractionPlugin = new UIInteractionPlugin();diff --git a/sdk/src/ui/layout/layout.ts b/sdk/src/ui/layout/layout.tsnew file mode 100644index 000000000..05f2772cb--- /dev/null+++ b/sdk/src/ui/layout/layout.ts@@ -0,0 +1,86 @@+/**+ * @file ui/layout/layout.ts+ * @brief Layout concept — the Yoga-backed layout driver.+ *+ * Owns the PreUpdate `UILayoutSystem` (drives the C++ Yoga pass via+ * `uiLayout_update` + `transform_update`) plus the PostUpdate late/final+ * passes that re-solve after scroll/list mutations. Co-located with the+ * `flex`/`grid`/`safe-area` schemas in this module (REARCH_GUI P0).+ *+ * Behaviour is byte-identical to the former flat `UILayoutPlugin.ts`, which+ * now re-exports from here (strangler-fig; legacy public symbols kept as+ * shims until REARCH_GUI P4).+ */+import type { App, Plugin } from '../../app';+import { registerComponent } from '../../component';+import { defineSystem, Schedule } from '../../system';+import { SystemLabel } from '../../systemLabels';+import { Res } from '../../resource';+import { UIRect } from '../core/ui-rect';+import { UIRenderer } from '../core/ui-renderer';+import { UICameraInfo } from '../UICameraInfo';+import type { UICameraData } from '../UICameraInfo';+import { UILayoutGeneration } from '../UILayoutGeneration';+import type { UILayoutGenerationData } from '../UILayoutGeneration';+import type { ESEngineModule } from '../../wasm';+import type { CppRegistry } from '../../wasm';+import { initUIHelpers } from '../uiHelpers';++export class UILayoutPlugin implements Plugin {+ name = 'uiLayout';++ build(app: App): void {+ registerComponent('UIRect', UIRect);+ registerComponent('UIRenderer', UIRenderer);++ const world = app.world;+ const module = app.wasmModule as ESEngineModule;+ const registry = world.getCppRegistry() as CppRegistry;++ initUIHelpers(module, registry);++ const layoutGen: UILayoutGenerationData = { generation: 0 };+ app.insertResource(UILayoutGeneration, layoutGen);++ const layoutFn = (camera: UICameraData) => {+ if (!camera.valid) return;+ module.uiLayout_update(+ registry,+ camera.worldLeft, camera.worldBottom,+ camera.worldRight, camera.worldTop,+ );+ module.transform_update(registry);+ layoutGen.generation++;+ };++ const layoutOnlyFn = (camera: UICameraData) => {+ if (!camera.valid) return;+ module.uiLayout_update(+ registry,+ camera.worldLeft, camera.worldBottom,+ camera.worldRight, camera.worldTop,+ );+ layoutGen.generation++;+ };++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(UICameraInfo)],+ layoutFn,+ { name: 'UILayoutSystem' }+ ));++ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(+ [Res(UICameraInfo)],+ layoutOnlyFn,+ { name: 'UILayoutLateSystem' }+ ), { runBefore: [SystemLabel.UIRenderOrder] });++ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(+ [],+ () => { module.transform_update(registry); },+ { name: 'UITransformFinalSystem' }+ ), { runAfter: [SystemLabel.ScrollView, SystemLabel.ListView], runBefore: [SystemLabel.UIRenderOrder] });+ }+}++export const uiLayoutPlugin = new UILayoutPlugin();diff --git a/sdk/src/ui/layout/safe-area.ts b/sdk/src/ui/layout/safe-area.tsnew file mode 100644index 000000000..ac1165ec4--- /dev/null+++ b/sdk/src/ui/layout/safe-area.ts@@ -0,0 +1,160 @@+/**+ * @file ui/layout/safe-area.ts+ * @brief Safe-area concept — component + the PreUpdate system that pushes+ * platform safe-area insets into UIRect offsets, co-located.+ *+ * Part of REARCH_GUI P0: the layout concept (Yoga driver + safe-area) is the+ * first concept relocated out of the flat legacy plugins into a cohesive+ * module. Behaviour is byte-identical to the former `SafeArea.ts` ++ * `SafeAreaPlugin.ts`; those files now re-export from here (strangler-fig —+ * legacy public symbols are kept as shims until REARCH_GUI P4).+ */+import type { App, Plugin } from '../../app';+import { isWeChat, platformDevicePixelRatio } from '../../platform';+import { defineComponent, registerComponent } from '../../component';+import { Res } from '../../resource';+import { defineSystem, Schedule } from '../../system';+import { UICameraInfo } from '../UICameraInfo';+import type { UICameraData } from '../UICameraInfo';+import { UIRect } from '../core/ui-rect';+import type { UIRectData } from '../core/ui-rect';+import { SystemLabel, PluginName } from '../../systemLabels';++export interface SafeAreaData {+ applyTop: boolean;+ applyBottom: boolean;+ applyLeft: boolean;+ applyRight: boolean;+}++export const SafeArea = defineComponent<SafeAreaData>('SafeArea', {+ applyTop: true,+ applyBottom: true,+ applyLeft: true,+ applyRight: true,+});++export interface SafeAreaInsets {+ top: number;+ bottom: number;+ left: number;+ right: number;+}++interface WxGlobal {+ wx?: {+ getSystemInfoSync?(): { safeArea: { top: number; bottom: number; left: number; right: number }; screenWidth: number; screenHeight: number } | undefined;+ onWindowResize?(cb: () => void): void;+ };+}++function getWeChatSafeAreaInsets(): SafeAreaInsets {+ const g = globalThis as unknown as WxGlobal;+ const info = g.wx?.getSystemInfoSync?.();+ if (!info || !info.safeArea) {+ return { top: 0, bottom: 0, left: 0, right: 0 };+ }+ const { safeArea, screenWidth, screenHeight } = info;+ return {+ top: safeArea.top,+ bottom: screenHeight - safeArea.bottom,+ left: safeArea.left,+ right: screenWidth - safeArea.right,+ };+}++function getWebSafeAreaInsets(): SafeAreaInsets {+ if (typeof document === 'undefined' || typeof getComputedStyle === 'undefined') {+ return { top: 0, bottom: 0, left: 0, right: 0 };+ }+ const style = getComputedStyle(document.documentElement);+ return {+ top: parseFloat(style.getPropertyValue('--sat') || '0'),+ bottom: parseFloat(style.getPropertyValue('--sab') || '0'),+ left: parseFloat(style.getPropertyValue('--sal') || '0'),+ right: parseFloat(style.getPropertyValue('--sar') || '0'),+ };+}++function getSafeAreaInsets(): SafeAreaInsets {+ if (isWeChat()) {+ return getWeChatSafeAreaInsets();+ }+ return getWebSafeAreaInsets();+}++export class SafeAreaPlugin implements Plugin {+ name = PluginName.SafeArea;+ dependencies = [PluginName.UILayout];++ build(app: App): void {+ registerComponent('SafeArea', SafeArea);++ const world = app.world;+ let cachedInsets: SafeAreaInsets = getSafeAreaInsets();+ let dirty = true;+ let prevScreenH = 0;+ let prevWorldH = 0;++ if (isWeChat()) {+ const g = globalThis as unknown as WxGlobal;+ g.wx?.onWindowResize?.(() => {+ cachedInsets = getSafeAreaInsets();+ dirty = true;+ });+ } else if (typeof window !== 'undefined') {+ window.addEventListener('resize', () => {+ cachedInsets = getSafeAreaInsets();+ dirty = true;+ });+ }++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [Res(UICameraInfo)],+ (camera: UICameraData) => {+ if (!camera.valid || camera.screenH === 0) return;++ const worldH = camera.worldTop - camera.worldBottom;+ if (camera.screenH !== prevScreenH || worldH !== prevWorldH) {+ prevScreenH = camera.screenH;+ prevWorldH = worldH;+ dirty = true;+ }++ if (!dirty) return;+ dirty = false;++ const dpr = platformDevicePixelRatio();+ const insetScale = isWeChat() ? (worldH / camera.screenH) : (dpr * worldH / camera.screenH);++ const entities = world.getEntitiesWithComponents([SafeArea, UIRect]);+ for (const entity of entities) {+ const sa = world.get(entity, SafeArea) as SafeAreaData;+ const rect = world.get(entity, UIRect) as UIRectData;++ const top = sa.applyTop ? cachedInsets.top * insetScale : 0;+ const bottom = sa.applyBottom ? cachedInsets.bottom * insetScale : 0;+ const left = sa.applyLeft ? cachedInsets.left * insetScale : 0;+ const right = sa.applyRight ? cachedInsets.right * insetScale : 0;++ let changed = false;+ if (rect.offsetMin.x !== left || rect.offsetMin.y !== bottom) {+ rect.offsetMin = { x: left, y: bottom };+ changed = true;+ }+ if (rect.offsetMax.x !== -right || rect.offsetMax.y !== -top) {+ rect.offsetMax = { x: -right, y: -top };+ changed = true;+ }++ if (changed) {+ world.insert(entity, UIRect, rect);+ }+ }+ },+ { name: 'SafeAreaSystem' }+ ), { runBefore: [SystemLabel.UILayout] });+ }+}++export const safeAreaPlugin = new SafeAreaPlugin();diff --git a/sdk/src/ui/plugin.ts b/sdk/src/ui/plugin.tsindex 2449346a6..f94207acc 100644--- a/sdk/src/ui/plugin.ts+++ b/sdk/src/ui/plugin.ts@@ -13,7 +13,7 @@ import {} from './behavior/systems';import { ListView, ListViewRegistry } from './collection/list-view';import { ScrollContainer, ScrollContainerRegistry } from './collection/scroll-container';-import { UIInteraction, type UIInteractionData } from './behavior/interactable';+import { UIInteraction, type UIInteractionData } from './input/interactable';/*** Wires the Layer 2 behavior systems — interactable-driven state machinediff --git a/sdk/src/ui/render/image.ts b/sdk/src/ui/render/image.tsnew file mode 100644index 000000000..26736c9be--- /dev/null+++ b/sdk/src/ui/render/image.ts@@ -0,0 +1,114 @@+import type { App, Plugin } from '../../app';+import type { Entity } from '../../types';+import { registerComponent } from '../../component';+import { defineSystem, Schedule } from '../../system';+import { Image, ImageType, FillMethod, FillOrigin } from '../core/image';+import type { ImageData } from '../core/image';+import { UIRect } from '../core/ui-rect';+import type { UIRectData } from '../core/ui-rect';+import { UIRenderer, UIVisualType } from '../core/ui-renderer';+import type { UIRendererData } from '../core/ui-renderer';+import { getEffectiveWidth, getEffectiveHeight, ensureUIRenderer } from '../uiHelpers';+import { SystemLabel, PluginName } from '../../systemLabels';++export class ImagePlugin implements Plugin {+ name = PluginName.Image;+ dependencies = [PluginName.UILayout];++ build(app: App): void {+ registerComponent('Image', Image);++ const world = app.world;+ const lastRenderedTick = new Map<Entity, number>();++ world.enableChangeTracking(Image);+ world.enableChangeTracking(UIRect);++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [],+ () => {+ for (const entity of lastRenderedTick.keys()) {+ if (!world.valid(entity) || !world.has(entity, Image)) {+ lastRenderedTick.delete(entity);+ }+ }++ const entities = world.getEntitiesWithComponents([Image]);++ for (const entity of entities) {+ const image = world.get(entity, Image) as ImageData;+ const uiRect = world.has(entity, UIRect)+ ? world.get(entity, UIRect) as UIRectData+ : null;++ const prevTick = lastRenderedTick.get(entity);+ if (prevTick !== undefined && world.has(entity, UIRenderer)) {+ const imageChanged = world.isChangedSince(entity, Image, prevTick);+ const rectChanged = uiRect && world.isChangedSince(entity, UIRect, prevTick);+ if (!imageChanged && !rectChanged) continue;+ }++ ensureUIRenderer(world, entity);++ const renderer = world.get(entity, UIRenderer) as UIRendererData;++ if (!image.enabled) {+ renderer.enabled = false;+ world.insert(entity, UIRenderer, renderer);+ lastRenderedTick.set(entity, world.getWorldTick());+ continue;+ }++ renderer.enabled = true;+ renderer.texture = image.texture;+ renderer.color = { r: image.color.r, g: image.color.g, b: image.color.b, a: image.color.a };+ renderer.material = image.material;++ renderer.uvOffset = { x: 0, y: 0 };+ renderer.uvScale = { x: 1, y: 1 };++ const hasTexture = !!image.texture;+ if (!hasTexture) {+ renderer.visualType = UIVisualType.SolidColor;+ } else if (image.imageType === ImageType.Sliced) {+ renderer.visualType = UIVisualType.NineSlice;+ } else {+ renderer.visualType = UIVisualType.Image;+ }++ if (image.imageType === ImageType.Filled) {+ const amount = Math.max(0, Math.min(1, image.fillAmount));++ if (image.fillMethod === FillMethod.Horizontal) {+ if (image.fillOrigin === FillOrigin.Left) {+ renderer.uvScale = { x: amount, y: 1 };+ } else {+ renderer.uvOffset = { x: 1 - amount, y: 0 };+ renderer.uvScale = { x: amount, y: 1 };+ }+ } else {+ if (image.fillOrigin === FillOrigin.Bottom) {+ renderer.uvScale = { x: 1, y: amount };+ } else {+ renderer.uvOffset = { x: 0, y: 1 - amount };+ renderer.uvScale = { x: 1, y: amount };+ }+ }+ } else if (image.imageType === ImageType.Tiled) {+ const w = uiRect ? getEffectiveWidth(uiRect, entity) : 0;+ const h = uiRect ? getEffectiveHeight(uiRect, entity) : 0;+ if (image.tileSize.x > 0 && image.tileSize.y > 0) {+ renderer.uvScale = { x: w / image.tileSize.x, y: h / image.tileSize.y };+ }+ }++ world.insert(entity, UIRenderer, renderer);+ lastRenderedTick.set(entity, world.getWorldTick());+ }+ },+ { name: 'ImageSystem' }+ ), { runAfter: [SystemLabel.UILayout] });+ }+}++export const imagePlugin = new ImagePlugin();diff --git a/sdk/src/ui/render/mask.ts b/sdk/src/ui/render/mask.tsnew file mode 100644index 000000000..20dddd3fb--- /dev/null+++ b/sdk/src/ui/render/mask.ts@@ -0,0 +1,14 @@+import type { App, Plugin } from '../../app';+import { registerComponent } from '../../component';+import { UIMask } from '../core/ui-mask';+import { PluginName } from '../../systemLabels';++export class UIMaskPlugin implements Plugin {+ name = PluginName.UIMask;++ build(app: App): void {+ registerComponent('UIMask', UIMask);+ }+}++export const uiMaskPlugin = new UIMaskPlugin();diff --git a/sdk/src/ui/render/render-order.ts b/sdk/src/ui/render/render-order.tsnew file mode 100644index 000000000..d41819c0d--- /dev/null+++ b/sdk/src/ui/render/render-order.ts@@ -0,0 +1,27 @@+import type { App, Plugin } from '../../app';+import { defineSystem, Schedule } from '../../system';+import type { ESEngineModule, CppRegistry } from '../../wasm';+import { PluginName } from '../../systemLabels';++export class UIRenderOrderPlugin implements Plugin {+ name = PluginName.UIRenderOrder;+ dependencies = [PluginName.UILayout];+ after = [+ PluginName.Text, PluginName.Image, PluginName.UIMask,+ PluginName.UIInteraction, PluginName.ScrollView,+ ];++ build(app: App): void {+ const world = app.world;+ const module = app.wasmModule as ESEngineModule;+ const registry = world.getCppRegistry() as CppRegistry;++ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(+ [],+ () => { module.uiRenderOrder_update(registry); },+ { name: 'UIRenderOrderSystem' }+ ));+ }+}++export const uiRenderOrderPlugin = new UIRenderOrderPlugin();