Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat: add C++ UI component system and migrate layout to WASM

esenginefeda47548821
diff --git a/sdk/src/ui/DragPlugin.ts b/sdk/src/ui/DragPlugin.ts
index 3bd1587b5..6efce3dc6 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, Sprite } from '../component';
-import type { LocalTransformData, WorldTransformData, ParentData, SpriteData } from '../component';
+import { registerComponent, Transform, Parent, Sprite } from '../component';
+import type { TransformData, ParentData, SpriteData } from '../component';
import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Input } from '../input';
@@ -14,6 +14,7 @@ import type { UIInteractionData } from './UIInteraction';
import { UIEvents, UIEventQueue } from './UIEvents';
import { UICameraInfo } from './UICameraInfo';
import type { UICameraData } from './UICameraInfo';
+import { isEditor } from '../env';
import { getEntityDepth } from './uiHelpers';
import { quaternionToAngle2D } from './uiMath';
@@ -28,14 +29,14 @@ function worldToLocalDelta(
}
const parentData = world.get(entity, Parent) as ParentData;
const parentEntity = parentData.entity;
- if (!world.valid(parentEntity) || !world.has(parentEntity, WorldTransform)) {
+ if (!world.valid(parentEntity) || !world.has(parentEntity, Transform)) {
return { x: dx, y: dy };
}
- const parentWt = world.get(parentEntity, WorldTransform) as WorldTransformData;
- const sx = parentWt.scale.x !== 0 ? parentWt.scale.x : 1;
- const sy = parentWt.scale.y !== 0 ? parentWt.scale.y : 1;
+ const parentWt = world.get(parentEntity, Transform) as TransformData;
+ const sx = parentWt.worldScale.x !== 0 ? parentWt.worldScale.x : 1;
+ const sy = parentWt.worldScale.y !== 0 ? parentWt.worldScale.y : 1;
- const angle = quaternionToAngle2D(parentWt.rotation.z, parentWt.rotation.w);
+ const angle = quaternionToAngle2D(parentWt.worldRotation.z, parentWt.worldRotation.w);
const sin = Math.sin(-angle);
const cos = Math.cos(-angle);
@@ -72,6 +73,7 @@ export class DragPlugin implements Plugin {
registerComponent('DragState', DragState);
const world = app.world;
+ const editorMode = isEditor();
const events = app.getResource(UIEvents) as UIEventQueue;
let pendingEntity: Entity | null = null;
@@ -81,6 +83,7 @@ export class DragPlugin implements Plugin {
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
[Res(Input), Res(UICameraInfo)],
(input: InputState, camera: UICameraData) => {
+ if (editorMode) return;
if (!camera.valid) return;
const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };
@@ -117,9 +120,9 @@ export class DragPlugin implements Plugin {
world.insert(bestEntity, DragState);
}
const dragState = world.get(bestEntity, DragState) as DragStateData;
- const wt = world.get(bestEntity, WorldTransform) as WorldTransformData;
- dragState.startWorldPos = { x: wt.position.x, y: wt.position.y };
- dragState.currentWorldPos = { x: wt.position.x, y: wt.position.y };
+ const wt = world.get(bestEntity, Transform) as TransformData;
+ dragState.startWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };
+ dragState.currentWorldPos = { x: wt.worldPosition.x, y: wt.worldPosition.y };
dragState.pointerStartWorld = { x: worldMouse.x, y: worldMouse.y };
dragState.deltaWorld = { x: 0, y: 0 };
dragState.totalDeltaWorld = { x: 0, y: 0 };
@@ -184,15 +187,15 @@ export class DragPlugin implements Plugin {
y: newWorldY - dragState.startWorldPos.y,
};
- if (world.has(activeEntity, LocalTransform)) {
+ if (world.has(activeEntity, Transform)) {
const localDelta = worldToLocalDelta(
world, activeEntity,
dragState.deltaWorld.x, dragState.deltaWorld.y
);
- const lt = world.get(activeEntity, LocalTransform) as LocalTransformData;
+ const lt = world.get(activeEntity, Transform) as TransformData;
lt.position.x += localDelta.x;
lt.position.y += localDelta.y;
- world.insert(activeEntity, LocalTransform, lt);
+ world.insert(activeEntity, Transform, lt);
}
events.emit(activeEntity, 'drag_move');
diff --git a/sdk/src/ui/DropdownPlugin.ts b/sdk/src/ui/DropdownPlugin.ts
index d8f6d3623..daa64674e 100644
--- a/sdk/src/ui/DropdownPlugin.ts
+++ b/sdk/src/ui/DropdownPlugin.ts
@@ -1,5 +1,5 @@
import type { App, Plugin } from '../app';
-import { registerComponent, LocalTransform, Name, Sprite } from '../component';
+import { registerComponent, Transform, Name, Sprite } from '../component';
import type { SpriteData } from '../component';
import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
@@ -15,9 +15,10 @@ 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 { UIMask, MaskMode } from './UIMask';
import { Input } from '../input';
import type { InputState } from '../input';
+import { isEditor } from '../env';
import { ensureComponent } from './uiHelpers';
import { DROPDOWN_ITEM_HEIGHT, DROPDOWN_FONT_SIZE, DROPDOWN_HIGHLIGHT_COLOR } from './uiConstants';
@@ -31,11 +32,13 @@ export class DropdownPlugin implements Plugin {
registerComponent('Dropdown', Dropdown);
const world = app.world;
+ const editorMode = isEditor();
const dropdownStates = new Map<Entity, DropdownState>();
app.addSystemToSchedule(Schedule.Update, defineSystem(
[Res(Input), Res(UIEvents)],
(input: InputState, events: UIEventQueue) => {
+ if (editorMode) return;
for (const [e] of dropdownStates) {
if (!world.valid(e)) dropdownStates.delete(e);
}
@@ -116,7 +119,7 @@ export class DropdownPlugin implements Plugin {
setListVisible(listEntity, true);
if (!world.has(listEntity, UIMask)) {
- world.insert(listEntity, UIMask, { enabled: true, mode: 'scissor' });
+ world.insert(listEntity, UIMask, { enabled: true, mode: MaskMode.Scissor });
}
destroyOptions(state);
@@ -136,7 +139,7 @@ export class DropdownPlugin implements Plugin {
size: { x: listWidth, y: DROPDOWN_ITEM_HEIGHT },
pivot: { x: 0.5, y: 1 },
});
- world.insert(optEntity, LocalTransform, {
+ world.insert(optEntity, Transform, {
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 },
diff --git a/sdk/src/ui/FlexContainer.ts b/sdk/src/ui/FlexContainer.ts
new file mode 100644
index 000000000..b59d94201
--- /dev/null
+++ b/sdk/src/ui/FlexContainer.ts
@@ -0,0 +1,32 @@
+import { defineBuiltin } from '../component';
+import type { Vec2, Vec4 } from '../types';
+
+export const FlexDirection = { Row: 0, Column: 1, RowReverse: 2, ColumnReverse: 3 } as const;
+export type FlexDirection = (typeof FlexDirection)[keyof typeof FlexDirection];
+
+export const FlexWrap = { NoWrap: 0, Wrap: 1 } as const;
+export type FlexWrap = (typeof FlexWrap)[keyof typeof FlexWrap];
+
+export const JustifyContent = { Start: 0, Center: 1, End: 2, SpaceBetween: 3, SpaceAround: 4, SpaceEvenly: 5 } as const;
+export type JustifyContent = (typeof JustifyContent)[keyof typeof JustifyContent];
+
+export const AlignItems = { Start: 0, Center: 1, End: 2, Stretch: 3 } as const;
+export type AlignItems = (typeof AlignItems)[keyof typeof AlignItems];
+
+export interface FlexContainerData {
+ direction: FlexDirection;
+ wrap: FlexWrap;
+ justifyContent: JustifyContent;
+ alignItems: AlignItems;
+ gap: Vec2;
+ padding: Vec4;
+}
+
+export const FlexContainer = defineBuiltin<FlexContainerData>('FlexContainer', {
+ direction: FlexDirection.Row,
+ wrap: FlexWrap.NoWrap,
+ justifyContent: JustifyContent.Start,
+ alignItems: AlignItems.Stretch,
+ gap: { x: 0, y: 0 },
+ padding: { x: 0, y: 0, z: 0, w: 0 },
+});
diff --git a/sdk/src/ui/FlexItem.ts b/sdk/src/ui/FlexItem.ts
new file mode 100644
index 000000000..72669aab4
--- /dev/null
+++ b/sdk/src/ui/FlexItem.ts
@@ -0,0 +1,15 @@
+import { defineBuiltin } from '../component';
+
+export interface FlexItemData {
+ flexGrow: number;
+ flexShrink: number;
+ flexBasis: number;
+ order: number;
+}
+
+export const FlexItem = defineBuiltin<FlexItemData>('FlexItem', {
+ flexGrow: 0,
+ flexShrink: 1,
+ flexBasis: -1,
+ order: 0,
+});
diff --git a/sdk/src/ui/FocusPlugin.ts b/sdk/src/ui/FocusPlugin.ts
index 48b9936c0..ea3af36c3 100644
--- a/sdk/src/ui/FocusPlugin.ts
+++ b/sdk/src/ui/FocusPlugin.ts
@@ -11,6 +11,7 @@ import { Interactable } from './Interactable';
import type { InteractableData } from './Interactable';
import { UIInteraction } from './UIInteraction';
import type { UIInteractionData } from './UIInteraction';
+import { isEditor } from '../env';
import { UIEvents, UIEventQueue } from './UIEvents';
export class FocusPlugin implements Plugin {
@@ -18,12 +19,14 @@ export class FocusPlugin implements Plugin {
registerComponent('Focusable', Focusable);
const world = app.world;
+ const editorMode = isEditor();
const focusManager = new FocusManagerState();
app.insertResource(FocusManager, focusManager);
app.addSystemToSchedule(Schedule.Update, defineSystem(
[Res(Input), Res(UIEvents)],
(input: InputState, events: UIEventQueue) => {
+ if (editorMode) return;
if (focusManager.focusedEntity !== null && !world.valid(focusManager.focusedEntity)) {
focusManager.focusedEntity = null;
}
diff --git a/sdk/src/ui/ImagePlugin.ts b/sdk/src/ui/ImagePlugin.ts
index 18d5bc7d2..f4afb01c6 100644
--- a/sdk/src/ui/ImagePlugin.ts
+++ b/sdk/src/ui/ImagePlugin.ts
@@ -13,6 +13,7 @@ import { createSnapshotUtils, type Snapshot } from './uiSnapshot';
interface ImageSource {
image: ImageData;
uiRect: UIRectData | null;
+ entity: Entity;
}
const imageSnapshot = createSnapshotUtils<ImageSource>({
@@ -29,8 +30,8 @@ const imageSnapshot = createSnapshotUtils<ImageSource>({
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,
+ rectWidth: s => s.uiRect ? getEffectiveWidth(s.uiRect, s.entity) : 0,
+ rectHeight: s => s.uiRect ? getEffectiveHeight(s.uiRect, s.entity) : 0,
enabled: s => s.image.enabled,
});
@@ -57,7 +58,7 @@ export class ImagePlugin implements Plugin {
const uiRect = world.has(entity, UIRect)
? world.get(entity, UIRect) as UIRectData
: null;
- const source: ImageSource = { image, uiRect };
+ const source: ImageSource = { image, uiRect, entity };
const prev = snapshots.get(entity);
if (prev && !imageSnapshot.changed(prev, source)) continue;
@@ -82,8 +83,8 @@ export class ImagePlugin implements Plugin {
sprite.material = image.material;
if (uiRect) {
- sprite.size.x = getEffectiveWidth(uiRect);
- sprite.size.y = getEffectiveHeight(uiRect);
+ sprite.size.x = getEffectiveWidth(uiRect, entity);
+ sprite.size.y = getEffectiveHeight(uiRect, entity);
}
sprite.uvOffset.x = 0;
diff --git a/sdk/src/ui/Interactable.ts b/sdk/src/ui/Interactable.ts
index 99e283453..545ed302b 100644
--- a/sdk/src/ui/Interactable.ts
+++ b/sdk/src/ui/Interactable.ts
@@ -1,4 +1,4 @@
-import { defineComponent } from '../component';
+import { defineBuiltin } from '../component';
export interface InteractableData {
enabled: boolean;
@@ -6,7 +6,7 @@ export interface InteractableData {
raycastTarget: boolean;
}
-export const Interactable = defineComponent<InteractableData>('Interactable', {
+export const Interactable = defineBuiltin<InteractableData>('Interactable', {
enabled: true,
blockRaycast: true,
raycastTarget: true,
diff --git a/sdk/src/ui/LayoutGroupPlugin.ts b/sdk/src/ui/LayoutGroupPlugin.ts
index adc9933c8..7ceeeed88 100644
--- a/sdk/src/ui/LayoutGroupPlugin.ts
+++ b/sdk/src/ui/LayoutGroupPlugin.ts
@@ -1,10 +1,11 @@
import type { App, Plugin } from '../app';
-import { registerComponent, Children, LocalTransform } from '../component';
-import type { ChildrenData, LocalTransformData } from '../component';
+import { registerComponent, Children, Transform } from '../component';
+import type { ChildrenData, TransformData } from '../component';
import { defineSystem, Schedule } from '../system';
import { LayoutGroup, LayoutDirection, ChildAlignment } from './LayoutGroup';
import type { LayoutGroupData } from './LayoutGroup';
import { UIRect } from './UIRect';
+import { getEffectiveWidth, getEffectiveHeight } from './uiHelpers';
import type { UIRectData } from './UIRect';
import type { Entity } from '../types';
@@ -27,7 +28,7 @@ export class LayoutGroupPlugin implements Plugin {
const validChildren: { entity: Entity; rect: UIRectData }[] = [];
for (const child of children.entities) {
- if (world.valid(child) && world.has(child, UIRect) && world.has(child, LocalTransform)) {
+ if (world.valid(child) && world.has(child, UIRect) && world.has(child, Transform)) {
validChildren.push({
entity: child,
rect: world.get(child, UIRect) as UIRectData,
@@ -40,8 +41,8 @@ export class LayoutGroupPlugin implements Plugin {
validChildren.reverse();
}
- const pw = parentRect._computedWidth ?? parentRect.size.x;
- const ph = parentRect._computedHeight ?? parentRect.size.y;
+ const pw = getEffectiveWidth(parentRect, entity);
+ const ph = getEffectiveHeight(parentRect, entity);
const pivotX = parentRect.pivot.x;
const pivotY = parentRect.pivot.y;
const pad = group.padding;
@@ -51,8 +52,8 @@ export class LayoutGroupPlugin implements Plugin {
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 cw = getEffectiveWidth(child.rect, child.entity);
+ const ch = getEffectiveHeight(child.rect, child.entity);
const cpx = child.rect.pivot.x;
const cpy = child.rect.pivot.y;
@@ -83,12 +84,10 @@ export class LayoutGroupPlugin implements Plugin {
if (i < validChildren.length - 1) cursor += group.spacing;
}
- child.rect._layoutManaged = true;
-
- const transform = world.get(child.entity, LocalTransform) as LocalTransformData;
+ const transform = world.get(child.entity, Transform) as TransformData;
transform.position.x = localX;
transform.position.y = localY;
- world.insert(child.entity, LocalTransform, transform);
+ world.insert(child.entity, Transform, transform);
}
}
},
diff --git a/sdk/src/ui/ListViewPlugin.ts b/sdk/src/ui/ListViewPlugin.ts
index ad2af9d2b..91249bed0 100644
--- a/sdk/src/ui/ListViewPlugin.ts
+++ b/sdk/src/ui/ListViewPlugin.ts
@@ -1,6 +1,6 @@
import type { App, Plugin } from '../app';
-import { registerComponent, LocalTransform, Name } from '../component';
-import type { LocalTransformData } from '../component';
+import { registerComponent, Transform, Name } from '../component';
+import type { TransformData } from '../component';
import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Input } from '../input';
@@ -9,11 +9,13 @@ import type { Entity } from '../types';
import { ListView } from './ListView';
import type { ListViewData, ListViewItemRenderer } from './ListView';
import { UIRect } from './UIRect';
+import { getEffectiveWidth, getEffectiveHeight } from './uiHelpers';
import type { UIRectData } from './UIRect';
import { Interactable } from './Interactable';
-import { UIMask } from './UIMask';
+import { UIMask, MaskMode } from './UIMask';
import { UIInteraction } from './UIInteraction';
import type { UIInteractionData } from './UIInteraction';
+import { isEditor } from '../env';
import { ensureComponent } from './uiHelpers';
import { SCROLL_WHEEL_SENSITIVITY } from './uiConstants';
@@ -50,12 +52,14 @@ export class ListViewPlugin implements Plugin {
registerComponent('ListView', ListView);
const world = app.world;
+ const editorMode = isEditor();
const listViewStates = new Map<Entity, ListViewState>();
activeListViewStates = listViewStates;
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
[Res(Input)],
(input: InputState) => {
+ if (editorMode) return;
for (const [e, st] of listViewStates) {
if (!world.valid(e)) {
for (const itemEntity of st.itemEntities.values()) {
@@ -70,7 +74,7 @@ export class ListViewPlugin implements Plugin {
const entities = world.getEntitiesWithComponents([ListView, UIRect]);
for (const entity of entities) {
ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });
- ensureComponent(world, entity, UIMask, { enabled: true, mode: 'scissor' });
+ ensureComponent(world, entity, UIMask, { enabled: true, mode: MaskMode.Scissor });
let state = listViewStates.get(entity);
if (!state) {
@@ -85,8 +89,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._computedHeight ?? rect.size.y;
- const viewWidth = rect._computedWidth ?? rect.size.x;
+ const viewHeight = getEffectiveHeight(rect, entity);
+ const viewWidth = getEffectiveWidth(rect, entity);
const interaction = world.has(entity, UIInteraction)
? world.get(entity, UIInteraction) as UIInteractionData
@@ -138,10 +142,10 @@ export class ListViewPlugin implements Plugin {
}
}
- if (world.has(itemEntity, LocalTransform)) {
- const lt = world.get(itemEntity, LocalTransform) as LocalTransformData;
+ if (world.has(itemEntity, Transform)) {
+ const lt = world.get(itemEntity, Transform) as TransformData;
lt.position.y = -(idx * lv.itemHeight - lv.scrollY);
- world.insert(itemEntity, LocalTransform, lt);
+ world.insert(itemEntity, Transform, lt);
}
}
diff --git a/sdk/src/ui/ScreenSpace.ts b/sdk/src/ui/ScreenSpace.ts
index 2c5c9d240..b0e7315d0 100644
--- a/sdk/src/ui/ScreenSpace.ts
+++ b/sdk/src/ui/ScreenSpace.ts
@@ -1,3 +1,3 @@
-import { defineTag } from '../component';
+import { defineBuiltin } from '../component';
-export const ScreenSpace = defineTag('ScreenSpace');
+export const ScreenSpace = defineBuiltin<{}>('ScreenSpace', {});
diff --git a/sdk/src/ui/ScrollViewPlugin.ts b/sdk/src/ui/ScrollViewPlugin.ts
index bdfe7492a..b717f568e 100644
--- a/sdk/src/ui/ScrollViewPlugin.ts
+++ b/sdk/src/ui/ScrollViewPlugin.ts
@@ -1,6 +1,6 @@
import type { App, Plugin } from '../app';
-import { registerComponent, LocalTransform } from '../component';
-import type { LocalTransformData } from '../component';
+import { registerComponent, Transform } from '../component';
+import type { TransformData } from '../component';
import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Input } from '../input';
@@ -11,11 +11,12 @@ import type { ScrollViewData } from './ScrollView';
import { UIRect } from './UIRect';
import type { UIRectData } from './UIRect';
import { Interactable } from './Interactable';
-import { UIMask } from './UIMask';
+import { UIMask, MaskMode } from './UIMask';
import { UIInteraction } from './UIInteraction';
import type { UIInteractionData } from './UIInteraction';
import { UICameraInfo } from './UICameraInfo';
import type { UICameraData } from './UICameraInfo';
+import { isEditor } from '../env';
import { getEffectiveWidth, getEffectiveHeight, ensureComponent } from './uiHelpers';
import {
SCROLL_VELOCITY_SMOOTHING, SCROLL_VELOCITY_NEW_WEIGHT,
@@ -36,12 +37,16 @@ export class ScrollViewPlugin implements Plugin {
registerComponent('ScrollView', ScrollView);
const world = app.world;
+ const editorMode = isEditor();
const states = new Map<Entity, ScrollState>();
let lastTime = 0;
+ const worldMouse = { x: 0, y: 0 };
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
[Res(Input), Res(UICameraInfo)],
(input: InputState, camera: UICameraData) => {
+ if (editorMode) return;
+
const now = performance.now() / 1000;
const dt = lastTime > 0 ? Math.min(now - lastTime, SCROLL_MAX_DT) : 0;
lastTime = now;
@@ -52,12 +57,13 @@ export class ScrollViewPlugin implements Plugin {
if (!world.valid(e)) states.delete(e);
}
- const worldMouse = { x: camera.worldMouseX, y: camera.worldMouseY };
+ worldMouse.x = camera.worldMouseX;
+ worldMouse.y = camera.worldMouseY;
const entities = world.getEntitiesWithComponents([ScrollView, UIRect]);
for (const entity of entities) {
ensureComponent(world, entity, Interactable, { enabled: true, blockRaycast: true });
- ensureComponent(world, entity, UIMask, { enabled: true, mode: 'scissor' });
+ ensureComponent(world, entity, UIMask, { enabled: true, mode: MaskMode.Scissor });
const sv = world.get(entity, ScrollView) as ScrollViewData;
const rect = world.get(entity, UIRect) as UIRectData;
@@ -131,8 +137,8 @@ export class ScrollViewPlugin implements Plugin {
}
}
- const viewW = getEffectiveWidth(rect);
- const viewH = getEffectiveHeight(rect);
+ const viewW = getEffectiveWidth(rect, entity);
+ const viewH = getEffectiveHeight(rect, entity);
const maxScrollX = Math.max(0, sv.contentWidth - viewW);
const maxScrollY = Math.max(0, sv.contentHeight - viewH);
const prevScrollX = sv.scrollX;
@@ -143,11 +149,11 @@ export class ScrollViewPlugin implements Plugin {
if (sv.scrollY !== prevScrollY) state.velocityY = 0;
if (sv.contentEntity !== 0 && world.valid(sv.contentEntity)) {
- if (world.has(sv.contentEntity, LocalTransform)) {
- const lt = world.get(sv.contentEntity, LocalTransform) as LocalTransformData;
+ if (world.has(sv.contentEntity, Transform)) {
+ const lt = world.get(sv.contentEntity, Transform) as TransformData;
lt.position.x = -sv.scrollX;
lt.position.y = sv.scrollY;
- world.insert(sv.contentEntity, LocalTransform, lt);
+ world.insert(sv.contentEntity, Transform, lt);
}
}
}
diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.ts
index 816e8f6cd..fe494916f 100644
--- a/sdk/src/ui/TextInputPlugin.ts
+++ b/sdk/src/ui/TextInputPlugin.ts
@@ -11,6 +11,7 @@ import { FocusManager, FocusManagerState } from './Focusable';
import { UIEvents, UIEventQueue } from './UIEvents';
import { Res } from '../resource';
import { platformCreateCanvas } from '../platform';
+import { isEditor } from '../env';
import { ensureSprite, wrapText, nextPowerOf2, ensureComponent } from './uiHelpers';
import { CURSOR_BLINK_INTERVAL, TEXT_INPUT_LINE_HEIGHT_RATIO } from './uiConstants';
@@ -27,6 +28,9 @@ export class TextInputPlugin implements Plugin {
build(app: App): void {
registerComponent('TextInput', TextInput);
+ const editorMode = isEditor();
+ if (editorMode) return;
+
const module = app.wasmModule;
if (!module) {
console.warn('TextInputPlugin: No WASM module available');
@@ -39,6 +43,9 @@ export class TextInputPlugin implements Plugin {
const ctx = canvas.getContext('2d', { willReadFrequently: true })! as
CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
+ let wasmPixelPtr = 0;
+ let wasmPixelSize = 0;
+
let composing = false;
let cursorVisible = true;
let cursorTimer = 0;
@@ -139,6 +146,11 @@ export class TextInputPlugin implements Plugin {
rm.releaseTexture(tex);
}
textureCache.clear();
+ if (wasmPixelPtr !== 0) {
+ module!._free(wasmPixelPtr);
+ wasmPixelPtr = 0;
+ wasmPixelSize = 0;
+ }
};
function syncFromTextarea(): void {
@@ -365,17 +377,23 @@ export class TextInputPlugin implements Plugin {
const imageData = ctx.getImageData(0, 0, w, h);
const pixels = new Uint8Array(imageData.data.buffer);
const rm = module!.getResourceManager();
- const ptr = module!._malloc(pixels.length);
- module!.HEAPU8.set(pixels, ptr);
+
+ if (pixels.length > wasmPixelSize) {
+ if (wasmPixelPtr !== 0) {
+ module!._free(wasmPixelPtr);
+ }
+ wasmPixelPtr = module!._malloc(pixels.length);
+ wasmPixelSize = pixels.length;
+ }
+ module!.HEAPU8.set(pixels, wasmPixelPtr);
const existingTex = textureCache.get(entity);
if (existingTex !== undefined) {
rm.releaseTexture(existingTex);
}
- const textureHandle = rm.createTexture(w, h, ptr, pixels.length, 1, true);
+ const textureHandle = rm.createTexture(w, h, wasmPixelPtr, pixels.length, 1, true);
textureCache.set(entity, textureHandle);
- module!._free(ptr);
const sprite = world.get(entity, Sprite) as SpriteData;
sprite.texture = textureHandle;
diff --git a/sdk/src/ui/TextPlugin.ts b/sdk/src/ui/TextPlugin.ts
index 16369bd97..009790601 100644
--- a/sdk/src/ui/TextPlugin.ts
+++ b/sdk/src/ui/TextPlugin.ts
@@ -11,6 +11,7 @@ import { createSnapshotUtils, type Snapshot } from './uiSnapshot';
interface TextSource {
text: TextData;
uiRect: UIRectData | null;
+ entity: Entity;
}
const textSnapshot = createSnapshotUtils<TextSource>({
@@ -26,8 +27,8 @@ const textSnapshot = createSnapshotUtils<TextSource>({
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,
+ containerWidth: s => s.uiRect ? getEffectiveWidth(s.uiRect, s.entity) : 0,
+ containerHeight: s => s.uiRect ? getEffectiveHeight(s.uiRect, s.entity) : 0,
});
export class TextPlugin implements Plugin {
@@ -68,7 +69,7 @@ export class TextPlugin implements Plugin {
const uiRect = world.has(entity, UIRect)
? world.get(entity, UIRect) as UIRectData
: null;
- const source: TextSource = { text, uiRect };
+ const source: TextSource = { text, uiRect, entity };
const prev = snapshots.get(entity);
if (prev && !textSnapshot.changed(prev, source)) continue;
diff --git a/sdk/src/ui/TogglePlugin.ts b/sdk/src/ui/TogglePlugin.ts
index 7c96528da..6b1c9ac4c 100644
--- a/sdk/src/ui/TogglePlugin.ts
+++ b/sdk/src/ui/TogglePlugin.ts
@@ -13,6 +13,7 @@ import type { ToggleData } from './Toggle';
import { ToggleGroup } from './ToggleGroup';
import type { ToggleGroupData } from './ToggleGroup';
import { UIEvents, UIEventQueue } from './UIEvents';
+import { isEditor } from '../env';
import { applyColorTransition, ensureComponent } from './uiHelpers';
export class TogglePlugin implements Plugin {
@@ -21,6 +22,7 @@ export class TogglePlugin implements Plugin {
registerComponent('ToggleGroup', ToggleGroup);
const world = app.world;
+ const editorMode = isEditor();
const initializedEntities = new Set<Entity>();
app.addSystemToSchedule(Schedule.Update, defineSystem(
@@ -28,68 +30,87 @@ export class TogglePlugin implements Plugin {
(events: UIEventQueue) => {
const toggleEntities = world.getEntitiesWithComponents([Toggle]);
- const groupFirstOn = new Map<Entity, Entity>();
- for (const entity of toggleEntities) {
- 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;
+ if (!editorMode) {
+ const groupFirstOn = new Map<Entity, Entity>();
+ for (const entity of toggleEntities) {
+ 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;
+ world.insert(entity, Toggle, toggle);
+ }
}
- }
- const togglesByGroup = new Map<Entity, Entity[]>();
- for (const entity of toggleEntities) {
- const toggle = world.get(entity, Toggle) as ToggleData;
- if (toggle.group !== 0 && world.valid(toggle.group)) {
- let group = togglesByGroup.get(toggle.group);
- if (!group) {
- group = [];
- togglesByGroup.set(toggle.group, group);
+ const togglesByGroup = new Map<Entity, Entity[]>();
+ for (const entity of toggleEntities) {
+ const toggle = world.get(entity, Toggle) as ToggleData;
+ if (toggle.group !== 0 && world.valid(toggle.group)) {
+ let group = togglesByGroup.get(toggle.group);
+ if (!group) {
+ group = [];
+ togglesByGroup.set(toggle.group, group);
+ }
+ group.push(entity);
}
- group.push(entity);
}
- }
- for (const entity of toggleEntities) {
- ensureComponent(world, entity, Interactable, { enabled: true });
- if (!world.has(entity, UIInteraction)) continue;
+ 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;
- const toggle = world.get(entity, Toggle) as ToggleData;
- const interactable = world.get(entity, Interactable) as InteractableData;
+ const interaction = world.get(entity, UIInteraction) as UIInteractionData;
+ const toggle = world.get(entity, Toggle) as ToggleData;
+ 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 (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;
- }
+ if (toggle.isOn && hasGroup) {
+ const group = world.get(groupEntity, ToggleGroup) as ToggleGroupData;
+ if (!group.allowSwitchOff) continue;
+ }
- toggle.isOn = !toggle.isOn;
+ toggle.isOn = !toggle.isOn;
+ world.insert(entity, Toggle, toggle);
- if (toggle.isOn && hasGroup) {
- const siblings = togglesByGroup.get(groupEntity);
- if (siblings) {
- for (const other of siblings) {
- if (other === entity) continue;
- const otherToggle = world.get(other, Toggle) as ToggleData;
- if (otherToggle.isOn) {
- otherToggle.isOn = false;
- events.emit(other, 'change');
+ if (toggle.isOn && hasGroup) {
+ const siblings = togglesByGroup.get(groupEntity);
+ if (siblings) {
+ for (const other of siblings) {
+ if (other === entity) continue;
+ const otherToggle = world.get(other, Toggle) as ToggleData;
+ if (otherToggle.isOn) {
+ otherToggle.isOn = false;
+ world.insert(other, Toggle, otherToggle);
+ events.emit(other, 'change');
+ }
}
}
}
+
+ events.emit(entity, 'change');
}
- events.emit(entity, 'change');
+ if (toggle.transition && world.has(entity, Sprite)) {
+ const sprite = world.get(entity, Sprite) as SpriteData;
+ sprite.color = applyColorTransition(
+ toggle.transition,
+ interactable.enabled,
+ interaction.pressed,
+ interaction.hovered,
+ );
+ world.insert(entity, Sprite, sprite);
+ }
}
+ }
+ for (const entity of toggleEntities) {
+ const toggle = world.get(entity, Toggle) as ToggleData;
if (toggle.graphicEntity && world.valid(toggle.graphicEntity)) {
if (world.has(toggle.graphicEntity, Sprite)) {
const sprite = world.get(toggle.graphicEntity, Sprite) as SpriteData;
@@ -97,17 +118,6 @@ export class TogglePlugin implements Plugin {
world.insert(toggle.graphicEntity, Sprite, sprite);
}
}
-
- if (toggle.transition && world.has(entity, Sprite)) {
- const sprite = world.get(entity, Sprite) as SpriteData;
- sprite.color = applyColorTransition(
- toggle.transition,
- interactable.enabled,
- interaction.pressed,
- interaction.hovered,
- );
- world.insert(entity, Sprite, sprite);
- }
}
},
{ name: 'ToggleSystem' }
diff --git a/sdk/src/ui/UIInteraction.ts b/sdk/src/ui/UIInteraction.ts
index ce5a2eea3..d68703175 100644
--- a/sdk/src/ui/UIInteraction.ts
+++ b/sdk/src/ui/UIInteraction.ts
@@ -1,4 +1,4 @@
-import { defineComponent } from '../component';
+import { defineBuiltin } from '../component';
export interface UIInteractionData {
hovered: boolean;
@@ -7,7 +7,7 @@ export interface UIInteractionData {
justReleased: boolean;
}
-export const UIInteraction = defineComponent<UIInteractionData>('UIInteraction', {
+export const UIInteraction = defineBuiltin<UIInteractionData>('UIInteraction', {
hovered: false,
pressed: false,
justPressed: false,
diff --git a/sdk/src/ui/UIInteractionPlugin.ts b/sdk/src/ui/UIInteractionPlugin.ts
index 726aaa3c9..5e5c9d59d 100644
--- a/sdk/src/ui/UIInteractionPlugin.ts
+++ b/sdk/src/ui/UIInteractionPlugin.ts
@@ -1,62 +1,30 @@
import type { App, Plugin } from '../app';
-import { registerComponent, WorldTransform, Sprite } from '../component';
-import type { WorldTransformData, SpriteData } from '../component';
+import { registerComponent, Transform, Sprite } from '../component';
+import type { SpriteData } from '../component';
import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Input } from '../input';
import type { InputState } from '../input';
import type { Entity } from '../types';
import type { World } from '../world';
+import { isEditor } from '../env';
import { Interactable } from './Interactable';
-import type { InteractableData } from './Interactable';
import { UIInteraction } from './UIInteraction';
import type { UIInteractionData } from './UIInteraction';
-import { UIRect } from './UIRect';
-import type { UIRectData } from './UIRect';
import { Button, ButtonState } from './Button';
import type { ButtonData } from './Button';
import { UIEvents, UIEventQueue } from './UIEvents';
import type { UIEventType } from './UIEvents';
import { UICameraInfo } from './UICameraInfo';
import type { UICameraData } from './UICameraInfo';
-import { UIMask } from './UIMask';
-import type { UIMaskData } from './UIMask';
-import { screenToWorld, pointInOBB, createInvVPCache } from './uiMath';
+import type { InteractableData } from './Interactable';
+import { screenToWorld, createInvVPCache } from './uiMath';
import { platformDevicePixelRatio } from '../platform';
-import { applyColorTransition, getEffectiveWidth, getEffectiveHeight, ensureComponent, walkParentChain } from './uiHelpers';
+import { applyColorTransition, ensureComponent, walkParentChain } from './uiHelpers';
+import type { ESEngineModule, CppRegistry } from '../wasm';
const vpCache = createInvVPCache();
-function isClippedByMask(
- world: World,
- entity: Entity,
- worldMouseX: number,
- worldMouseY: number,
-): boolean {
- let clipped = false;
- walkParentChain(world, entity, (ancestor) => {
- if (!world.has(ancestor, UIMask)) return false;
- const mask = world.get(ancestor, UIMask) as UIMaskData;
- if (!mask.enabled || !world.has(ancestor, UIRect) || !world.has(ancestor, WorldTransform)) return false;
- const wt = world.get(ancestor, WorldTransform) as WorldTransformData;
- const rect = world.get(ancestor, UIRect) as UIRectData;
- 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,
- )) {
- clipped = true;
- return true;
- }
- return false;
- });
- return clipped;
-}
-
function emitWithBubbling(
world: World,
events: UIEventQueue,
@@ -81,9 +49,13 @@ export class UIInteractionPlugin implements Plugin {
registerComponent('Button', Button);
const world = app.world;
+ const module = app.wasmModule as ESEngineModule;
+ const registry = world.getCppRegistry() as CppRegistry;
const events = new UIEventQueue();
app.insertResource(UIEvents, events);
+ const editorMode = isEditor();
+
let hoveredEntity: Entity | null = null;
let pressedEntity: Entity | null = null;
@@ -92,11 +64,16 @@ export class UIInteractionPlugin implements Plugin {
(input: InputState, camera: UICameraData) => {
events.drain();
+ if (editorMode) return;
+
const interactionEntities = world.getEntitiesWithComponents([UIInteraction]);
for (const entity of interactionEntities) {
const interaction = world.get(entity, UIInteraction) as UIInteractionData;
- interaction.justPressed = false;
- interaction.justReleased = false;
+ if (interaction.justPressed || interaction.justReleased) {
+ interaction.justPressed = false;
+ interaction.justReleased = false;
+ world.insert(entity, UIInteraction, interaction);
+ }
}
if (!camera.valid) return;
@@ -115,46 +92,18 @@ export class UIInteractionPlugin implements Plugin {
camera.worldMouseX = worldMouse.x;
camera.worldMouseY = worldMouse.y;
- const interactableEntities = world.getEntitiesWithComponents(
- [Interactable, UIRect, WorldTransform]
- );
-
- let hitEntity: Entity | null = null;
- let hitLayer = -Infinity;
+ const mouseDown = input.isMouseButtonDown(0);
+ const mousePressed = input.isMouseButtonPressed(0);
+ const mouseReleased = input.isMouseButtonReleased(0);
- for (const entity of interactableEntities) {
- ensureComponent(world, entity, UIInteraction);
-
- 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;
- const worldW = getEffectiveWidth(rect) * wt.scale.x;
- const worldH = getEffectiveHeight(rect) * wt.scale.y;
-
- if (pointInOBB(
- worldMouse.x, worldMouse.y,
- wt.position.x, wt.position.y,
- worldW, worldH,
- rect.pivot.x, rect.pivot.y,
- wt.rotation.z, wt.rotation.w,
- )) {
- if (isClippedByMask(world, entity, worldMouse.x, worldMouse.y)) {
- continue;
- }
+ module.uiHitTest_update(
+ registry,
+ worldMouse.x, worldMouse.y,
+ mouseDown, mousePressed, mouseReleased,
+ );
- let layer = 0;
- if (world.has(entity, Sprite)) {
- layer = (world.get(entity, Sprite) as SpriteData).layer;
- }
- if (layer > hitLayer) {
- hitLayer = layer;
- hitEntity = entity;
- }
- }
- }
+ const hitEntityRaw = module.uiHitTest_getHitEntity();
+ const hitEntity: Entity | null = hitEntityRaw === 0xFFFFFFFF ? null : hitEntityRaw;
if (hoveredEntity !== null && !world.valid(hoveredEntity)) {
hoveredEntity = null;
@@ -164,29 +113,34 @@ export class UIInteractionPlugin implements Plugin {
if (hoveredEntity !== null && world.valid(hoveredEntity) && world.has(hoveredEntity, UIInteraction)) {
const prev = world.get(hoveredEntity, UIInteraction) as UIInteractionData;
prev.hovered = false;
+ world.insert(hoveredEntity, UIInteraction, prev);
events.emit(hoveredEntity, 'hover_exit');
}
if (hitEntity !== null) {
+ ensureComponent(world, hitEntity, UIInteraction);
const curr = world.get(hitEntity, UIInteraction) as UIInteractionData;
curr.hovered = true;
+ world.insert(hitEntity, UIInteraction, curr);
events.emit(hitEntity, 'hover_enter');
}
hoveredEntity = hitEntity;
}
- if (input.isMouseButtonPressed(0) && hitEntity !== null) {
+ if (mousePressed && hitEntity !== null) {
const interaction = world.get(hitEntity, UIInteraction) as UIInteractionData;
interaction.pressed = true;
interaction.justPressed = true;
+ world.insert(hitEntity, UIInteraction, interaction);
pressedEntity = hitEntity;
emitWithBubbling(world, events, hitEntity, 'press');
}
- if (input.isMouseButtonReleased(0) && pressedEntity !== null) {
+ if (mouseReleased && pressedEntity !== null) {
if (world.valid(pressedEntity) && world.has(pressedEntity, UIInteraction)) {
const interaction = world.get(pressedEntity, UIInteraction) as UIInteractionData;
interaction.pressed = false;
interaction.justReleased = true;
+ world.insert(pressedEntity, UIInteraction, interaction);
emitWithBubbling(world, events, pressedEntity, 'release');
if (pressedEntity === hoveredEntity) {
emitWithBubbling(world, events, pressedEntity, 'click');
diff --git a/sdk/src/ui/UILayoutPlugin.ts b/sdk/src/ui/UILayoutPlugin.ts
index ad875e9d5..e12de84b0 100644
--- a/sdk/src/ui/UILayoutPlugin.ts
+++ b/sdk/src/ui/UILayoutPlugin.ts
@@ -1,202 +1,45 @@
import type { App, Plugin } from '../app';
-import { registerComponent, LocalTransform, Children, Parent, Sprite } from '../component';
-import type { LocalTransformData, ChildrenData, ParentData, SpriteData } from '../component';
+import { registerComponent } from '../component';
import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { UIRect } from './UIRect';
-import type { UIRectData } from './UIRect';
-import { ScreenSpace } from './ScreenSpace';
import { UICameraInfo } from './UICameraInfo';
import type { UICameraData } from './UICameraInfo';
-import type { Entity } from '../types';
-import type { World } from '../world';
-import { computeUIRectLayout, type LayoutRect } from './uiLayout';
-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;
- while (true) {
- if (world.has(current, ScreenSpace)) return current;
- if (!world.has(current, Parent)) return null;
- const parent = world.get(current, Parent) as ParentData;
- if (!world.valid(parent.entity)) return null;
- current = parent.entity;
- }
-}
-
-function layoutEntity(
- world: World,
- entity: Entity,
- parentRect: LayoutRect,
- parentOriginX: number,
- parentOriginY: number,
- isRoot: boolean,
-): 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) {
- 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);
- }
-
- if (!world.has(entity, Children)) return;
-
- const children = world.get(entity, Children) as ChildrenData;
- if (!children || !children.entities) return;
-
- for (const child of children.entities) {
- if (world.valid(child)) {
- layoutEntity(world, child, result.rect, result.originX, result.originY, false);
- }
- }
-}
+import type { ESEngineModule } from '../wasm';
+import type { CppRegistry } from '../wasm';
+import { initUIHelpers } from './uiHelpers';
export class UILayoutPlugin implements Plugin {
build(app: App): void {
registerComponent('UIRect', UIRect);
const world = app.world;
- const snapshots = new Map<Entity, Snapshot>();
- const rootCache = new Map<Entity, Entity | null>();
- let prevCameraLeft = NaN;
- let prevCameraBottom = NaN;
- let prevCameraRight = NaN;
- let prevCameraTop = NaN;
+ const module = app.wasmModule as ESEngineModule;
+ const registry = world.getCppRegistry() as CppRegistry;
- 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;
- }
+ initUIHelpers(module, registry);
- 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);
- }
- }
- }
+ const layoutFn = (camera: UICameraData) => {
+ if (!camera.valid) return;
+ module.uiLayout_update(
+ registry,
+ camera.worldLeft, camera.worldBottom,
+ camera.worldRight, camera.worldTop,
+ );
+ module.uiFlexLayout_update(registry);
+ };
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
[Res(UICameraInfo)],
- (camera: UICameraData) => {
- if (!camera.valid) return;
-
- const cameraRect: LayoutRect = {
- left: camera.worldLeft,
- bottom: camera.worldBottom,
- right: camera.worldRight,
- top: camera.worldTop,
- };
- const cameraOriginX = (cameraRect.left + cameraRect.right) * 0.5;
- const cameraOriginY = (cameraRect.bottom + cameraRect.top) * 0.5;
-
- const cameraChanged = prevCameraLeft !== camera.worldLeft
- || prevCameraBottom !== camera.worldBottom
- || prevCameraRight !== camera.worldRight
- || prevCameraTop !== camera.worldTop;
-
- prevCameraLeft = camera.worldLeft;
- prevCameraBottom = camera.worldBottom;
- prevCameraRight = camera.worldRight;
- prevCameraTop = camera.worldTop;
-
- 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 (rect._dirty || !snap || rectSnapshot.changed(snap, rect)) {
- rect._dirty = false;
- clearSubtreeCache(entity);
- const root = getCachedRoot(entity);
- if (root !== null) {
- dirtyRoots.add(root);
- }
- }
- }
-
- for (const root of dirtyRoots) {
- 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) {
- rectSnapshot.update(existing, rect);
- } else {
- snapshots.set(entity, rectSnapshot.take(rect));
- }
- }
- },
+ layoutFn,
{ name: 'UILayoutSystem' }
));
+
+ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(
+ [Res(UICameraInfo)],
+ layoutFn,
+ { name: 'UILayoutLateSystem' }
+ ), { runBefore: ['UIRenderOrderSystem'] });
}
}
diff --git a/sdk/src/ui/UIMask.ts b/sdk/src/ui/UIMask.ts
index b37c0eea9..fd647506c 100644
--- a/sdk/src/ui/UIMask.ts
+++ b/sdk/src/ui/UIMask.ts
@@ -1,13 +1,17 @@
-import { defineComponent } from '../component';
+import { defineBuiltin } from '../component';
-export type MaskMode = 'scissor' | 'stencil';
+export const MaskMode = {
+ Scissor: 0,
+ Stencil: 1,
+} as const;
+export type MaskMode = (typeof MaskMode)[keyof typeof MaskMode];
export interface UIMaskData {
enabled: boolean;
mode: MaskMode;
}
-export const UIMask = defineComponent<UIMaskData>('UIMask', {
+export const UIMask = defineBuiltin<UIMaskData>('UIMask', {
enabled: true,
- mode: 'scissor',
+ mode: MaskMode.Scissor,
});
diff --git a/sdk/src/ui/UIMaskPlugin.ts b/sdk/src/ui/UIMaskPlugin.ts
index 40fa9e7b7..67d2e3559 100644
--- a/sdk/src/ui/UIMaskPlugin.ts
+++ b/sdk/src/ui/UIMaskPlugin.ts
@@ -3,9 +3,9 @@ import type { ESEngineModule, CppRegistry } from '../wasm';
import type { MaskProcessorFn } from '../renderPipeline';
import type { Entity } from '../types';
import type { World } from '../world';
-import { registerComponent, WorldTransform } from '../component';
-import type { WorldTransformData } from '../component';
-import { UIMask, type UIMaskData } from './UIMask';
+import { registerComponent, Transform } from '../component';
+import type { TransformData } from '../component';
+import { UIMask, MaskMode, type UIMaskData } from './UIMask';
import { UIRect, type UIRectData } from './UIRect';
import { intersectRects, quaternionToAngle2D, worldToScreen, type ScreenRect } from './uiMath';
import { getEffectiveWidth, getEffectiveHeight, walkParentChain } from './uiHelpers';
@@ -14,15 +14,15 @@ function computeMaskScreenRect(
world: World, entity: Entity,
vp: Float32Array, vpX: number, vpY: number, vpW: number, vpH: number
): ScreenRect | null {
- if (!world.has(entity, UIRect) || !world.has(entity, WorldTransform)) {
+ if (!world.has(entity, UIRect) || !world.has(entity, Transform)) {
return null;
}
const uiRect = world.get(entity, UIRect) as UIRectData;
- const wt = world.get(entity, WorldTransform) as WorldTransformData;
- 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 wt = world.get(entity, Transform) as TransformData;
+ const worldW = getEffectiveWidth(uiRect, entity) * wt.worldScale.x;
+ const worldH = getEffectiveHeight(uiRect, entity) * wt.worldScale.y;
+ const cx = wt.worldPosition.x;
+ const cy = wt.worldPosition.y;
const px = uiRect.pivot.x;
const py = uiRect.pivot.y;
@@ -31,8 +31,8 @@ function computeMaskScreenRect(
const localBottom = -worldH * py;
const localTop = worldH * (1 - py);
- const rz = wt.rotation.z;
- const rw = wt.rotation.w;
+ const rz = wt.worldRotation.z;
+ const rw = wt.worldRotation.w;
const angle = quaternionToAngle2D(rz, rw);
const cos = Math.cos(angle);
const sin = Math.sin(angle);
@@ -83,7 +83,7 @@ export function createMaskProcessor(wasm: ESEngineModule, world: World): MaskPro
const mask = world.get(e, UIMask) as UIMaskData;
if (!mask.enabled) continue;
maskSet.add(e as number);
- if (mask.mode === 'stencil') {
+ if (mask.mode === MaskMode.Stencil) {
stencilMasks.push(e);
stencilMaskSet.add(e as number);
} else {
@@ -117,7 +117,7 @@ function processScissorMasks(
walkParentChain(world, entity, (ancestor) => {
if (maskSet.has(ancestor as number)) {
const parentMask = world.get(ancestor, UIMask) as UIMaskData;
- if (parentMask.mode === 'scissor') {
+ if (parentMask.mode === MaskMode.Scissor) {
isRoot = false;
return true;
}
@@ -134,7 +134,7 @@ function processScissorMasks(
if (maskSet.has(childId)) {
const childMask = world.get(childId as Entity, UIMask) as UIMaskData;
- if (childMask.mode === 'scissor') {
+ if (childMask.mode === MaskMode.Scissor) {
const childRect = computeMaskScreenRect(
world, childId as Entity,
vp, vpX, vpY, vpW, vpH
diff --git a/sdk/src/ui/UIRect.ts b/sdk/src/ui/UIRect.ts
index 9dcb67570..1ddc18c93 100644
--- a/sdk/src/ui/UIRect.ts
+++ b/sdk/src/ui/UIRect.ts
@@ -1,4 +1,4 @@
-import { defineComponent } from '../component';
+import { defineBuiltin } from '../component';
import type { Vec2 } from '../types';
export interface UIRectData {
@@ -8,21 +8,13 @@ export interface UIRectData {
offsetMax: Vec2;
size: Vec2;
pivot: Vec2;
- _dirty: boolean;
- _computedWidth?: number;
- _computedHeight?: number;
- _layoutManaged?: boolean;
}
-export const UIRect = defineComponent<UIRectData>('UIRect', {
+export const UIRect = defineBuiltin<UIRectData>('UIRect', {
anchorMin: { x: 0.5, y: 0.5 },
anchorMax: { x: 0.5, y: 0.5 },
offsetMin: { x: 0, y: 0 },
offsetMax: { x: 0, y: 0 },
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.ts
index bb973cb95..4f81c6f84 100644
--- a/sdk/src/ui/UIRenderOrderPlugin.ts
+++ b/sdk/src/ui/UIRenderOrderPlugin.ts
@@ -1,45 +1,17 @@
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;
-}
+import type { ESEngineModule, CppRegistry } from '../wasm';
export class UIRenderOrderPlugin implements Plugin {
build(app: App): void {
const world = app.world;
+ const module = app.wasmModule as ESEngineModule;
+ const registry = world.getCppRegistry() as CppRegistry;
app.addSystemToSchedule(Schedule.PostUpdate, defineSystem(
[],
() => {
- let counter = 0;
- const roots = world.getEntitiesWithComponents([ScreenSpace, UIRect]);
- for (const root of roots) {
- counter = assignRenderOrder(world, root, counter);
- }
+ module.uiRenderOrder_update(registry);
},
{ name: 'UIRenderOrderSystem' }
));
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 06e08a3dc..371045157 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -11,6 +11,7 @@ export {
// Shared Helpers
export {
+ initUIHelpers,
ensureSprite,
computeFillAnchors,
computeHandleAnchors,
@@ -79,7 +80,7 @@ export {
// UIMask Component
export {
UIMask,
- type MaskMode,
+ MaskMode,
type UIMaskData,
} from './UIMask';
@@ -325,6 +326,22 @@ export {
layoutGroupPlugin,
} from './LayoutGroupPlugin';
+// FlexContainer Component
+export {
+ FlexContainer,
+ FlexDirection,
+ FlexWrap,
+ JustifyContent,
+ AlignItems,
+ type FlexContainerData,
+} from './FlexContainer';
+
+// FlexItem Component
+export {
+ FlexItem,
+ type FlexItemData,
+} from './FlexItem';
+
// UIRenderOrder Plugin
export {
UIRenderOrderPlugin,
diff --git a/sdk/src/ui/uiHelpers.ts b/sdk/src/ui/uiHelpers.ts
index 04787f1fb..6f9665a18 100644
--- a/sdk/src/ui/uiHelpers.ts
+++ b/sdk/src/ui/uiHelpers.ts
@@ -1,5 +1,5 @@
-import { Sprite, Parent, LocalTransform } from '../component';
-import type { ParentData, SpriteData, LocalTransformData, AnyComponentDef } from '../component';
+import { Sprite, Parent, Transform } from '../component';
+import type { ParentData, SpriteData, TransformData, AnyComponentDef } from '../component';
import { computeUIRectLayout, type LayoutRect } from './uiLayout';
import { INVALID_TEXTURE } from '../types';
import type { Entity, Color } from '../types';
@@ -8,6 +8,15 @@ import { UIRect } from './UIRect';
import type { UIRectData } from './UIRect';
import { FillDirection } from './uiTypes';
import type { ColorTransition } from './uiTypes';
+import type { ESEngineModule, CppRegistry } from '../wasm';
+
+let module_: ESEngineModule | null = null;
+let nativeRegistry_: CppRegistry | null = null;
+
+export function initUIHelpers(module: ESEngineModule, registry: CppRegistry): void {
+ module_ = module;
+ nativeRegistry_ = registry;
+}
export function ensureSprite(world: World, entity: Entity): void {
if (!world.has(entity, Sprite)) {
@@ -189,12 +198,20 @@ export function getEntityDepth(world: World, entity: Entity): number {
return depth;
}
-export function getEffectiveWidth(rect: UIRectData): number {
- return rect._computedWidth ?? rect.size.x;
+export function getEffectiveWidth(rect: UIRectData, entity: Entity): number {
+ if (module_ && nativeRegistry_) {
+ const w = module_.getUIRectComputedWidth(nativeRegistry_, entity);
+ if (w > 0) return w;
+ }
+ return rect.size.x;
}
-export function getEffectiveHeight(rect: UIRectData): number {
- return rect._computedHeight ?? rect.size.y;
+export function getEffectiveHeight(rect: UIRectData, entity: Entity): number {
+ if (module_ && nativeRegistry_) {
+ const h = module_.getUIRectComputedHeight(nativeRegistry_, entity);
+ if (h > 0) return h;
+ }
+ return rect.size.y;
}
export function syncFillSpriteSize(
@@ -265,8 +282,6 @@ export function layoutChildEntity(
);
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;
@@ -277,10 +292,33 @@ export function layoutChildEntity(
}
}
- if (!rect._layoutManaged && world.has(entity, LocalTransform)) {
- const transform = world.get(entity, LocalTransform) as LocalTransformData;
+ if (world.has(entity, Transform)) {
+ const transform = world.get(entity, Transform) as TransformData;
transform.position.x = result.originX - parentOriginX;
transform.position.y = result.originY - parentOriginY;
- world.insert(entity, LocalTransform, transform);
+ world.insert(entity, Transform, transform);
+ }
+}
+
+export function syncChildSpriteSize(
+ world: World, entity: Entity,
+ parentRect: LayoutRect,
+): void {
+ if (!world.has(entity, UIRect) || !world.has(entity, Sprite)) 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;
+
+ 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);
}
}
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index 6a830de7f..6569978a4 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -10,6 +10,15 @@ import type { Entity, Vec2, Vec3, Vec4, Quat } from './types';
export interface UVec2 { x: number; y: number; }
export type Mat4 = number[];
+// Emscripten Vector Types
+export interface VectorEntity {
+ size(): number;
+ get(index: number): number;
+ push_back(value: number): void;
+ set(index: number, value: number): boolean;
+ delete(): void;
+}
+
// Enums
export enum BodyType {
@@ -24,6 +33,39 @@ export enum TextAlign {
Right = 2,
}
+export enum MaskMode {
+ Scissor = 0,
+ Stencil = 1,
+}
+
+export enum FlexDirection {
+ Row = 0,
+ Column = 1,
+ RowReverse = 2,
+ ColumnReverse = 3,
+}
+
+export enum FlexWrap {
+ NoWrap = 0,
+ Wrap = 1,
+}
+
+export enum JustifyContent {
+ Start = 0,
+ Center = 1,
+ End = 2,
+ SpaceBetween = 3,
+ SpaceAround = 4,
+ SpaceEvenly = 5,
+}
+
+export enum AlignItems {
+ Start = 0,
+ Center = 1,
+ End = 2,
+ Stretch = 3,
+}
+
export enum CanvasScaleMode {
FixedWidth = 0,
FixedHeight = 1,
@@ -39,6 +81,22 @@ export enum ProjectionType {
// Components
+export interface UIRect {
+ anchorMin: Vec2;
+ anchorMax: Vec2;
+ offsetMin: Vec2;
+ offsetMax: Vec2;
+ size: Vec2;
+ pivot: Vec2;
+}
+
+export interface FlexItem {
+ flexGrow: number;
+ flexShrink: number;
+ flexBasis: number;
+ order: number;
+}
+
export interface BoxCollider {
halfExtents: Vec2;
offset: Vec2;
@@ -70,16 +128,13 @@ export interface CapsuleCollider {
enabled: boolean;
}
-export interface LocalTransform {
- position: Vec3;
- rotation: Quat;
- scale: Vec3;
-}
-
-export interface WorldTransform {
+export interface Transform {
position: Vec3;
rotation: Quat;
scale: Vec3;
+ worldPosition: Vec3;
+ worldRotation: Quat;
+ worldScale: Vec3;
}
export interface Velocity {
@@ -104,6 +159,19 @@ export interface SpineAnimation {
enabled: boolean;
}
+export interface Interactable {
+ enabled: boolean;
+ blockRaycast: boolean;
+ raycastTarget: boolean;
+}
+
+export interface UIInteraction {
+ hovered: boolean;
+ pressed: boolean;
+ justPressed: boolean;
+ justReleased: boolean;
+}
+
export interface RigidBody {
bodyType: number;
gravityScale: number;
@@ -138,11 +206,29 @@ export interface Sprite {
enabled: boolean;
}
+export interface UIMask {
+ enabled: boolean;
+ mode: number;
+}
+
+export interface FlexContainer {
+ direction: number;
+ wrap: number;
+ justifyContent: number;
+ alignItems: number;
+ gap: Vec2;
+ padding: Vec4;
+}
+
export interface Parent {
entity: number;
}
export interface Children {
+ entities: VectorEntity;
+}
+
+export interface ScreenSpace {
}
export interface Canvas {
@@ -176,6 +262,14 @@ export interface Registry {
valid(entity: Entity): boolean;
entityCount(): number;
+ hasUIRect(entity: Entity): boolean;
+ getUIRect(entity: Entity): UIRect;
+ addUIRect(entity: Entity, component: UIRect): void;
+ removeUIRect(entity: Entity): void;
+ hasFlexItem(entity: Entity): boolean;
+ getFlexItem(entity: Entity): FlexItem;
+ addFlexItem(entity: Entity, component: FlexItem): void;
+ removeFlexItem(entity: Entity): void;
hasBoxCollider(entity: Entity): boolean;
getBoxCollider(entity: Entity): BoxCollider;
addBoxCollider(entity: Entity, component: BoxCollider): void;
@@ -188,14 +282,10 @@ export interface Registry {
getCapsuleCollider(entity: Entity): CapsuleCollider;
addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
removeCapsuleCollider(entity: Entity): void;
- hasLocalTransform(entity: Entity): boolean;
- getLocalTransform(entity: Entity): LocalTransform;
- addLocalTransform(entity: Entity, component: LocalTransform): void;
- removeLocalTransform(entity: Entity): void;
- hasWorldTransform(entity: Entity): boolean;
- getWorldTransform(entity: Entity): WorldTransform;
- addWorldTransform(entity: Entity, component: WorldTransform): void;
- removeWorldTransform(entity: Entity): void;
+ hasTransform(entity: Entity): boolean;
+ getTransform(entity: Entity): Transform;
+ addTransform(entity: Entity, component: Transform): void;
+ removeTransform(entity: Entity): void;
hasVelocity(entity: Entity): boolean;
getVelocity(entity: Entity): Velocity;
addVelocity(entity: Entity, component: Velocity): void;
@@ -204,6 +294,14 @@ export interface Registry {
getSpineAnimation(entity: Entity): SpineAnimation;
addSpineAnimation(entity: Entity, component: SpineAnimation): void;
removeSpineAnimation(entity: Entity): void;
+ hasInteractable(entity: Entity): boolean;
+ getInteractable(entity: Entity): Interactable;
+ addInteractable(entity: Entity, component: Interactable): void;
+ removeInteractable(entity: Entity): void;
+ hasUIInteraction(entity: Entity): boolean;
+ getUIInteraction(entity: Entity): UIInteraction;
+ addUIInteraction(entity: Entity, component: UIInteraction): void;
+ removeUIInteraction(entity: Entity): void;
hasRigidBody(entity: Entity): boolean;
getRigidBody(entity: Entity): RigidBody;
addRigidBody(entity: Entity, component: RigidBody): void;
@@ -216,6 +314,14 @@ export interface Registry {
getSprite(entity: Entity): Sprite;
addSprite(entity: Entity, component: Sprite): void;
removeSprite(entity: Entity): void;
+ hasUIMask(entity: Entity): boolean;
+ getUIMask(entity: Entity): UIMask;
+ addUIMask(entity: Entity, component: UIMask): void;
+ removeUIMask(entity: Entity): void;
+ hasFlexContainer(entity: Entity): boolean;
+ getFlexContainer(entity: Entity): FlexContainer;
+ addFlexContainer(entity: Entity, component: FlexContainer): void;
+ removeFlexContainer(entity: Entity): void;
hasParent(entity: Entity): boolean;
getParent(entity: Entity): Parent;
addParent(entity: Entity, component: Parent): void;
@@ -224,6 +330,10 @@ export interface Registry {
getChildren(entity: Entity): Children;
addChildren(entity: Entity, component: Children): void;
removeChildren(entity: Entity): void;
+ hasScreenSpace(entity: Entity): boolean;
+ getScreenSpace(entity: Entity): ScreenSpace;
+ addScreenSpace(entity: Entity, component: ScreenSpace): void;
+ removeScreenSpace(entity: Entity): void;
hasCanvas(entity: Entity): boolean;
getCanvas(entity: Entity): Canvas;
addCanvas(entity: Entity, component: Canvas): void;
@@ -240,18 +350,24 @@ export interface Registry {
// Module
export interface ESEngineModule {
Registry: new () => Registry;
+ UIRect: new () => UIRect;
+ FlexItem: new () => FlexItem;
BoxCollider: new () => BoxCollider;
CircleCollider: new () => CircleCollider;
CapsuleCollider: new () => CapsuleCollider;
- LocalTransform: new () => LocalTransform;
- WorldTransform: new () => WorldTransform;
+ Transform: new () => Transform;
Velocity: new () => Velocity;
SpineAnimation: new () => SpineAnimation;
+ Interactable: new () => Interactable;
+ UIInteraction: new () => UIInteraction;
RigidBody: new () => RigidBody;
BitmapText: new () => BitmapText;
Sprite: new () => Sprite;
+ UIMask: new () => UIMask;
+ FlexContainer: new () => FlexContainer;
Parent: new () => Parent;
Children: new () => Children;
+ ScreenSpace: new () => ScreenSpace;
Canvas: new () => Canvas;
Camera: new () => Camera;
}
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 6ac9aef0d..cc03c5b22 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -87,6 +87,10 @@ export interface ESEngineModule {
getResourceManager(): CppResourceManager;
getSpineBounds?(registry: CppRegistry, entity: number): SpineBounds;
+ // Material cache
+ invalidateMaterialCache(materialId: number): void;
+ clearMaterialCache(): void;
+
// ImmediateDraw API
draw_begin(matrixPtr: number): void;
draw_end(): void;
@@ -188,12 +192,25 @@ export interface ESEngineModule {
registry_getCanvasEntity(registry: CppRegistry): number;
registry_getCameraEntities(registry: CppRegistry): number[];
getChildEntities(registry: CppRegistry, entity: number): number[];
+ registry_getGeneration(registry: CppRegistry, entity: number): number;
+ registry_getSchemaPoolVersion(registry: CppRegistry, poolId: number): number;
// GL Debug API
gl_enableErrorCheck(enabled: boolean): void;
gl_checkErrors(context: string): number;
renderer_diagnose(): void;
+ // UI Systems
+ uiLayout_update(registry: CppRegistry, camLeft: number, camBottom: number, camRight: number, camTop: number): void;
+ uiHitTest_update(registry: CppRegistry, mouseWorldX: number, mouseWorldY: number, mouseDown: boolean, mousePressed: boolean, mouseReleased: boolean): void;
+ uiHitTest_getHitEntity(): number;
+ uiHitTest_getHitEntityPrev(): number;
+ uiRenderOrder_update(registry: CppRegistry): void;
+ uiFlexLayout_update(registry: CppRegistry): void;
+ getUIRectComputedWidth(registry: CppRegistry, entity: number): number;
+ getUIRectComputedHeight(registry: CppRegistry, entity: number): number;
+ transform_update(registry: CppRegistry): void;
+
_malloc(size: number): number;
_free(ptr: number): void;
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index fd1622285..b425a6bbd 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -8,8 +8,12 @@ export { textPlugin, TextPlugin } from './ui/TextPlugin';
export { uiMaskPlugin, UIMaskPlugin } from './ui/UIMaskPlugin';
export { uiInteractionPlugin, UIInteractionPlugin } from './ui/UIInteractionPlugin';
export { uiLayoutPlugin, UILayoutPlugin } from './ui/UILayoutPlugin';
+export { uiRenderOrderPlugin, UIRenderOrderPlugin } from './ui/UIRenderOrderPlugin';
export { textInputPlugin, TextInputPlugin } from './ui/TextInputPlugin';
+export { progressBarPlugin, ProgressBarPlugin } from './ui/ProgressBarPlugin';
+export { sliderPlugin, SliderPlugin } from './ui/SliderPlugin';
+
export { PhysicsPlugin, PhysicsEvents, Physics, loadPhysicsModule } from './physics';
export function createWebApp(module: ESEngineModule, options?: WebAppOptions): App {
diff --git a/sdk/wasm.generated.ts b/sdk/wasm.generated.ts
index 04684c2ee..6569978a4 100644
--- a/sdk/wasm.generated.ts
+++ b/sdk/wasm.generated.ts
@@ -10,11 +10,60 @@ import type { Entity, Vec2, Vec3, Vec4, Quat } from './types';
export interface UVec2 { x: number; y: number; }
export type Mat4 = number[];
+// Emscripten Vector Types
+export interface VectorEntity {
+ size(): number;
+ get(index: number): number;
+ push_back(value: number): void;
+ set(index: number, value: number): boolean;
+ delete(): void;
+}
+
// Enums
-export enum ProjectionType {
- Perspective = 0,
- Orthographic = 1,
+export enum BodyType {
+ Static = 0,
+ Kinematic = 1,
+ Dynamic = 2,
+}
+
+export enum TextAlign {
+ Left = 0,
+ Center = 1,
+ Right = 2,
+}
+
+export enum MaskMode {
+ Scissor = 0,
+ Stencil = 1,
+}
+
+export enum FlexDirection {
+ Row = 0,
+ Column = 1,
+ RowReverse = 2,
+ ColumnReverse = 3,
+}
+
+export enum FlexWrap {
+ NoWrap = 0,
+ Wrap = 1,
+}
+
+export enum JustifyContent {
+ Start = 0,
+ Center = 1,
+ End = 2,
+ SpaceBetween = 3,
+ SpaceAround = 4,
+ SpaceEvenly = 5,
+}
+
+export enum AlignItems {
+ Start = 0,
+ Center = 1,
+ End = 2,
+ Stretch = 3,
}
export enum CanvasScaleMode {
@@ -25,32 +74,123 @@ export enum CanvasScaleMode {
Match = 4,
}
+export enum ProjectionType {
+ Perspective = 0,
+ Orthographic = 1,
+}
+
// Components
-export interface Camera {
- projectionType: number;
- fov: number;
- orthoSize: number;
- nearPlane: number;
- farPlane: number;
- aspectRatio: number;
- isActive: boolean;
- priority: number;
+export interface UIRect {
+ anchorMin: Vec2;
+ anchorMax: Vec2;
+ offsetMin: Vec2;
+ offsetMax: Vec2;
+ size: Vec2;
+ pivot: Vec2;
}
-export interface Canvas {
- designResolution: UVec2;
- pixelsPerUnit: number;
- scaleMode: number;
- matchWidthOrHeight: number;
- backgroundColor: Vec4;
+export interface FlexItem {
+ flexGrow: number;
+ flexShrink: number;
+ flexBasis: number;
+ order: number;
}
-export interface Parent {
- entity: number;
+export interface BoxCollider {
+ halfExtents: Vec2;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
}
-export interface Children {
+export interface CircleCollider {
+ radius: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
+export interface CapsuleCollider {
+ radius: number;
+ halfHeight: number;
+ offset: Vec2;
+ density: number;
+ friction: number;
+ restitution: number;
+ isSensor: boolean;
+ enabled: boolean;
+}
+
+export interface Transform {
+ position: Vec3;
+ rotation: Quat;
+ scale: Vec3;
+ worldPosition: Vec3;
+ worldRotation: Quat;
+ worldScale: Vec3;
+}
+
+export interface Velocity {
+ linear: Vec3;
+ angular: Vec3;
+}
+
+export interface SpineAnimation {
+ skeletonPath: string;
+ atlasPath: string;
+ skin: string;
+ animation: string;
+ timeScale: number;
+ loop: boolean;
+ playing: boolean;
+ flipX: boolean;
+ flipY: boolean;
+ color: Vec4;
+ layer: number;
+ skeletonScale: number;
+ material: number;
+ enabled: boolean;
+}
+
+export interface Interactable {
+ enabled: boolean;
+ blockRaycast: boolean;
+ raycastTarget: boolean;
+}
+
+export interface UIInteraction {
+ hovered: boolean;
+ pressed: boolean;
+ justPressed: boolean;
+ justReleased: boolean;
+}
+
+export interface RigidBody {
+ bodyType: number;
+ gravityScale: number;
+ linearDamping: number;
+ angularDamping: number;
+ fixedRotation: boolean;
+ bullet: boolean;
+ enabled: boolean;
+}
+
+export interface BitmapText {
+ text: string;
+ color: Vec4;
+ fontSize: number;
+ align: number;
+ spacing: number;
+ layer: number;
+ font: number;
+ enabled: boolean;
}
export interface Sprite {
@@ -62,23 +202,57 @@ export interface Sprite {
layer: number;
flipX: boolean;
flipY: boolean;
+ material: number;
+ enabled: boolean;
}
-export interface LocalTransform {
- position: Vec3;
- rotation: Quat;
- scale: Vec3;
+export interface UIMask {
+ enabled: boolean;
+ mode: number;
}
-export interface WorldTransform {
- position: Vec3;
- rotation: Quat;
- scale: Vec3;
+export interface FlexContainer {
+ direction: number;
+ wrap: number;
+ justifyContent: number;
+ alignItems: number;
+ gap: Vec2;
+ padding: Vec4;
}
-export interface Velocity {
- linear: Vec3;
- angular: Vec3;
+export interface Parent {
+ entity: number;
+}
+
+export interface Children {
+ entities: VectorEntity;
+}
+
+export interface ScreenSpace {
+}
+
+export interface Canvas {
+ designResolution: UVec2;
+ pixelsPerUnit: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+ backgroundColor: Vec4;
+}
+
+export interface Camera {
+ projectionType: number;
+ fov: number;
+ orthoSize: number;
+ nearPlane: number;
+ farPlane: number;
+ aspectRatio: number;
+ isActive: boolean;
+ priority: number;
+ viewportX: number;
+ viewportY: number;
+ viewportW: number;
+ viewportH: number;
+ clearFlags: number;
}
// Registry
@@ -88,14 +262,66 @@ export interface Registry {
valid(entity: Entity): boolean;
entityCount(): number;
- hasCamera(entity: Entity): boolean;
- getCamera(entity: Entity): Camera;
- addCamera(entity: Entity, component: Camera): void;
- removeCamera(entity: Entity): void;
- hasCanvas(entity: Entity): boolean;
- getCanvas(entity: Entity): Canvas;
- addCanvas(entity: Entity, component: Canvas): void;
- removeCanvas(entity: Entity): void;
+ hasUIRect(entity: Entity): boolean;
+ getUIRect(entity: Entity): UIRect;
+ addUIRect(entity: Entity, component: UIRect): void;
+ removeUIRect(entity: Entity): void;
+ hasFlexItem(entity: Entity): boolean;
+ getFlexItem(entity: Entity): FlexItem;
+ addFlexItem(entity: Entity, component: FlexItem): void;
+ removeFlexItem(entity: Entity): void;
+ hasBoxCollider(entity: Entity): boolean;
+ getBoxCollider(entity: Entity): BoxCollider;
+ addBoxCollider(entity: Entity, component: BoxCollider): void;
+ removeBoxCollider(entity: Entity): void;
+ hasCircleCollider(entity: Entity): boolean;
+ getCircleCollider(entity: Entity): CircleCollider;
+ addCircleCollider(entity: Entity, component: CircleCollider): void;
+ removeCircleCollider(entity: Entity): void;
+ hasCapsuleCollider(entity: Entity): boolean;
+ getCapsuleCollider(entity: Entity): CapsuleCollider;
+ addCapsuleCollider(entity: Entity, component: CapsuleCollider): void;
+ removeCapsuleCollider(entity: Entity): void;
+ hasTransform(entity: Entity): boolean;
+ getTransform(entity: Entity): Transform;
+ addTransform(entity: Entity, component: Transform): void;
+ removeTransform(entity: Entity): void;
+ hasVelocity(entity: Entity): boolean;
+ getVelocity(entity: Entity): Velocity;
+ addVelocity(entity: Entity, component: Velocity): void;
+ removeVelocity(entity: Entity): void;
+ hasSpineAnimation(entity: Entity): boolean;
+ getSpineAnimation(entity: Entity): SpineAnimation;
+ addSpineAnimation(entity: Entity, component: SpineAnimation): void;
+ removeSpineAnimation(entity: Entity): void;
+ hasInteractable(entity: Entity): boolean;
+ getInteractable(entity: Entity): Interactable;
+ addInteractable(entity: Entity, component: Interactable): void;
+ removeInteractable(entity: Entity): void;
+ hasUIInteraction(entity: Entity): boolean;
+ getUIInteraction(entity: Entity): UIInteraction;
+ addUIInteraction(entity: Entity, component: UIInteraction): void;
+ removeUIInteraction(entity: Entity): void;
+ hasRigidBody(entity: Entity): boolean;
+ getRigidBody(entity: Entity): RigidBody;
+ addRigidBody(entity: Entity, component: RigidBody): void;
+ removeRigidBody(entity: Entity): void;
+ hasBitmapText(entity: Entity): boolean;
+ getBitmapText(entity: Entity): BitmapText;
+ addBitmapText(entity: Entity, component: BitmapText): void;
+ removeBitmapText(entity: Entity): void;
+ hasSprite(entity: Entity): boolean;
+ getSprite(entity: Entity): Sprite;
+ addSprite(entity: Entity, component: Sprite): void;
+ removeSprite(entity: Entity): void;
+ hasUIMask(entity: Entity): boolean;
+ getUIMask(entity: Entity): UIMask;
+ addUIMask(entity: Entity, component: UIMask): void;
+ removeUIMask(entity: Entity): void;
+ hasFlexContainer(entity: Entity): boolean;
+ getFlexContainer(entity: Entity): FlexContainer;
+ addFlexContainer(entity: Entity, component: FlexContainer): void;
+ removeFlexContainer(entity: Entity): void;
hasParent(entity: Entity): boolean;
getParent(entity: Entity): Parent;
addParent(entity: Entity, component: Parent): void;
@@ -104,22 +330,18 @@ export interface Registry {
getChildren(entity: Entity): Children;
addChildren(entity: Entity, component: Children): void;
removeChildren(entity: Entity): void;
- hasSprite(entity: Entity): boolean;
- getSprite(entity: Entity): Sprite;
- addSprite(entity: Entity, component: Sprite): void;
- removeSprite(entity: Entity): void;
- hasLocalTransform(entity: Entity): boolean;
- getLocalTransform(entity: Entity): LocalTransform;
- addLocalTransform(entity: Entity, component: LocalTransform): void;
- removeLocalTransform(entity: Entity): void;
- hasWorldTransform(entity: Entity): boolean;
- getWorldTransform(entity: Entity): WorldTransform;
- addWorldTransform(entity: Entity, component: WorldTransform): void;
- removeWorldTransform(entity: Entity): void;
- hasVelocity(entity: Entity): boolean;
- getVelocity(entity: Entity): Velocity;
- addVelocity(entity: Entity, component: Velocity): void;
- removeVelocity(entity: Entity): void;
+ hasScreenSpace(entity: Entity): boolean;
+ getScreenSpace(entity: Entity): ScreenSpace;
+ addScreenSpace(entity: Entity, component: ScreenSpace): void;
+ removeScreenSpace(entity: Entity): void;
+ hasCanvas(entity: Entity): boolean;
+ getCanvas(entity: Entity): Canvas;
+ addCanvas(entity: Entity, component: Canvas): void;
+ removeCanvas(entity: Entity): void;
+ hasCamera(entity: Entity): boolean;
+ getCamera(entity: Entity): Camera;
+ addCamera(entity: Entity, component: Camera): void;
+ removeCamera(entity: Entity): void;
// Hierarchy Utilities
setParent(child: Entity, parent: Entity): void;
@@ -128,12 +350,24 @@ export interface Registry {
// Module
export interface ESEngineModule {
Registry: new () => Registry;
- Camera: new () => Camera;
- Canvas: new () => Canvas;
+ UIRect: new () => UIRect;
+ FlexItem: new () => FlexItem;
+ BoxCollider: new () => BoxCollider;
+ CircleCollider: new () => CircleCollider;
+ CapsuleCollider: new () => CapsuleCollider;
+ Transform: new () => Transform;
+ Velocity: new () => Velocity;
+ SpineAnimation: new () => SpineAnimation;
+ Interactable: new () => Interactable;
+ UIInteraction: new () => UIInteraction;
+ RigidBody: new () => RigidBody;
+ BitmapText: new () => BitmapText;
+ Sprite: new () => Sprite;
+ UIMask: new () => UIMask;
+ FlexContainer: new () => FlexContainer;
Parent: new () => Parent;
Children: new () => Children;
- Sprite: new () => Sprite;
- LocalTransform: new () => LocalTransform;
- WorldTransform: new () => WorldTransform;
- Velocity: new () => Velocity;
+ ScreenSpace: new () => ScreenSpace;
+ Canvas: new () => Canvas;
+ Camera: new () => Camera;
}
diff --git a/src/esengine/bindings/EngineContext.hpp b/src/esengine/bindings/EngineContext.hpp
index 43bf0d777..a9d904d22 100644
--- a/src/esengine/bindings/EngineContext.hpp
+++ b/src/esengine/bindings/EngineContext.hpp
@@ -85,6 +85,12 @@ public:
viewportHeight_ = height;
}
+ f32 deltaTime() const { return deltaTime_; }
+ void setDeltaTime(f32 dt) { deltaTime_ = dt; }
+
+ bool transformsUpdated() const { return transformsUpdated_; }
+ void setTransformsUpdated(bool v) { transformsUpdated_ = v; }
+
const glm::vec4& clearColor() const { return clearColor_; }
void setClearColor(const glm::vec4& color) { clearColor_ = color; }
@@ -130,6 +136,8 @@ private:
u32 viewportHeight_ = 720;
glm::vec4 clearColor_{0.0f, 0.0f, 0.0f, 1.0f};
glm::mat4 currentViewProjection_{1.0f};
+ f32 deltaTime_ = 0.016f;
+ bool transformsUpdated_ = false;
};
} // namespace esengine
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 2e651f334..834d01b13 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -52,8 +52,10 @@ static u32 checkGLErrors(const char* context) {
case GL_INVALID_OPERATION: errStr = "INVALID_OPERATION"; break;
case GL_INVALID_FRAMEBUFFER_OPERATION: errStr = "INVALID_FRAMEBUFFER_OPERATION"; break;
case GL_OUT_OF_MEMORY: errStr = "OUT_OF_MEMORY"; break;
+ case GL_CONTEXT_LOST: errStr = "CONTEXT_LOST"; break;
+ case GL_CONTEXT_LOST_WEBGL: errStr = "CONTEXT_LOST_WEBGL"; break;
}
- ES_LOG_ERROR("[GL Error] {} at: {}", errStr, context);
+ ES_LOG_ERROR("[GL Error] {} (0x{:04X}) at: {}", errStr, static_cast<u32>(err), context);
errorCount++;
}
return errorCount;
@@ -85,7 +87,7 @@ void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight)
#ifdef ES_ENABLE_SPINE
if (g_spineSystem) {
- g_spineSystem->update(registry, 0.016f);
+ g_spineSystem->update(registry, ctx().deltaTime());
}
#endif
@@ -93,18 +95,19 @@ void renderFrame(ecs::Registry& registry, i32 viewportWidth, i32 viewportHeight)
g_renderFrame->resize(g_viewportWidth, g_viewportHeight);
glViewport(0, 0, viewportWidth, viewportHeight);
- glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+ const auto& cc = ctx().clearColor();
+ glClearColor(cc.r, cc.g, cc.b, cc.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 viewProjection = glm::mat4(1.0f);
- auto cameraView = registry.view<ecs::Camera, ecs::LocalTransform>();
+ auto cameraView = registry.view<ecs::Camera, ecs::Transform>();
for (auto entity : cameraView) {
auto& camera = registry.get<ecs::Camera>(entity);
if (!camera.isActive) continue;
- auto& transform = registry.get<ecs::LocalTransform>(entity);
+ auto& transform = registry.get<ecs::Transform>(entity);
glm::mat4 view = glm::inverse(glm::translate(glm::mat4(1.0f), transform.position));
glm::mat4 projection;
@@ -142,13 +145,17 @@ void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewp
uintptr_t matrixPtr) {
if (!g_initialized || !g_renderFrame) return;
+ if (auto* rm = ctx().resourceManager()) {
+ rm->update();
+ }
+
if (g_transformSystem) {
g_transformSystem->update(registry, 0.0f);
}
#ifdef ES_ENABLE_SPINE
if (g_spineSystem) {
- g_spineSystem->update(registry, 0.016f);
+ g_spineSystem->update(registry, ctx().deltaTime());
}
#endif
@@ -156,7 +163,8 @@ void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewp
g_renderFrame->resize(g_viewportWidth, g_viewportHeight);
glViewport(0, 0, viewportWidth, viewportHeight);
- glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
+ const auto& cc = ctx().clearColor();
+ glClearColor(cc.r, cc.g, cc.b, cc.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
@@ -188,6 +196,8 @@ void renderer_resize(u32 width, u32 height) {
void renderer_begin(uintptr_t matrixPtr, u32 targetHandle) {
if (!g_renderFrame) return;
+ ctx().setTransformsUpdated(false);
+
const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);
glm::mat4 viewProjection = glm::make_mat4(matrixData);
@@ -206,22 +216,30 @@ void renderer_end() {
checkGLErrors("renderer_end");
}
+static void ensureTransformsUpdated(ecs::Registry& registry) {
+ if (!ctx().transformsUpdated() && g_transformSystem) {
+ g_transformSystem->update(registry, 0.0f);
+ ctx().setTransformsUpdated(true);
+ }
+}
+
void renderer_submitSprites(ecs::Registry& registry) {
- if (!g_renderFrame || !g_transformSystem) return;
- g_transformSystem->update(registry, 0.0f);
+ if (!g_renderFrame) return;
+ ensureTransformsUpdated(registry);
g_renderFrame->submitSprites(registry);
}
void renderer_submitBitmapText(ecs::Registry& registry) {
- if (!g_renderFrame || !g_transformSystem) return;
- g_transformSystem->update(registry, 0.0f);
+ if (!g_renderFrame) return;
+ ensureTransformsUpdated(registry);
g_renderFrame->submitBitmapText(registry);
}
#ifdef ES_ENABLE_SPINE
void renderer_submitSpine(ecs::Registry& registry) {
if (!g_renderFrame || !g_spineSystem) return;
- g_spineSystem->update(registry, 0.016f);
+ ensureTransformsUpdated(registry);
+ g_spineSystem->update(registry, ctx().deltaTime());
g_renderFrame->submitSpine(registry, *g_spineSystem);
checkGLErrors("renderer_submitSpine");
}
@@ -311,6 +329,10 @@ u32 renderer_getCulled() {
return g_renderFrame->stats().culled;
}
+void renderer_setDeltaTime(f32 dt) {
+ ctx().setDeltaTime(dt);
+}
+
void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a) {
ctx().setClearColor(glm::vec4(r, g, b, a));
}
@@ -442,7 +464,7 @@ i32 registry_getCanvasEntity(ecs::Registry& registry) {
}
emscripten::val registry_getCameraEntities(ecs::Registry& registry) {
- auto cameraView = registry.view<ecs::Camera, ecs::LocalTransform>();
+ auto cameraView = registry.view<ecs::Camera, ecs::Transform>();
auto result = emscripten::val::array();
u32 idx = 0;
for (auto entity : cameraView) {
@@ -467,6 +489,14 @@ emscripten::val getChildEntities(ecs::Registry& registry, u32 entity) {
return result;
}
+u32 registry_getGeneration(ecs::Registry& registry, u32 entity) {
+ return registry.generation(static_cast<Entity>(entity));
+}
+
+u32 registry_getSchemaPoolVersion(ecs::Registry& registry, u32 poolId) {
+ return registry.getSchemaPoolVersion(poolId);
+}
+
} // namespace esengine
#endif // ES_PLATFORM_WEB
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 69493cf8c..c9159ff5b 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -60,6 +60,7 @@ u32 renderer_getSpine();
u32 renderer_getText();
u32 renderer_getMeshes();
u32 renderer_getCulled();
+void renderer_setDeltaTime(f32 dt);
void renderer_setClearColor(f32 r, f32 g, f32 b, f32 a);
void renderer_setViewport(i32 x, i32 y, i32 w, i32 h);
void renderer_setScissor(i32 x, i32 y, i32 w, i32 h, bool enable);
@@ -81,6 +82,8 @@ u32 gl_checkErrors(const std::string& context);
i32 registry_getCanvasEntity(ecs::Registry& registry);
emscripten::val registry_getCameraEntities(ecs::Registry& registry);
emscripten::val getChildEntities(ecs::Registry& registry, u32 entity);
+u32 registry_getGeneration(ecs::Registry& registry, u32 entity);
+u32 registry_getSchemaPoolVersion(ecs::Registry& registry, u32 poolId);
} // namespace esengine
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 0bbf81fc2..04bd2d286 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -16,11 +16,18 @@
#include "../ecs/components/Camera.hpp"
#include "../ecs/components/Canvas.hpp"
#include "../ecs/components/Collider.hpp"
+#include "../ecs/components/FlexContainer.hpp"
+#include "../ecs/components/FlexItem.hpp"
#include "../ecs/components/Hierarchy.hpp"
+#include "../ecs/components/Interactable.hpp"
#include "../ecs/components/RigidBody.hpp"
+#include "../ecs/components/ScreenSpace.hpp"
#include "../ecs/components/SpineAnimation.hpp"
#include "../ecs/components/Sprite.hpp"
#include "../ecs/components/Transform.hpp"
+#include "../ecs/components/UIInteraction.hpp"
+#include "../ecs/components/UIMask.hpp"
+#include "../ecs/components/UIRect.hpp"
#include "../ecs/components/Velocity.hpp"
using namespace emscripten;
@@ -73,6 +80,34 @@ EMSCRIPTEN_BINDINGS(esengine_enums) {
.value("Center", esengine::ecs::TextAlign::Center)
.value("Right", esengine::ecs::TextAlign::Right);
+ enum_<esengine::ecs::MaskMode>("MaskMode")
+ .value("Scissor", esengine::ecs::MaskMode::Scissor)
+ .value("Stencil", esengine::ecs::MaskMode::Stencil);
+
+ enum_<esengine::ecs::FlexDirection>("FlexDirection")
+ .value("Row", esengine::ecs::FlexDirection::Row)
+ .value("Column", esengine::ecs::FlexDirection::Column)
+ .value("RowReverse", esengine::ecs::FlexDirection::RowReverse)
+ .value("ColumnReverse", esengine::ecs::FlexDirection::ColumnReverse);
+
+ enum_<esengine::ecs::FlexWrap>("FlexWrap")
+ .value("NoWrap", esengine::ecs::FlexWrap::NoWrap)
+ .value("Wrap", esengine::ecs::FlexWrap::Wrap);
+
+ enum_<esengine::ecs::JustifyContent>("JustifyContent")
+ .value("Start", esengine::ecs::JustifyContent::Start)
+ .value("Center", esengine::ecs::JustifyContent::Center)
+ .value("End", esengine::ecs::JustifyContent::End)
+ .value("SpaceBetween", esengine::ecs::JustifyContent::SpaceBetween)
+ .value("SpaceAround", esengine::ecs::JustifyContent::SpaceAround)
+ .value("SpaceEvenly", esengine::ecs::JustifyContent::SpaceEvenly);
+
+ enum_<esengine::ecs::AlignItems>("AlignItems")
+ .value("Start", esengine::ecs::AlignItems::Start)
+ .value("Center", esengine::ecs::AlignItems::Center)
+ .value("End", esengine::ecs::AlignItems::End)
+ .value("Stretch", esengine::ecs::AlignItems::Stretch);
+
enum_<esengine::ecs::CanvasScaleMode>("CanvasScaleMode")
.value("FixedWidth", esengine::ecs::CanvasScaleMode::FixedWidth)
.value("FixedHeight", esengine::ecs::CanvasScaleMode::FixedHeight)
@@ -204,6 +239,56 @@ SpriteJS spriteToJS(const esengine::ecs::Sprite& c) {
return js;
}
+struct UIMaskJS {
+ bool enabled;
+ i32 mode;
+};
+
+esengine::ecs::UIMask uimaskFromJS(const UIMaskJS& js) {
+ esengine::ecs::UIMask c;
+ c.enabled = js.enabled;
+ c.mode = static_cast<MaskMode>(js.mode);
+ return c;
+}
+
+UIMaskJS uimaskToJS(const esengine::ecs::UIMask& c) {
+ UIMaskJS js;
+ js.enabled = c.enabled;
+ js.mode = static_cast<i32>(c.mode);
+ return js;
+}
+
+struct FlexContainerJS {
+ i32 direction;
+ i32 wrap;
+ i32 justifyContent;
+ i32 alignItems;
+ glm::vec2 gap;
+ glm::vec4 padding;
+};
+
+esengine::ecs::FlexContainer flexcontainerFromJS(const FlexContainerJS& js) {
+ esengine::ecs::FlexContainer c;
+ c.direction = static_cast<FlexDirection>(js.direction);
+ c.wrap = static_cast<FlexWrap>(js.wrap);
+ c.justifyContent = static_cast<JustifyContent>(js.justifyContent);
+ c.alignItems = static_cast<AlignItems>(js.alignItems);
+ c.gap = js.gap;
+ c.padding = js.padding;
+ return c;
+}
+
+FlexContainerJS flexcontainerToJS(const esengine::ecs::FlexContainer& c) {
+ FlexContainerJS js;
+ js.direction = static_cast<i32>(c.direction);
+ js.wrap = static_cast<i32>(c.wrap);
+ js.justifyContent = static_cast<i32>(c.justifyContent);
+ js.alignItems = static_cast<i32>(c.alignItems);
+ js.gap = c.gap;
+ js.padding = c.padding;
+ return js;
+}
+
struct CanvasJS {
glm::uvec2 designResolution;
f32 pixelsPerUnit;
@@ -285,6 +370,22 @@ CameraJS cameraToJS(const esengine::ecs::Camera& c) {
}
EMSCRIPTEN_BINDINGS(esengine_components) {
+ register_vector<u32>("VectorEntity");
+
+ value_object<esengine::ecs::UIRect>("UIRect")
+ .field("anchorMin", &esengine::ecs::UIRect::anchorMin)
+ .field("anchorMax", &esengine::ecs::UIRect::anchorMax)
+ .field("offsetMin", &esengine::ecs::UIRect::offsetMin)
+ .field("offsetMax", &esengine::ecs::UIRect::offsetMax)
+ .field("size", &esengine::ecs::UIRect::size)
+ .field("pivot", &esengine::ecs::UIRect::pivot);
+
+ value_object<esengine::ecs::FlexItem>("FlexItem")
+ .field("flexGrow", &esengine::ecs::FlexItem::flexGrow)
+ .field("flexShrink", &esengine::ecs::FlexItem::flexShrink)
+ .field("flexBasis", &esengine::ecs::FlexItem::flexBasis)
+ .field("order", &esengine::ecs::FlexItem::order);
+
value_object<esengine::ecs::BoxCollider>("BoxCollider")
.field("halfExtents", &esengine::ecs::BoxCollider::halfExtents)
.field("offset", &esengine::ecs::BoxCollider::offset)
@@ -313,15 +414,13 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("isSensor", &esengine::ecs::CapsuleCollider::isSensor)
.field("enabled", &esengine::ecs::CapsuleCollider::enabled);
- value_object<esengine::ecs::LocalTransform>("LocalTransform")
- .field("position", &esengine::ecs::LocalTransform::position)
- .field("rotation", &esengine::ecs::LocalTransform::rotation)
- .field("scale", &esengine::ecs::LocalTransform::scale);
-
- value_object<esengine::ecs::WorldTransform>("WorldTransform")
- .field("position", &esengine::ecs::WorldTransform::position)
- .field("rotation", &esengine::ecs::WorldTransform::rotation)
- .field("scale", &esengine::ecs::WorldTransform::scale);
+ value_object<esengine::ecs::Transform>("Transform")
+ .field("position", &esengine::ecs::Transform::position)
+ .field("rotation", &esengine::ecs::Transform::rotation)
+ .field("scale", &esengine::ecs::Transform::scale)
+ .field("worldPosition", &esengine::ecs::Transform::worldPosition)
+ .field("worldRotation", &esengine::ecs::Transform::worldRotation)
+ .field("worldScale", &esengine::ecs::Transform::worldScale);
value_object<esengine::ecs::Velocity>("Velocity")
.field("linear", &esengine::ecs::Velocity::linear)
@@ -343,6 +442,17 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("material", &esengine::ecs::SpineAnimation::material)
.field("enabled", &esengine::ecs::SpineAnimation::enabled);
+ value_object<esengine::ecs::Interactable>("Interactable")
+ .field("enabled", &esengine::ecs::Interactable::enabled)
+ .field("blockRaycast", &esengine::ecs::Interactable::blockRaycast)
+ .field("raycastTarget", &esengine::ecs::Interactable::raycastTarget);
+
+ value_object<esengine::ecs::UIInteraction>("UIInteraction")
+ .field("hovered", &esengine::ecs::UIInteraction::hovered)
+ .field("pressed", &esengine::ecs::UIInteraction::pressed)
+ .field("justPressed", &esengine::ecs::UIInteraction::justPressed)
+ .field("justReleased", &esengine::ecs::UIInteraction::justReleased);
+
value_object<RigidBodyJS>("RigidBody")
.field("bodyType", &RigidBodyJS::bodyType)
.field("gravityScale", &RigidBodyJS::gravityScale)
@@ -374,10 +484,25 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("material", &SpriteJS::material)
.field("enabled", &SpriteJS::enabled);
+ value_object<UIMaskJS>("UIMask")
+ .field("enabled", &UIMaskJS::enabled)
+ .field("mode", &UIMaskJS::mode);
+
+ value_object<FlexContainerJS>("FlexContainer")
+ .field("direction", &FlexContainerJS::direction)
+ .field("wrap", &FlexContainerJS::wrap)
+ .field("justifyContent", &FlexContainerJS::justifyContent)
+ .field("alignItems", &FlexContainerJS::alignItems)
+ .field("gap", &FlexContainerJS::gap)
+ .field("padding", &FlexContainerJS::padding);
+
value_object<esengine::ecs::Parent>("Parent")
.field("entity", &esengine::ecs::Parent::entity);
- value_object<esengine::ecs::Children>("Children");
+ value_object<esengine::ecs::Children>("Children")
+ .field("entities", &esengine::ecs::Children::entities);
+
+ value_object<esengine::ecs::ScreenSpace>("ScreenSpace");
value_object<CanvasJS>("Canvas")
.field("designResolution", &CanvasJS::designResolution)
@@ -421,6 +546,34 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
}))
.function("entityCount", &Registry::entityCount)
+ // UIRect
+ .function("hasUIRect", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::UIRect>(static_cast<Entity>(e));
+ }))
+ .function("getUIRect", optional_override([](Registry& r, u32 e) -> esengine::ecs::UIRect& {
+ return r.get<esengine::ecs::UIRect>(static_cast<Entity>(e));
+ }), allow_raw_pointers())
+ .function("addUIRect", optional_override([](Registry& r, u32 e, const esengine::ecs::UIRect& c) {
+ r.emplaceOrReplace<esengine::ecs::UIRect>(static_cast<Entity>(e), c);
+ }))
+ .function("removeUIRect", optional_override([](Registry& r, u32 e) {
+ r.remove<esengine::ecs::UIRect>(static_cast<Entity>(e));
+ }))
+
+ // FlexItem
+ .function("hasFlexItem", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::FlexItem>(static_cast<Entity>(e));
+ }))
+ .function("getFlexItem", optional_override([](Registry& r, u32 e) -> esengine::ecs::FlexItem& {
+ return r.get<esengine::ecs::FlexItem>(static_cast<Entity>(e));
+ }), allow_raw_pointers())
+ .function("addFlexItem", optional_override([](Registry& r, u32 e, const esengine::ecs::FlexItem& c) {
+ r.emplaceOrReplace<esengine::ecs::FlexItem>(static_cast<Entity>(e), c);
+ }))
+ .function("removeFlexItem", optional_override([](Registry& r, u32 e) {
+ r.remove<esengine::ecs::FlexItem>(static_cast<Entity>(e));
+ }))
+
// BoxCollider
.function("hasBoxCollider", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::BoxCollider>(static_cast<Entity>(e));
@@ -463,32 +616,20 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::CapsuleCollider>(static_cast<Entity>(e));
}))
- // LocalTransform
- .function("hasLocalTransform", optional_override([](Registry& r, u32 e) {
- return r.has<esengine::ecs::LocalTransform>(static_cast<Entity>(e));
+ // Transform
+ .function("hasTransform", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::Transform>(static_cast<Entity>(e));
}))
- .function("getLocalTransform", optional_override([](Registry& r, u32 e) -> esengine::ecs::LocalTransform& {
- return r.get<esengine::ecs::LocalTransform>(static_cast<Entity>(e));
+ .function("getTransform", optional_override([](Registry& r, u32 e) -> esengine::ecs::Transform& {
+ auto& t = r.get<esengine::ecs::Transform>(static_cast<Entity>(e));
+ t.ensureDecomposed();
+ return t;
}), allow_raw_pointers())
- .function("addLocalTransform", optional_override([](Registry& r, u32 e, const esengine::ecs::LocalTransform& c) {
- r.emplaceOrReplace<esengine::ecs::LocalTransform>(static_cast<Entity>(e), c);
+ .function("addTransform", optional_override([](Registry& r, u32 e, const esengine::ecs::Transform& c) {
+ r.emplaceOrReplace<esengine::ecs::Transform>(static_cast<Entity>(e), c);
}))
- .function("removeLocalTransform", optional_override([](Registry& r, u32 e) {
- r.remove<esengine::ecs::LocalTransform>(static_cast<Entity>(e));
- }))
-
- // WorldTransform
- .function("hasWorldTransform", optional_override([](Registry& r, u32 e) {
- return r.has<esengine::ecs::WorldTransform>(static_cast<Entity>(e));
- }))
- .function("getWorldTransform", optional_override([](Registry& r, u32 e) -> esengine::ecs::WorldTransform& {
- return r.get<esengine::ecs::WorldTransform>(static_cast<Entity>(e));
- }), allow_raw_pointers())
- .function("addWorldTransform", optional_override([](Registry& r, u32 e, const esengine::ecs::WorldTransform& c) {
- r.emplaceOrReplace<esengine::ecs::WorldTransform>(static_cast<Entity>(e), c);
- }))
- .function("removeWorldTransform", optional_override([](Registry& r, u32 e) {
- r.remove<esengine::ecs::WorldTransform>(static_cast<Entity>(e));
+ .function("removeTransform", optional_override([](Registry& r, u32 e) {
+ r.remove<esengine::ecs::Transform>(static_cast<Entity>(e));
}))
// Velocity
@@ -519,6 +660,34 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::SpineAnimation>(static_cast<Entity>(e));
}))
+ // Interactable
+ .function("hasInteractable", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::Interactable>(static_cast<Entity>(e));
+ }))
+ .function("getInteractable", optional_override([](Registry& r, u32 e) -> esengine::ecs::Interactable& {
+ return r.get<esengine::ecs::Interactable>(static_cast<Entity>(e));
+ }), allow_raw_pointers())
+ .function("addInteractable", optional_override([](Registry& r, u32 e, const esengine::ecs::Interactable& c) {
+ r.emplaceOrReplace<esengine::ecs::Interactable>(static_cast<Entity>(e), c);
+ }))
+ .function("removeInteractable", optional_override([](Registry& r, u32 e) {
+ r.remove<esengine::ecs::Interactable>(static_cast<Entity>(e));
+ }))
+
+ // UIInteraction
+ .function("hasUIInteraction", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::UIInteraction>(static_cast<Entity>(e));
+ }))
+ .function("getUIInteraction", optional_override([](Registry& r, u32 e) -> esengine::ecs::UIInteraction& {
+ return r.get<esengine::ecs::UIInteraction>(static_cast<Entity>(e));
+ }), allow_raw_pointers())
+ .function("addUIInteraction", optional_override([](Registry& r, u32 e, const esengine::ecs::UIInteraction& c) {
+ r.emplaceOrReplace<esengine::ecs::UIInteraction>(static_cast<Entity>(e), c);
+ }))
+ .function("removeUIInteraction", optional_override([](Registry& r, u32 e) {
+ r.remove<esengine::ecs::UIInteraction>(static_cast<Entity>(e));
+ }))
+
// RigidBody
.function("hasRigidBody", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::RigidBody>(static_cast<Entity>(e));
@@ -561,6 +730,34 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::Sprite>(static_cast<Entity>(e));
}))
+ // UIMask
+ .function("hasUIMask", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::UIMask>(static_cast<Entity>(e));
+ }))
+ .function("getUIMask", optional_override([](Registry& r, u32 e) {
+ return uimaskToJS(r.get<esengine::ecs::UIMask>(static_cast<Entity>(e)));
+ }))
+ .function("addUIMask", optional_override([](Registry& r, u32 e, const UIMaskJS& js) {
+ r.emplaceOrReplace<esengine::ecs::UIMask>(static_cast<Entity>(e), uimaskFromJS(js));
+ }))
+ .function("removeUIMask", optional_override([](Registry& r, u32 e) {
+ r.remove<esengine::ecs::UIMask>(static_cast<Entity>(e));
+ }))
+
+ // FlexContainer
+ .function("hasFlexContainer", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::FlexContainer>(static_cast<Entity>(e));
+ }))
+ .function("getFlexContainer", optional_override([](Registry& r, u32 e) {
+ return flexcontainerToJS(r.get<esengine::ecs::FlexContainer>(static_cast<Entity>(e)));
+ }))
+ .function("addFlexContainer", optional_override([](Registry& r, u32 e, const FlexContainerJS& js) {
+ r.emplaceOrReplace<esengine::ecs::FlexContainer>(static_cast<Entity>(e), flexcontainerFromJS(js));
+ }))
+ .function("removeFlexContainer", optional_override([](Registry& r, u32 e) {
+ r.remove<esengine::ecs::FlexContainer>(static_cast<Entity>(e));
+ }))
+
// Parent
.function("hasParent", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Parent>(static_cast<Entity>(e));
@@ -589,6 +786,20 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::Children>(static_cast<Entity>(e));
}))
+ // ScreenSpace
+ .function("hasScreenSpace", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::ScreenSpace>(static_cast<Entity>(e));
+ }))
+ .function("getScreenSpace", optional_override([](Registry& r, u32 e) -> esengine::ecs::ScreenSpace& {
+ return r.get<esengine::ecs::ScreenSpace>(static_cast<Entity>(e));
+ }), allow_raw_pointers())
+ .function("addScreenSpace", optional_override([](Registry& r, u32 e, const esengine::ecs::ScreenSpace& c) {
+ r.emplaceOrReplace<esengine::ecs::ScreenSpace>(static_cast<Entity>(e), c);
+ }))
+ .function("removeScreenSpace", optional_override([](Registry& r, u32 e) {
+ r.remove<esengine::ecs::ScreenSpace>(static_cast<Entity>(e));
+ }))
+
// Canvas
.function("hasCanvas", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::Canvas>(static_cast<Entity>(e));
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index 02f774ed9..07ed548ae 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -22,6 +22,11 @@
#include "GeometryBindings.hpp"
#include "PostProcessBindings.hpp"
+#include "../ecs/UILayoutSystem.hpp"
+#include "../ecs/UIHitTestSystem.hpp"
+#include "../ecs/UIRenderOrderSystem.hpp"
+#include "../ecs/UIFlexLayoutSystem.hpp"
+
#include "../renderer/OpenGLHeaders.hpp"
#include "../renderer/RenderContext.hpp"
#include "../renderer/RenderFrame.hpp"
@@ -64,6 +69,19 @@ EM_JS(void, callMaterialProvider, (int materialId, int outShaderIdPtr, int outBl
}
});
+struct CachedMaterialData {
+ u32 shaderId = 0;
+ u32 blendMode = 0;
+ std::vector<MaterialUniformData> uniforms;
+};
+static std::unordered_map<u32, CachedMaterialData> s_materialCache;
+
+void clearMaterialCache() { s_materialCache.clear(); }
+
+void invalidateMaterialCache(u32 materialId) {
+ s_materialCache.erase(materialId);
+}
+
bool getMaterialData(u32 materialId, u32& shaderId, u32& blendMode) {
if (materialId == 0) {
return false;
@@ -79,18 +97,20 @@ bool getMaterialData(u32 materialId, u32& shaderId, u32& blendMode) {
return shaderId != 0;
}
-struct UniformData {
- char name[32];
- u32 type;
- f32 values[4];
-};
-
bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,
- std::vector<UniformData>& uniforms) {
+ std::vector<MaterialUniformData>& uniforms) {
if (materialId == 0) {
return false;
}
+ auto cacheIt = s_materialCache.find(materialId);
+ if (cacheIt != s_materialCache.end()) {
+ shaderId = cacheIt->second.shaderId;
+ blendMode = cacheIt->second.blendMode;
+ uniforms = cacheIt->second.uniforms;
+ return shaderId != 0;
+ }
+
u32 uniformBufferPtr = 0;
u32 uniformCount = 0;
auto toPtr = [](auto* p) { return static_cast<int>(reinterpret_cast<uintptr_t>(p)); };
@@ -100,7 +120,10 @@ bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,
toPtr(&uniformBufferPtr),
toPtr(&uniformCount));
- if (shaderId == 0) return false;
+ if (shaderId == 0) {
+ s_materialCache[materialId] = {};
+ return false;
+ }
constexpr u32 MAX_UNIFORMS = 64;
if (uniformCount > MAX_UNIFORMS) {
@@ -123,7 +146,7 @@ bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,
usize alignedNameLen = ((nameLen + 3) / 4) * 4;
if (ptr + alignedNameLen > bufferEnd) break;
- UniformData ud;
+ MaterialUniformData ud;
usize copyLen = std::min<usize>(nameLen, 31);
std::memcpy(ud.name, reinterpret_cast<const char*>(ptr), copyLen);
ud.name[copyLen] = '\0';
@@ -141,40 +164,11 @@ bool getMaterialDataWithUniforms(u32 materialId, u32& shaderId, u32& blendMode,
}
}
+ s_materialCache[materialId] = { shaderId, blendMode, uniforms };
return true;
}
-bool initRendererInternal(const char* canvasSelector) {
- if (g_initialized) return true;
-
- EmscriptenWebGLContextAttributes attrs;
- emscripten_webgl_init_context_attributes(&attrs);
- attrs.majorVersion = 2;
- attrs.minorVersion = 0;
- attrs.alpha = true;
- attrs.depth = true;
- attrs.stencil = true;
- attrs.antialias = true;
- attrs.premultipliedAlpha = true;
- attrs.preserveDrawingBuffer = false;
- attrs.powerPreference = EM_WEBGL_POWER_PREFERENCE_DEFAULT;
- attrs.failIfMajorPerformanceCaveat = false;
-
- EMSCRIPTEN_WEBGL_CONTEXT_HANDLE webglCtx = emscripten_webgl_create_context(canvasSelector, &attrs);
- if (webglCtx <= 0) {
- ES_LOG_ERROR("Failed to create WebGL2 context for '{}': {}", canvasSelector, webglCtx);
- return false;
- }
- ctx().setWebglContext(webglCtx);
-
- EMSCRIPTEN_RESULT result = emscripten_webgl_make_context_current(g_webglContext);
- if (result != EMSCRIPTEN_RESULT_SUCCESS) {
- ES_LOG_ERROR("Failed to make WebGL context current: {}", result);
- return false;
- }
-
- ES_LOG_INFO("WebGL2 context created for '{}'", canvasSelector);
-
+static void initSubsystems() {
auto resourceManager = makeUnique<resource::ResourceManager>();
resourceManager->init();
ctx().setResourceManager(std::move(resourceManager));
@@ -204,9 +198,43 @@ bool initRendererInternal(const char* canvasSelector) {
ctx().setInitialized(true);
- glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
+ const auto& cc = ctx().clearColor();
+ glClearColor(cc.r, cc.g, cc.b, cc.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+}
+
+bool initRendererInternal(const char* canvasSelector) {
+ if (g_initialized) return true;
+
+ EmscriptenWebGLContextAttributes attrs;
+ emscripten_webgl_init_context_attributes(&attrs);
+ attrs.majorVersion = 2;
+ attrs.minorVersion = 0;
+ attrs.alpha = true;
+ attrs.depth = true;
+ attrs.stencil = true;
+ attrs.antialias = true;
+ attrs.premultipliedAlpha = true;
+ attrs.preserveDrawingBuffer = false;
+ attrs.powerPreference = EM_WEBGL_POWER_PREFERENCE_DEFAULT;
+ attrs.failIfMajorPerformanceCaveat = false;
+
+ EMSCRIPTEN_WEBGL_CONTEXT_HANDLE webglCtx = emscripten_webgl_create_context(canvasSelector, &attrs);
+ if (webglCtx <= 0) {
+ ES_LOG_ERROR("Failed to create WebGL2 context for '{}': {}", canvasSelector, webglCtx);
+ return false;
+ }
+ ctx().setWebglContext(webglCtx);
+ EMSCRIPTEN_RESULT result = emscripten_webgl_make_context_current(g_webglContext);
+ if (result != EMSCRIPTEN_RESULT_SUCCESS) {
+ ES_LOG_ERROR("Failed to make WebGL context current: {}", result);
+ return false;
+ }
+
+ ES_LOG_INFO("WebGL2 context created for '{}'", canvasSelector);
+
+ initSubsystems();
return true;
}
@@ -235,38 +263,7 @@ bool initRendererWithContext(int contextHandle) {
ES_LOG_INFO("WebGL context set from external handle: {}", contextHandle);
- auto resourceManager = makeUnique<resource::ResourceManager>();
- resourceManager->init();
- ctx().setResourceManager(std::move(resourceManager));
-
- auto renderContext = makeUnique<RenderContext>();
- renderContext->init();
- ctx().setRenderContext(std::move(renderContext));
-
- ctx().setTransformSystem(makeUnique<ecs::TransformSystem>());
-
-#ifdef ES_ENABLE_SPINE
- auto spineResourceManager = makeUnique<spine::SpineResourceManager>(*g_resourceManager);
- spineResourceManager->init();
- ctx().setSpineResourceManager(std::move(spineResourceManager));
- ctx().setSpineSystem(makeUnique<spine::SpineSystem>(*g_spineResourceManager));
-#endif
-
- auto immediateDraw = makeUnique<ImmediateDraw>(*g_renderContext, *g_resourceManager);
- immediateDraw->init();
- ctx().setImmediateDraw(std::move(immediateDraw));
-
- ctx().setGeometryManager(makeUnique<GeometryManager>());
-
- auto renderFrame = makeUnique<RenderFrame>(*g_renderContext, *g_resourceManager);
- renderFrame->init(1280, 720);
- ctx().setRenderFrame(std::move(renderFrame));
-
- ctx().setInitialized(true);
-
- glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-
+ initSubsystems();
return true;
}
@@ -317,6 +314,9 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("getSpineBounds", &esengine::getSpineBounds);
#endif
+ emscripten::function("invalidateMaterialCache", &esengine::invalidateMaterialCache);
+ emscripten::function("clearMaterialCache", &esengine::clearMaterialCache);
+
emscripten::function("draw_begin", &esengine::draw_begin);
emscripten::function("draw_end", &esengine::draw_end);
emscripten::function("draw_line", &esengine::draw_line);
@@ -384,6 +384,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("renderer_getText", &esengine::renderer_getText);
emscripten::function("renderer_getMeshes", &esengine::renderer_getMeshes);
emscripten::function("renderer_getCulled", &esengine::renderer_getCulled);
+ emscripten::function("renderer_setDeltaTime", &esengine::renderer_setDeltaTime);
emscripten::function("renderer_setClearColor", &esengine::renderer_setClearColor);
emscripten::function("renderer_setViewport", &esengine::renderer_setViewport);
emscripten::function("renderer_setScissor", &esengine::renderer_setScissor);
@@ -401,12 +402,80 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {
emscripten::function("registry_getCanvasEntity", &esengine::registry_getCanvasEntity);
emscripten::function("registry_getCameraEntities", &esengine::registry_getCameraEntities);
emscripten::function("getChildEntities", &esengine::getChildEntities);
+ emscripten::function("registry_getGeneration", &esengine::registry_getGeneration);
+ emscripten::function("registry_getSchemaPoolVersion", &esengine::registry_getSchemaPoolVersion);
emscripten::function("gl_enableErrorCheck", &esengine::gl_enableErrorCheck);
emscripten::function("gl_checkErrors", &esengine::gl_checkErrors);
emscripten::function("renderer_diagnose", &esengine::renderer_diagnose);
}
+// =============================================================================
+// UI Systems
+// =============================================================================
+
+namespace esengine {
+
+void uiLayout_update(ecs::Registry& registry, f32 camLeft, f32 camBottom, f32 camRight, f32 camTop) {
+ ecs::uiLayoutUpdate(registry, camLeft, camBottom, camRight, camTop);
+}
+
+void uiHitTest_update(ecs::Registry& registry, f32 mouseWorldX, f32 mouseWorldY,
+ bool mouseDown, bool mousePressed, bool mouseReleased) {
+ ecs::uiHitTestUpdate(registry, mouseWorldX, mouseWorldY, mouseDown, mousePressed, mouseReleased);
+}
+
+u32 uiHitTest_getHitEntity() {
+ return ecs::uiHitTestGetHitEntity();
+}
+
+u32 uiHitTest_getHitEntityPrev() {
+ return ecs::uiHitTestGetHitEntityPrev();
+}
+
+void uiRenderOrder_update(ecs::Registry& registry) {
+ ecs::uiRenderOrderUpdate(registry);
+}
+
+void uiFlexLayout_update(ecs::Registry& registry) {
+ ecs::uiFlexLayoutUpdate(registry);
+}
+
+f32 getUIRectComputedWidth(ecs::Registry& registry, u32 entity) {
+ auto* rect = registry.tryGet<ecs::UIRect>(static_cast<Entity>(entity));
+ if (!rect) return 0.0f;
+ return rect->computed_width_;
+}
+
+f32 getUIRectComputedHeight(ecs::Registry& registry, u32 entity) {
+ auto* rect = registry.tryGet<ecs::UIRect>(static_cast<Entity>(entity));
+ if (!rect) return 0.0f;
+ return rect->computed_height_;
+}
+
+void transform_update(ecs::Registry& registry) {
+ if (ctx().transformSystem()) {
+ ctx().transformSystem()->update(registry, 0.0f);
+ } else {
+ ecs::TransformSystem ts;
+ ts.update(registry, 0.0f);
+ }
+}
+
+} // namespace esengine
+
+EMSCRIPTEN_BINDINGS(esengine_ui_systems) {
+ emscripten::function("uiLayout_update", &esengine::uiLayout_update);
+ emscripten::function("uiHitTest_update", &esengine::uiHitTest_update);
+ emscripten::function("uiHitTest_getHitEntity", &esengine::uiHitTest_getHitEntity);
+ emscripten::function("uiHitTest_getHitEntityPrev", &esengine::uiHitTest_getHitEntityPrev);
+ emscripten::function("uiRenderOrder_update", &esengine::uiRenderOrder_update);
+ emscripten::function("uiFlexLayout_update", &esengine::uiFlexLayout_update);
+ emscripten::function("getUIRectComputedWidth", &esengine::getUIRectComputedWidth);
+ emscripten::function("getUIRectComputedHeight", &esengine::getUIRectComputedHeight);
+ emscripten::function("transform_update", &esengine::transform_update);
+}
+
int main() {
return 0;
}
diff --git a/src/esengine/ecs/UIFlexLayoutSystem.hpp b/src/esengine/ecs/UIFlexLayoutSystem.hpp
new file mode 100644
index 000000000..e31e6c49a
--- /dev/null
+++ b/src/esengine/ecs/UIFlexLayoutSystem.hpp
@@ -0,0 +1,237 @@
+#pragma once
+
+#include "Registry.hpp"
+#include "components/Transform.hpp"
+#include "components/Hierarchy.hpp"
+#include "components/UIRect.hpp"
+#include "components/Sprite.hpp"
+#include "components/FlexContainer.hpp"
+#include "components/FlexItem.hpp"
+
+#include <algorithm>
+#include <vector>
+#include <cmath>
+
+namespace esengine::ecs {
+
+struct FlexChildItem {
+ Entity entity;
+ f32 grow;
+ f32 shrink;
+ f32 basis;
+ i32 order;
+ f32 main_size;
+ f32 cross_size;
+};
+
+inline void uiFlexLayoutUpdate(Registry& registry) {
+ registry.each<FlexContainer>([&](Entity entity, FlexContainer& flex) {
+ if (!registry.has<UIRect>(entity) || !registry.has<Children>(entity)) return;
+
+ auto& parentRect = registry.get<UIRect>(entity);
+ auto& children = registry.get<Children>(entity);
+ if (children.entities.empty()) return;
+
+ f32 parentW = parentRect.computed_width_ > 0.0f ? parentRect.computed_width_ : parentRect.size.x;
+ f32 parentH = parentRect.computed_height_ > 0.0f ? parentRect.computed_height_ : parentRect.size.y;
+ f32 pivotX = parentRect.pivot.x;
+ f32 pivotY = parentRect.pivot.y;
+
+ // padding: x=left, y=top, z=right, w=bottom
+ f32 padLeft = flex.padding.x;
+ f32 padTop = flex.padding.y;
+ f32 padRight = flex.padding.z;
+ f32 padBottom = flex.padding.w;
+
+ bool isRow = (flex.direction == FlexDirection::Row || flex.direction == FlexDirection::RowReverse);
+ bool isReverse = (flex.direction == FlexDirection::RowReverse || flex.direction == FlexDirection::ColumnReverse);
+
+ f32 contentW = parentW - padLeft - padRight;
+ f32 contentH = parentH - padTop - padBottom;
+ f32 mainSpace = isRow ? contentW : contentH;
+ f32 crossSpace = isRow ? contentH : contentW;
+ f32 mainGap = isRow ? flex.gap.x : flex.gap.y;
+
+ std::vector<FlexChildItem> items;
+ items.reserve(children.entities.size());
+
+ for (Entity child : children.entities) {
+ if (!registry.valid(child)) continue;
+ auto* childRect = registry.tryGet<UIRect>(child);
+ if (!childRect) continue;
+ if (!registry.has<Transform>(child)) continue;
+
+ FlexChildItem item;
+ item.entity = child;
+
+ auto* fi = registry.tryGet<FlexItem>(child);
+ if (fi) {
+ item.grow = fi->flexGrow;
+ item.shrink = fi->flexShrink;
+ item.basis = fi->flexBasis;
+ item.order = fi->order;
+ } else {
+ item.grow = 0.0f;
+ item.shrink = 1.0f;
+ item.basis = -1.0f;
+ item.order = 0;
+ }
+
+ f32 cw = childRect->computed_width_ > 0.0f ? childRect->computed_width_ : childRect->size.x;
+ f32 ch = childRect->computed_height_ > 0.0f ? childRect->computed_height_ : childRect->size.y;
+
+ if (item.basis >= 0.0f) {
+ item.main_size = item.basis;
+ } else {
+ item.main_size = isRow ? cw : ch;
+ }
+ item.cross_size = isRow ? ch : cw;
+
+ items.push_back(item);
+ }
+
+ if (items.empty()) return;
+
+ std::stable_sort(items.begin(), items.end(), [](const FlexChildItem& a, const FlexChildItem& b) {
+ return a.order < b.order;
+ });
+
+ if (isReverse) {
+ std::reverse(items.begin(), items.end());
+ }
+
+ f32 totalMainSize = 0.0f;
+ for (auto& item : items) {
+ totalMainSize += item.main_size;
+ }
+ totalMainSize += mainGap * static_cast<f32>(items.size() - 1);
+
+ f32 freeSpace = mainSpace - totalMainSize;
+
+ if (freeSpace > 0.0f) {
+ f32 totalGrow = 0.0f;
+ for (auto& item : items) {
+ totalGrow += item.grow;
+ }
+ if (totalGrow > 0.0f) {
+ for (auto& item : items) {
+ item.main_size += freeSpace * (item.grow / totalGrow);
+ }
+ freeSpace = 0.0f;
+ }
+ } else if (freeSpace < 0.0f) {
+ f32 totalShrinkBasis = 0.0f;
+ for (auto& item : items) {
+ totalShrinkBasis += item.shrink * item.main_size;
+ }
+ if (totalShrinkBasis > 0.0f) {
+ for (auto& item : items) {
+ item.main_size += freeSpace * (item.shrink * item.main_size / totalShrinkBasis);
+ item.main_size = std::max(0.0f, item.main_size);
+ }
+ freeSpace = 0.0f;
+ }
+ }
+
+ // justify-content positioning
+ f32 cursor = 0.0f;
+ f32 gap = mainGap;
+ usize n = items.size();
+
+ switch (flex.justifyContent) {
+ case JustifyContent::Start:
+ cursor = 0.0f;
+ break;
+ case JustifyContent::Center:
+ cursor = freeSpace * 0.5f;
+ break;
+ case JustifyContent::End:
+ cursor = freeSpace;
+ break;
+ case JustifyContent::SpaceBetween:
+ cursor = 0.0f;
+ if (n > 1) gap = mainGap + freeSpace / static_cast<f32>(n - 1);
+ break;
+ case JustifyContent::SpaceAround:
+ if (n > 0) {
+ f32 spacePerItem = freeSpace / static_cast<f32>(n);
+ cursor = spacePerItem * 0.5f;
+ gap = mainGap + spacePerItem;
+ }
+ break;
+ case JustifyContent::SpaceEvenly:
+ if (n > 0) {
+ f32 spaceUnit = freeSpace / static_cast<f32>(n + 1);
+ cursor = spaceUnit;
+ gap = mainGap + spaceUnit;
+ }
+ break;
+ }
+
+ for (usize i = 0; i < n; i++) {
+ auto& item = items[i];
+ auto& childRect = registry.get<UIRect>(item.entity);
+ auto& transform = registry.get<Transform>(item.entity);
+
+ f32 mainPos = cursor;
+ cursor += item.main_size;
+ if (i < n - 1) cursor += gap;
+
+ // align-items positioning on cross axis
+ f32 crossPos = 0.0f;
+ f32 finalCrossSize = item.cross_size;
+
+ switch (flex.alignItems) {
+ case AlignItems::Start:
+ crossPos = 0.0f;
+ break;
+ case AlignItems::Center:
+ crossPos = (crossSpace - finalCrossSize) * 0.5f;
+ break;
+ case AlignItems::End:
+ crossPos = crossSpace - finalCrossSize;
+ break;
+ case AlignItems::Stretch:
+ crossPos = 0.0f;
+ finalCrossSize = crossSpace;
+ break;
+ }
+
+ f32 finalW, finalH;
+ f32 localX, localY;
+
+ if (isRow) {
+ finalW = item.main_size;
+ finalH = finalCrossSize;
+ f32 cpx = childRect.pivot.x;
+ f32 cpy = childRect.pivot.y;
+ localX = -pivotX * parentW + padLeft + mainPos + cpx * finalW;
+ localY = (1.0f - pivotY) * parentH - padTop - crossPos - (1.0f - cpy) * finalH;
+ } else {
+ finalW = finalCrossSize;
+ finalH = item.main_size;
+ f32 cpx = childRect.pivot.x;
+ f32 cpy = childRect.pivot.y;
+ localX = -pivotX * parentW + padLeft + crossPos + cpx * finalW;
+ localY = (1.0f - pivotY) * parentH - padTop - mainPos - (1.0f - cpy) * finalH;
+ }
+
+ transform.position.x = localX;
+ transform.position.y = localY;
+
+ childRect.computed_width_ = finalW;
+ childRect.computed_height_ = finalH;
+ childRect.layout_managed_ = true;
+
+ auto* sprite = registry.tryGet<Sprite>(item.entity);
+ if (sprite) {
+ if (sprite->size.x != finalW || sprite->size.y != finalH) {
+ sprite->size.x = finalW;
+ sprite->size.y = finalH;
+ }
+ }
+ }
+ });
+}
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/UIHitTestSystem.hpp b/src/esengine/ecs/UIHitTestSystem.hpp
new file mode 100644
index 000000000..6777e3da3
--- /dev/null
+++ b/src/esengine/ecs/UIHitTestSystem.hpp
@@ -0,0 +1,149 @@
+#pragma once
+
+#include "Registry.hpp"
+#include "components/Transform.hpp"
+#include "components/Hierarchy.hpp"
+#include "components/UIRect.hpp"
+#include "components/Sprite.hpp"
+#include "components/Interactable.hpp"
+#include "components/UIInteraction.hpp"
+#include "components/UIMask.hpp"
+
+#include <cmath>
+#include <limits>
+
+namespace esengine::ecs {
+
+inline f32 quaternionToAngle2D(f32 rz, f32 rw) {
+ return 2.0f * std::atan2(rz, rw);
+}
+
+inline bool pointInOBB(
+ f32 px, f32 py,
+ f32 worldX, f32 worldY,
+ f32 worldW, f32 worldH,
+ f32 pivotX, f32 pivotY,
+ f32 rotationZ, f32 rotationW
+) {
+ f32 angle = quaternionToAngle2D(rotationZ, rotationW);
+ f32 sinA = std::sin(-angle);
+ f32 cosA = std::cos(-angle);
+
+ f32 dx = px - worldX;
+ f32 dy = py - worldY;
+ f32 localX = dx * cosA - dy * sinA + worldX;
+ f32 localY = dx * sinA + dy * cosA + worldY;
+
+ f32 left = worldX - worldW * pivotX;
+ f32 right = worldX + worldW * (1.0f - pivotX);
+ f32 bottom = worldY - worldH * pivotY;
+ f32 top = worldY + worldH * (1.0f - pivotY);
+
+ return localX >= left && localX <= right && localY >= bottom && localY <= top;
+}
+
+inline bool isClippedByMask(
+ Registry& registry,
+ Entity entity,
+ f32 worldMouseX,
+ f32 worldMouseY
+) {
+ Entity current = entity;
+ while (registry.has<Parent>(current)) {
+ Entity ancestor = registry.get<Parent>(current).entity;
+ if (!registry.valid(ancestor)) break;
+
+ auto* mask = registry.tryGet<UIMask>(ancestor);
+ if (mask && mask->enabled) {
+ auto* t = registry.tryGet<Transform>(ancestor);
+ auto* rect = registry.tryGet<UIRect>(ancestor);
+ if (t && rect) {
+ t->ensureDecomposed();
+ f32 maskW = (rect->computed_width_ > 0.0f ? rect->computed_width_ : rect->size.x) * t->worldScale.x;
+ f32 maskH = (rect->computed_height_ > 0.0f ? rect->computed_height_ : rect->size.y) * t->worldScale.y;
+ if (!pointInOBB(
+ worldMouseX, worldMouseY,
+ t->worldPosition.x, t->worldPosition.y,
+ maskW, maskH,
+ rect->pivot.x, rect->pivot.y,
+ t->worldRotation.z, t->worldRotation.w
+ )) {
+ return true;
+ }
+ }
+ }
+ current = ancestor;
+ }
+ return false;
+}
+
+struct UIHitTestResult {
+ Entity hit_entity{INVALID_ENTITY};
+ Entity prev_hit_entity{INVALID_ENTITY};
+};
+
+static UIHitTestResult s_hit_test_result;
+
+inline void uiHitTestUpdate(
+ Registry& registry,
+ f32 mouseWorldX, f32 mouseWorldY,
+ bool mouseDown, bool mousePressed, bool mouseReleased
+) {
+ (void)mouseDown;
+ (void)mousePressed;
+ (void)mouseReleased;
+
+ s_hit_test_result.prev_hit_entity = s_hit_test_result.hit_entity;
+ s_hit_test_result.hit_entity = INVALID_ENTITY;
+
+ Entity hitEntity = INVALID_ENTITY;
+ i32 hitLayer = std::numeric_limits<i32>::min();
+
+ registry.each<Interactable>([&](Entity entity, Interactable& interactable) {
+ if (!interactable.enabled || !interactable.raycastTarget) return;
+ if (!registry.has<UIRect>(entity) || !registry.has<Transform>(entity)) return;
+
+ registry.getOrEmplace<UIInteraction>(entity);
+
+ auto& t = registry.get<Transform>(entity);
+ t.ensureDecomposed();
+ auto& rect = registry.get<UIRect>(entity);
+
+ f32 worldW = (rect.computed_width_ > 0.0f ? rect.computed_width_ : rect.size.x) * t.worldScale.x;
+ f32 worldH = (rect.computed_height_ > 0.0f ? rect.computed_height_ : rect.size.y) * t.worldScale.y;
+
+ if (pointInOBB(
+ mouseWorldX, mouseWorldY,
+ t.worldPosition.x, t.worldPosition.y,
+ worldW, worldH,
+ rect.pivot.x, rect.pivot.y,
+ t.worldRotation.z, t.worldRotation.w
+ )) {
+ if (isClippedByMask(registry, entity, mouseWorldX, mouseWorldY)) {
+ return;
+ }
+
+ i32 layer = 0;
+ auto* sprite = registry.tryGet<Sprite>(entity);
+ if (sprite) {
+ layer = sprite->layer;
+ }
+ if (layer > hitLayer) {
+ hitLayer = layer;
+ hitEntity = entity;
+ }
+ }
+ });
+
+ s_hit_test_result.hit_entity = hitEntity;
+}
+
+inline u32 uiHitTestGetHitEntity() {
+ return static_cast<u32>(s_hit_test_result.hit_entity);
+}
+
+inline u32 uiHitTestGetHitEntityPrev() {
+ return static_cast<u32>(s_hit_test_result.prev_hit_entity);
+}
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/UILayoutSystem.hpp b/src/esengine/ecs/UILayoutSystem.hpp
new file mode 100644
index 000000000..0425069ea
--- /dev/null
+++ b/src/esengine/ecs/UILayoutSystem.hpp
@@ -0,0 +1,143 @@
+#pragma once
+
+#include "Registry.hpp"
+#include "components/Transform.hpp"
+#include "components/Hierarchy.hpp"
+#include "components/UIRect.hpp"
+#include "components/Sprite.hpp"
+#include "components/ScreenSpace.hpp"
+
+#include <algorithm>
+#include <cmath>
+
+namespace esengine::ecs {
+
+struct LayoutRect {
+ f32 left;
+ f32 bottom;
+ f32 right;
+ f32 top;
+};
+
+struct LayoutResult {
+ f32 origin_x;
+ f32 origin_y;
+ LayoutRect rect;
+};
+
+inline LayoutResult computeAnchorLayout(
+ const glm::vec2& anchorMin, const glm::vec2& anchorMax,
+ const glm::vec2& offsetMin, const glm::vec2& offsetMax,
+ const glm::vec2& size, const LayoutRect& parentRect,
+ const glm::vec2& pivot
+) {
+ f32 parentW = parentRect.right - parentRect.left;
+ f32 parentH = parentRect.top - parentRect.bottom;
+
+ f32 aLeft = parentRect.left + anchorMin.x * parentW;
+ f32 aRight = parentRect.left + anchorMax.x * parentW;
+ f32 aBottom = parentRect.bottom + anchorMin.y * parentH;
+ f32 aTop = parentRect.bottom + anchorMax.y * parentH;
+
+ f32 myLeft, myBottom, myRight, myTop;
+
+ if (anchorMin.x == anchorMax.x) {
+ 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) {
+ myBottom = aBottom + offsetMin.y - size.y * pivot.y;
+ myTop = myBottom + size.y;
+ } else {
+ myBottom = aBottom + offsetMin.y;
+ myTop = aTop + offsetMax.y;
+ }
+
+ f32 width = std::max(0.0f, myRight - myLeft);
+ f32 height = std::max(0.0f, myTop - myBottom);
+ f32 originX = myLeft + pivot.x * width;
+ f32 originY = myBottom + pivot.y * height;
+
+ return {
+ originX,
+ originY,
+ { myLeft, myBottom, myLeft + width, myBottom + height },
+ };
+}
+
+inline void layoutEntity(
+ Registry& registry,
+ Entity entity,
+ const LayoutRect& parentRect,
+ f32 parentOriginX,
+ f32 parentOriginY,
+ bool isRoot
+) {
+ auto* uiRect = registry.tryGet<UIRect>(entity);
+ if (!uiRect) return;
+
+ auto result = computeAnchorLayout(
+ uiRect->anchorMin, uiRect->anchorMax,
+ uiRect->offsetMin, uiRect->offsetMax,
+ uiRect->size, parentRect, uiRect->pivot
+ );
+
+ f32 width = result.rect.right - result.rect.left;
+ f32 height = result.rect.top - result.rect.bottom;
+ uiRect->computed_width_ = width;
+ uiRect->computed_height_ = height;
+
+ auto* sprite = registry.tryGet<Sprite>(entity);
+ if (sprite) {
+ if (sprite->size.x != width || sprite->size.y != height) {
+ sprite->size.x = width;
+ sprite->size.y = height;
+ }
+ }
+
+ if (!uiRect->layout_managed_) {
+ auto* transform = registry.tryGet<Transform>(entity);
+ if (transform) {
+ if (isRoot) {
+ transform->position.x = result.origin_x;
+ transform->position.y = result.origin_y;
+ } else {
+ transform->position.x = result.origin_x - parentOriginX;
+ transform->position.y = result.origin_y - parentOriginY;
+ }
+ }
+ }
+
+ auto* children = registry.tryGet<Children>(entity);
+ if (!children) return;
+
+ for (Entity child : children->entities) {
+ if (registry.valid(child)) {
+ layoutEntity(registry, child, result.rect, result.origin_x, result.origin_y, false);
+ }
+ }
+}
+
+inline void uiLayoutUpdate(
+ Registry& registry,
+ f32 camLeft, f32 camBottom, f32 camRight, f32 camTop
+) {
+ registry.each<UIRect>([](Entity, UIRect& rect) {
+ rect.layout_managed_ = false;
+ });
+
+ LayoutRect cameraRect{ camLeft, camBottom, camRight, camTop };
+ f32 cameraOriginX = (camLeft + camRight) * 0.5f;
+ f32 cameraOriginY = (camBottom + camTop) * 0.5f;
+
+ registry.each<ScreenSpace>([&](Entity entity, ScreenSpace&) {
+ if (!registry.has<UIRect>(entity) || !registry.has<Transform>(entity)) return;
+ layoutEntity(registry, entity, cameraRect, cameraOriginX, cameraOriginY, true);
+ });
+}
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/UIRenderOrderSystem.hpp b/src/esengine/ecs/UIRenderOrderSystem.hpp
new file mode 100644
index 000000000..9e94af661
--- /dev/null
+++ b/src/esengine/ecs/UIRenderOrderSystem.hpp
@@ -0,0 +1,39 @@
+#pragma once
+
+#include "Registry.hpp"
+#include "components/Hierarchy.hpp"
+#include "components/UIRect.hpp"
+#include "components/Sprite.hpp"
+#include "components/ScreenSpace.hpp"
+
+namespace esengine::ecs {
+
+inline i32 assignRenderOrder(Registry& registry, Entity entity, i32 counter) {
+ if (registry.has<Sprite>(entity) && registry.has<UIRect>(entity)) {
+ auto& sprite = registry.get<Sprite>(entity);
+ if (sprite.layer != counter) {
+ sprite.layer = counter;
+ }
+ counter++;
+ }
+
+ auto* children = registry.tryGet<Children>(entity);
+ if (!children) return counter;
+
+ for (Entity child : children->entities) {
+ if (registry.valid(child)) {
+ counter = assignRenderOrder(registry, child, counter);
+ }
+ }
+ return counter;
+}
+
+inline void uiRenderOrderUpdate(Registry& registry) {
+ i32 counter = 0;
+ registry.each<ScreenSpace>([&](Entity entity, ScreenSpace&) {
+ if (!registry.has<UIRect>(entity)) return;
+ counter = assignRenderOrder(registry, entity, counter);
+ });
+}
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/FlexContainer.hpp b/src/esengine/ecs/components/FlexContainer.hpp
new file mode 100644
index 000000000..e11aa274a
--- /dev/null
+++ b/src/esengine/ecs/components/FlexContainer.hpp
@@ -0,0 +1,57 @@
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+#include "../../math/Math.hpp"
+
+namespace esengine::ecs {
+
+ES_ENUM()
+enum class FlexDirection : u8 {
+ Row,
+ Column,
+ RowReverse,
+ ColumnReverse
+};
+
+ES_ENUM()
+enum class FlexWrap : u8 {
+ NoWrap,
+ Wrap
+};
+
+ES_ENUM()
+enum class JustifyContent : u8 {
+ Start,
+ Center,
+ End,
+ SpaceBetween,
+ SpaceAround,
+ SpaceEvenly
+};
+
+ES_ENUM()
+enum class AlignItems : u8 {
+ Start,
+ Center,
+ End,
+ Stretch
+};
+
+ES_COMPONENT()
+struct FlexContainer {
+ ES_PROPERTY()
+ FlexDirection direction{FlexDirection::Row};
+ ES_PROPERTY()
+ FlexWrap wrap{FlexWrap::NoWrap};
+ ES_PROPERTY()
+ JustifyContent justifyContent{JustifyContent::Start};
+ ES_PROPERTY()
+ AlignItems alignItems{AlignItems::Stretch};
+ ES_PROPERTY()
+ glm::vec2 gap{0.0f, 0.0f};
+ ES_PROPERTY()
+ glm::vec4 padding{0.0f, 0.0f, 0.0f, 0.0f};
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/FlexItem.hpp b/src/esengine/ecs/components/FlexItem.hpp
new file mode 100644
index 000000000..f7a1f0fe0
--- /dev/null
+++ b/src/esengine/ecs/components/FlexItem.hpp
@@ -0,0 +1,20 @@
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+
+namespace esengine::ecs {
+
+ES_COMPONENT()
+struct FlexItem {
+ ES_PROPERTY()
+ f32 flexGrow{0.0f};
+ ES_PROPERTY()
+ f32 flexShrink{1.0f};
+ ES_PROPERTY()
+ f32 flexBasis{-1.0f};
+ ES_PROPERTY()
+ i32 order{0};
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/Interactable.hpp b/src/esengine/ecs/components/Interactable.hpp
new file mode 100644
index 000000000..c00c157b5
--- /dev/null
+++ b/src/esengine/ecs/components/Interactable.hpp
@@ -0,0 +1,18 @@
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+
+namespace esengine::ecs {
+
+ES_COMPONENT()
+struct Interactable {
+ ES_PROPERTY()
+ bool enabled{true};
+ ES_PROPERTY()
+ bool blockRaycast{true};
+ ES_PROPERTY()
+ bool raycastTarget{true};
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/ScreenSpace.hpp b/src/esengine/ecs/components/ScreenSpace.hpp
new file mode 100644
index 000000000..584eb85a7
--- /dev/null
+++ b/src/esengine/ecs/components/ScreenSpace.hpp
@@ -0,0 +1,11 @@
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+
+namespace esengine::ecs {
+
+ES_COMPONENT()
+struct ScreenSpace {};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/UIInteraction.hpp b/src/esengine/ecs/components/UIInteraction.hpp
new file mode 100644
index 000000000..aeb88e5ed
--- /dev/null
+++ b/src/esengine/ecs/components/UIInteraction.hpp
@@ -0,0 +1,20 @@
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+
+namespace esengine::ecs {
+
+ES_COMPONENT()
+struct UIInteraction {
+ ES_PROPERTY()
+ bool hovered{false};
+ ES_PROPERTY()
+ bool pressed{false};
+ ES_PROPERTY()
+ bool justPressed{false};
+ ES_PROPERTY()
+ bool justReleased{false};
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/UIMask.hpp b/src/esengine/ecs/components/UIMask.hpp
new file mode 100644
index 000000000..140cf7382
--- /dev/null
+++ b/src/esengine/ecs/components/UIMask.hpp
@@ -0,0 +1,22 @@
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+
+namespace esengine::ecs {
+
+ES_ENUM()
+enum class MaskMode : u8 {
+ Scissor,
+ Stencil
+};
+
+ES_COMPONENT()
+struct UIMask {
+ ES_PROPERTY()
+ bool enabled{true};
+ ES_PROPERTY()
+ MaskMode mode{MaskMode::Scissor};
+};
+
+} // namespace esengine::ecs
diff --git a/src/esengine/ecs/components/UIRect.hpp b/src/esengine/ecs/components/UIRect.hpp
new file mode 100644
index 000000000..ec2e56fdb
--- /dev/null
+++ b/src/esengine/ecs/components/UIRect.hpp
@@ -0,0 +1,37 @@
+#pragma once
+
+#include "../../core/Types.hpp"
+#include "../../core/Reflection.hpp"
+#include "../../math/Math.hpp"
+
+namespace esengine::ecs {
+
+ES_COMPONENT()
+struct UIRect {
+ ES_PROPERTY()
+ glm::vec2 anchorMin{0.5f, 0.5f};
+
+ ES_PROPERTY()
+ glm::vec2 anchorMax{0.5f, 0.5f};
+
+ ES_PROPERTY()
+ glm::vec2 offsetMin{0.0f, 0.0f};
+
+ ES_PROPERTY()
+ glm::vec2 offsetMax{0.0f, 0.0f};
+
+ ES_PROPERTY()
+ glm::vec2 size{100.0f, 100.0f};
+
+ ES_PROPERTY()
+ glm::vec2 pivot{0.5f, 0.5f};
+
+ f32 computed_width_{0.0f};
+ f32 computed_height_{0.0f};
+ bool dirty_{true};
+ bool layout_managed_{false};
+
+ UIRect() = default;
+};
+
+} // namespace esengine::ecs