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: enhance UI framework with layout system and slider drag fix
esengine96b54ea311d7
diff --git a/sdk/src/ui/DragPlugin.ts b/sdk/src/ui/DragPlugin.tsindex 2c8b37761..3bd1587b5 100644--- a/sdk/src/ui/DragPlugin.ts+++ b/sdk/src/ui/DragPlugin.ts@@ -1,6 +1,6 @@import type { App, Plugin } from '../app';-import { registerComponent, LocalTransform, WorldTransform, Parent } from '../component';-import type { LocalTransformData, WorldTransformData, ParentData } from '../component';+import { registerComponent, LocalTransform, WorldTransform, Parent, Sprite } from '../component';+import type { LocalTransformData, WorldTransformData, ParentData, SpriteData } from '../component';import { defineSystem, Schedule } from '../system';import { Res } from '../resource';import { Input } from '../input';@@ -14,41 +14,8 @@ import type { UIInteractionData } from './UIInteraction';import { UIEvents, UIEventQueue } from './UIEvents';import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';-import { invertMatrix4, screenToWorld } from './uiMath';--const _dragInvVP = new Float32Array(16);-const _dragCachedVP = new Float32Array(16);-let _dragInvVPDirty = true;--function updateDragInvVPCache(vp: Float32Array): void {- let dirty = false;- for (let i = 0; i < 16; i++) {- if (_dragCachedVP[i] !== vp[i]) {- dirty = true;- break;- }- }- if (dirty) {- _dragCachedVP.set(vp);- _dragInvVPDirty = true;- }-}--function getWorldMousePos(input: InputState, camera: UICameraData, dpr: number): { x: number; y: number } {- const mouseGLX = input.mouseX * dpr;- const mouseGLY = camera.screenH - input.mouseY * dpr;-- updateDragInvVPCache(camera.viewProjection);- if (_dragInvVPDirty) {- invertMatrix4(camera.viewProjection, _dragInvVP);- _dragInvVPDirty = false;- }-- return screenToWorld(- mouseGLX, mouseGLY, _dragInvVP,- camera.vpX, camera.vpY, camera.vpW, camera.vpH,- );-}+import { getEntityDepth } from './uiHelpers';+import { quaternionToAngle2D } from './uiMath';function worldToLocalDelta(world: World,@@ -68,7 +35,7 @@ function worldToLocalDelta(const sx = parentWt.scale.x !== 0 ? parentWt.scale.x : 1;const sy = parentWt.scale.y !== 0 ? parentWt.scale.y : 1;- const angle = 2 * Math.atan2(parentWt.rotation.z, parentWt.rotation.w);+ const angle = quaternionToAngle2D(parentWt.rotation.z, parentWt.rotation.w);const sin = Math.sin(-angle);const cos = Math.cos(-angle);@@ -110,25 +77,35 @@ export class DragPlugin implements Plugin {let pendingEntity: Entity | null = null;let pendingStartWorld = { x: 0, y: 0 };let activeEntity: Entity | null = null;- const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Res(Input), Res(UICameraInfo)],(input: InputState, camera: UICameraData) => {if (!camera.valid) return;- const worldMouse = getWorldMousePos(input, camera, dpr);+ 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) {- bestEntity = 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;+ }}}@@ -227,7 +204,7 @@ export class DragPlugin implements Plugin {}}},- { name: 'DragSystem' }+ { name: 'DragSystem', runAfter: ['UIInteractionSystem'] }));}}diff --git a/sdk/src/ui/DropdownPlugin.ts b/sdk/src/ui/DropdownPlugin.tsindex 3cb835ab6..30788a589 100644--- a/sdk/src/ui/DropdownPlugin.ts+++ b/sdk/src/ui/DropdownPlugin.ts@@ -1,43 +1,48 @@import type { App, Plugin } from '../app';import { registerComponent, LocalTransform, Name, Sprite } from '../component';-import type { LocalTransformData, SpriteData } from '../component';+import type { SpriteData } from '../component';import { defineSystem, Schedule } from '../system';import { Res } from '../resource';import type { Entity } from '../types';import { Dropdown } from './Dropdown';import type { DropdownData } from './Dropdown';import { Interactable } from './Interactable';+import type { InteractableData } from './Interactable';import { UIInteraction } from './UIInteraction';import type { UIInteractionData } from './UIInteraction';import { UIEvents, UIEventQueue } from './UIEvents';-import { Text } from './text';+import { Text, TextAlign, TextVerticalAlign, TextOverflow } from './text';import type { TextData } from './text';import { UIRect } from './UIRect';import type { UIRectData } from './UIRect';+import { UIMask } from './UIMask';import { Input } from '../input';import type { InputState } from '../input';+import { ensureComponent } from './uiHelpers';+import { DROPDOWN_ITEM_HEIGHT, DROPDOWN_FONT_SIZE, DROPDOWN_HIGHLIGHT_COLOR } from './uiConstants';interface DropdownState {optionEntities: Entity[];highlightIndex: number;}-const dropdownStates = new Map<Entity, DropdownState>();-export class DropdownPlugin implements Plugin {build(app: App): void {registerComponent('Dropdown', Dropdown);const world = app.world;+ const dropdownStates = new Map<Entity, DropdownState>();app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Input), Res(UIEvents)],(input: InputState, events: UIEventQueue) => {+ for (const [e] of dropdownStates) {+ if (!world.valid(e)) dropdownStates.delete(e);+ }+const entities = world.getEntitiesWithComponents([Dropdown]);for (const entity of entities) {- if (!world.has(entity, Interactable)) {- world.insert(entity, Interactable, { enabled: true, blockRaycast: true });- }+ ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });const dropdown = world.get(entity, Dropdown) as DropdownData;const interaction = world.has(entity, UIInteraction)@@ -70,13 +75,18 @@ export class DropdownPlugin implements Plugin {}if (input.isKeyPressed('ArrowDown')) {- state.highlightIndex = Math.min(- state.highlightIndex + 1,- dropdown.options.length - 1- );+ if (state.highlightIndex >= dropdown.options.length - 1) {+ state.highlightIndex = 0;+ } else {+ state.highlightIndex++;+ }updateHighlight(state);} else if (input.isKeyPressed('ArrowUp')) {- state.highlightIndex = Math.max(state.highlightIndex - 1, 0);+ if (state.highlightIndex <= 0) {+ state.highlightIndex = dropdown.options.length - 1;+ } else {+ state.highlightIndex--;+ }updateHighlight(state);} else if (input.isKeyPressed('Enter') && state.highlightIndex >= 0) {selectOption(entity, dropdown, state, state.highlightIndex, events);@@ -105,13 +115,15 @@ export class DropdownPlugin implements Plugin {if (listEntity === 0 || !world.valid(listEntity)) return;setListVisible(listEntity, true);+ if (!world.has(listEntity, UIMask)) {+ world.insert(listEntity, UIMask, { enabled: true, mode: 'scissor' });+ }destroyOptions(state);const listRect = world.has(listEntity, UIRect)? world.get(listEntity, UIRect) as UIRectData: null;const listWidth = listRect ? listRect.size.x : 160;- const itemHeight = 30;for (let i = 0; i < dropdown.options.length; i++) {const optEntity = world.spawn();@@ -121,32 +133,44 @@ export class DropdownPlugin implements Plugin {anchorMax: { x: 1, y: 1 },offsetMin: { x: 0, y: 0 },offsetMax: { x: 0, y: 0 },- size: { x: listWidth, y: itemHeight },+ size: { x: listWidth, y: DROPDOWN_ITEM_HEIGHT },pivot: { x: 0.5, y: 1 },});world.insert(optEntity, LocalTransform, {- position: { x: 0, y: -(i * itemHeight), z: 0 },+ position: { x: 0, y: -(i * DROPDOWN_ITEM_HEIGHT), z: 0 },rotation: { w: 1, x: 0, y: 0, z: 0 },scale: { x: 1, y: 1, z: 1 },});world.insert(optEntity, Text, {content: dropdown.options[i],- fontSize: 16,+ fontSize: DROPDOWN_FONT_SIZE,fontFamily: 'Arial',color: { r: 1, g: 1, b: 1, a: 1 },- align: 0,- verticalAlign: 1,+ align: TextAlign.Left,+ verticalAlign: TextVerticalAlign.Middle,wordWrap: false,- overflow: 1,+ overflow: TextOverflow.Clip,lineHeight: 1.2,});+ world.insert(optEntity, Sprite, {+ texture: 0,+ color: { r: 1, g: 1, b: 1, a: 0 },+ size: { x: listWidth, y: DROPDOWN_ITEM_HEIGHT },+ uvOffset: { x: 0, y: 0 },+ uvScale: { x: 1, y: 1 },+ layer: 0,+ flipX: false,+ flipY: false,+ material: 0,+ enabled: true,+ });world.insert(optEntity, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });world.setParent(optEntity, listEntity);state.optionEntities.push(optEntity);}if (listRect) {- listRect.size.y = dropdown.options.length * itemHeight;+ listRect.size.y = dropdown.options.length * DROPDOWN_ITEM_HEIGHT;world.insert(listEntity, UIRect, listRect);}@@ -198,11 +222,16 @@ export class DropdownPlugin implements Plugin {function setListVisible(entity: Entity, visible: boolean): void {if (entity === 0 || !world.valid(entity)) return;- if (!world.has(entity, LocalTransform)) return;- const lt = world.get(entity, LocalTransform) as LocalTransformData;- const s = visible ? 1 : 0;- lt.scale = { x: s, y: s, z: s };- world.insert(entity, LocalTransform, lt);+ if (world.has(entity, Interactable)) {+ const inter = world.get(entity, Interactable) as InteractableData;+ inter.enabled = visible;+ world.insert(entity, Interactable, inter);+ }+ if (world.has(entity, Sprite)) {+ const sprite = world.get(entity, Sprite) as SpriteData;+ sprite.enabled = visible;+ world.insert(entity, Sprite, sprite);+ }}function updateHighlight(state: DropdownState): void {@@ -211,9 +240,9 @@ export class DropdownPlugin implements Plugin {if (!world.valid(optEntity) || !world.has(optEntity, Sprite)) continue;const sprite = world.get(optEntity, Sprite) as SpriteData;if (i === state.highlightIndex) {- sprite.color = { r: 0.3, g: 0.5, b: 0.8, a: 1 };+ sprite.color = { ...DROPDOWN_HIGHLIGHT_COLOR };} else {- sprite.color = { r: 1, g: 1, b: 1, a: 1 };+ sprite.color = { r: 1, g: 1, b: 1, a: 0 };}world.insert(optEntity, Sprite, sprite);}diff --git a/sdk/src/ui/FocusPlugin.ts b/sdk/src/ui/FocusPlugin.tsindex c8521052c..48b9936c0 100644--- a/sdk/src/ui/FocusPlugin.ts+++ b/sdk/src/ui/FocusPlugin.ts@@ -7,6 +7,8 @@ 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 './UIInteraction';import type { UIInteractionData } from './UIInteraction';import { UIEvents, UIEventQueue } from './UIEvents';@@ -22,6 +24,10 @@ export class FocusPlugin implements Plugin {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) {@@ -56,6 +62,11 @@ export class FocusPlugin implements Plugin {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 });}diff --git a/sdk/src/ui/ImagePlugin.ts b/sdk/src/ui/ImagePlugin.tsindex 31c7238de..18d5bc7d2 100644--- a/sdk/src/ui/ImagePlugin.ts+++ b/sdk/src/ui/ImagePlugin.ts@@ -1,4 +1,5 @@import type { App, Plugin } from '../app';+import type { Entity } from '../types';import { registerComponent, Sprite } from '../component';import type { SpriteData } from '../component';import { defineSystem, Schedule } from '../system';@@ -6,26 +7,72 @@ import { Image, ImageType, FillMethod, FillOrigin } from './Image';import type { ImageData } from './Image';import { UIRect } from './UIRect';import type { UIRectData } from './UIRect';-import { ensureSprite } from './uiHelpers';+import { ensureSprite, getEffectiveWidth, getEffectiveHeight } from './uiHelpers';+import { createSnapshotUtils, type Snapshot } from './uiSnapshot';++interface ImageSource {+ image: ImageData;+ uiRect: UIRectData | null;+}++const imageSnapshot = createSnapshotUtils<ImageSource>({+ texture: s => s.image.texture,+ colorR: s => s.image.color.r,+ colorG: s => s.image.color.g,+ colorB: s => s.image.color.b,+ colorA: s => s.image.color.a,+ layer: s => s.image.layer,+ material: s => s.image.material,+ imageType: s => s.image.imageType,+ fillMethod: s => s.image.fillMethod,+ fillOrigin: s => s.image.fillOrigin,+ fillAmount: s => s.image.fillAmount,+ tileSizeX: s => s.image.tileSize.x,+ tileSizeY: s => s.image.tileSize.y,+ rectWidth: s => s.uiRect ? getEffectiveWidth(s.uiRect) : 0,+ rectHeight: s => s.uiRect ? getEffectiveHeight(s.uiRect) : 0,+ enabled: s => s.image.enabled,+});export class ImagePlugin implements Plugin {build(app: App): void {registerComponent('Image', Image);const world = app.world;+ const snapshots = new Map<Entity, Snapshot>();app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([],() => {+ for (const entity of snapshots.keys()) {+ if (!world.valid(entity) || !world.has(entity, Image)) {+ snapshots.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 source: ImageSource = { image, uiRect };++ const prev = snapshots.get(entity);+ if (prev && !imageSnapshot.changed(prev, source)) continue;ensureSprite(world, entity);const sprite = world.get(entity, Sprite) as SpriteData;+ if (!image.enabled) {+ sprite.color.a = 0;+ world.insert(entity, Sprite, sprite);+ snapshots.set(entity, imageSnapshot.take(source));+ continue;+ }+sprite.texture = image.texture;sprite.color.r = image.color.r;sprite.color.g = image.color.g;@@ -34,10 +81,9 @@ export class ImagePlugin implements Plugin {sprite.layer = image.layer;sprite.material = image.material;- if (world.has(entity, UIRect)) {- const rect = world.get(entity, UIRect) as UIRectData;- sprite.size.x = rect.size.x;- sprite.size.y = rect.size.y;+ if (uiRect) {+ sprite.size.x = getEffectiveWidth(uiRect);+ sprite.size.y = getEffectiveHeight(uiRect);}sprite.uvOffset.x = 0;@@ -47,24 +93,26 @@ export class ImagePlugin implements Plugin {if (image.imageType === ImageType.Filled) {const amount = Math.max(0, Math.min(1, image.fillAmount));+ const fullWidth = sprite.size.x;+ const fullHeight = sprite.size.y;if (image.fillMethod === FillMethod.Horizontal) {if (image.fillOrigin === FillOrigin.Left) {sprite.uvScale.x = amount;- sprite.size.x *= amount;+ sprite.size.x = fullWidth * amount;} else {sprite.uvOffset.x = 1 - amount;sprite.uvScale.x = amount;- sprite.size.x *= amount;+ sprite.size.x = fullWidth * amount;}} else {if (image.fillOrigin === FillOrigin.Bottom) {sprite.uvScale.y = amount;- sprite.size.y *= amount;+ sprite.size.y = fullHeight * amount;} else {sprite.uvOffset.y = 1 - amount;sprite.uvScale.y = amount;- sprite.size.y *= amount;+ sprite.size.y = fullHeight * amount;}}} else if (image.imageType === ImageType.Tiled) {@@ -75,6 +123,7 @@ export class ImagePlugin implements Plugin {}world.insert(entity, Sprite, sprite);+ snapshots.set(entity, imageSnapshot.take(source));}},{ name: 'ImageSystem' }diff --git a/sdk/src/ui/LayoutGroupPlugin.ts b/sdk/src/ui/LayoutGroupPlugin.tsindex 83dd26db5..adc9933c8 100644--- a/sdk/src/ui/LayoutGroupPlugin.ts+++ b/sdk/src/ui/LayoutGroupPlugin.ts@@ -1,5 +1,3 @@--import type { App, Plugin } from '../app';import { registerComponent, Children, LocalTransform } from '../component';import type { ChildrenData, LocalTransformData } from '../component';@@ -42,50 +40,50 @@ export class LayoutGroupPlugin implements Plugin {validChildren.reverse();}- const pw = parentRect.size.x;- const ph = parentRect.size.y;+ const pw = parentRect._computedWidth ?? parentRect.size.x;+ const ph = parentRect._computedHeight ?? parentRect.size.y;+ const pivotX = parentRect.pivot.x;+ const pivotY = parentRect.pivot.y;const pad = group.padding;- const contentW = pw - pad.left - pad.right;- const contentH = ph - pad.top - pad.bottom;const isHorizontal = group.direction === LayoutDirection.Horizontal;let cursor = 0;- for (const child of validChildren) {- const cw = child.rect.size.x;- const ch = child.rect.size.y;+ for (let i = 0; i < validChildren.length; i++) {+ const child = validChildren[i];+ const cw = child.rect._computedWidth ?? child.rect.size.x;+ const ch = child.rect._computedHeight ?? child.rect.size.y;+ const cpx = child.rect.pivot.x;+ const cpy = child.rect.pivot.y;let localX: number;let localY: number;if (isHorizontal) {- localX = -pw * 0.5 + pad.left + cursor + cw * 0.5;+ localX = -pivotX * pw + pad.left + cursor + cpx * cw;if (group.childAlignment === ChildAlignment.Start) {- localY = ph * 0.5 - pad.top - ch * 0.5;+ localY = (1 - pivotY) * ph - pad.top - (1 - cpy) * ch;} else if (group.childAlignment === ChildAlignment.End) {- localY = -ph * 0.5 + pad.bottom + ch * 0.5;+ localY = -pivotY * ph + pad.bottom + cpy * ch;} else {- localY = (pad.bottom - pad.top) * 0.5;+ localY = (0.5 - pivotY) * ph + (pad.bottom - pad.top) * 0.5 + (cpy - 0.5) * ch;}- cursor += cw + group.spacing;+ cursor += cw;+ if (i < validChildren.length - 1) cursor += group.spacing;} else {if (group.childAlignment === ChildAlignment.Start) {- localX = -pw * 0.5 + pad.left + cw * 0.5;+ localX = -pivotX * pw + pad.left + cpx * cw;} else if (group.childAlignment === ChildAlignment.End) {- localX = pw * 0.5 - pad.right - cw * 0.5;+ localX = (1 - pivotX) * pw - pad.right - (1 - cpx) * cw;} else {- localX = (pad.left - pad.right) * 0.5;+ localX = (0.5 - pivotX) * pw + (pad.left - pad.right) * 0.5 + (cpx - 0.5) * cw;}- localY = ph * 0.5 - pad.top - cursor - ch * 0.5;- cursor += ch + group.spacing;+ localY = (1 - pivotY) * ph - pad.top - cursor - (1 - cpy) * ch;+ cursor += ch;+ if (i < validChildren.length - 1) cursor += group.spacing;}- child.rect.anchorMin.x = 0.5;- child.rect.anchorMin.y = 0.5;- child.rect.anchorMax.x = 0.5;- child.rect.anchorMax.y = 0.5;- child.rect.offsetMin.x = localX;- child.rect.offsetMin.y = localY;+ child.rect._layoutManaged = true;const transform = world.get(child.entity, LocalTransform) as LocalTransformData;transform.position.x = localX;diff --git a/sdk/src/ui/ListViewPlugin.ts b/sdk/src/ui/ListViewPlugin.tsindex 63180d6c9..608b3d4b8 100644--- a/sdk/src/ui/ListViewPlugin.ts+++ b/sdk/src/ui/ListViewPlugin.ts@@ -14,6 +14,8 @@ import { Interactable } from './Interactable';import { UIMask } from './UIMask';import { UIInteraction } from './UIInteraction';import type { UIInteractionData } from './UIInteraction';+import { ensureComponent } from './uiHelpers';+import { SCROLL_WHEEL_SENSITIVITY } from './uiConstants';interface ListViewState {visibleStart: number;@@ -22,32 +24,53 @@ interface ListViewState {renderer: ListViewItemRenderer | null;}-const listViewStates = new Map<Entity, ListViewState>();-export function setListViewRenderer(entity: Entity, renderer: ListViewItemRenderer): void {- const state = listViewStates.get(entity);+ const activeStates = ListViewPlugin.activeStates;+ if (!activeStates) {+ console.warn('setListViewRenderer: ListViewPlugin has not been initialized');+ return;+ }+ const state = activeStates.get(entity);if (state) {state.renderer = renderer;+ } else {+ activeStates.set(entity, {+ visibleStart: 0,+ visibleEnd: 0,+ itemEntities: new Map(),+ renderer,+ });}}export class ListViewPlugin implements Plugin {+ static activeStates: Map<Entity, ListViewState> | null = null;+build(app: App): void {registerComponent('ListView', ListView);const world = app.world;+ const listViewStates = new Map<Entity, ListViewState>();+ ListViewPlugin.activeStates = listViewStates;app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Res(Input)],(input: InputState) => {+ for (const [e, st] of listViewStates) {+ if (!world.valid(e)) {+ for (const itemEntity of st.itemEntities.values()) {+ if (world.valid(itemEntity)) {+ world.despawn(itemEntity);+ }+ }+ listViewStates.delete(e);+ }+ }+const entities = world.getEntitiesWithComponents([ListView, UIRect]);for (const entity of entities) {- if (!world.has(entity, Interactable)) {- world.insert(entity, Interactable, { enabled: true, blockRaycast: true });- }- if (!world.has(entity, UIMask)) {- world.insert(entity, UIMask, { enabled: true, mode: 'scissor' });- }+ ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });+ ensureComponent(world, entity, UIMask, { enabled: true, mode: 'scissor' });let state = listViewStates.get(entity);if (!state) {@@ -62,7 +85,8 @@ export class ListViewPlugin implements Plugin {const lv = world.get(entity, ListView) as ListViewData;const rect = world.get(entity, UIRect) as UIRectData;- const viewHeight = rect.size.y;+ const viewHeight = rect._computedHeight ?? rect.size.y;+ const viewWidth = rect._computedWidth ?? rect.size.x;const interaction = world.has(entity, UIInteraction)? world.get(entity, UIInteraction) as UIInteractionData@@ -71,7 +95,7 @@ export class ListViewPlugin implements Plugin {if (interaction?.hovered) {const scroll = input.getScrollDelta();if (scroll.y !== 0) {- lv.scrollY += scroll.y * 0.1;+ lv.scrollY += scroll.y * SCROLL_WHEEL_SENSITIVITY;}}@@ -103,7 +127,7 @@ export class ListViewPlugin implements Plugin {anchorMax: { x: 1, y: 1 },offsetMin: { x: 0, y: 0 },offsetMax: { x: 0, y: 0 },- size: { x: rect.size.x, y: lv.itemHeight },+ size: { x: viewWidth, y: lv.itemHeight },pivot: { x: 0.5, y: 1 },});world.setParent(itemEntity, entity);diff --git a/sdk/src/ui/ProgressBarPlugin.ts b/sdk/src/ui/ProgressBarPlugin.tsindex 4b353a493..04759595c 100644--- a/sdk/src/ui/ProgressBarPlugin.ts+++ b/sdk/src/ui/ProgressBarPlugin.ts@@ -25,7 +25,7 @@ export class ProgressBarPlugin implements Plugin {}},{ name: 'ProgressBarSystem' }- ));+ ), { runAfter: ['UILayoutSystem'] });}}diff --git a/sdk/src/ui/SafeAreaPlugin.ts b/sdk/src/ui/SafeAreaPlugin.tsindex e28372e15..398df6a73 100644--- a/sdk/src/ui/SafeAreaPlugin.ts+++ b/sdk/src/ui/SafeAreaPlugin.ts@@ -1,9 +1,11 @@import type { App, Plugin } from '../app';import { registerComponent } from '../component';+import { Res } from '../resource';import { defineSystem, Schedule } from '../system';-import type { Entity } from '../types';import { SafeArea } from './SafeArea';import type { SafeAreaData } from './SafeArea';+import { UICameraInfo } from './UICameraInfo';+import type { UICameraData } from './UICameraInfo';import { UIRect } from './UIRect';import type { UIRectData } from './UIRect';@@ -33,27 +35,47 @@ export class SafeAreaPlugin implements Plugin {registerComponent('SafeArea', SafeArea);const world = app.world;- let cachedInsets: SafeAreaInsets = { top: 0, bottom: 0, left: 0, right: 0 };- let frameCount = 0;+ let cachedInsets: SafeAreaInsets = getSafeAreaInsets();+ let dirty = true;+ let prevScreenH = 0;+ let prevWorldH = 0;++ if (typeof window !== 'undefined') {+ window.addEventListener('resize', () => {+ cachedInsets = getSafeAreaInsets();+ dirty = true;+ });+ }app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [],- () => {- if (frameCount++ % 60 === 0) {- cachedInsets = getSafeAreaInsets();+ [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 = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;+ const cssToWorld = 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;- let changed = false;- const top = sa.applyTop ? cachedInsets.top : 0;- const bottom = sa.applyBottom ? cachedInsets.bottom : 0;- const left = sa.applyLeft ? cachedInsets.left : 0;- const right = sa.applyRight ? cachedInsets.right : 0;+ const top = sa.applyTop ? cachedInsets.top * cssToWorld : 0;+ const bottom = sa.applyBottom ? cachedInsets.bottom * cssToWorld : 0;+ const left = sa.applyLeft ? cachedInsets.left * cssToWorld : 0;+ const right = sa.applyRight ? cachedInsets.right * cssToWorld : 0;+ let changed = false;if (rect.offsetMin.x !== left || rect.offsetMin.y !== bottom) {rect.offsetMin = { x: left, y: bottom };changed = true;diff --git a/sdk/src/ui/ScrollViewPlugin.ts b/sdk/src/ui/ScrollViewPlugin.tsindex f03a17e58..bdfe7492a 100644--- a/sdk/src/ui/ScrollViewPlugin.ts+++ b/sdk/src/ui/ScrollViewPlugin.ts@@ -16,6 +16,12 @@ import { UIInteraction } from './UIInteraction';import type { UIInteractionData } from './UIInteraction';import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';+import { getEffectiveWidth, getEffectiveHeight, ensureComponent } from './uiHelpers';+import {+ SCROLL_VELOCITY_SMOOTHING, SCROLL_VELOCITY_NEW_WEIGHT,+ SCROLL_WHEEL_SENSITIVITY, SCROLL_MAX_DT,+ SCROLL_FPS_REFERENCE, SCROLL_VELOCITY_THRESHOLD,+} from './uiConstants';interface ScrollState {isDragging: boolean;@@ -37,21 +43,21 @@ export class ScrollViewPlugin implements Plugin {[Res(Input), Res(UICameraInfo)],(input: InputState, camera: UICameraData) => {const now = performance.now() / 1000;- const dt = lastTime > 0 ? Math.min(now - lastTime, 0.05) : 0;+ const dt = lastTime > 0 ? Math.min(now - lastTime, SCROLL_MAX_DT) : 0;lastTime = now;if (!camera.valid) return;+ for (const [e] of states) {+ if (!world.valid(e)) states.delete(e);+ }+const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };const entities = world.getEntitiesWithComponents([ScrollView, UIRect]);for (const entity of entities) {- if (!world.has(entity, Interactable)) {- world.insert(entity, Interactable, { enabled: true, blockRaycast: true });- }- if (!world.has(entity, UIMask)) {- world.insert(entity, UIMask, { enabled: true, mode: 'scissor' });- }+ ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });+ ensureComponent(world, entity, UIMask, { enabled: true, mode: 'scissor' });const sv = world.get(entity, ScrollView) as ScrollViewData;const rect = world.get(entity, UIRect) as UIRectData;@@ -80,11 +86,13 @@ export class ScrollViewPlugin implements Plugin {if (sv.horizontalEnabled) {sv.scrollX -= dx;- state.velocityX = dt > 0 ? -dx / dt : 0;+ const instantVx = dt > 0 ? -dx / dt : 0;+ state.velocityX = state.velocityX * SCROLL_VELOCITY_SMOOTHING + instantVx * SCROLL_VELOCITY_NEW_WEIGHT;}if (sv.verticalEnabled) {sv.scrollY -= dy;- state.velocityY = dt > 0 ? -dy / dt : 0;+ const instantVy = dt > 0 ? -dy / dt : 0;+ state.velocityY = state.velocityY * SCROLL_VELOCITY_SMOOTHING + instantVy * SCROLL_VELOCITY_NEW_WEIGHT;}state.lastWorldX = worldMouse.x;@@ -98,24 +106,24 @@ export class ScrollViewPlugin implements Plugin {if (interaction?.hovered) {const scroll = input.getScrollDelta();if (sv.verticalEnabled && scroll.y !== 0) {- sv.scrollY += scroll.y * 0.1;+ sv.scrollY += scroll.y * SCROLL_WHEEL_SENSITIVITY;state.velocityY = 0;}if (sv.horizontalEnabled && scroll.x !== 0) {- sv.scrollX += scroll.x * 0.1;+ sv.scrollX += scroll.x * SCROLL_WHEEL_SENSITIVITY;state.velocityX = 0;}}if (!state.isDragging && sv.inertia && dt > 0) {- const decay = Math.pow(sv.decelerationRate, dt);- if (sv.horizontalEnabled && Math.abs(state.velocityX) > 0.1) {+ const decay = Math.pow(sv.decelerationRate, dt * SCROLL_FPS_REFERENCE);+ if (sv.horizontalEnabled && Math.abs(state.velocityX) > SCROLL_VELOCITY_THRESHOLD) {sv.scrollX += state.velocityX * dt;state.velocityX *= decay;} else {state.velocityX = 0;}- if (sv.verticalEnabled && Math.abs(state.velocityY) > 0.1) {+ if (sv.verticalEnabled && Math.abs(state.velocityY) > SCROLL_VELOCITY_THRESHOLD) {sv.scrollY += state.velocityY * dt;state.velocityY *= decay;} else {@@ -123,12 +131,16 @@ export class ScrollViewPlugin implements Plugin {}}- const viewW = rect.size.x;- const viewH = rect.size.y;+ const viewW = getEffectiveWidth(rect);+ const viewH = getEffectiveHeight(rect);const maxScrollX = Math.max(0, sv.contentWidth - viewW);const maxScrollY = Math.max(0, sv.contentHeight - viewH);+ const prevScrollX = sv.scrollX;+ const prevScrollY = sv.scrollY;sv.scrollX = Math.max(0, Math.min(sv.scrollX, maxScrollX));sv.scrollY = Math.max(0, Math.min(sv.scrollY, maxScrollY));+ if (sv.scrollX !== prevScrollX) state.velocityX = 0;+ if (sv.scrollY !== prevScrollY) state.velocityY = 0;if (sv.contentEntity !== 0 && world.valid(sv.contentEntity)) {if (world.has(sv.contentEntity, LocalTransform)) {@@ -141,7 +153,7 @@ export class ScrollViewPlugin implements Plugin {}},{ name: 'ScrollViewSystem' }- ));+ ), { runAfter: ['UIInteractionSystem'] });}}diff --git a/sdk/src/ui/SliderPlugin.ts b/sdk/src/ui/SliderPlugin.tsindex 4b1fbeea1..9f44767f7 100644--- a/sdk/src/ui/SliderPlugin.ts+++ b/sdk/src/ui/SliderPlugin.ts@@ -11,11 +11,15 @@ import type { SliderData } from './Slider';import { UIRect } from './UIRect';import type { UIRectData } from './UIRect';import { Interactable } from './Interactable';+import type { InteractableData } from './Interactable';import { UIInteraction } from './UIInteraction';import type { UIInteractionData } from './UIInteraction';import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';-import { applyDirectionalFill } from './uiHelpers';+import { UIEvents, UIEventQueue } from './UIEvents';+import { applyDirectionalFill, getEffectiveWidth, getEffectiveHeight, ensureComponent, layoutChildEntity } from './uiHelpers';+import type { LayoutRect } from './uiLayout';+import { quaternionToAngle2D } from './uiMath';export class SliderPlugin implements Plugin {build(app: App): void {@@ -25,17 +29,19 @@ export class SliderPlugin implements Plugin {let draggingSlider: Entity | null = null;app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(Input), Res(UICameraInfo)],- (input: InputState, camera: UICameraData) => {+ [Res(Input), Res(UICameraInfo), Res(UIEvents)],+ (input: InputState, camera: UICameraData, events: UIEventQueue) => {if (!camera.valid) return;+ if (draggingSlider !== null && !world.valid(draggingSlider)) {+ draggingSlider = null;+ }+const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };const entities = world.getEntitiesWithComponents([Slider, UIRect, WorldTransform]);for (const entity of entities) {- if (!world.has(entity, Interactable)) {- world.insert(entity, Interactable, { enabled: true, blockRaycast: true });- }+ ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });const slider = world.get(entity, Slider) as SliderData;const rect = world.get(entity, UIRect) as UIRectData;@@ -44,29 +50,58 @@ export class SliderPlugin implements Plugin {? world.get(entity, UIInteraction) as UIInteractionData: null;- if (interaction?.justPressed) {+ const handleEntity = slider.handleEntity;+ if (handleEntity !== 0 && world.valid(handleEntity)) {+ ensureComponent(world, handleEntity, Interactable, { enabled: true, blockRaycast: false });+ if (world.has(handleEntity, Interactable)) {+ const hi = world.get(handleEntity, Interactable) as InteractableData;+ if (hi.blockRaycast) {+ hi.blockRaycast = false;+ world.insert(handleEntity, Interactable, hi);+ }+ }+ }++ let pressed = interaction?.justPressed ?? false;+ if (!pressed && handleEntity !== 0 && world.valid(handleEntity) && world.has(handleEntity, UIInteraction)) {+ const handleInteraction = world.get(handleEntity, UIInteraction) as UIInteractionData;+ pressed = handleInteraction.justPressed;+ }++ if (pressed) {draggingSlider = entity;}if (draggingSlider === entity && input.isMouseButtonDown(0)) {- const worldW = rect.size.x * wt.scale.x;- const worldH = rect.size.y * wt.scale.y;- const originX = wt.position.x - rect.pivot.x * worldW;- const originY = wt.position.y - rect.pivot.y * worldH;+ const localW = getEffectiveWidth(rect);+ const localH = getEffectiveHeight(rect);+ const worldW = localW * wt.scale.x;+ const worldH = localH * wt.scale.y;++ const angle = quaternionToAngle2D(wt.rotation.z, wt.rotation.w);+ const sin = Math.sin(-angle);+ const cos = Math.cos(-angle);+ const dx = worldMouse.x - wt.position.x;+ const dy = worldMouse.y - wt.position.y;+ const localMouseX = dx * cos - dy * sin;+ const localMouseY = dx * sin + dy * cos;++ const originX = -rect.pivot.x * worldW;+ const originY = -rect.pivot.y * worldH;let t: number;switch (slider.direction) {case FillDirection.LeftToRight:- t = worldW > 0 ? (worldMouse.x - originX) / worldW : 0;+ t = worldW > 0 ? (localMouseX - originX) / worldW : 0;break;case FillDirection.RightToLeft:- t = worldW > 0 ? 1 - (worldMouse.x - originX) / worldW : 0;+ t = worldW > 0 ? 1 - (localMouseX - originX) / worldW : 0;break;case FillDirection.BottomToTop:- t = worldH > 0 ? (worldMouse.y - originY) / worldH : 0;+ t = worldH > 0 ? (localMouseY - originY) / worldH : 0;break;case FillDirection.TopToBottom:- t = worldH > 0 ? 1 - (worldMouse.y - originY) / worldH : 0;+ t = worldH > 0 ? 1 - (localMouseY - originY) / worldH : 0;break;}@@ -75,7 +110,13 @@ export class SliderPlugin implements Plugin {if (slider.wholeNumbers) {newValue = Math.round(newValue);}+ const oldValue = slider.value;slider.value = Math.max(slider.minValue, Math.min(slider.maxValue, newValue));+ world.insert(entity, Slider, slider);++ if (slider.value !== oldValue) {+ events.emit(entity, 'change');+ }}if (draggingSlider === entity && input.isMouseButtonReleased(0)) {@@ -84,14 +125,27 @@ export class SliderPlugin implements Plugin {const range = slider.maxValue - slider.minValue;const normalizedValue = range > 0 ? (slider.value - slider.minValue) / range : 0;+ const sliderW = getEffectiveWidth(rect);+ const sliderH = getEffectiveHeight(rect);++ const sliderPivot = rect.pivot;+ const sliderParentRect: LayoutRect = {+ left: -sliderPivot.x * sliderW,+ bottom: -sliderPivot.y * sliderH,+ right: (1 - sliderPivot.x) * sliderW,+ top: (1 - sliderPivot.y) * sliderH,+ };if (slider.fillEntity !== 0 && world.valid(slider.fillEntity)) {applyDirectionalFill(world, slider.fillEntity, slider.direction, normalizedValue);+ layoutChildEntity(world, slider.fillEntity, sliderParentRect, 0, 0);}if (slider.handleEntity !== 0 && world.valid(slider.handleEntity)) {if (world.has(slider.handleEntity, UIRect)) {const handleRect = world.get(slider.handleEntity, UIRect) as UIRectData;+ handleRect.offsetMin = { x: 0, y: 0 };+ handleRect.offsetMax = { x: 0, y: 0 };switch (slider.direction) {case FillDirection.LeftToRight:handleRect.anchorMin = { x: normalizedValue, y: 0 };@@ -112,11 +166,12 @@ export class SliderPlugin implements Plugin {}world.insert(slider.handleEntity, UIRect, handleRect);}+ layoutChildEntity(world, slider.handleEntity, sliderParentRect, 0, 0);}}},{ name: 'SliderSystem' }- ));+ ), { runAfter: ['UIInteractionSystem'] });}}diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.tsindex ba88aba28..e2905fa6e 100644--- a/sdk/src/ui/TextInputPlugin.ts+++ b/sdk/src/ui/TextInputPlugin.ts@@ -6,11 +6,13 @@ import { registerComponent, Sprite, type SpriteData } from '../component';import { TextInput, type TextInputData } from './TextInput';import { UIRect, type UIRectData } from './UIRect';import { Interactable } from './Interactable';-import { UIInteraction, type UIInteractionData } from './UIInteraction';+import { Focusable } from './Focusable';+import { FocusManager, FocusManagerState } from './Focusable';import { UIEvents, UIEventQueue } from './UIEvents';import { Res } from '../resource';import { platformCreateCanvas } from '../platform';-import { ensureSprite, wrapText, nextPowerOf2 } from './uiHelpers';+import { ensureSprite, wrapText, nextPowerOf2, ensureComponent } from './uiHelpers';+import { CURSOR_BLINK_INTERVAL, TEXT_INPUT_LINE_HEIGHT_RATIO } from './uiConstants';export class TextInputPlugin implements Plugin {private cleanupListeners_: (() => void) | null = null;@@ -37,7 +39,6 @@ export class TextInputPlugin implements Plugin {const ctx = canvas.getContext('2d', { willReadFrequently: true })! asCanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;- let focusedEntity: Entity | null = null;let composing = false;let cursorVisible = true;let cursorTimer = 0;@@ -49,8 +50,16 @@ export class TextInputPlugin implements Plugin {}const textarea = textareaOrNull;+ function getFocusedTextInput(): Entity | null {+ const fm = app.getResource(FocusManager) as FocusManagerState | null;+ if (!fm || fm.focusedEntity === null) return null;+ const entity = fm.focusedEntity;+ if (!world.valid(entity) || !world.has(entity, TextInput)) return null;+ return entity;+ }+const onInput = () => {- if (composing || focusedEntity === null) return;+ if (composing || getFocusedTextInput() === null) return;syncFromTextarea();};@@ -64,18 +73,19 @@ export class TextInputPlugin implements Plugin {};const onKeyDown = (e: KeyboardEvent) => {- if (focusedEntity === null) return;+ const focused = getFocusedTextInput();+ if (focused === null) return;if (e.key === 'Escape') {blurCurrent();return;}- const ti = world.get(focusedEntity, TextInput) as TextInputData;+ const ti = world.get(focused, TextInput) as TextInputData;if (e.key === 'Enter' && !ti.multiline) {e.preventDefault();const events = app.getResource(UIEvents) as UIEventQueue;- events.emit(focusedEntity, 'submit');+ events.emit(focused, 'submit');blurCurrent();return;}@@ -101,12 +111,14 @@ export class TextInputPlugin implements Plugin {};const onBlur = () => {- if (focusedEntity !== null && world.valid(focusedEntity) && world.has(focusedEntity, TextInput)) {- const ti = world.get(focusedEntity, TextInput) as TextInputData;+ const focused = getFocusedTextInput();+ if (focused !== null) {+ const ti = world.get(focused, TextInput) as TextInputData;ti.focused = false;ti.dirty = true;+ const fm = app.getResource(FocusManager) as FocusManagerState;+ fm.blur();}- focusedEntity = null;};textarea.addEventListener('input', onInput);@@ -125,8 +137,9 @@ export class TextInputPlugin implements Plugin {};function syncFromTextarea(): void {- if (focusedEntity === null || !world.valid(focusedEntity)) return;- const ti = world.get(focusedEntity, TextInput) as TextInputData;+ const focused = getFocusedTextInput();+ if (focused === null) return;+ const ti = world.get(focused, TextInput) as TextInputData;if (ti.readOnly) return;let val = textarea.value;@@ -138,21 +151,17 @@ export class TextInputPlugin implements Plugin {if (val !== ti.value) {ti.value = val;const events = app.getResource(UIEvents) as UIEventQueue;- events.emit(focusedEntity, 'change');+ events.emit(focused, 'change');}ti.cursorPos = textarea.selectionStart ?? val.length;ti.dirty = true;resetCursorBlink();}- function focusEntity(entity: Entity): void {- if (focusedEntity === entity) return;- blurCurrent();-+ function activateTextarea(entity: Entity): void {const ti = world.get(entity, TextInput) as TextInputData;if (ti.readOnly) return;- focusedEntity = entity;ti.focused = true;ti.dirty = true;@@ -164,12 +173,14 @@ export class TextInputPlugin implements Plugin {}function blurCurrent(): void {- if (focusedEntity !== null && world.valid(focusedEntity) && world.has(focusedEntity, TextInput)) {- const ti = world.get(focusedEntity, TextInput) as TextInputData;+ const focused = getFocusedTextInput();+ if (focused !== null) {+ const ti = world.get(focused, TextInput) as TextInputData;ti.focused = false;ti.dirty = true;}- focusedEntity = null;+ const fm = app.getResource(FocusManager) as FocusManagerState;+ fm.blur();textarea.blur();}@@ -178,54 +189,54 @@ export class TextInputPlugin implements Plugin {cursorTimer = 0;}- // Focus system- app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(- [Res(UIEvents)],- (events: UIEventQueue) => {- const textInputEntities = world.getEntitiesWithComponents([TextInput, Interactable]);+ let prevFocusedTextInput: Entity | null = null;+ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Res(FocusManager)],+ (focusManager: FocusManagerState) => {+ const textInputEntities = world.getEntitiesWithComponents([TextInput]);for (const entity of textInputEntities) {- if (!world.has(entity, UIInteraction)) continue;- const interaction = world.get(entity, UIInteraction) as UIInteractionData;- if (interaction.justPressed) {- focusEntity(entity);- return;- }+ ensureComponent(world, entity, Focusable, { tabIndex: 0, isFocused: false });+ ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });}- if (focusedEntity !== null) {- const allInteractables = world.getEntitiesWithComponents([Interactable]);- for (const entity of allInteractables) {- if (world.has(entity, TextInput)) continue;- if (!world.has(entity, UIInteraction)) continue;- const interaction = world.get(entity, UIInteraction) as UIInteractionData;- if (interaction.justPressed) {- blurCurrent();- return;- }+ const currentFocused = getFocusedTextInput();++ if (currentFocused !== prevFocusedTextInput) {+ if (prevFocusedTextInput !== null && world.valid(prevFocusedTextInput) && world.has(prevFocusedTextInput, TextInput)) {+ const ti = world.get(prevFocusedTextInput, TextInput) as TextInputData;+ ti.focused = false;+ ti.dirty = true;+ textarea.blur();}++ if (currentFocused !== null) {+ activateTextarea(currentFocused);+ }++ prevFocusedTextInput = currentFocused;}},{ name: 'TextInputFocusSystem' }- ));+ ), { runAfter: ['FocusSystem'] });// Render systemapp.addSystemToSchedule(Schedule.PreUpdate, defineSystem([],() => {const now = typeof performance !== 'undefined' ? performance.now() : Date.now();- const dt = lastTime === 0 ? 0 : (now - lastTime) / 1000;+ let dt = lastTime === 0 ? 0 : (now - lastTime) / 1000;lastTime = now;+ dt = Math.min(dt, 0.1);- if (focusedEntity !== null) {+ const focused = getFocusedTextInput();+ if (focused !== null) {cursorTimer += dt;- if (cursorTimer >= 0.5) {- cursorTimer -= 0.5;+ if (cursorTimer >= CURSOR_BLINK_INTERVAL) {+ cursorTimer -= CURSOR_BLINK_INTERVAL;cursorVisible = !cursorVisible;- if (focusedEntity !== null && world.valid(focusedEntity) && world.has(focusedEntity, TextInput)) {- const ti = world.get(focusedEntity, TextInput) as TextInputData;- ti.dirty = true;- }+ const ti = world.get(focused, TextInput) as TextInputData;+ ti.dirty = true;}}@@ -264,7 +275,6 @@ export class TextInputPlugin implements Plugin {ctx.clearRect(0, 0, canvas.width, canvas.height);- // Backgroundconst bg = ti.backgroundColor;ctx.fillStyle = `rgba(${Math.round(bg.r * 255)}, ${Math.round(bg.g * 255)}, ${Math.round(bg.b * 255)}, ${bg.a})`;ctx.fillRect(0, 0, w, h);@@ -288,7 +298,7 @@ export class TextInputPlugin implements Plugin {const textColor = isEmpty ? ti.placeholderColor : ti.color;ctx.fillStyle = `rgba(${Math.round(textColor.r * 255)}, ${Math.round(textColor.g * 255)}, ${Math.round(textColor.b * 255)}, ${textColor.a})`;- const lineHeight = Math.ceil(ti.fontSize * 1.2);+ const lineHeight = Math.ceil(ti.fontSize * TEXT_INPUT_LINE_HEIGHT_RATIO);const padding = ti.padding;if (ti.multiline) {@@ -303,7 +313,6 @@ export class TextInputPlugin implements Plugin {ctx.fillText(displayText, padding, textY);}- // Cursorif (ti.focused && cursorVisible) {const cursorText = ti.password? '\u25CF'.repeat(ti.cursorPos)@@ -314,10 +323,27 @@ export class TextInputPlugin implements Plugin {let cursorH: number;if (ti.multiline) {- const lines = wrapText(ctx, ti.value.substring(0, ti.cursorPos), w - padding * 2);- const lastLine = lines.length > 0 ? lines[lines.length - 1] : '';- cursorX = padding + ctx.measureText(lastLine).width;- cursorY = padding + (lines.length - 1) * lineHeight;+ const lines = wrapText(ctx, ti.value, w - padding * 2);+ let charCount = 0;+ let cursorLine = 0;+ let cursorCol = 0;+ for (let i = 0; i < lines.length; i++) {+ const lineLen = lines[i].length;+ if (charCount + lineLen >= ti.cursorPos) {+ cursorLine = i;+ cursorCol = ti.cursorPos - charCount;+ break;+ }+ charCount += lineLen;+ if (i < lines.length - 1 && charCount < ti.value.length && ti.value[charCount] === '\n') {+ charCount++;+ }+ cursorLine = i + 1;+ cursorCol = 0;+ }+ const partialLine = cursorLine < lines.length ? lines[cursorLine].substring(0, cursorCol) : '';+ cursorX = padding + ctx.measureText(partialLine).width;+ cursorY = padding + cursorLine * lineHeight;cursorH = lineHeight;} else {cursorX = padding + ctx.measureText(cursorText).width;@@ -331,7 +357,6 @@ export class TextInputPlugin implements Plugin {ctx.restore();- // Upload textureconst imageData = ctx.getImageData(0, 0, w, h);const pixels = new Uint8Array(imageData.data.buffer);const rm = module!.getResourceManager();diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.tsindex 09f2bb9fb..16369bd97 100644--- a/sdk/src/ui/TextPlugin.ts+++ b/sdk/src/ui/TextPlugin.ts@@ -1,73 +1,34 @@-/**- * @file TextPlugin.ts- * @brief Plugin that automatically syncs Text components to Sprite textures- */-import type { App, Plugin } from '../app';-import type { Entity } from '../types';+import { INVALID_TEXTURE, type Entity } from '../types';import { defineSystem, Schedule } from '../system';import { registerComponent, Sprite, type SpriteData } from '../component';import { Text, type TextData } from './text';import { TextRenderer } from './TextRenderer';import { UIRect, type UIRectData } from './UIRect';-import { ensureSprite } from './uiHelpers';--interface TextSnapshot {- content: string;- fontFamily: string;- fontSize: number;- colorR: number;- colorG: number;- colorB: number;- colorA: number;- align: number;- verticalAlign: number;- wordWrap: boolean;- overflow: number;- lineHeight: number;- containerWidth: number;- containerHeight: number;-}--function takeSnapshot(text: TextData, uiRect?: UIRectData | null): TextSnapshot {- return {- content: text.content,- fontFamily: text.fontFamily,- fontSize: text.fontSize,- colorR: text.color.r,- colorG: text.color.g,- colorB: text.color.b,- colorA: text.color.a,- align: text.align,- verticalAlign: text.verticalAlign,- wordWrap: text.wordWrap,- overflow: text.overflow,- lineHeight: text.lineHeight,- containerWidth: uiRect ? uiRect.size.x : 0,- containerHeight: uiRect ? uiRect.size.y : 0,- };-}+import { ensureSprite, getEffectiveWidth, getEffectiveHeight } from './uiHelpers';+import { createSnapshotUtils, type Snapshot } from './uiSnapshot';-function snapshotChanged(snap: TextSnapshot, text: TextData, uiRect?: UIRectData | null): boolean {- return snap.content !== text.content- || snap.fontFamily !== text.fontFamily- || snap.fontSize !== text.fontSize- || snap.colorR !== text.color.r- || snap.colorG !== text.color.g- || snap.colorB !== text.color.b- || snap.colorA !== text.color.a- || snap.align !== text.align- || snap.verticalAlign !== text.verticalAlign- || snap.wordWrap !== text.wordWrap- || snap.overflow !== text.overflow- || snap.lineHeight !== text.lineHeight- || snap.containerWidth !== (uiRect ? uiRect.size.x : 0)- || snap.containerHeight !== (uiRect ? uiRect.size.y : 0);+interface TextSource {+ text: TextData;+ uiRect: UIRectData | null;}-// =============================================================================-// Text Plugin-// =============================================================================+const textSnapshot = createSnapshotUtils<TextSource>({+ content: s => s.text.content,+ fontFamily: s => s.text.fontFamily,+ fontSize: s => s.text.fontSize,+ colorR: s => s.text.color.r,+ colorG: s => s.text.color.g,+ colorB: s => s.text.color.b,+ colorA: s => s.text.color.a,+ align: s => s.text.align,+ verticalAlign: s => s.text.verticalAlign,+ wordWrap: s => s.text.wordWrap,+ overflow: s => s.text.overflow,+ lineHeight: s => s.text.lineHeight,+ containerWidth: s => s.uiRect ? getEffectiveWidth(s.uiRect) : 0,+ containerHeight: s => s.uiRect ? getEffectiveHeight(s.uiRect) : 0,+});export class TextPlugin implements Plugin {build(app: App): void {@@ -81,15 +42,21 @@ export class TextPlugin implements Plugin {const renderer = new TextRenderer(module);const world = app.world;- const snapshots = new Map<Entity, TextSnapshot>();+ const snapshots = new Map<Entity, Snapshot>();app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([],() => {+ renderer.beginFrame();renderer.cleanupOrphaned(e => world.valid(e) && world.has(e, Text));for (const entity of snapshots.keys()) {if (!world.valid(entity) || !world.has(entity, Text)) {+ if (world.valid(entity) && world.has(entity, Sprite)) {+ const sprite = world.get(entity, Sprite) as SpriteData;+ sprite.texture = INVALID_TEXTURE;+ world.insert(entity, Sprite, sprite);+ }snapshots.delete(entity);}}@@ -101,9 +68,10 @@ export class TextPlugin implements Plugin {const uiRect = world.has(entity, UIRect)? world.get(entity, UIRect) as UIRectData: null;+ const source: TextSource = { text, uiRect };const prev = snapshots.get(entity);- if (prev && !snapshotChanged(prev, text, uiRect)) continue;+ if (prev && !textSnapshot.changed(prev, source)) continue;ensureSprite(world, entity);@@ -119,7 +87,7 @@ export class TextPlugin implements Plugin {sprite.uvScale.y = 1;world.insert(entity, Sprite, sprite);- snapshots.set(entity, takeSnapshot(text, uiRect));+ snapshots.set(entity, textSnapshot.take(source));}},{ name: 'TextSystem' }diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.tsindex dbb9526a9..533df9599 100644--- a/sdk/src/ui/TextRenderer.ts+++ b/sdk/src/ui/TextRenderer.ts@@ -9,6 +9,7 @@ import type { ESEngineModule } from '../wasm';import { TextAlign, TextVerticalAlign, TextOverflow, type TextData } from './text';import { platformCreateCanvas } from '../platform';import { wrapText, nextPowerOf2 } from './uiHelpers';+import { TEXT_PADDING_RATIO, TEXT_CANVAS_SHRINK_FRAMES, TEXT_CANVAS_OVERSIZE_RATIO } from './uiConstants';interface SizedRect {size: { x: number; y: number };@@ -33,6 +34,9 @@ export class TextRenderer {private ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;private module: ESEngineModule;private cache = new Map<Entity, TextRenderResult>();+ private shrinkCounter_ = 0;+ private frameMaxW_ = 0;+ private frameMaxH_ = 0;constructor(module: ESEngineModule) {this.module = module;@@ -40,10 +44,38 @@ export class TextRenderer {this.ctx = this.canvas.getContext('2d', { willReadFrequently: true })! as CanvasRenderingContext2D;}- /**- * Renders text to a texture and returns the handle- */- renderText(text: TextData, uiRect?: SizedRect | null): TextRenderResult {+ beginFrame(): void {+ const canvas = this.canvas;+ if (this.frameMaxW_ > 0) {+ if (canvas.width < this.frameMaxW_ || canvas.height < this.frameMaxH_) {+ canvas.width = Math.max(canvas.width, nextPowerOf2(this.frameMaxW_));+ canvas.height = Math.max(canvas.height, nextPowerOf2(this.frameMaxH_));+ this.shrinkCounter_ = 0;+ } else if (canvas.width > this.frameMaxW_ * TEXT_CANVAS_OVERSIZE_RATIO || canvas.height > this.frameMaxH_ * TEXT_CANVAS_OVERSIZE_RATIO) {+ this.shrinkCounter_++;+ if (this.shrinkCounter_ >= TEXT_CANVAS_SHRINK_FRAMES) {+ canvas.width = nextPowerOf2(this.frameMaxW_);+ canvas.height = nextPowerOf2(this.frameMaxH_);+ this.shrinkCounter_ = 0;+ }+ } else {+ this.shrinkCounter_ = 0;+ }+ }+ this.frameMaxW_ = 0;+ this.frameMaxH_ = 0;+ }++ private renderText(text: TextData, uiRect?: SizedRect | null): TextRenderResult {+ try {+ return this.renderTextInner(text, uiRect);+ } catch (e) {+ console.error('TextRenderer: render failed', e);+ return { textureHandle: 0, width: 0, height: 0 };+ }+ }++ private renderTextInner(text: TextData, uiRect?: SizedRect | null): TextRenderResult {const ctx = this.ctx;const canvas = this.canvas;@@ -56,7 +88,7 @@ export class TextRenderer {const shouldWrap = text.wordWrap && hasContainer;let lines = wrapText(ctx, text.content, shouldWrap ? containerWidth : 0);const lineHeightPx = Math.ceil(text.fontSize * text.lineHeight);- const padding = Math.ceil(text.fontSize * 0.2);+ const padding = Math.ceil(text.fontSize * TEXT_PADDING_RATIO);const measuredWidth = Math.ceil(this.measureWidth(lines));const measuredHeight = Math.ceil(lines.length * lineHeightPx);@@ -64,7 +96,6 @@ export class TextRenderer {const width = hasContainer ? Math.ceil(containerWidth) : measuredWidth + padding * 2;const height = hasContainer ? Math.ceil(containerHeight) : measuredHeight + padding * 2;- // Handle overflow ellipsisif (hasContainer && text.overflow === TextOverflow.Ellipsis && measuredHeight > containerHeight) {const maxLines = Math.floor(containerHeight / lineHeightPx);if (maxLines > 0 && lines.length > maxLines) {@@ -74,11 +105,12 @@ export class TextRenderer {}}+ this.frameMaxW_ = Math.max(this.frameMaxW_, width);+ this.frameMaxH_ = Math.max(this.frameMaxH_, height);+if (canvas.width < width || canvas.height < height) {- const newWidth = Math.max(canvas.width, nextPowerOf2(width));- const newHeight = Math.max(canvas.height, nextPowerOf2(height));- canvas.width = newWidth;- canvas.height = newHeight;+ canvas.width = Math.max(canvas.width, nextPowerOf2(width));+ canvas.height = Math.max(canvas.height, nextPowerOf2(height));}const r = Math.round(text.color.r * 255);@@ -105,7 +137,7 @@ export class TextRenderer {if (hasContainer) {switch (text.verticalAlign) {case TextVerticalAlign.Top: startY = padding; break;- case TextVerticalAlign.Middle: startY = (height - textBlockHeight) / 2; break;+ case TextVerticalAlign.Middle: startY = padding + (height - 2 * padding - textBlockHeight) / 2; break;case TextVerticalAlign.Bottom: startY = height - textBlockHeight - padding; break;default: startY = padding;}@@ -224,11 +256,7 @@ export class TextRenderer {private measureWidth(lines: string[]): number {let maxWidth = 0;for (const line of lines) {- const metrics = this.ctx.measureText(line);- const width = metrics.actualBoundingBoxLeft !== undefined- ? metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight- : metrics.width;- maxWidth = Math.max(maxWidth, width);+ maxWidth = Math.max(maxWidth, this.ctx.measureText(line).width);}return maxWidth;}diff --git a/sdk/src/ui/TogglePlugin.ts b/sdk/src/ui/TogglePlugin.tsindex 9aa073382..01778bc32 100644--- a/sdk/src/ui/TogglePlugin.ts+++ b/sdk/src/ui/TogglePlugin.ts@@ -3,6 +3,7 @@ import { registerComponent, Sprite } from '../component';import type { SpriteData } from '../component';import { defineSystem, Schedule } from '../system';import { Res } from '../resource';+import type { Entity } from '../types';import { Interactable } from './Interactable';import type { InteractableData } from './Interactable';import { UIInteraction } from './UIInteraction';@@ -12,7 +13,7 @@ import type { ToggleData } from './Toggle';import { ToggleGroup } from './ToggleGroup';import type { ToggleGroupData } from './ToggleGroup';import { UIEvents, UIEventQueue } from './UIEvents';-import { applyColorTransition } from './uiHelpers';+import { applyColorTransition, ensureComponent } from './uiHelpers';export class TogglePlugin implements Plugin {build(app: App): void {@@ -20,15 +21,27 @@ export class TogglePlugin implements Plugin {registerComponent('ToggleGroup', ToggleGroup);const world = app.world;+ const initializedEntities = new Set<Entity>();app.addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents)],(events: UIEventQueue) => {const toggleEntities = world.getEntitiesWithComponents([Toggle]);++ const groupFirstOn = new Map<Entity, Entity>();for (const entity of toggleEntities) {- if (!world.has(entity, Interactable)) {- world.insert(entity, Interactable, { enabled: true });+ if (initializedEntities.has(entity)) continue;+ initializedEntities.add(entity);+ const toggle = world.get(entity, Toggle) as ToggleData;+ if (!toggle.isOn || toggle.group === 0 || !world.valid(toggle.group)) continue;+ if (!groupFirstOn.has(toggle.group)) {+ groupFirstOn.set(toggle.group, entity);+ } else {+ toggle.isOn = false;}+ }+ for (const entity of toggleEntities) {+ ensureComponent(world, entity, Interactable, { enabled: true });if (!world.has(entity, UIInteraction)) continue;const interaction = world.get(entity, UIInteraction) as UIInteractionData;@@ -64,7 +77,7 @@ export class TogglePlugin implements Plugin {if (toggle.graphicEntity && world.valid(toggle.graphicEntity)) {if (world.has(toggle.graphicEntity, Sprite)) {const sprite = world.get(toggle.graphicEntity, Sprite) as SpriteData;- sprite.color.a = toggle.isOn ? 1 : 0;+ sprite.enabled = toggle.isOn;world.insert(toggle.graphicEntity, Sprite, sprite);}}diff --git a/sdk/src/ui/UIInteractionPlugin.ts b/sdk/src/ui/UIInteractionPlugin.tsindex 822bd1635..6ab33f0f2 100644--- a/sdk/src/ui/UIInteractionPlugin.ts+++ b/sdk/src/ui/UIInteractionPlugin.ts@@ -21,27 +21,10 @@ import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';import { UIMask } from './UIMask';import type { UIMaskData } from './UIMask';-import { invertMatrix4, screenToWorld, pointInOBB, pointInWorldRect } from './uiMath';-import { applyColorTransition } from './uiHelpers';--const _invVP = new Float32Array(16);-const _cachedVP = new Float32Array(16);-let _invVPDirty = true;-let _cachedDpr = 1;--function updateInvVPCache(vp: Float32Array): void {- let dirty = false;- for (let i = 0; i < 16; i++) {- if (_cachedVP[i] !== vp[i]) {- dirty = true;- break;- }- }- if (dirty) {- _cachedVP.set(vp);- _invVPDirty = true;- }-}+import { screenToWorld, pointInOBB, createInvVPCache } from './uiMath';+import { applyColorTransition, getEffectiveWidth, getEffectiveHeight, ensureComponent } from './uiHelpers';++const vpCache = createInvVPCache();function isClippedByMask(world: World,@@ -60,13 +43,14 @@ function isClippedByMask(if (mask.enabled && world.has(parentEntity, UIRect) && world.has(parentEntity, WorldTransform)) {const wt = world.get(parentEntity, WorldTransform) as WorldTransformData;const rect = world.get(parentEntity, UIRect) as UIRectData;- const maskW = rect.size.x * wt.scale.x;- const maskH = rect.size.y * wt.scale.y;- if (!pointInWorldRect(+ const maskW = getEffectiveWidth(rect) * wt.scale.x;+ const maskH = getEffectiveHeight(rect) * wt.scale.y;+ if (!pointInOBB(worldMouseX, worldMouseY,wt.position.x, wt.position.y,maskW, maskH,rect.pivot.x, rect.pivot.y,+ wt.rotation.z, wt.rotation.w,)) {return true;}@@ -114,7 +98,6 @@ export class UIInteractionPlugin implements Plugin {let hoveredEntity: Entity | null = null;let pressedEntity: Entity | null = null;- _cachedDpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Res(Input), Res(UICameraInfo)],@@ -130,16 +113,14 @@ export class UIInteractionPlugin implements Plugin {if (!camera.valid) return;- const mouseGLX = input.mouseX * _cachedDpr;- const mouseGLY = camera.screenH - input.mouseY * _cachedDpr;+ const dpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;+ const mouseGLX = input.mouseX * dpr;+ const mouseGLY = camera.screenH - input.mouseY * dpr;- updateInvVPCache(camera.viewProjection);- if (_invVPDirty) {- invertMatrix4(camera.viewProjection, _invVP);- _invVPDirty = false;- }+ vpCache.update(camera.viewProjection);+ const invVP = vpCache.getInverse(camera.viewProjection);const worldMouse = screenToWorld(- mouseGLX, mouseGLY, _invVP,+ mouseGLX, mouseGLY, invVP,camera.vpX, camera.vpY, camera.vpW, camera.vpH,);@@ -154,9 +135,7 @@ export class UIInteractionPlugin implements Plugin {let hitLayer = -Infinity;for (const entity of interactableEntities) {- if (!world.has(entity, UIInteraction)) {- world.insert(entity, UIInteraction);- }+ ensureComponent(world, entity, UIInteraction);const interactable = world.get(entity, Interactable) as InteractableData;if (!interactable.enabled) continue;@@ -164,8 +143,8 @@ export class UIInteractionPlugin implements Plugin {const wt = world.get(entity, WorldTransform) as WorldTransformData;const rect = world.get(entity, UIRect) as UIRectData;- const worldW = rect.size.x * wt.scale.x;- const worldH = rect.size.y * wt.scale.y;+ const worldW = getEffectiveWidth(rect) * wt.scale.x;+ const worldH = getEffectiveHeight(rect) * wt.scale.y;if (pointInOBB(worldMouse.x, worldMouse.y,@@ -182,13 +161,17 @@ export class UIInteractionPlugin implements Plugin {if (world.has(entity, Sprite)) {layer = (world.get(entity, Sprite) as SpriteData).layer;}- if (layer >= hitLayer) {+ if (layer > hitLayer) {hitLayer = layer;hitEntity = entity;}}}+ 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;@@ -227,20 +210,21 @@ export class UIInteractionPlugin implements Plugin {{ name: 'UIInteractionSystem' }));+ const buttonInitialized = new Set<Entity>();+app.addSystemToSchedule(Schedule.Update, defineSystem([],() => {const buttonEntities = world.getEntitiesWithComponents([Button]);for (const entity of buttonEntities) {- if (!world.has(entity, Interactable)) {- world.insert(entity, Interactable, { enabled: true });- }+ ensureComponent(world, entity, Interactable, { enabled: true });if (!world.has(entity, UIInteraction)) continue;const interaction = world.get(entity, UIInteraction) as UIInteractionData;const button = world.get(entity, Button) as ButtonData;const interactable = world.get(entity, Interactable) as InteractableData;+ const isFirstFrame = !buttonInitialized.has(entity);const prevState = button.state;if (!interactable.enabled) {@@ -253,7 +237,11 @@ export class UIInteractionPlugin implements Plugin {button.state = ButtonState.Normal;}- if (prevState !== button.state && button.transition && world.has(entity, Sprite)) {+ if (isFirstFrame) {+ buttonInitialized.add(entity);+ }++ if ((isFirstFrame || prevState !== button.state) && button.transition && world.has(entity, Sprite)) {const sprite = world.get(entity, Sprite) as SpriteData;sprite.color = applyColorTransition(button.transition,diff --git a/sdk/src/ui/UILayoutPlugin.ts b/sdk/src/ui/UILayoutPlugin.tsindex 81a5093b5..ad875e9d5 100644--- a/sdk/src/ui/UILayoutPlugin.ts+++ b/sdk/src/ui/UILayoutPlugin.ts@@ -1,6 +1,6 @@import type { App, Plugin } from '../app';-import { registerComponent, LocalTransform, Children, Parent } from '../component';-import type { LocalTransformData, ChildrenData, ParentData } from '../component';+import { registerComponent, LocalTransform, Children, Parent, Sprite } from '../component';+import type { LocalTransformData, ChildrenData, ParentData, SpriteData } from '../component';import { defineSystem, Schedule } from '../system';import { Res } from '../resource';import { UIRect } from './UIRect';@@ -11,60 +11,20 @@ import type { UICameraData } from './UICameraInfo';import type { Entity } from '../types';import type { World } from '../world';import { computeUIRectLayout, type LayoutRect } from './uiLayout';--interface RectSnapshot {- anchorMinX: number;- anchorMinY: number;- anchorMaxX: number;- anchorMaxY: number;- offsetMinX: number;- offsetMinY: number;- offsetMaxX: number;- offsetMaxY: number;- sizeX: number;- sizeY: number;-}--function updateSnapshot(snap: RectSnapshot, rect: UIRectData): void {- snap.anchorMinX = rect.anchorMin.x;- snap.anchorMinY = rect.anchorMin.y;- snap.anchorMaxX = rect.anchorMax.x;- snap.anchorMaxY = rect.anchorMax.y;- snap.offsetMinX = rect.offsetMin.x;- snap.offsetMinY = rect.offsetMin.y;- snap.offsetMaxX = rect.offsetMax.x;- snap.offsetMaxY = rect.offsetMax.y;- snap.sizeX = rect.size.x;- snap.sizeY = rect.size.y;-}--function createSnapshot(rect: UIRectData): RectSnapshot {- return {- anchorMinX: rect.anchorMin.x,- anchorMinY: rect.anchorMin.y,- anchorMaxX: rect.anchorMax.x,- anchorMaxY: rect.anchorMax.y,- offsetMinX: rect.offsetMin.x,- offsetMinY: rect.offsetMin.y,- offsetMaxX: rect.offsetMax.x,- offsetMaxY: rect.offsetMax.y,- sizeX: rect.size.x,- sizeY: rect.size.y,- };-}--function rectChanged(snap: RectSnapshot, rect: UIRectData): boolean {- return snap.anchorMinX !== rect.anchorMin.x- || snap.anchorMinY !== rect.anchorMin.y- || snap.anchorMaxX !== rect.anchorMax.x- || snap.anchorMaxY !== rect.anchorMax.y- || snap.offsetMinX !== rect.offsetMin.x- || snap.offsetMinY !== rect.offsetMin.y- || snap.offsetMaxX !== rect.offsetMax.x- || snap.offsetMaxY !== rect.offsetMax.y- || snap.sizeX !== rect.size.x- || snap.sizeY !== rect.size.y;-}+import { createSnapshotUtils, type Snapshot } from './uiSnapshot';++const rectSnapshot = createSnapshotUtils<UIRectData>({+ anchorMinX: r => r.anchorMin.x,+ anchorMinY: r => r.anchorMin.y,+ anchorMaxX: r => r.anchorMax.x,+ anchorMaxY: r => r.anchorMax.y,+ offsetMinX: r => r.offsetMin.x,+ offsetMinY: r => r.offsetMin.y,+ offsetMaxX: r => r.offsetMax.x,+ offsetMaxY: r => r.offsetMax.y,+ sizeX: r => r.size.x,+ sizeY: r => r.size.y,+});function findRoot(world: World, entity: Entity): Entity | null {let current = entity;@@ -81,8 +41,8 @@ function layoutEntity(world: World,entity: Entity,parentRect: LayoutRect,- parentCenterX: number,- parentCenterY: number,+ parentOriginX: number,+ parentOriginY: number,isRoot: boolean,): void {if (!world.has(entity, UIRect)) return;@@ -92,23 +52,34 @@ function layoutEntity(const result = computeUIRectLayout(rect.anchorMin, rect.anchorMax,rect.offsetMin, rect.offsetMax,- rect.size, parentRect,+ rect.size, parentRect, rect.pivot,);- if (rect.anchorMin.x !== rect.anchorMax.x || rect.anchorMin.y !== rect.anchorMax.y) {- rect.size.x = result.width;- rect.size.y = result.height;+ const width = result.rect.right - result.rect.left;+ const height = result.rect.top - result.rect.bottom;+ rect._computedWidth = width;+ rect._computedHeight = height;++ if (world.has(entity, Sprite)) {+ const sprite = world.get(entity, Sprite) as SpriteData;+ if (sprite.size.x !== width || sprite.size.y !== height) {+ sprite.size.x = width;+ sprite.size.y = height;+ world.insert(entity, Sprite, sprite);+ }}- const transform = world.get(entity, LocalTransform) as LocalTransformData;- if (isRoot) {- transform.position.x = result.centerX;- transform.position.y = result.centerY;- } else {- transform.position.x = result.centerX - parentCenterX;- transform.position.y = result.centerY - parentCenterY;+ if (!rect._layoutManaged) {+ const transform = world.get(entity, LocalTransform) as LocalTransformData;+ if (isRoot) {+ transform.position.x = result.originX;+ transform.position.y = result.originY;+ } else {+ transform.position.x = result.originX - parentOriginX;+ transform.position.y = result.originY - parentOriginY;+ }+ world.insert(entity, LocalTransform, transform);}- world.insert(entity, LocalTransform, transform);if (!world.has(entity, Children)) return;@@ -117,7 +88,7 @@ function layoutEntity(for (const child of children.entities) {if (world.valid(child)) {- layoutEntity(world, child, result.rect, result.centerX, result.centerY, false);+ layoutEntity(world, child, result.rect, result.originX, result.originY, false);}}}@@ -127,7 +98,7 @@ export class UILayoutPlugin implements Plugin {registerComponent('UIRect', UIRect);const world = app.world;- const snapshots = new Map<Entity, RectSnapshot>();+ const snapshots = new Map<Entity, Snapshot>();const rootCache = new Map<Entity, Entity | null>();let prevCameraLeft = NaN;let prevCameraBottom = NaN;@@ -142,6 +113,18 @@ export class UILayoutPlugin implements Plugin {return root;}+ function clearSubtreeCache(entity: Entity): void {+ rootCache.delete(entity);+ if (!world.has(entity, Children)) return;+ const ch = world.get(entity, Children) as ChildrenData;+ if (!ch || !ch.entities) return;+ for (const child of ch.entities) {+ if (world.valid(child)) {+ clearSubtreeCache(child);+ }+ }+ }+app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Res(UICameraInfo)],(camera: UICameraData) => {@@ -153,8 +136,8 @@ export class UILayoutPlugin implements Plugin {right: camera.worldRight,top: camera.worldTop,};- const cameraCenterX = (cameraRect.left + cameraRect.right) * 0.5;- const cameraCenterY = (cameraRect.bottom + cameraRect.top) * 0.5;+ const cameraOriginX = (cameraRect.left + cameraRect.right) * 0.5;+ const cameraOriginY = (cameraRect.bottom + cameraRect.top) * 0.5;const cameraChanged = prevCameraLeft !== camera.worldLeft|| prevCameraBottom !== camera.worldBottom@@ -188,9 +171,9 @@ export class UILayoutPlugin implements Plugin {const rect = world.get(entity, UIRect) as UIRectData;const snap = snapshots.get(entity);- if (rect._dirty || !snap || rectChanged(snap, rect)) {+ if (rect._dirty || !snap || rectSnapshot.changed(snap, rect)) {rect._dirty = false;- rootCache.delete(entity);+ clearSubtreeCache(entity);const root = getCachedRoot(entity);if (root !== null) {dirtyRoots.add(root);@@ -199,16 +182,16 @@ export class UILayoutPlugin implements Plugin {}for (const root of dirtyRoots) {- layoutEntity(world, root, cameraRect, cameraCenterX, cameraCenterY, true);+ layoutEntity(world, root, cameraRect, cameraOriginX, cameraOriginY, true);}for (const entity of allUIRectEntities) {const rect = world.get(entity, UIRect) as UIRectData;const existing = snapshots.get(entity);if (existing) {- updateSnapshot(existing, rect);+ rectSnapshot.update(existing, rect);} else {- snapshots.set(entity, createSnapshot(rect));+ snapshots.set(entity, rectSnapshot.take(rect));}}},diff --git a/sdk/src/ui/UIMaskPlugin.ts b/sdk/src/ui/UIMaskPlugin.tsindex 2ac8e053c..1100bf0d4 100644--- a/sdk/src/ui/UIMaskPlugin.ts+++ b/sdk/src/ui/UIMaskPlugin.ts@@ -7,7 +7,8 @@ import { registerComponent, WorldTransform, Parent } from '../component';import type { WorldTransformData, ParentData } from '../component';import { UIMask, type UIMaskData } from './UIMask';import { UIRect, type UIRectData } from './UIRect';-import { worldRectToScreen, intersectRects, type ScreenRect } from './uiMath';+import { intersectRects, quaternionToAngle2D, worldToScreen, type ScreenRect } from './uiMath';+import { getEffectiveWidth, getEffectiveHeight } from './uiHelpers';function computeMaskScreenRect(world: World, entity: Entity,@@ -18,14 +19,46 @@ function computeMaskScreenRect(}const uiRect = world.get(entity, UIRect) as UIRectData;const wt = world.get(entity, WorldTransform) as WorldTransformData;- const worldW = uiRect.size.x * wt.scale.x;- const worldH = uiRect.size.y * wt.scale.y;- return worldRectToScreen(- wt.position.x, wt.position.y,- worldW, worldH,- uiRect.pivot.x, uiRect.pivot.y,- vp, vpX, vpY, vpW, vpH- );+ const worldW = getEffectiveWidth(uiRect) * wt.scale.x;+ const worldH = getEffectiveHeight(uiRect) * wt.scale.y;+ const cx = wt.position.x;+ const cy = wt.position.y;+ const px = uiRect.pivot.x;+ const py = uiRect.pivot.y;++ const localLeft = -worldW * px;+ const localRight = worldW * (1 - px);+ const localBottom = -worldH * py;+ const localTop = worldH * (1 - py);++ const rz = wt.rotation.z;+ const rw = wt.rotation.w;+ const angle = quaternionToAngle2D(rz, rw);+ const cos = Math.cos(angle);+ const sin = Math.sin(angle);++ const corners: [number, number][] = [+ [cx + localLeft * cos - localBottom * sin, cy + localLeft * sin + localBottom * cos],+ [cx + localRight * cos - localBottom * sin, cy + localRight * sin + localBottom * cos],+ [cx + localRight * cos - localTop * sin, cy + localRight * sin + localTop * cos],+ [cx + localLeft * cos - localTop * sin, cy + localLeft * sin + localTop * cos],+ ];++ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;+ for (const [wx, wy] of corners) {+ const [sx, sy] = worldToScreen(wx, wy, vp, vpX, vpY, vpW, vpH);+ minX = Math.min(minX, sx);+ minY = Math.min(minY, sy);+ maxX = Math.max(maxX, sx);+ maxY = Math.max(maxY, sy);+ }++ return {+ x: Math.round(minX),+ y: Math.round(minY),+ w: Math.round(maxX - minX),+ h: Math.round(maxY - minY),+ };}export function createMaskProcessor(wasm: ESEngineModule, world: World): MaskProcessorFn {@@ -65,7 +98,8 @@ export function createMaskProcessor(wasm: ESEngineModule, world: World): MaskProif (stencilMasks.length > 0) {processStencilMasks(wasm, world, cppRegistry, stencilMasks, stencilMaskSet, vp, vpX, vpY, vpW, vpH);}- } catch (_) {+ } catch (e) {+ console.error('Mask processing error:', e);wasm.renderer_clearAllClipRects();wasm.renderer_clearAllStencilMasks();}@@ -153,14 +187,26 @@ function processStencilMasks(}let nextRef = 1;+ let overflowed = false;++ function allocStencilRef(): number | null {+ if (nextRef > 255) {+ if (!overflowed) console.warn('Stencil mask overflow');+ overflowed = true;+ return null;+ }+ return nextRef++;+ }function applyStencilHierarchy(entity: Entity, refValue: number): void {+ if (overflowed) return;wasm.renderer_setEntityStencilMask(entity as number, refValue);const children = wasm.getChildEntities(cppRegistry, entity as number);for (const childId of children) {if (stencilMaskSet.has(childId)) {- const childRef = nextRef++;+ const childRef = allocStencilRef();+ if (childRef === null) return;applyStencilHierarchy(childId as Entity, childRef);} else {wasm.renderer_setEntityStencilTest(childId, refValue);@@ -170,10 +216,12 @@ function processStencilMasks(}function applyStencilDescendants(entity: Entity, refValue: number): void {+ if (overflowed) return;const children = wasm.getChildEntities(cppRegistry, entity as number);for (const childId of children) {if (stencilMaskSet.has(childId)) {- const childRef = nextRef++;+ const childRef = allocStencilRef();+ if (childRef === null) return;applyStencilHierarchy(childId as Entity, childRef);} else {wasm.renderer_setEntityStencilTest(childId, refValue);@@ -183,7 +231,9 @@ function processStencilMasks(}for (const entity of rootMasks) {- const refValue = nextRef++;+ if (overflowed) break;+ const refValue = allocStencilRef();+ if (refValue === null) return;applyStencilHierarchy(entity, refValue);}}diff --git a/sdk/src/ui/UIRect.ts b/sdk/src/ui/UIRect.tsindex 838afbf23..9dcb67570 100644--- a/sdk/src/ui/UIRect.ts+++ b/sdk/src/ui/UIRect.ts@@ -9,6 +9,9 @@ export interface UIRectData {size: Vec2;pivot: Vec2;_dirty: boolean;+ _computedWidth?: number;+ _computedHeight?: number;+ _layoutManaged?: boolean;}export const UIRect = defineComponent<UIRectData>('UIRect', {@@ -19,4 +22,7 @@ export const UIRect = defineComponent<UIRectData>('UIRect', {size: { x: 100, y: 100 },pivot: { x: 0.5, y: 0.5 },_dirty: true,+ _computedWidth: undefined,+ _computedHeight: undefined,+ _layoutManaged: undefined,});diff --git a/sdk/src/ui/UIRenderOrderPlugin.ts b/sdk/src/ui/UIRenderOrderPlugin.tsnew file mode 100644index 000000000..bb973cb95--- /dev/null+++ b/sdk/src/ui/UIRenderOrderPlugin.ts@@ -0,0 +1,49 @@+import type { App, Plugin } from '../app';+import { Children, Sprite } from '../component';+import type { ChildrenData, SpriteData } from '../component';+import { defineSystem, Schedule } from '../system';+import { ScreenSpace } from './ScreenSpace';+import { UIRect } from './UIRect';+import type { Entity } from '../types';+import type { World } from '../world';++function assignRenderOrder(world: World, entity: Entity, counter: number): number {+ if (world.has(entity, Sprite) && world.has(entity, UIRect)) {+ const sprite = world.get(entity, Sprite) as SpriteData;+ if (sprite.layer !== counter) {+ sprite.layer = counter;+ world.insert(entity, Sprite, sprite);+ }+ counter++;+ }++ if (!world.has(entity, Children)) return counter;+ const children = world.get(entity, Children) as ChildrenData;+ if (!children || !children.entities) return counter;+ for (const child of children.entities) {+ if (world.valid(child)) {+ counter = assignRenderOrder(world, child, counter);+ }+ }+ return counter;+}++export class UIRenderOrderPlugin implements Plugin {+ build(app: App): void {+ const world = app.world;++ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(+ [],+ () => {+ let counter = 0;+ const roots = world.getEntitiesWithComponents([ScreenSpace, UIRect]);+ for (const root of roots) {+ counter = assignRenderOrder(world, root, counter);+ }+ },+ { name: 'UIRenderOrderSystem' }+ ));+ }+}++export const uiRenderOrderPlugin = new UIRenderOrderPlugin();diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex 7643a9cf9..1eb87bdc5 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -12,12 +12,42 @@ export {// Shared Helpersexport {ensureSprite,+ computeFillAnchors,+ computeHandleAnchors,+ computeFillSize,applyDirectionalFill,applyColorTransition,wrapText,nextPowerOf2,+ ensureComponent,+ syncFillSpriteSize,+ layoutChildEntity,} from './uiHelpers';+// Snapshot Utilities+export {+ createSnapshotUtils,+ type Snapshot,+} from './uiSnapshot';++// UI Constants+export {+ TEXT_PADDING_RATIO,+ TEXT_CANVAS_SHRINK_FRAMES,+ TEXT_CANVAS_OVERSIZE_RATIO,+ TEXT_INPUT_LINE_HEIGHT_RATIO,+ CURSOR_BLINK_INTERVAL,+ SCROLL_VELOCITY_SMOOTHING,+ SCROLL_VELOCITY_NEW_WEIGHT,+ SCROLL_WHEEL_SENSITIVITY,+ SCROLL_MAX_DT,+ SCROLL_FPS_REFERENCE,+ SCROLL_VELOCITY_THRESHOLD,+ DROPDOWN_ITEM_HEIGHT,+ DROPDOWN_FONT_SIZE,+ DROPDOWN_HIGHLIGHT_COLOR,+} from './uiConstants';+// Text Componentexport {Text,@@ -61,12 +91,14 @@ export {// UI Math Utilitiesexport {- worldRectToScreen,intersectRects,invertMatrix4,screenToWorld,pointInWorldRect,pointInOBB,+ quaternionToAngle2D,+ worldToScreen,+ createInvVPCache,type ScreenRect,} from './uiMath';@@ -291,3 +323,9 @@ export {LayoutGroupPlugin,layoutGroupPlugin,} from './LayoutGroupPlugin';++// UIRenderOrder Plugin+export {+ UIRenderOrderPlugin,+ uiRenderOrderPlugin,+} from './UIRenderOrderPlugin';diff --git a/sdk/src/ui/uiConstants.ts b/sdk/src/ui/uiConstants.tsnew file mode 100644index 000000000..b4e257d5f--- /dev/null+++ b/sdk/src/ui/uiConstants.ts@@ -0,0 +1,17 @@+export const TEXT_PADDING_RATIO = 0.2;+export const TEXT_CANVAS_SHRINK_FRAMES = 60;+export const TEXT_CANVAS_OVERSIZE_RATIO = 4;++export const TEXT_INPUT_LINE_HEIGHT_RATIO = 1.2;+export const CURSOR_BLINK_INTERVAL = 0.5;++export const SCROLL_VELOCITY_SMOOTHING = 0.8;+export const SCROLL_VELOCITY_NEW_WEIGHT = 0.2;+export const SCROLL_WHEEL_SENSITIVITY = 0.1;+export const SCROLL_MAX_DT = 0.05;+export const SCROLL_FPS_REFERENCE = 60;+export const SCROLL_VELOCITY_THRESHOLD = 0.1;++export const DROPDOWN_ITEM_HEIGHT = 30;+export const DROPDOWN_FONT_SIZE = 16;+export const DROPDOWN_HIGHLIGHT_COLOR = { r: 0.3, g: 0.5, b: 0.8, a: 1 };diff --git a/sdk/src/ui/uiHelpers.ts b/sdk/src/ui/uiHelpers.tsindex 9b66d11ec..796fcb117 100644--- a/sdk/src/ui/uiHelpers.ts+++ b/sdk/src/ui/uiHelpers.ts@@ -1,10 +1,12 @@-import { Sprite } from '../component';+import { Sprite, Parent, LocalTransform } from '../component';+import type { ParentData, SpriteData, LocalTransformData, AnyComponentDef } from '../component';+import { computeUIRectLayout, type LayoutRect } from './uiLayout';import { INVALID_TEXTURE } from '../types';import type { Entity, Color } from '../types';import type { World } from '../world';import { UIRect } from './UIRect';import type { UIRectData } from './UIRect';-import type { FillDirection } from './uiTypes';+import { FillDirection } from './uiTypes';import type { ColorTransition } from './uiTypes';export function ensureSprite(world: World, entity: Entity): void {@@ -23,35 +25,78 @@ export function ensureSprite(world: World, entity: Entity): void {}}+interface FillAnchors {+ anchorMin: { x: number; y: number };+ anchorMax: { x: number; y: number };+ offsetMin: { x: number; y: number };+ offsetMax: { x: number; y: number };+}++export function computeFillAnchors(direction: number, value: number): FillAnchors {+ switch (direction) {+ case FillDirection.RightToLeft:+ return {+ anchorMin: { x: 1 - value, y: 0 }, anchorMax: { x: 1, y: 1 },+ offsetMin: { x: 0, y: 0 }, offsetMax: { x: 0, y: 0 },+ };+ case FillDirection.BottomToTop:+ return {+ anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: value },+ offsetMin: { x: 0, y: 0 }, offsetMax: { x: 0, y: 0 },+ };+ case FillDirection.TopToBottom:+ return {+ anchorMin: { x: 0, y: 1 - value }, anchorMax: { x: 1, y: 1 },+ offsetMin: { x: 0, y: 0 }, offsetMax: { x: 0, y: 0 },+ };+ default:+ return {+ anchorMin: { x: 0, y: 0 }, anchorMax: { x: value, y: 1 },+ offsetMin: { x: 0, y: 0 }, offsetMax: { x: 0, y: 0 },+ };+ }+}++export function computeHandleAnchors(+ direction: number, value: number,+): { anchorMin: { x: number; y: number }; anchorMax: { x: number; y: number } } {+ switch (direction) {+ case FillDirection.RightToLeft:+ return { anchorMin: { x: 1 - value, y: 0 }, anchorMax: { x: 1 - value, y: 1 } };+ case FillDirection.BottomToTop:+ return { anchorMin: { x: 0, y: value }, anchorMax: { x: 1, y: value } };+ case FillDirection.TopToBottom:+ return { anchorMin: { x: 0, y: 1 - value }, anchorMax: { x: 1, y: 1 - value } };+ default:+ return { anchorMin: { x: value, y: 0 }, anchorMax: { x: value, y: 1 } };+ }+}++export function computeFillSize(+ direction: number, value: number, parentW: number, parentH: number,+): { x: number; y: number } {+ switch (direction) {+ case FillDirection.BottomToTop:+ case FillDirection.TopToBottom:+ return { x: parentW, y: parentH * value };+ default:+ return { x: parentW * value, y: parentH };+ }+}+export function applyDirectionalFill(world: World,fillEntity: Entity,- direction: FillDirection,+ direction: number,value: number,): void {if (!world.has(fillEntity, UIRect)) return;const fillRect = world.get(fillEntity, UIRect) as UIRectData;-- switch (direction) {- case 0: // LeftToRight- fillRect.anchorMin = { x: 0, y: 0 };- fillRect.anchorMax = { x: value, y: 1 };- break;- case 1: // RightToLeft- fillRect.anchorMin = { x: 1 - value, y: 0 };- fillRect.anchorMax = { x: 1, y: 1 };- break;- case 2: // BottomToTop- fillRect.anchorMin = { x: 0, y: 0 };- fillRect.anchorMax = { x: 1, y: value };- break;- case 3: // TopToBottom- fillRect.anchorMin = { x: 0, y: 1 - value };- fillRect.anchorMax = { x: 1, y: 1 };- break;- }- fillRect.offsetMin = { x: 0, y: 0 };- fillRect.offsetMax = { x: 0, y: 0 };+ const anchors = computeFillAnchors(direction, value);+ fillRect.anchorMin = anchors.anchorMin;+ fillRect.anchorMax = anchors.anchorMax;+ fillRect.offsetMin = anchors.offsetMin;+ fillRect.offsetMax = anchors.offsetMax;world.insert(fillEntity, UIRect, fillRect);}@@ -124,3 +169,98 @@ export function nextPowerOf2(n: number): number {while (p < n) p *= 2;return p;}++export function getEntityDepth(world: World, entity: Entity): number {+ let depth = 0;+ let current = entity;+ while (world.has(current, Parent)) {+ const parentData = world.get(current, Parent) as ParentData;+ const parentEntity = parentData.entity;+ if (!world.valid(parentEntity)) break;+ depth++;+ current = parentEntity;+ }+ return depth;+}++export function getEffectiveWidth(rect: UIRectData): number {+ return rect._computedWidth ?? rect.size.x;+}++export function getEffectiveHeight(rect: UIRectData): number {+ return rect._computedHeight ?? rect.size.y;+}++export function syncFillSpriteSize(+ world: World,+ fillEntity: Entity,+ direction: number,+ normalizedValue: number,+ sliderW: number,+ sliderH: number,+): void {+ if (!world.has(fillEntity, Sprite)) return;+ const sprite = world.get(fillEntity, Sprite) as SpriteData;+ let w: number;+ let h: number;+ switch (direction) {+ case FillDirection.BottomToTop:+ case FillDirection.TopToBottom:+ w = sliderW;+ h = sliderH * normalizedValue;+ break;+ default:+ w = sliderW * normalizedValue;+ h = sliderH;+ break;+ }+ if (sprite.size.x !== w || sprite.size.y !== h) {+ sprite.size.x = w;+ sprite.size.y = h;+ world.insert(fillEntity, Sprite, sprite);+ }+}++export function ensureComponent(+ world: World, entity: Entity,+ component: AnyComponentDef, defaults?: Record<string, unknown>,+): void {+ if (!world.has(entity, component)) {+ world.insert(entity, component, defaults);+ }+}++export function layoutChildEntity(+ world: World, entity: Entity,+ parentRect: LayoutRect,+ parentOriginX: number, parentOriginY: number,+): void {+ if (!world.has(entity, UIRect)) return;+ const rect = world.get(entity, UIRect) as UIRectData;++ const result = computeUIRectLayout(+ rect.anchorMin, rect.anchorMax,+ rect.offsetMin, rect.offsetMax,+ rect.size, parentRect, rect.pivot,+ );+ const width = result.rect.right - result.rect.left;+ const height = result.rect.top - result.rect.bottom;+ rect._computedWidth = width;+ rect._computedHeight = height;++ if (world.has(entity, Sprite)) {+ const sprite = world.get(entity, Sprite) as SpriteData;+ if (sprite.size.x !== width || sprite.size.y !== height) {+ sprite.size.x = width;+ sprite.size.y = height;+ world.insert(entity, Sprite, sprite);+ }+ }++ if (!rect._layoutManaged && world.has(entity, LocalTransform)) {+ const transform = world.get(entity, LocalTransform) as LocalTransformData;+ transform.position.x = result.originX - parentOriginX;+ transform.position.y = result.originY - parentOriginY;+ world.insert(entity, LocalTransform, transform);+ }+}diff --git a/sdk/src/ui/uiLayout.ts b/sdk/src/ui/uiLayout.tsindex cc7c2ad0a..2c1af6f76 100644--- a/sdk/src/ui/uiLayout.ts+++ b/sdk/src/ui/uiLayout.ts@@ -6,8 +6,8 @@ export interface LayoutRect {}export interface LayoutResult {- centerX: number;- centerY: number;+ originX: number;+ originY: number;width: number;height: number;rect: LayoutRect;@@ -20,6 +20,7 @@ export function computeUIRectLayout(offsetMax: { x: number; y: number },size: { x: number; y: number },parentRect: LayoutRect,+ pivot: { x: number; y: number } = { x: 0.5, y: 0.5 },): LayoutResult {const parentW = parentRect.right - parentRect.left;const parentH = parentRect.top - parentRect.bottom;@@ -35,33 +36,29 @@ export function computeUIRectLayout(let myTop: number;if (anchorMin.x === anchorMax.x) {- const cx = aLeft + offsetMin.x;- const hw = size.x * 0.5;- myLeft = cx - hw;- myRight = cx + hw;+ myLeft = aLeft + offsetMin.x - size.x * pivot.x;+ myRight = myLeft + size.x;} else {myLeft = aLeft + offsetMin.x;myRight = aRight + offsetMax.x;}if (anchorMin.y === anchorMax.y) {- const cy = aBottom + offsetMin.y;- const hh = size.y * 0.5;- myBottom = cy - hh;- myTop = cy + hh;+ myBottom = aBottom + offsetMin.y - size.y * pivot.y;+ myTop = myBottom + size.y;} else {myBottom = aBottom + offsetMin.y;myTop = aTop + offsetMax.y;}- const width = myRight - myLeft;- const height = myTop - myBottom;- const centerX = (myLeft + myRight) * 0.5;- const centerY = (myBottom + myTop) * 0.5;+ const width = Math.max(0, myRight - myLeft);+ const height = Math.max(0, myTop - myBottom);+ const originX = myLeft + pivot.x * width;+ const originY = myBottom + pivot.y * height;return {- centerX,- centerY,+ originX,+ originY,width,height,rect: { left: myLeft, bottom: myBottom, right: myRight, top: myTop },diff --git a/sdk/src/ui/uiMath.ts b/sdk/src/ui/uiMath.tsindex f025e7b2a..cbbe176fe 100644--- a/sdk/src/ui/uiMath.ts+++ b/sdk/src/ui/uiMath.ts@@ -13,46 +13,6 @@ export function intersectRects(a: ScreenRect, b: ScreenRect): ScreenRect {return { x, y, w: Math.max(0, r - x), h: Math.max(0, t - y) };}-export function worldRectToScreen(- worldX: number, worldY: number,- worldW: number, worldH: number,- pivotX: number, pivotY: number,- vp: Float32Array,- vpX: number, vpY: number, vpW: number, vpH: number-): ScreenRect {- const left = worldX - worldW * pivotX;- const right = worldX + worldW * (1 - pivotX);- const bottom = worldY - worldH * pivotY;- const top = worldY + worldH * (1 - pivotY);-- function toScreen(wx: number, wy: number): [number, number] {- const clipX = vp[0] * wx + vp[4] * wy + vp[12];- const clipY = vp[1] * wx + vp[5] * wy + vp[13];- const clipW = vp[3] * wx + vp[7] * wy + vp[15];- const ndcX = clipX / clipW;- const ndcY = clipY / clipW;- return [- vpX + (ndcX * 0.5 + 0.5) * vpW,- vpY + (ndcY * 0.5 + 0.5) * vpH,- ];- }-- const [px0, py0] = toScreen(left, bottom);- const [px1, py1] = toScreen(right, top);-- const minX = Math.min(px0, px1);- const maxX = Math.max(px0, px1);- const minY = Math.min(py0, py1);- const maxY = Math.max(py0, py1);-- return {- x: Math.round(minX),- y: Math.round(minY),- w: Math.round(maxX - minX),- h: Math.round(maxY - minY),- };-}-export function invertMatrix4(m: Float32Array, result?: Float32Array): Float32Array {const out = result ?? new Float32Array(16);@@ -126,6 +86,50 @@ export function pointInWorldRect(return px >= left && px <= right && py >= bottom && py <= top;}+export function quaternionToAngle2D(rz: number, rw: number): number {+ return 2 * Math.atan2(rz, rw);+}++export function worldToScreen(+ wx: number, wy: number,+ vp: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number+): [number, number] {+ const clipX = vp[0] * wx + vp[4] * wy + vp[12];+ const clipY = vp[1] * wx + vp[5] * wy + vp[13];+ const clipW = vp[3] * wx + vp[7] * wy + vp[15];+ const ndcX = clipX / clipW;+ const ndcY = clipY / clipW;+ return [+ vpX + (ndcX * 0.5 + 0.5) * vpW,+ vpY + (ndcY * 0.5 + 0.5) * vpH,+ ];+}++export function createInvVPCache() {+ const invVP = new Float32Array(16);+ const cachedVP = new Float32Array(16);+ let dirty = true;++ return {+ update(vp: Float32Array): void {+ for (let i = 0; i < 16; i++) {+ if (cachedVP[i] !== vp[i]) {+ cachedVP.set(vp);+ dirty = true;+ break;+ }+ }+ },+ getInverse(vp: Float32Array): Float32Array {+ if (dirty) {+ invertMatrix4(vp, invVP);+ dirty = false;+ }+ return invVP;+ },+ };+}+export function pointInOBB(px: number, py: number,worldX: number, worldY: number,@@ -133,7 +137,7 @@ export function pointInOBB(pivotX: number, pivotY: number,rotationZ: number, rotationW: number,): boolean {- const angle = 2 * Math.atan2(rotationZ, rotationW);+ const angle = quaternionToAngle2D(rotationZ, rotationW);const sin = Math.sin(-angle);const cos = Math.cos(-angle);diff --git a/sdk/src/ui/uiSnapshot.ts b/sdk/src/ui/uiSnapshot.tsnew file mode 100644index 000000000..e560a2225--- /dev/null+++ b/sdk/src/ui/uiSnapshot.ts@@ -0,0 +1,31 @@+type SnapshotValue = number | string | boolean;++export type Snapshot = Record<string, SnapshotValue>;++export function createSnapshotUtils<TSource>(+ spec: Record<string, (source: TSource) => SnapshotValue>+) {+ const keys = Object.keys(spec);+ const extractors = keys.map(k => spec[k]);++ return {+ take(source: TSource): Snapshot {+ const snap: Snapshot = {};+ for (let i = 0; i < keys.length; i++) {+ snap[keys[i]] = extractors[i](source);+ }+ return snap;+ },+ changed(snapshot: Snapshot, source: TSource): boolean {+ for (let i = 0; i < keys.length; i++) {+ if (snapshot[keys[i]] !== extractors[i](source)) return true;+ }+ return false;+ },+ update(snapshot: Snapshot, source: TSource): void {+ for (let i = 0; i < keys.length; i++) {+ snapshot[keys[i]] = extractors[i](source);+ }+ },+ };+}diff --git a/sdk/src/uiPlugins.ts b/sdk/src/uiPlugins.tsindex 3b41f1694..f280754d6 100644--- a/sdk/src/uiPlugins.ts+++ b/sdk/src/uiPlugins.ts@@ -14,6 +14,7 @@ import { safeAreaPlugin } from './ui/SafeAreaPlugin';import { listViewPlugin } from './ui/ListViewPlugin';import { dropdownPlugin } from './ui/DropdownPlugin';import { layoutGroupPlugin } from './ui/LayoutGroupPlugin';+import { uiRenderOrderPlugin } from './ui/UIRenderOrderPlugin';import type { Plugin } from './app';export const uiPlugins: Plugin[] = [@@ -23,4 +24,5 @@ export const uiPlugins: Plugin[] = [togglePlugin, textInputPlugin,focusPlugin, safeAreaPlugin, listViewPlugin, dropdownPlugin,layoutGroupPlugin,+ uiRenderOrderPlugin,];