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: overhaul UI framework architecture and add missing features
esengine416e8144736f
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.tsindex 1e0376dd1..f44eafa03 100644--- a/editor/src/schemas/ComponentSchemas.ts+++ b/editor/src/schemas/ComponentSchemas.ts@@ -230,6 +230,7 @@ export const InteractableSchema: ComponentSchema = {properties: [{ name: 'enabled', type: 'boolean' },{ name: 'blockRaycast', type: 'boolean' },+ { name: 'raycastTarget', type: 'boolean' },],};@@ -391,6 +392,7 @@ export const ImageSchema: ComponentSchema = {},{ name: 'fillAmount', type: 'number', min: 0, max: 1, step: 0.01 },{ name: 'preserveAspect', type: 'boolean' },+ { name: 'tileSize', type: 'vec2' },{ name: 'layer', type: 'number', min: -1000, max: 1000 },],};@@ -512,6 +514,32 @@ export const DropdownSchema: ComponentSchema = {],};+export const LayoutGroupSchema: ComponentSchema = {+ name: 'LayoutGroup',+ category: 'ui',+ properties: [+ {+ name: 'direction',+ type: 'enum',+ options: [+ { label: 'Horizontal', value: 0 },+ { label: 'Vertical', value: 1 },+ ],+ },+ { name: 'spacing', type: 'number', step: 1 },+ {+ name: 'childAlignment',+ type: 'enum',+ options: [+ { label: 'Start', value: 0 },+ { label: 'Center', value: 1 },+ { label: 'End', value: 2 },+ ],+ },+ { name: 'reverseOrder', type: 'boolean' },+ ],+};+// =============================================================================// Registry// =============================================================================@@ -640,6 +668,7 @@ export function registerBuiltinSchemas(options?: BuiltinSchemaOptions): void {registerComponentSchema(SafeAreaSchema);registerComponentSchema(ListViewSchema);registerComponentSchema(DropdownSchema);+ registerComponentSchema(LayoutGroupSchema);registerComponentSchema(RigidBodySchema);registerComponentSchema(BoxColliderSchema);registerComponentSchema(CircleColliderSchema);diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex 64e274832..710bd5194 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -537,6 +537,7 @@ export function createWebApp(module: ESEngineModule, options?: WebAppOptions): AvpX: 0, vpY: 0, vpW: 0, vpH: 0,screenW: 0, screenH: 0,worldLeft: 0, worldBottom: 0, worldRight: 0, worldTop: 0,+ worldMouseX: 0, worldMouseY: 0,valid: false,});diff --git a/sdk/src/ui/Button.ts b/sdk/src/ui/Button.tsindex 129a5d1b2..12640fc73 100644--- a/sdk/src/ui/Button.ts+++ b/sdk/src/ui/Button.ts@@ -1,28 +1,24 @@import { defineComponent } from '../component';-import type { Color } from '../types';+import type { ColorTransition } from './uiTypes';-export enum ButtonState {- Normal = 0,- Hovered = 1,- Pressed = 2,- Disabled = 3,-}+export type { ColorTransition } from './uiTypes';+export type ButtonTransition = ColorTransition;-export interface ButtonTransition {- normalColor: Color;- hoveredColor: Color;- pressedColor: Color;- disabledColor: Color;-}+export const ButtonState = {+ Normal: 0,+ Hovered: 1,+ Pressed: 2,+ Disabled: 3,+} as const;++export type ButtonState = (typeof ButtonState)[keyof typeof ButtonState];export interface ButtonData {state: ButtonState;- transition: ButtonTransition | null;- enabled: boolean;+ transition: ColorTransition | null;}export const Button = defineComponent<ButtonData>('Button', {state: ButtonState.Normal,transition: null,- enabled: true,});diff --git a/sdk/src/ui/Dropdown.ts b/sdk/src/ui/Dropdown.tsindex 50bf6fd03..d782b90a6 100644--- a/sdk/src/ui/Dropdown.ts+++ b/sdk/src/ui/Dropdown.ts@@ -1,17 +1,18 @@import { defineComponent } from '../component';+import type { Entity } from '../types';export interface DropdownData {options: string[];selectedIndex: number;isOpen: boolean;- listEntity: number;- labelEntity: number;+ listEntity: Entity;+ labelEntity: Entity;}export const Dropdown = defineComponent<DropdownData>('Dropdown', {options: [],selectedIndex: -1,isOpen: false,- listEntity: 0,- labelEntity: 0,+ listEntity: 0 as Entity,+ labelEntity: 0 as Entity,});diff --git a/sdk/src/ui/DropdownPlugin.ts b/sdk/src/ui/DropdownPlugin.tsindex 71af8edd7..3cb835ab6 100644--- a/sdk/src/ui/DropdownPlugin.ts+++ b/sdk/src/ui/DropdownPlugin.ts@@ -1,6 +1,6 @@import type { App, Plugin } from '../app';-import { registerComponent, LocalTransform } from '../component';-import type { LocalTransformData } from '../component';+import { registerComponent, LocalTransform, Name, Sprite } from '../component';+import type { LocalTransformData, SpriteData } from '../component';import { defineSystem, Schedule } from '../system';import { Res } from '../resource';import type { Entity } from '../types';@@ -10,9 +10,20 @@ import { Interactable } from './Interactable';import { UIInteraction } from './UIInteraction';import type { UIInteractionData } from './UIInteraction';import { UIEvents, UIEventQueue } from './UIEvents';+import { Text } from './text';+import type { TextData } from './text';+import { UIRect } from './UIRect';+import type { UIRectData } from './UIRect';import { Input } from '../input';import type { InputState } from '../input';+interface DropdownState {+ optionEntities: Entity[];+ highlightIndex: number;+}++const dropdownStates = new Map<Entity, DropdownState>();+export class DropdownPlugin implements Plugin {build(app: App): void {registerComponent('Dropdown', Dropdown);@@ -33,39 +44,189 @@ export class DropdownPlugin implements Plugin {? world.get(entity, UIInteraction) as UIInteractionData: null;+ let state = dropdownStates.get(entity);+ if (!state) {+ state = { optionEntities: [], highlightIndex: -1 };+ dropdownStates.set(entity, state);+ }+if (interaction?.justPressed) {- dropdown.isOpen = !dropdown.isOpen;- setListScale(dropdown.listEntity, dropdown.isOpen);- events.emit(entity, 'change', entity);+ if (dropdown.isOpen) {+ closeDropdown(entity, dropdown, state);+ } else {+ openDropdown(entity, dropdown, state);+ }}- if (dropdown.isOpen && input.isMouseButtonPressed(0)) {- if (!interaction?.hovered) {- const listHovered = dropdown.listEntity !== 0- && world.valid(dropdown.listEntity as Entity)- && world.has(dropdown.listEntity as Entity, UIInteraction)- && (world.get(dropdown.listEntity as Entity, UIInteraction) as UIInteractionData).hovered;+ if (dropdown.isOpen) {+ for (let i = 0; i < state.optionEntities.length; i++) {+ const optEntity = state.optionEntities[i];+ if (!world.valid(optEntity) || !world.has(optEntity, UIInteraction)) continue;+ const optInteraction = world.get(optEntity, UIInteraction) as UIInteractionData;+ if (optInteraction.justPressed) {+ selectOption(entity, dropdown, state, i, events);+ break;+ }+ }- if (!listHovered) {- dropdown.isOpen = false;- setListScale(dropdown.listEntity, false);+ if (input.isKeyPressed('ArrowDown')) {+ state.highlightIndex = Math.min(+ state.highlightIndex + 1,+ dropdown.options.length - 1+ );+ updateHighlight(state);+ } else if (input.isKeyPressed('ArrowUp')) {+ state.highlightIndex = Math.max(state.highlightIndex - 1, 0);+ updateHighlight(state);+ } else if (input.isKeyPressed('Enter') && state.highlightIndex >= 0) {+ selectOption(entity, dropdown, state, state.highlightIndex, events);+ } else if (input.isKeyPressed('Escape')) {+ closeDropdown(entity, dropdown, state);+ }++ if (input.isMouseButtonPressed(0)) {+ if (!interaction?.hovered && !isAnyOptionHovered(state)) {+ closeDropdown(entity, dropdown, state);}}}- }- function setListScale(listEntityId: number, visible: boolean): void {- if (listEntityId === 0) return;- const listEntity = listEntityId as Entity;- if (!world.valid(listEntity) || !world.has(listEntity, LocalTransform)) return;- const lt = world.get(listEntity, LocalTransform) as LocalTransformData;- const s = visible ? 1 : 0;- lt.scale = { x: s, y: s, z: s };- world.insert(listEntity, LocalTransform, lt);+ syncLabel(dropdown);}},{ name: 'DropdownSystem' }));++ function openDropdown(entity: Entity, dropdown: DropdownData, state: DropdownState): void {+ dropdown.isOpen = true;+ state.highlightIndex = dropdown.selectedIndex;++ const listEntity = dropdown.listEntity;+ if (listEntity === 0 || !world.valid(listEntity)) return;++ setListVisible(listEntity, true);+ 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();+ world.insert(optEntity, Name, { value: `Option_${i}` });+ world.insert(optEntity, UIRect, {+ anchorMin: { x: 0, y: 1 },+ anchorMax: { x: 1, y: 1 },+ offsetMin: { x: 0, y: 0 },+ offsetMax: { x: 0, y: 0 },+ size: { x: listWidth, y: itemHeight },+ pivot: { x: 0.5, y: 1 },+ });+ world.insert(optEntity, LocalTransform, {+ position: { x: 0, y: -(i * itemHeight), 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,+ fontFamily: 'Arial',+ color: { r: 1, g: 1, b: 1, a: 1 },+ align: 0,+ verticalAlign: 1,+ wordWrap: false,+ overflow: 1,+ lineHeight: 1.2,+ });+ 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;+ world.insert(listEntity, UIRect, listRect);+ }++ updateHighlight(state);+ }++ function closeDropdown(_entity: Entity, dropdown: DropdownData, state: DropdownState): void {+ dropdown.isOpen = false;+ destroyOptions(state);+ setListVisible(dropdown.listEntity, false);+ }++ function selectOption(+ entity: Entity,+ dropdown: DropdownData,+ state: DropdownState,+ index: number,+ events: UIEventQueue,+ ): void {+ dropdown.selectedIndex = index;+ closeDropdown(entity, dropdown, state);+ events.emit(entity, 'change');+ }++ function syncLabel(dropdown: DropdownData): void {+ const labelEntity = dropdown.labelEntity;+ if (labelEntity === 0 || !world.valid(labelEntity)) return;+ if (!world.has(labelEntity, Text)) return;++ const text = world.get(labelEntity, Text) as TextData;+ const selectedText = dropdown.selectedIndex >= 0 && dropdown.selectedIndex < dropdown.options.length+ ? dropdown.options[dropdown.selectedIndex]+ : '';++ if (text.content !== selectedText) {+ text.content = selectedText;+ world.insert(labelEntity, Text, text);+ }+ }++ function destroyOptions(state: DropdownState): void {+ for (const optEntity of state.optionEntities) {+ if (world.valid(optEntity)) {+ world.despawn(optEntity);+ }+ }+ state.optionEntities = [];+ }++ 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);+ }++ function updateHighlight(state: DropdownState): void {+ for (let i = 0; i < state.optionEntities.length; i++) {+ const optEntity = state.optionEntities[i];+ 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 };+ } else {+ sprite.color = { r: 1, g: 1, b: 1, a: 1 };+ }+ world.insert(optEntity, Sprite, sprite);+ }+ }++ function isAnyOptionHovered(state: DropdownState): boolean {+ for (const optEntity of state.optionEntities) {+ if (!world.valid(optEntity) || !world.has(optEntity, UIInteraction)) continue;+ const optInteraction = world.get(optEntity, UIInteraction) as UIInteractionData;+ if (optInteraction.hovered) return true;+ }+ return false;+ }}}diff --git a/sdk/src/ui/FocusPlugin.ts b/sdk/src/ui/FocusPlugin.tsindex 8355b6d32..c8521052c 100644--- a/sdk/src/ui/FocusPlugin.ts+++ b/sdk/src/ui/FocusPlugin.ts@@ -70,13 +70,13 @@ export class FocusPlugin implements Plugin {if (prev !== null && world.valid(prev) && world.has(prev, Focusable)) {const prevF = world.get(prev, Focusable) as FocusableData;prevF.isFocused = false;- events.emit(prev, 'hover_exit', prev);+ events.emit(prev, 'blur', prev);}focusManager.focus(entity);const f = world.get(entity, Focusable) as FocusableData;f.isFocused = true;- events.emit(entity, 'hover_enter', entity);+ events.emit(entity, 'focus', entity);}},{ name: 'FocusSystem' }diff --git a/sdk/src/ui/Image.ts b/sdk/src/ui/Image.tsindex 37c4e336a..a3101ddfb 100644--- a/sdk/src/ui/Image.ts+++ b/sdk/src/ui/Image.ts@@ -35,6 +35,7 @@ export interface ImageData {fillOrigin: number;fillAmount: number;preserveAspect: boolean;+ tileSize: { x: number; y: number };layer: number;material: number;enabled: boolean;@@ -48,6 +49,7 @@ export const Image = defineComponent<ImageData>('Image', {fillOrigin: FillOrigin.Left,fillAmount: 1,preserveAspect: false,+ tileSize: { x: 32, y: 32 },layer: 0,material: 0,enabled: true,diff --git a/sdk/src/ui/ImagePlugin.ts b/sdk/src/ui/ImagePlugin.tsindex b732f75ba..31c7238de 100644--- a/sdk/src/ui/ImagePlugin.ts+++ b/sdk/src/ui/ImagePlugin.ts@@ -2,11 +2,11 @@ import type { App, Plugin } from '../app';import { registerComponent, Sprite } from '../component';import type { SpriteData } from '../component';import { defineSystem, Schedule } from '../system';-import { INVALID_TEXTURE } from '../types';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';export class ImagePlugin implements Plugin {build(app: App): void {@@ -22,19 +22,7 @@ export class ImagePlugin implements Plugin {for (const entity of entities) {const image = world.get(entity, Image) as ImageData;- if (!world.has(entity, Sprite)) {- world.insert(entity, Sprite, {- texture: INVALID_TEXTURE,- color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: 0, y: 0 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- material: 0,- });- }+ ensureSprite(world, entity);const sprite = world.get(entity, Sprite) as SpriteData;@@ -79,13 +67,18 @@ export class ImagePlugin implements Plugin {sprite.size.y *= amount;}}+ } else if (image.imageType === ImageType.Tiled) {+ if (image.tileSize.x > 0 && image.tileSize.y > 0) {+ sprite.uvScale.x = sprite.size.x / image.tileSize.x;+ sprite.uvScale.y = sprite.size.y / image.tileSize.y;+ }}world.insert(entity, Sprite, sprite);}},{ name: 'ImageSystem' }- ));+ ), { runAfter: ['UILayoutSystem'] });}}diff --git a/sdk/src/ui/Interactable.ts b/sdk/src/ui/Interactable.tsindex 16be5b0f4..99e283453 100644--- a/sdk/src/ui/Interactable.ts+++ b/sdk/src/ui/Interactable.ts@@ -3,9 +3,11 @@ import { defineComponent } from '../component';export interface InteractableData {enabled: boolean;blockRaycast: boolean;+ raycastTarget: boolean;}export const Interactable = defineComponent<InteractableData>('Interactable', {enabled: true,blockRaycast: true,+ raycastTarget: true,});diff --git a/sdk/src/ui/LayoutGroup.ts b/sdk/src/ui/LayoutGroup.tsnew file mode 100644index 000000000..f5fca6862--- /dev/null+++ b/sdk/src/ui/LayoutGroup.ts@@ -0,0 +1,32 @@+import { defineComponent } from '../component';++export const LayoutDirection = {+ Horizontal: 0,+ Vertical: 1,+} as const;++export type LayoutDirection = (typeof LayoutDirection)[keyof typeof LayoutDirection];++export const ChildAlignment = {+ Start: 0,+ Center: 1,+ End: 2,+} as const;++export type ChildAlignment = (typeof ChildAlignment)[keyof typeof ChildAlignment];++export interface LayoutGroupData {+ direction: number;+ spacing: number;+ padding: { left: number; top: number; right: number; bottom: number };+ childAlignment: number;+ reverseOrder: boolean;+}++export const LayoutGroup = defineComponent<LayoutGroupData>('LayoutGroup', {+ direction: LayoutDirection.Horizontal,+ spacing: 0,+ padding: { left: 0, top: 0, right: 0, bottom: 0 },+ childAlignment: ChildAlignment.Start,+ reverseOrder: false,+});diff --git a/sdk/src/ui/LayoutGroupPlugin.ts b/sdk/src/ui/LayoutGroupPlugin.tsnew file mode 100644index 000000000..83dd26db5--- /dev/null+++ b/sdk/src/ui/LayoutGroupPlugin.ts@@ -0,0 +1,102 @@+++import type { App, Plugin } from '../app';+import { registerComponent, Children, LocalTransform } from '../component';+import type { ChildrenData, LocalTransformData } from '../component';+import { defineSystem, Schedule } from '../system';+import { LayoutGroup, LayoutDirection, ChildAlignment } from './LayoutGroup';+import type { LayoutGroupData } from './LayoutGroup';+import { UIRect } from './UIRect';+import type { UIRectData } from './UIRect';+import type { Entity } from '../types';++export class LayoutGroupPlugin implements Plugin {+ build(app: App): void {+ registerComponent('LayoutGroup', LayoutGroup);++ const world = app.world;++ app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [],+ () => {+ const entities = world.getEntitiesWithComponents([LayoutGroup, UIRect, Children]);++ for (const entity of entities) {+ const group = world.get(entity, LayoutGroup) as LayoutGroupData;+ const parentRect = world.get(entity, UIRect) as UIRectData;+ const children = world.get(entity, Children) as ChildrenData;+ if (!children.entities || children.entities.length === 0) continue;++ const validChildren: { entity: Entity; rect: UIRectData }[] = [];+ for (const child of children.entities) {+ if (world.valid(child) && world.has(child, UIRect) && world.has(child, LocalTransform)) {+ validChildren.push({+ entity: child,+ rect: world.get(child, UIRect) as UIRectData,+ });+ }+ }+ if (validChildren.length === 0) continue;++ if (group.reverseOrder) {+ validChildren.reverse();+ }++ const pw = parentRect.size.x;+ const ph = parentRect.size.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;++ let localX: number;+ let localY: number;++ if (isHorizontal) {+ localX = -pw * 0.5 + pad.left + cursor + cw * 0.5;+ if (group.childAlignment === ChildAlignment.Start) {+ localY = ph * 0.5 - pad.top - ch * 0.5;+ } else if (group.childAlignment === ChildAlignment.End) {+ localY = -ph * 0.5 + pad.bottom + ch * 0.5;+ } else {+ localY = (pad.bottom - pad.top) * 0.5;+ }+ cursor += cw + group.spacing;+ } else {+ if (group.childAlignment === ChildAlignment.Start) {+ localX = -pw * 0.5 + pad.left + cw * 0.5;+ } else if (group.childAlignment === ChildAlignment.End) {+ localX = pw * 0.5 - pad.right - cw * 0.5;+ } else {+ localX = (pad.left - pad.right) * 0.5;+ }+ localY = ph * 0.5 - pad.top - cursor - ch * 0.5;+ cursor += ch + 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;++ const transform = world.get(child.entity, LocalTransform) as LocalTransformData;+ transform.position.x = localX;+ transform.position.y = localY;+ world.insert(child.entity, LocalTransform, transform);+ }+ }+ },+ { name: 'LayoutGroupSystem' }+ ), { runAfter: ['UILayoutSystem'] });+ }+}++export const layoutGroupPlugin = new LayoutGroupPlugin();diff --git a/sdk/src/ui/ProgressBar.ts b/sdk/src/ui/ProgressBar.tsindex 9abdb450f..8906e10b8 100644--- a/sdk/src/ui/ProgressBar.ts+++ b/sdk/src/ui/ProgressBar.ts@@ -1,21 +1,19 @@import { defineComponent } from '../component';import type { Entity } from '../types';+import { FillDirection } from './uiTypes';-export enum ProgressBarDirection {- LeftToRight = 0,- RightToLeft = 1,- BottomToTop = 2,- TopToBottom = 3,-}+export { FillDirection } from './uiTypes';+export const ProgressBarDirection = FillDirection;+export type ProgressBarDirection = FillDirection;export interface ProgressBarData {value: number;fillEntity: Entity;- direction: number;+ direction: FillDirection;}export const ProgressBar = defineComponent<ProgressBarData>('ProgressBar', {value: 0,fillEntity: 0 as Entity,- direction: ProgressBarDirection.LeftToRight,+ direction: FillDirection.LeftToRight,});diff --git a/sdk/src/ui/ProgressBarPlugin.ts b/sdk/src/ui/ProgressBarPlugin.tsindex f4a075f75..4b353a493 100644--- a/sdk/src/ui/ProgressBarPlugin.ts+++ b/sdk/src/ui/ProgressBarPlugin.ts@@ -1,11 +1,10 @@import type { App, Plugin } from '../app';import { registerComponent } from '../component';import { defineSystem, Schedule } from '../system';-import type { Entity } from '../types';import { UIRect } from './UIRect';-import type { UIRectData } from './UIRect';-import { ProgressBar, ProgressBarDirection } from './ProgressBar';+import { ProgressBar } from './ProgressBar';import type { ProgressBarData } from './ProgressBar';+import { applyDirectionalFill } from './uiHelpers';export class ProgressBarPlugin implements Plugin {build(app: App): void {@@ -19,36 +18,10 @@ export class ProgressBarPlugin implements Plugin {const entities = world.getEntitiesWithComponents([ProgressBar, UIRect]);for (const entity of entities) {const bar = world.get(entity, ProgressBar) as ProgressBarData;- if (!bar.fillEntity || !world.valid(bar.fillEntity as Entity)) continue;+ if (!bar.fillEntity || !world.valid(bar.fillEntity)) continue;- const fillEntity = bar.fillEntity as Entity;- if (!world.has(fillEntity, UIRect)) continue;-- const fillRect = world.get(fillEntity, UIRect) as UIRectData;const value = Math.max(0, Math.min(1, bar.value));-- switch (bar.direction) {- case ProgressBarDirection.LeftToRight:- fillRect.anchorMin = { x: 0, y: 0 };- fillRect.anchorMax = { x: value, y: 1 };- break;- case ProgressBarDirection.RightToLeft:- fillRect.anchorMin = { x: 1 - value, y: 0 };- fillRect.anchorMax = { x: 1, y: 1 };- break;- case ProgressBarDirection.BottomToTop:- fillRect.anchorMin = { x: 0, y: 0 };- fillRect.anchorMax = { x: 1, y: value };- break;- case ProgressBarDirection.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 };- world.insert(fillEntity, UIRect, fillRect);+ applyDirectionalFill(world, bar.fillEntity, bar.direction, value);}},{ name: 'ProgressBarSystem' }diff --git a/sdk/src/ui/SafeAreaPlugin.ts b/sdk/src/ui/SafeAreaPlugin.tsindex c39ffb231..e28372e15 100644--- a/sdk/src/ui/SafeAreaPlugin.ts+++ b/sdk/src/ui/SafeAreaPlugin.ts@@ -69,7 +69,7 @@ export class SafeAreaPlugin implements Plugin {}},{ name: 'SafeAreaSystem' }- ));+ ), { runBefore: ['UILayoutSystem'] });}}diff --git a/sdk/src/ui/ScrollView.ts b/sdk/src/ui/ScrollView.tsindex 9f78eb432..98860b7f2 100644--- a/sdk/src/ui/ScrollView.ts+++ b/sdk/src/ui/ScrollView.ts@@ -1,7 +1,8 @@import { defineComponent } from '../component';+import type { Entity } from '../types';export interface ScrollViewData {- contentEntity: number;+ contentEntity: Entity;horizontalEnabled: boolean;verticalEnabled: boolean;contentWidth: number;@@ -13,7 +14,7 @@ export interface ScrollViewData {}export const ScrollView = defineComponent<ScrollViewData>('ScrollView', {- contentEntity: 0,+ contentEntity: 0 as Entity,horizontalEnabled: false,verticalEnabled: true,contentWidth: 0,diff --git a/sdk/src/ui/ScrollViewPlugin.ts b/sdk/src/ui/ScrollViewPlugin.tsindex 148a9dd70..f03a17e58 100644--- a/sdk/src/ui/ScrollViewPlugin.ts+++ b/sdk/src/ui/ScrollViewPlugin.ts@@ -16,7 +16,6 @@ import { UIInteraction } from './UIInteraction';import type { UIInteractionData } from './UIInteraction';import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';-import { invertMatrix4, screenToWorld } from './uiMath';interface ScrollState {isDragging: boolean;@@ -32,8 +31,6 @@ export class ScrollViewPlugin implements Plugin {const world = app.world;const states = new Map<Entity, ScrollState>();- const invVP = new Float32Array(16);- const cachedDpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;let lastTime = 0;app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(@@ -45,13 +42,7 @@ export class ScrollViewPlugin implements Plugin {if (!camera.valid) return;- const mouseGLX = input.mouseX * cachedDpr;- const mouseGLY = camera.screenH - input.mouseY * cachedDpr;- invertMatrix4(camera.viewProjection, invVP);- const worldMouse = screenToWorld(- mouseGLX, mouseGLY, invVP,- camera.vpX, camera.vpY, camera.vpW, camera.vpH,- );+ const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };const entities = world.getEntitiesWithComponents([ScrollView, UIRect]);for (const entity of entities) {@@ -139,13 +130,12 @@ export class ScrollViewPlugin implements Plugin {sv.scrollX = Math.max(0, Math.min(sv.scrollX, maxScrollX));sv.scrollY = Math.max(0, Math.min(sv.scrollY, maxScrollY));- if (sv.contentEntity !== 0 && world.valid(sv.contentEntity as Entity)) {- const contentEntity = sv.contentEntity as Entity;- if (world.has(contentEntity, LocalTransform)) {- const lt = world.get(contentEntity, LocalTransform) as LocalTransformData;+ if (sv.contentEntity !== 0 && world.valid(sv.contentEntity)) {+ if (world.has(sv.contentEntity, LocalTransform)) {+ const lt = world.get(sv.contentEntity, LocalTransform) as LocalTransformData;lt.position.x = -sv.scrollX;lt.position.y = sv.scrollY;- world.insert(contentEntity, LocalTransform, lt);+ world.insert(sv.contentEntity, LocalTransform, lt);}}}diff --git a/sdk/src/ui/Slider.ts b/sdk/src/ui/Slider.tsindex f668aadb4..39de49e02 100644--- a/sdk/src/ui/Slider.ts+++ b/sdk/src/ui/Slider.ts@@ -1,30 +1,27 @@import { defineComponent } from '../component';+import type { Entity } from '../types';+import { FillDirection } from './uiTypes';-export enum SliderDirection {- LeftToRight,- RightToLeft,- BottomToTop,- TopToBottom,-}+export { FillDirection } from './uiTypes';+export const SliderDirection = FillDirection;+export type SliderDirection = FillDirection;export interface SliderData {value: number;minValue: number;maxValue: number;- direction: SliderDirection;- fillEntity: number;- handleEntity: number;+ direction: FillDirection;+ fillEntity: Entity;+ handleEntity: Entity;wholeNumbers: boolean;- enabled: boolean;}export const Slider = defineComponent<SliderData>('Slider', {value: 0,minValue: 0,maxValue: 1,- direction: SliderDirection.LeftToRight,- fillEntity: 0,- handleEntity: 0,+ direction: FillDirection.LeftToRight,+ fillEntity: 0 as Entity,+ handleEntity: 0 as Entity,wholeNumbers: false,- enabled: true,});diff --git a/sdk/src/ui/SliderPlugin.ts b/sdk/src/ui/SliderPlugin.tsindex 983f7f61a..4b1fbeea1 100644--- a/sdk/src/ui/SliderPlugin.ts+++ b/sdk/src/ui/SliderPlugin.ts@@ -6,7 +6,7 @@ import { Res } from '../resource';import { Input } from '../input';import type { InputState } from '../input';import type { Entity } from '../types';-import { Slider, SliderDirection } from './Slider';+import { Slider, FillDirection } from './Slider';import type { SliderData } from './Slider';import { UIRect } from './UIRect';import type { UIRectData } from './UIRect';@@ -15,15 +15,13 @@ import { UIInteraction } from './UIInteraction';import type { UIInteractionData } from './UIInteraction';import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';-import { invertMatrix4, screenToWorld, pointInOBB } from './uiMath';+import { applyDirectionalFill } from './uiHelpers';export class SliderPlugin implements Plugin {build(app: App): void {registerComponent('Slider', Slider);const world = app.world;- const invVP = new Float32Array(16);- const cachedDpr = typeof window !== 'undefined' ? (window.devicePixelRatio || 1) : 1;let draggingSlider: Entity | null = null;app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(@@ -31,13 +29,7 @@ export class SliderPlugin implements Plugin {(input: InputState, camera: UICameraData) => {if (!camera.valid) return;- const mouseGLX = input.mouseX * cachedDpr;- const mouseGLY = camera.screenH - input.mouseY * cachedDpr;- invertMatrix4(camera.viewProjection, invVP);- const worldMouse = screenToWorld(- mouseGLX, mouseGLY, invVP,- camera.vpX, camera.vpY, camera.vpW, camera.vpH,- );+ const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };const entities = world.getEntitiesWithComponents([Slider, UIRect, WorldTransform]);for (const entity of entities) {@@ -64,16 +56,16 @@ export class SliderPlugin implements Plugin {let t: number;switch (slider.direction) {- case SliderDirection.LeftToRight:+ case FillDirection.LeftToRight:t = worldW > 0 ? (worldMouse.x - originX) / worldW : 0;break;- case SliderDirection.RightToLeft:+ case FillDirection.RightToLeft:t = worldW > 0 ? 1 - (worldMouse.x - originX) / worldW : 0;break;- case SliderDirection.BottomToTop:+ case FillDirection.BottomToTop:t = worldH > 0 ? (worldMouse.y - originY) / worldH : 0;break;- case SliderDirection.TopToBottom:+ case FillDirection.TopToBottom:t = worldH > 0 ? 1 - (worldMouse.y - originY) / worldH : 0;break;}@@ -93,55 +85,32 @@ export class SliderPlugin implements Plugin {const range = slider.maxValue - slider.minValue;const normalizedValue = range > 0 ? (slider.value - slider.minValue) / range : 0;- if (slider.fillEntity !== 0 && world.valid(slider.fillEntity as Entity)) {- const fillEntity = slider.fillEntity as Entity;- if (world.has(fillEntity, UIRect)) {- const fillRect = world.get(fillEntity, UIRect) as UIRectData;- switch (slider.direction) {- case SliderDirection.LeftToRight:- fillRect.anchorMin = { x: 0, y: 0 };- fillRect.anchorMax = { x: normalizedValue, y: 1 };- break;- case SliderDirection.RightToLeft:- fillRect.anchorMin = { x: 1 - normalizedValue, y: 0 };- fillRect.anchorMax = { x: 1, y: 1 };- break;- case SliderDirection.BottomToTop:- fillRect.anchorMin = { x: 0, y: 0 };- fillRect.anchorMax = { x: 1, y: normalizedValue };- break;- case SliderDirection.TopToBottom:- fillRect.anchorMin = { x: 0, y: 1 - normalizedValue };- fillRect.anchorMax = { x: 1, y: 1 };- break;- }- world.insert(fillEntity, UIRect, fillRect);- }+ if (slider.fillEntity !== 0 && world.valid(slider.fillEntity)) {+ applyDirectionalFill(world, slider.fillEntity, slider.direction, normalizedValue);}- if (slider.handleEntity !== 0 && world.valid(slider.handleEntity as Entity)) {- const handleEntity = slider.handleEntity as Entity;- if (world.has(handleEntity, UIRect)) {- const handleRect = world.get(handleEntity, UIRect) as UIRectData;+ if (slider.handleEntity !== 0 && world.valid(slider.handleEntity)) {+ if (world.has(slider.handleEntity, UIRect)) {+ const handleRect = world.get(slider.handleEntity, UIRect) as UIRectData;switch (slider.direction) {- case SliderDirection.LeftToRight:+ case FillDirection.LeftToRight:handleRect.anchorMin = { x: normalizedValue, y: 0 };handleRect.anchorMax = { x: normalizedValue, y: 1 };break;- case SliderDirection.RightToLeft:+ case FillDirection.RightToLeft:handleRect.anchorMin = { x: 1 - normalizedValue, y: 0 };handleRect.anchorMax = { x: 1 - normalizedValue, y: 1 };break;- case SliderDirection.BottomToTop:+ case FillDirection.BottomToTop:handleRect.anchorMin = { x: 0, y: normalizedValue };handleRect.anchorMax = { x: 1, y: normalizedValue };break;- case SliderDirection.TopToBottom:+ case FillDirection.TopToBottom:handleRect.anchorMin = { x: 0, y: 1 - normalizedValue };handleRect.anchorMax = { x: 1, y: 1 - normalizedValue };break;}- world.insert(handleEntity, UIRect, handleRect);+ world.insert(slider.handleEntity, UIRect, handleRect);}}}diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.tsindex a3844e853..ba88aba28 100644--- a/sdk/src/ui/TextInputPlugin.ts+++ b/sdk/src/ui/TextInputPlugin.ts@@ -1,6 +1,5 @@import type { App, Plugin } from '../app';import type { Entity } from '../types';-import { INVALID_TEXTURE } from '../types';import { RuntimeConfig } from '../defaults';import { defineSystem, Schedule } from '../system';import { registerComponent, Sprite, type SpriteData } from '../component';@@ -11,6 +10,7 @@ import { UIInteraction, type UIInteractionData } from './UIInteraction';import { UIEvents, UIEventQueue } from './UIEvents';import { Res } from '../resource';import { platformCreateCanvas } from '../platform';+import { ensureSprite, wrapText, nextPowerOf2 } from './uiHelpers';export class TextInputPlugin implements Plugin {private cleanupListeners_: (() => void) | null = null;@@ -247,19 +247,7 @@ export class TextInputPlugin implements Plugin {const h = Math.ceil(uiRect.size.y);if (w <= 0 || h <= 0) continue;- if (!world.has(entity, Sprite)) {- world.insert(entity, Sprite, {- texture: INVALID_TEXTURE,- color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: w, y: h },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- material: 0,- });- }+ ensureSprite(world, entity);renderTextInput(entity, ti, w, h);ti.dirty = false;@@ -393,36 +381,4 @@ function createHiddenTextarea(): HTMLTextAreaElement | null {return textarea;}-function wrapText(- ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,- text: string,- maxWidth: number-): string[] {- if (!text) return [''];- if (maxWidth <= 0) return text.split('\n');- const paragraphs = text.split('\n');- const lines: string[] = [];- for (const paragraph of paragraphs) {- if (!paragraph) { lines.push(''); continue; }- let currentLine = '';- for (const char of paragraph) {- const testLine = currentLine + char;- if (ctx.measureText(testLine).width > maxWidth && currentLine) {- lines.push(currentLine);- currentLine = char;- } else {- currentLine = testLine;- }- }- if (currentLine) lines.push(currentLine);- }- return lines.length > 0 ? lines : [''];-}--function nextPowerOf2(n: number): number {- let p = 1;- while (p < n) p *= 2;- return p;-}-export const textInputPlugin = new TextInputPlugin();diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.tsindex 01ec50da2..09f2bb9fb 100644--- a/sdk/src/ui/TextPlugin.ts+++ b/sdk/src/ui/TextPlugin.ts@@ -5,12 +5,12 @@import type { App, Plugin } from '../app';import type { Entity } from '../types';-import { INVALID_TEXTURE } 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;@@ -105,19 +105,7 @@ export class TextPlugin implements Plugin {if (prev && !snapshotChanged(prev, text, uiRect)) continue;- if (!world.has(entity, Sprite)) {- world.insert(entity, Sprite, {- texture: INVALID_TEXTURE,- color: { r: 1, g: 1, b: 1, a: 1 },- size: { x: 0, y: 0 },- uvOffset: { x: 0, y: 0 },- uvScale: { x: 1, y: 1 },- layer: 0,- flipX: false,- flipY: false,- material: 0,- });- }+ ensureSprite(world, entity);const result = renderer.renderForEntity(entity, text, uiRect);@@ -133,8 +121,9 @@ export class TextPlugin implements Plugin {snapshots.set(entity, takeSnapshot(text, uiRect));}- }- ));+ },+ { name: 'TextSystem' }+ ), { runAfter: ['UILayoutSystem'] });}}diff --git a/sdk/src/ui/TextRenderer.ts b/sdk/src/ui/TextRenderer.tsindex c8d9893fd..dbb9526a9 100644--- a/sdk/src/ui/TextRenderer.ts+++ b/sdk/src/ui/TextRenderer.ts@@ -3,12 +3,16 @@* @brief Renders text to GPU textures using Canvas 2D API*/-import type { Entity, Vec2 } from '../types';+import type { Entity } from '../types';import { RuntimeConfig } from '../defaults';-import type { ESEngineModule, CppResourceManager } from '../wasm';+import type { ESEngineModule } from '../wasm';import { TextAlign, TextVerticalAlign, TextOverflow, type TextData } from './text';-import type { UIRectData } from './UIRect';import { platformCreateCanvas } from '../platform';+import { wrapText, nextPowerOf2 } from './uiHelpers';++interface SizedRect {+ size: { x: number; y: number };+}// =============================================================================// Text Render Result@@ -39,7 +43,7 @@ export class TextRenderer {/*** Renders text to a texture and returns the handle*/- renderText(text: TextData, uiRect?: UIRectData | null): TextRenderResult {+ renderText(text: TextData, uiRect?: SizedRect | null): TextRenderResult {const ctx = this.ctx;const canvas = this.canvas;@@ -50,7 +54,7 @@ export class TextRenderer {const containerHeight = hasContainer ? uiRect!.size.y : 0;const shouldWrap = text.wordWrap && hasContainer;- let lines = this.wrapText(text.content, shouldWrap ? containerWidth : 0);+ 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);@@ -71,8 +75,8 @@ export class TextRenderer {}if (canvas.width < width || canvas.height < height) {- const newWidth = Math.max(canvas.width, this.nextPowerOf2(width));- const newHeight = Math.max(canvas.height, this.nextPowerOf2(height));+ const newWidth = Math.max(canvas.width, nextPowerOf2(width));+ const newHeight = Math.max(canvas.height, nextPowerOf2(height));canvas.width = newWidth;canvas.height = newHeight;}@@ -165,7 +169,7 @@ export class TextRenderer {/*** Renders text for an entity and caches the result*/- renderForEntity(entity: Entity, text: TextData, uiRect?: UIRectData | null): TextRenderResult {+ renderForEntity(entity: Entity, text: TextData, uiRect?: SizedRect | null): TextRenderResult {const existing = this.cache.get(entity);if (existing) {const rm = this.module.getResourceManager();@@ -217,44 +221,6 @@ export class TextRenderer {this.cache.clear();}- // =========================================================================- // Private Methods- // =========================================================================-- private wrapText(text: string, maxWidth: number): string[] {- if (!text) return [''];- if (maxWidth <= 0) return text.split('\n');-- const paragraphs = text.split('\n');- const lines: string[] = [];-- for (const paragraph of paragraphs) {- if (!paragraph) {- lines.push('');- continue;- }-- let currentLine = '';-- for (const char of paragraph) {- const testLine = currentLine + char;- const metrics = this.ctx.measureText(testLine);-- if (metrics.width > maxWidth && currentLine) {- lines.push(currentLine);- currentLine = char;- } else {- currentLine = testLine;- }- }- if (currentLine) {- lines.push(currentLine);- }- }-- return lines.length > 0 ? lines : [''];- }-private measureWidth(lines: string[]): number {let maxWidth = 0;for (const line of lines) {@@ -278,10 +244,4 @@ export class TextRenderer {}}- private nextPowerOf2(n: number): number {- let p = 1;- while (p < n) p *= 2;- return p;- }-}diff --git a/sdk/src/ui/Toggle.ts b/sdk/src/ui/Toggle.tsindex 57687a132..1cbbabdd9 100644--- a/sdk/src/ui/Toggle.ts+++ b/sdk/src/ui/Toggle.ts@@ -1,23 +1,20 @@import { defineComponent } from '../component';-import type { Color, Entity } from '../types';+import type { Entity } from '../types';+import type { ColorTransition } from './uiTypes';-export interface ToggleTransition {- normalColor: Color;- hoveredColor: Color;- pressedColor: Color;- disabledColor: Color;-}+export type { ColorTransition } from './uiTypes';+export type ToggleTransition = ColorTransition;export interface ToggleData {isOn: boolean;graphicEntity: Entity;- transition: ToggleTransition | null;- enabled: boolean;+ group: Entity;+ transition: ColorTransition | null;}export const Toggle = defineComponent<ToggleData>('Toggle', {isOn: true,graphicEntity: 0 as Entity,+ group: 0 as Entity,transition: null,- enabled: true,});diff --git a/sdk/src/ui/ToggleGroup.ts b/sdk/src/ui/ToggleGroup.tsnew file mode 100644index 000000000..e309b8716--- /dev/null+++ b/sdk/src/ui/ToggleGroup.ts@@ -0,0 +1,9 @@+import { defineComponent } from '../component';++export interface ToggleGroupData {+ allowSwitchOff: boolean;+}++export const ToggleGroup = defineComponent<ToggleGroupData>('ToggleGroup', {+ allowSwitchOff: false,+});diff --git a/sdk/src/ui/TogglePlugin.ts b/sdk/src/ui/TogglePlugin.tsindex 309e9f17f..9aa073382 100644--- a/sdk/src/ui/TogglePlugin.ts+++ b/sdk/src/ui/TogglePlugin.ts@@ -3,18 +3,21 @@ 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';import type { UIInteractionData } from './UIInteraction';import { Toggle } from './Toggle';import type { ToggleData } from './Toggle';+import { ToggleGroup } from './ToggleGroup';+import type { ToggleGroupData } from './ToggleGroup';import { UIEvents, UIEventQueue } from './UIEvents';+import { applyColorTransition } from './uiHelpers';export class TogglePlugin implements Plugin {build(app: App): void {registerComponent('Toggle', Toggle);+ registerComponent('ToggleGroup', ToggleGroup);const world = app.world;@@ -33,31 +36,47 @@ export class TogglePlugin implements Plugin {const interactable = world.get(entity, Interactable) as InteractableData;if (interaction.justPressed && interactable.enabled) {+ const groupEntity = toggle.group;+ const hasGroup = groupEntity !== 0 && world.valid(groupEntity)+ && world.has(groupEntity, ToggleGroup);++ if (toggle.isOn && hasGroup) {+ const group = world.get(groupEntity, ToggleGroup) as ToggleGroupData;+ if (!group.allowSwitchOff) continue;+ }+toggle.isOn = !toggle.isOn;++ if (toggle.isOn && hasGroup) {+ for (const other of toggleEntities) {+ if (other === entity) continue;+ const otherToggle = world.get(other, Toggle) as ToggleData;+ if (otherToggle.group === groupEntity && otherToggle.isOn) {+ otherToggle.isOn = false;+ events.emit(other, 'change');+ }+ }+ }+events.emit(entity, 'change');}- if (toggle.graphicEntity && world.valid(toggle.graphicEntity as Entity)) {- const graphicEntity = toggle.graphicEntity as Entity;- if (world.has(graphicEntity, Sprite)) {- const sprite = world.get(graphicEntity, Sprite) as SpriteData;+ 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;- world.insert(graphicEntity, Sprite, sprite);+ world.insert(toggle.graphicEntity, Sprite, sprite);}}if (toggle.transition && world.has(entity, Sprite)) {const sprite = world.get(entity, Sprite) as SpriteData;- const t = toggle.transition;- if (!interactable.enabled) {- sprite.color = { ...t.disabledColor };- } else if (interaction.pressed) {- sprite.color = { ...t.pressedColor };- } else if (interaction.hovered) {- sprite.color = { ...t.hoveredColor };- } else {- sprite.color = { ...t.normalColor };- }+ sprite.color = applyColorTransition(+ toggle.transition,+ interactable.enabled,+ interaction.pressed,+ interaction.hovered,+ );world.insert(entity, Sprite, sprite);}}diff --git a/sdk/src/ui/UICameraInfo.ts b/sdk/src/ui/UICameraInfo.tsindex 7a5c3de8e..c4f74c58b 100644--- a/sdk/src/ui/UICameraInfo.ts+++ b/sdk/src/ui/UICameraInfo.ts@@ -12,6 +12,8 @@ export interface UICameraData {worldBottom: number;worldRight: number;worldTop: number;+ worldMouseX: number;+ worldMouseY: number;valid: boolean;}@@ -20,5 +22,6 @@ export const UICameraInfo = defineResource<UICameraData>({vpX: 0, vpY: 0, vpW: 0, vpH: 0,screenW: 0, screenH: 0,worldLeft: 0, worldBottom: 0, worldRight: 0, worldTop: 0,+ worldMouseX: 0, worldMouseY: 0,valid: false,}, 'UICameraInfo');diff --git a/sdk/src/ui/UIEvents.ts b/sdk/src/ui/UIEvents.tsindex 274d65437..d6bcf9b32 100644--- a/sdk/src/ui/UIEvents.ts+++ b/sdk/src/ui/UIEvents.ts@@ -1,7 +1,7 @@import { defineResource } from '../resource';import type { Entity } from '../types';-export type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit' | 'submit' | 'change' | 'drag_start' | 'drag_move' | 'drag_end' | 'scroll';+export type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit' | 'focus' | 'blur' | 'submit' | 'change' | 'drag_start' | 'drag_move' | 'drag_end' | 'scroll';export interface UIEvent {entity: Entity;diff --git a/sdk/src/ui/UIInteractionPlugin.ts b/sdk/src/ui/UIInteractionPlugin.tsindex 138a9b992..822bd1635 100644--- a/sdk/src/ui/UIInteractionPlugin.ts+++ b/sdk/src/ui/UIInteractionPlugin.ts@@ -19,7 +19,10 @@ import { UIEvents, UIEventQueue } from './UIEvents';import type { UIEventType } from './UIEvents';import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';-import { invertMatrix4, screenToWorld, pointInOBB } from './uiMath';+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);@@ -40,6 +43,40 @@ function updateInvVPCache(vp: Float32Array): void {}}+function isClippedByMask(+ world: World,+ entity: Entity,+ worldMouseX: number,+ worldMouseY: number,+): boolean {+ 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;++ if (world.has(parentEntity, UIMask)) {+ const mask = world.get(parentEntity, UIMask) as UIMaskData;+ 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(+ worldMouseX, worldMouseY,+ wt.position.x, wt.position.y,+ maskW, maskH,+ rect.pivot.x, rect.pivot.y,+ )) {+ return true;+ }+ }+ }+ current = parentEntity;+ }+ return false;+}+function emitWithBubbling(world: World,events: UIEventQueue,@@ -106,6 +143,9 @@ export class UIInteractionPlugin implements Plugin {camera.vpX, camera.vpY, camera.vpW, camera.vpH,);+ camera.worldMouseX = worldMouse.x;+ camera.worldMouseY = worldMouse.y;+const interactableEntities = world.getEntitiesWithComponents([Interactable, UIRect, WorldTransform]);@@ -120,6 +160,7 @@ export class UIInteractionPlugin implements Plugin {const interactable = world.get(entity, Interactable) as InteractableData;if (!interactable.enabled) continue;+ if (!interactable.raycastTarget) continue;const wt = world.get(entity, WorldTransform) as WorldTransformData;const rect = world.get(entity, UIRect) as UIRectData;@@ -133,6 +174,10 @@ export class UIInteractionPlugin implements Plugin {rect.pivot.x, rect.pivot.y,wt.rotation.z, wt.rotation.w,)) {+ if (isClippedByMask(world, entity, worldMouse.x, worldMouse.y)) {+ continue;+ }+let layer = 0;if (world.has(entity, Sprite)) {layer = (world.get(entity, Sprite) as SpriteData).layer;@@ -210,13 +255,12 @@ export class UIInteractionPlugin implements Plugin {if (prevState !== button.state && button.transition && world.has(entity, Sprite)) {const sprite = world.get(entity, Sprite) as SpriteData;- const t = button.transition;- switch (button.state) {- case ButtonState.Normal: sprite.color = { ...t.normalColor }; break;- case ButtonState.Hovered: sprite.color = { ...t.hoveredColor }; break;- case ButtonState.Pressed: sprite.color = { ...t.pressedColor }; break;- case ButtonState.Disabled: sprite.color = { ...t.disabledColor }; break;- }+ sprite.color = applyColorTransition(+ button.transition,+ interactable.enabled,+ interaction.pressed,+ interaction.hovered,+ );world.insert(entity, Sprite, sprite);}}diff --git a/sdk/src/ui/UILayoutPlugin.ts b/sdk/src/ui/UILayoutPlugin.tsindex b1402f868..81a5093b5 100644--- a/sdk/src/ui/UILayoutPlugin.ts+++ b/sdk/src/ui/UILayoutPlugin.ts@@ -25,7 +25,20 @@ interface RectSnapshot {sizeY: number;}-function takeRectSnapshot(rect: UIRectData): RectSnapshot {+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,@@ -115,11 +128,20 @@ export class UILayoutPlugin implements Plugin {const world = app.world;const snapshots = new Map<Entity, RectSnapshot>();+ const rootCache = new Map<Entity, Entity | null>();let prevCameraLeft = NaN;let prevCameraBottom = NaN;let prevCameraRight = NaN;let prevCameraTop = NaN;+ function getCachedRoot(entity: Entity): Entity | null {+ let root = rootCache.get(entity);+ if (root !== undefined) return root;+ root = findRoot(world, entity);+ rootCache.set(entity, root);+ return root;+ }+app.addSystemToSchedule(Schedule.PreUpdate, defineSystem([Res(UICameraInfo)],(camera: UICameraData) => {@@ -147,29 +169,29 @@ export class UILayoutPlugin implements Plugin {const dirtyRoots = new Set<Entity>();if (cameraChanged) {+ rootCache.clear();const roots = world.getEntitiesWithComponents([ScreenSpace, UIRect, LocalTransform]);for (const root of roots) {dirtyRoots.add(root);}}+ for (const entity of snapshots.keys()) {+ if (!world.valid(entity) || !world.has(entity, UIRect)) {+ snapshots.delete(entity);+ rootCache.delete(entity);+ }+ }+const allUIRectEntities = world.getEntitiesWithComponents([UIRect]);for (const entity of allUIRectEntities) {const rect = world.get(entity, UIRect) as UIRectData;const snap = snapshots.get(entity);- if (!snap || rectChanged(snap, rect)) {- const root = findRoot(world, entity);- if (root !== null) {- dirtyRoots.add(root);- }- }- }-- for (const entity of snapshots.keys()) {- if (!world.valid(entity) || !world.has(entity, UIRect)) {- snapshots.delete(entity);- const root = findRoot(world, entity);+ if (rect._dirty || !snap || rectChanged(snap, rect)) {+ rect._dirty = false;+ rootCache.delete(entity);+ const root = getCachedRoot(entity);if (root !== null) {dirtyRoots.add(root);}@@ -182,7 +204,12 @@ export class UILayoutPlugin implements Plugin {for (const entity of allUIRectEntities) {const rect = world.get(entity, UIRect) as UIRectData;- snapshots.set(entity, takeRectSnapshot(rect));+ const existing = snapshots.get(entity);+ if (existing) {+ updateSnapshot(existing, rect);+ } else {+ snapshots.set(entity, createSnapshot(rect));+ }}},{ name: 'UILayoutSystem' }diff --git a/sdk/src/ui/UIRect.ts b/sdk/src/ui/UIRect.tsindex ca81fec75..838afbf23 100644--- a/sdk/src/ui/UIRect.ts+++ b/sdk/src/ui/UIRect.ts@@ -8,6 +8,7 @@ export interface UIRectData {offsetMax: Vec2;size: Vec2;pivot: Vec2;+ _dirty: boolean;}export const UIRect = defineComponent<UIRectData>('UIRect', {@@ -17,4 +18,5 @@ export const UIRect = defineComponent<UIRectData>('UIRect', {offsetMax: { x: 0, y: 0 },size: { x: 100, y: 100 },pivot: { x: 0.5, y: 0.5 },+ _dirty: true,});diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex b26ec2663..7643a9cf9 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -3,6 +3,21 @@* @brief UI module exports*/+// Shared Types+export {+ FillDirection,+ type ColorTransition,+} from './uiTypes';++// Shared Helpers+export {+ ensureSprite,+ applyDirectionalFill,+ applyColorTransition,+ wrapText,+ nextPowerOf2,+} from './uiHelpers';+// Text Componentexport {Text,@@ -147,6 +162,12 @@ export {type ToggleData,} from './Toggle';+// ToggleGroup Component+export {+ ToggleGroup,+ type ToggleGroupData,+} from './ToggleGroup';+// Toggle Pluginexport {TogglePlugin,@@ -256,3 +277,17 @@ export {DropdownPlugin,dropdownPlugin,} from './DropdownPlugin';++// LayoutGroup Component+export {+ LayoutGroup,+ LayoutDirection,+ ChildAlignment,+ type LayoutGroupData,+} from './LayoutGroup';++// LayoutGroup Plugin+export {+ LayoutGroupPlugin,+ layoutGroupPlugin,+} from './LayoutGroupPlugin';diff --git a/sdk/src/ui/text.ts b/sdk/src/ui/text.tsindex 77f496164..593429659 100644--- a/sdk/src/ui/text.ts+++ b/sdk/src/ui/text.ts@@ -1,36 +1,29 @@-/**- * @file text.ts- * @brief Text component definition for UI text rendering- */-import { defineComponent } from '../component';import type { Color } from '../types';-// =============================================================================-// Text Alignment Enums-// =============================================================================+export const TextAlign = {+ Left: 0,+ Center: 1,+ Right: 2,+} as const;-export enum TextAlign {- Left = 0,- Center = 1,- Right = 2,-}+export type TextAlign = (typeof TextAlign)[keyof typeof TextAlign];-export enum TextVerticalAlign {- Top = 0,- Middle = 1,- Bottom = 2,-}+export const TextVerticalAlign = {+ Top: 0,+ Middle: 1,+ Bottom: 2,+} as const;-export enum TextOverflow {- Visible = 0,- Clip = 1,- Ellipsis = 2,-}+export type TextVerticalAlign = (typeof TextVerticalAlign)[keyof typeof TextVerticalAlign];++export const TextOverflow = {+ Visible: 0,+ Clip: 1,+ Ellipsis: 2,+} as const;-// =============================================================================-// Text Component Data-// =============================================================================+export type TextOverflow = (typeof TextOverflow)[keyof typeof TextOverflow];export interface TextData {content: string;@@ -44,10 +37,6 @@ export interface TextData {lineHeight: number;}-// =============================================================================-// Text Component Definition-// =============================================================================-export const Text = defineComponent<TextData>('Text', {content: '',fontFamily: 'Arial',diff --git a/sdk/src/ui/uiHelpers.ts b/sdk/src/ui/uiHelpers.tsnew file mode 100644index 000000000..9b66d11ec--- /dev/null+++ b/sdk/src/ui/uiHelpers.ts@@ -0,0 +1,126 @@+import { Sprite } from '../component';+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 type { ColorTransition } from './uiTypes';++export function ensureSprite(world: World, entity: Entity): void {+ if (!world.has(entity, Sprite)) {+ world.insert(entity, Sprite, {+ texture: INVALID_TEXTURE,+ color: { r: 1, g: 1, b: 1, a: 1 },+ size: { x: 0, y: 0 },+ uvOffset: { x: 0, y: 0 },+ uvScale: { x: 1, y: 1 },+ layer: 0,+ flipX: false,+ flipY: false,+ material: 0,+ });+ }+}++export function applyDirectionalFill(+ world: World,+ fillEntity: Entity,+ direction: FillDirection,+ 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 };+ world.insert(fillEntity, UIRect, fillRect);+}++export function applyColorTransition(+ transition: ColorTransition,+ enabled: boolean,+ pressed: boolean,+ hovered: boolean,+): Color {+ if (!enabled) return { ...transition.disabledColor };+ if (pressed) return { ...transition.pressedColor };+ if (hovered) return { ...transition.hoveredColor };+ return { ...transition.normalColor };+}++function isWordChar(code: number): boolean {+ return (code >= 0x41 && code <= 0x5A)+ || (code >= 0x61 && code <= 0x7A)+ || (code >= 0x30 && code <= 0x39)+ || code === 0x5F;+}++export function wrapText(+ ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,+ text: string,+ maxWidth: number,+): string[] {+ if (!text) return [''];+ if (maxWidth <= 0) return text.split('\n');+ const paragraphs = text.split('\n');+ const lines: string[] = [];+ for (const paragraph of paragraphs) {+ if (!paragraph) { lines.push(''); continue; }+ let currentLine = '';+ for (let i = 0; i < paragraph.length; i++) {+ const char = paragraph[i];+ const testLine = currentLine + char;+ if (ctx.measureText(testLine).width > maxWidth && currentLine) {+ const code = char.charCodeAt(0);+ if (isWordChar(code) && currentLine.length > 0 && isWordChar(currentLine.charCodeAt(currentLine.length - 1))) {+ let breakPos = -1;+ for (let j = currentLine.length - 1; j >= 0; j--) {+ if (!isWordChar(currentLine.charCodeAt(j))) {+ breakPos = j;+ break;+ }+ }+ if (breakPos >= 0) {+ lines.push(currentLine.substring(0, breakPos + 1));+ currentLine = currentLine.substring(breakPos + 1) + char;+ } else {+ lines.push(currentLine);+ currentLine = char;+ }+ } else {+ lines.push(currentLine);+ currentLine = char;+ }+ } else {+ currentLine = testLine;+ }+ }+ if (currentLine) lines.push(currentLine);+ }+ return lines.length > 0 ? lines : [''];+}++export function nextPowerOf2(n: number): number {+ let p = 1;+ while (p < n) p *= 2;+ return p;+}diff --git a/sdk/src/ui/uiTypes.ts b/sdk/src/ui/uiTypes.tsnew file mode 100644index 000000000..f4e559bf0--- /dev/null+++ b/sdk/src/ui/uiTypes.ts@@ -0,0 +1,17 @@+import type { Color } from '../types';++export interface ColorTransition {+ normalColor: Color;+ hoveredColor: Color;+ pressedColor: Color;+ disabledColor: Color;+}++export const FillDirection = {+ LeftToRight: 0,+ RightToLeft: 1,+ BottomToTop: 2,+ TopToBottom: 3,+} as const;++export type FillDirection = (typeof FillDirection)[keyof typeof FillDirection];diff --git a/sdk/src/uiPlugins.ts b/sdk/src/uiPlugins.tsindex b74dfa5f2..3b41f1694 100644--- a/sdk/src/uiPlugins.ts+++ b/sdk/src/uiPlugins.ts@@ -13,6 +13,7 @@ import { focusPlugin } from './ui/FocusPlugin';import { safeAreaPlugin } from './ui/SafeAreaPlugin';import { listViewPlugin } from './ui/ListViewPlugin';import { dropdownPlugin } from './ui/DropdownPlugin';+import { layoutGroupPlugin } from './ui/LayoutGroupPlugin';import type { Plugin } from './app';export const uiPlugins: Plugin[] = [@@ -21,4 +22,5 @@ export const uiPlugins: Plugin[] = [uiInteractionPlugin, dragPlugin, scrollViewPlugin, sliderPlugin,togglePlugin, textInputPlugin,focusPlugin, safeAreaPlugin, listViewPlugin, dropdownPlugin,+ layoutGroupPlugin,];