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.

docs: improve UI interaction, asset loading, and masking documentation

esengine0444a3b38966
diff --git a/docs/astro/src/content/docs/guides/assets.mdx b/docs/astro/src/content/docs/guides/assets.mdx
index deae713bb..2a81e66f9 100644
--- a/docs/astro/src/content/docs/guides/assets.mdx
+++ b/docs/astro/src/content/docs/guides/assets.mdx
@@ -37,12 +37,17 @@ sprite.texture = tex.handle;
### Other Texture Methods
-| Method | Description |
-|--------|-------------|
-| `getTexture(path)` | Returns cached `TextureInfo` if already loaded, `undefined` otherwise |
-| `hasTexture(path)` | Returns `true` if the texture is cached |
-| `releaseTexture(path)` | Releases the texture from GPU memory and cache |
-| `releaseAll()` | Releases all cached assets |
+| Method | Returns | Description |
+|--------|---------|-------------|
+| `loadTextureRaw(source)` | `Promise<TextureInfo>` | Load without vertical flip (used by Spine runtime) |
+| `getTexture(path)` | `TextureInfo \| undefined` | Returns cached `TextureInfo` if already loaded |
+| `hasTexture(path)` | `boolean` | Returns `true` if the texture is cached |
+| `releaseTexture(path)` | `void` | Decrements ref count; releases from GPU when count reaches zero |
+| `releaseAll()` | `void` | Releases all cached assets (textures, fonts, materials, shaders, prefabs, spine) |
+
+<Aside type="note">
+ Textures are reference-counted. Each `loadTexture()` call increments the count; `releaseTexture()` decrements it. The GPU resource is only freed when the count reaches zero.
+</Aside>
### 9-Slice Metadata
@@ -55,6 +60,14 @@ assets.setTextureMetadata(tex.handle, {
});
```
+You can also set metadata by path if the texture is already loaded:
+
+```typescript
+assets.setTextureMetadataByPath('assets/panel.png', {
+ left: 10, right: 10, top: 10, bottom: 10
+});
+```
+
## Spine Loading
```typescript
@@ -69,10 +82,11 @@ if (!result.success) {
2. Parses the atlas for texture filenames and loads each texture
3. Fetches the skeleton file (`.json` or `.skel` binary) and writes it to the virtual filesystem
-| Method | Description |
-|--------|-------------|
-| `loadSpine(skeleton, atlas, baseUrl?)` | Load Spine skeleton and atlas |
-| `isSpineLoaded(skeleton, atlas)` | Check if a Spine asset pair is already loaded |
+| Method | Returns | Description |
+|--------|---------|-------------|
+| `loadSpine(skeleton, atlas, baseUrl?)` | `Promise<SpineLoadResult>` | Load Spine skeleton and atlas |
+| `isSpineLoaded(skeleton, atlas)` | `boolean` | Check if a Spine asset pair is already loaded |
+| `releaseSpine(key)` | `void` | Release a loaded Spine asset (`key` = `"skeleton:atlas"`) |
## BitmapFont Loading
@@ -84,8 +98,8 @@ Supports `.fnt` (BMFont text format) and `.bmfont` (JSON metadata) files. The lo
| Method | Returns | Description |
|--------|---------|-------------|
-| `loadBitmapFont(path)` | `Promise<number>` | Load a bitmap font file and its textures. Returns a font handle |
-| `getFont(path)` | `number \| undefined` | Get cached font handle, `undefined` if not loaded |
+| `loadBitmapFont(path, baseUrl?)` | `Promise<FontHandle>` | Load a bitmap font file and its textures. Returns a font handle |
+| `getFont(path)` | `FontHandle \| undefined` | Get cached font handle, `undefined` if not loaded |
| `releaseFont(path)` | `void` | Release the font and its textures from memory |
## Prefab Loading
@@ -167,6 +181,12 @@ const loaded = await assets.loadMaterial('assets/effects/glow.esmaterial');
sprite.material = loaded.handle;
```
+| Method | Returns | Description |
+|--------|---------|-------------|
+| `loadMaterial(path, baseUrl?)` | `Promise<LoadedMaterial>` | Load and compile a `.esmaterial` file |
+| `getMaterial(path, baseUrl?)` | `LoadedMaterial \| undefined` | Get cached material if already loaded |
+| `hasMaterial(path, baseUrl?)` | `boolean` | Check if a material is cached |
+
See [Materials & Shaders](/microes/guides/materials/) for the full material API and `.esmaterial` file format.
## Caching
@@ -189,10 +209,30 @@ const tex = await assets.loadTexture('sprites/player.png');
Absolute paths and full URLs are not affected by `baseUrl`.
+## Scene Loading
+
+Load a scene file with all its referenced assets in a single call:
+
+```typescript
+const sceneData = await assets.loadJson<SceneData>('assets/scenes/main.esscene');
+const entityMap = await assets.loadScene(world, sceneData);
+```
+
+`loadScene` pre-collects all asset references in the scene (textures, materials, Spine, fonts, prefabs), loads them in parallel via `Promise.all`, then instantiates the entity hierarchy. Returns a `Map<number, Entity>` mapping scene IDs to runtime entities.
+
## Embedded Assets
For Playable Ad builds, the editor's build pipeline automatically embeds all referenced assets as data URIs into the output bundle. At runtime, `assets.loadTexture()` / `assets.loadJson()` and other load calls resolve from the embedded data instead of fetching over the network — no code changes are needed.
+For custom builds, you can register embedded assets manually:
+
+```typescript
+assets.registerEmbeddedAssets({
+ 'assets/player.png': 'data:image/png;base64,...',
+ 'assets/config.json': 'data:application/json;base64,...',
+});
+```
+
## Addressable Assets
Addressable assets let you load resources by logical address, label, or group instead of raw file paths. The editor builds an `AddressableManifest` during the build process, which maps addresses and labels to asset paths.
@@ -203,6 +243,15 @@ Addressable assets let you load resources by logical address, label, or group in
const texture = await assets.load('player-idle');
```
+To resolve an address to its manifest entry without loading:
+
+```typescript
+const entry = assets.resolveAddress('player-idle');
+if (entry) {
+ console.log(`Type: ${entry.type}, Path: ${entry.path}`);
+}
+```
+
### Loading by Label
Load all assets tagged with a label. Returns an `AssetBundle`:
diff --git a/docs/astro/src/content/docs/guides/ui-interaction.mdx b/docs/astro/src/content/docs/guides/ui-interaction.mdx
index 1f44d7e86..88878f818 100644
--- a/docs/astro/src/content/docs/guides/ui-interaction.mdx
+++ b/docs/astro/src/content/docs/guides/ui-interaction.mdx
@@ -43,9 +43,54 @@ addSystem(defineSystem(
));
```
-**Event types:** `click`, `press`, `release`, `hover_enter`, `hover_exit`, `focus`, `blur`, `submit`, `change`, `drag_start`, `drag_move`, `drag_end`, `scroll`
+### Event Types
+
+| Type | Description | Bubbles | Triggered By |
+|------|-------------|---------|-------------|
+| `click` | Pointer released on same entity where pressed | Yes | UIInteraction |
+| `press` | Pointer button pressed down | Yes | UIInteraction |
+| `release` | Pointer button released | Yes | UIInteraction |
+| `hover_enter` | Pointer entered entity bounds | No | UIInteraction |
+| `hover_exit` | Pointer left entity bounds | No | UIInteraction |
+| `focus` | Element received keyboard focus (click or Tab) | No | Focusable |
+| `blur` | Element lost keyboard focus | No | Focusable |
+| `submit` | Enter key pressed on single-line TextInput | No | TextInput |
+| `change` | Value changed on Slider, Toggle, TextInput, or Dropdown | No | Widget-specific |
+| `drag_start` | Pointer moved beyond drag threshold | No | Draggable |
+| `drag_move` | Pointer moved while dragging | No | Draggable |
+| `drag_end` | Pointer released after drag | No | Draggable |
+| `scroll` | ScrollView content scrolled | No | ScrollView |
+
+### UIEvent Structure
+
+Each event object contains:
-Events bubble up the entity hierarchy. If a parent has `Interactable` with `blockRaycast: true`, bubbling stops there.
+| Property | Type | Description |
+|----------|------|-------------|
+| `entity` | Entity | The entity that received the event |
+| `type` | string | Event type (see table above) |
+| `target` | Entity | Original entity that triggered the event |
+
+### Querying Events
+
+```typescript
+// Query all events of a specific type
+for (const e of events.query('click')) {
+ console.log('Clicked:', e.entity);
+}
+
+// Check if a specific entity has a specific event
+if (events.hasEvent(buttonEntity, 'click')) {
+ handleButton();
+}
+
+// Drain all events (returns and clears the queue)
+const all = events.drain();
+```
+
+### Event Bubbling
+
+`press`, `release`, and `click` events bubble up the entity hierarchy. If a parent has `Interactable` with `blockRaycast: true`, bubbling stops there. `hover_enter` and `hover_exit` do **not** bubble.
## Focusable
@@ -67,6 +112,31 @@ Enables drag-to-move on a UI element.
| `lockX` | boolean | `false` | Lock horizontal movement |
| `lockY` | boolean | `false` | Lock vertical movement |
+When dragging is active, the engine adds a `DragState` component to the entity:
+
+| Property | Type | Description |
+|----------|------|-------------|
+| `isDragging` | boolean | Currently dragging |
+| `startWorldPos` | `{x, y}` | Entity position when drag started |
+| `currentWorldPos` | `{x, y}` | Current world position |
+| `deltaWorld` | `{x, y}` | Movement this frame |
+| `totalDeltaWorld` | `{x, y}` | Total movement since drag start |
+
+## Processing Pipeline
+
+UI interaction systems run in a fixed order each frame:
+
+| Schedule | System | Purpose |
+|----------|--------|---------|
+| Last (prev frame) | InputPlugin | Clears one-frame input state |
+| PreUpdate | UIInteractionSystem | Hit test, hover, press, release, click |
+| PreUpdate | DragPlugin | Drag state tracking, drag events |
+| Update | ButtonSystem, TogglePlugin, SliderPlugin, etc. | Widget state updates |
+
+<Aside type="tip">
+ `justPressed` and `justReleased` on UIInteraction are only `true` for one frame. Read them in PreUpdate or Update — by PostUpdate they are already cleared.
+</Aside>
+
## Next Steps
- [Widgets](/microes/guides/ui-widgets/) — buttons, sliders, toggles, and more
diff --git a/docs/astro/src/content/docs/guides/ui-masking.mdx b/docs/astro/src/content/docs/guides/ui-masking.mdx
index b7f77633a..b2f120c38 100644
--- a/docs/astro/src/content/docs/guides/ui-masking.mdx
+++ b/docs/astro/src/content/docs/guides/ui-masking.mdx
@@ -7,29 +7,165 @@ import { Aside } from '@astrojs/starlight/components';
## UIMask
-Clips child entities to the parent's `UIRect` bounds.
+Clips all **child** entities to the parent's `UIRect` bounds. The entity with `UIMask` itself is not clipped — only its descendants.
+
+**Required components:** The masked entity must have `Transform` and `UIRect`.
+
+### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `enabled` | boolean | `true` | Whether clipping is active |
-| `mode` | MaskMode | `Scissor` | `Scissor` (0), `Stencil` (1) |
+| `mode` | MaskMode | `Scissor` | Masking technique (see below) |
+
+### MaskMode
+
+| Mode | Value | Description |
+|------|-------|-------------|
+| `Scissor` | 0 | GPU scissor test — fast, axis-aligned rectangles only |
+| `Stencil` | 1 | Stencil buffer — supports arbitrary shapes and nesting |
+
+**When to use which:**
+
+- **Scissor** — Use for simple rectangular containers like scroll views, panels, and card lists. Faster but limited to axis-aligned rectangles.
+- **Stencil** — Use when you need non-rectangular masks (circular avatars, custom shapes) or when nesting masks inside masks (supports up to 255 levels). Slightly more expensive.
+
+### Setup in Editor
+
+1. Select or create a UI entity with `UIRect` (this defines the clipping bounds)
+2. Add the `UIMask` component in the Inspector
+3. Choose `Scissor` or `Stencil` mode
+4. Any child entities added under this entity will be clipped to its bounds
+
+### Setup in Code
+
+```typescript
+import { UIMask, MaskMode } from 'esengine';
-Nested `UIMask` entities clip to the intersection of all parent masks.
+// Create a mask container
+const panel = world.spawn();
+world.insert(panel, UIRect, {
+ anchorMin: { x: 0.1, y: 0.1 },
+ anchorMax: { x: 0.9, y: 0.9 },
+});
+world.insert(panel, UIMask, { enabled: true, mode: MaskMode.Scissor });
+
+// Child content — automatically clipped
+const content = world.spawn();
+world.setParent(content, panel);
+world.insert(content, Sprite, { texture: myTexture });
+```
+
+### Nested Masks
+
+Scissor masks intersect with parent scissors — a child scissor mask produces the overlapping rectangle of both.
+
+Stencil masks support true nesting: each level gets its own stencil ref value, and children are tested against their parent's stencil. Up to 255 nesting levels are supported.
+
+```
+Root (UIMask Stencil)
+ ├── Header (clipped to Root)
+ └── Body (UIMask Stencil) ← nested mask
+ ├── Item 1 (clipped to Body ∩ Root)
+ └── Item 2 (clipped to Body ∩ Root)
+```
<Aside type="caution">
- `UIMask` only clips **child** entities — the entity with UIMask itself is not clipped.
+ Mixing Scissor and Stencil modes in the same hierarchy is allowed — they use independent GPU features and don't interfere with each other.
</Aside>
+---
+
## SafeArea
-Adapts layout to device safe areas (notches, rounded corners). Useful for mobile and WeChat MiniGame.
+Automatically adapts a UI element's layout to device safe areas (notches, rounded corners, status bars). The component adjusts `UIRect.offsetMin` and `UIRect.offsetMax` to shrink the element away from unsafe edges.
+
+**Required components:** The entity must have `UIRect`.
+
+### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
-| `applyTop` | boolean | `true` | Apply to top edge |
-| `applyBottom` | boolean | `true` | Apply to bottom edge |
-| `applyLeft` | boolean | `true` | Apply to left edge |
-| `applyRight` | boolean | `true` | Apply to right edge |
+| `applyTop` | boolean | `true` | Shrink from top edge (status bar, notch) |
+| `applyBottom` | boolean | `true` | Shrink from bottom edge (home indicator) |
+| `applyLeft` | boolean | `true` | Shrink from left edge (landscape notch) |
+| `applyRight` | boolean | `true` | Shrink from right edge (landscape notch) |
+
+### How It Works
+
+1. The `SafeAreaPlugin` reads device insets at startup and on window resize
+2. Insets are scaled from screen pixels to world units based on canvas aspect ratio
+3. Each frame (PreUpdate), the plugin applies the scaled insets to `UIRect.offsetMin` / `UIRect.offsetMax` for each entity with `SafeArea`
+
+### Typical Usage
+
+Create a full-screen container with `SafeArea` and place all UI content inside it:
+
+```
+Canvas (full screen)
+ └── SafeArea Container (UIRect: anchors 0,0 → 1,1) ← add SafeArea here
+ ├── HUD
+ ├── Score
+ └── Controls
+```
+
+**In the editor:** Add `SafeArea` to your root UI panel. Set anchors to stretch (0,0 → 1,1). All children will be laid out within the safe area.
+
+**In code:**
+
+```typescript
+import { SafeArea } from 'esengine';
+
+const safeContainer = world.spawn();
+world.insert(safeContainer, UIRect, {
+ anchorMin: { x: 0, y: 0 },
+ anchorMax: { x: 1, y: 1 },
+});
+world.insert(safeContainer, SafeArea, {
+ applyTop: true,
+ applyBottom: true,
+ applyLeft: true,
+ applyRight: true,
+});
+```
+
+### Selective Edges
+
+You may want SafeArea on some edges but not others. For example, a bottom navigation bar only needs the bottom safe area:
+
+```typescript
+world.insert(navBar, SafeArea, {
+ applyTop: false,
+ applyBottom: true,
+ applyLeft: true,
+ applyRight: true,
+});
+```
+
+### Platform Support
+
+| Platform | How Insets are Detected |
+|----------|----------------------|
+| **Web** | CSS `env(safe-area-inset-*)` via computed style variables `--sat`, `--sab`, `--sal`, `--sar` |
+| **WeChat MiniGame** | `wx.getSystemInfoSync()` — reads `safeArea` field, auto-updates on window resize |
+| **Desktop** | Returns zero insets (no safe area concerns) |
+
+<Aside type="tip">
+ For web, ensure your HTML has `<meta name="viewport" content="viewport-fit=cover">` so the browser exposes safe area insets. Without this, all insets will be zero.
+</Aside>
+
+### Plugin Registration
+
+Both `uiMaskPlugin` and `safeAreaPlugin` are **automatically registered** when using `createWebApp()`. For manual setup:
+
+```typescript
+import { uiMaskPlugin, safeAreaPlugin } from 'esengine';
+
+const app = App.new()
+ .addPlugin(uiMaskPlugin)
+ .addPlugin(safeAreaPlugin)
+ .run();
+```
## Next Steps
diff --git a/docs/astro/src/content/docs/zh/guides/assets.mdx b/docs/astro/src/content/docs/zh/guides/assets.mdx
index ac511d767..e6b9f2c3e 100644
--- a/docs/astro/src/content/docs/zh/guides/assets.mdx
+++ b/docs/astro/src/content/docs/zh/guides/assets.mdx
@@ -37,12 +37,17 @@ sprite.texture = tex.handle;
### 其他纹理方法
-| 方法 | 说明 |
-|------|------|
-| `getTexture(path)` | 返回已缓存的 `TextureInfo`,未加载则返回 `undefined` |
-| `hasTexture(path)` | 判断纹理是否已缓存 |
-| `releaseTexture(path)` | 从 GPU 内存和缓存中释放纹理 |
-| `releaseAll()` | 释放所有已缓存的资源 |
+| 方法 | 返回值 | 说明 |
+|------|--------|------|
+| `loadTextureRaw(source)` | `Promise<TextureInfo>` | 不翻转加载(Spine 运行时使用) |
+| `getTexture(path)` | `TextureInfo \| undefined` | 返回已缓存的 `TextureInfo` |
+| `hasTexture(path)` | `boolean` | 判断纹理是否已缓存 |
+| `releaseTexture(path)` | `void` | 减少引用计数;计数归零时释放 GPU 资源 |
+| `releaseAll()` | `void` | 释放所有已缓存的资源(纹理、字体、材质、着色器、预制体、Spine) |
+
+<Aside type="note">
+ 纹理使用引用计数。每次 `loadTexture()` 调用递增计数;`releaseTexture()` 递减。GPU 资源仅在计数归零时释放。
+</Aside>
### 九宫格元数据
@@ -55,6 +60,14 @@ assets.setTextureMetadata(tex.handle, {
});
```
+也可以按路径设置(纹理已加载时):
+
+```typescript
+assets.setTextureMetadataByPath('assets/panel.png', {
+ left: 10, right: 10, top: 10, bottom: 10
+});
+```
+
## Spine 加载
```typescript
@@ -69,10 +82,11 @@ if (!result.success) {
2. 解析 atlas 中的纹理文件名并逐一加载
3. 获取骨骼文件(`.json` 或 `.skel` 二进制)并写入虚拟文件系统
-| 方法 | 说明 |
-|------|------|
-| `loadSpine(skeleton, atlas, baseUrl?)` | 加载 Spine 骨骼和图集 |
-| `isSpineLoaded(skeleton, atlas)` | 检查 Spine 资源对是否已加载 |
+| 方法 | 返回值 | 说明 |
+|------|--------|------|
+| `loadSpine(skeleton, atlas, baseUrl?)` | `Promise<SpineLoadResult>` | 加载 Spine 骨骼和图集 |
+| `isSpineLoaded(skeleton, atlas)` | `boolean` | 检查 Spine 资源对是否已加载 |
+| `releaseSpine(key)` | `void` | 释放已加载的 Spine 资源(`key` = `"skeleton:atlas"`) |
## 位图字体加载
@@ -84,8 +98,8 @@ const fontHandle = await assets.loadBitmapFont('assets/my-font.fnt');
| 方法 | 返回值 | 说明 |
|------|--------|------|
-| `loadBitmapFont(path)` | `Promise<number>` | 加载位图字体文件及其纹理,返回字体句柄 |
-| `getFont(path)` | `number \| undefined` | 获取已缓存的字体句柄,未加载则返回 `undefined` |
+| `loadBitmapFont(path, baseUrl?)` | `Promise<FontHandle>` | 加载位图字体文件及其纹理,返回字体句柄 |
+| `getFont(path)` | `FontHandle \| undefined` | 获取已缓存的字体句柄,未加载则返回 `undefined` |
| `releaseFont(path)` | `void` | 从内存中释放字体及其纹理 |
## 预制体加载
@@ -167,6 +181,12 @@ const loaded = await assets.loadMaterial('assets/effects/glow.esmaterial');
sprite.material = loaded.handle;
```
+| 方法 | 返回值 | 说明 |
+|------|--------|------|
+| `loadMaterial(path, baseUrl?)` | `Promise<LoadedMaterial>` | 加载并编译 `.esmaterial` 文件 |
+| `getMaterial(path, baseUrl?)` | `LoadedMaterial \| undefined` | 获取已缓存的材质 |
+| `hasMaterial(path, baseUrl?)` | `boolean` | 检查材质是否已缓存 |
+
详见[材质与着色器](/microes/zh/guides/materials/)了解完整的材质 API 和 `.esmaterial` 文件格式。
## 缓存机制
@@ -189,10 +209,30 @@ const tex = await assets.loadTexture('sprites/player.png');
绝对路径和完整 URL 不受 `baseUrl` 影响。
+## 场景加载
+
+通过一次调用加载场景文件及其所有引用的资源:
+
+```typescript
+const sceneData = await assets.loadJson<SceneData>('assets/scenes/main.esscene');
+const entityMap = await assets.loadScene(world, sceneData);
+```
+
+`loadScene` 预先收集场景中所有资产引用(纹理、材质、Spine、字体、预制体),通过 `Promise.all` 并行加载,然后实例化实体层级。返回 `Map<number, Entity>`,将场景 ID 映射到运行时实体。
+
## 嵌入式资源
对于 Playable Ad 构建,编辑器的构建流程会自动将所有引用的资源以 data URI 形式嵌入输出包中。运行时 `assets.loadTexture()` / `assets.loadJson()` 等加载调用会直接从嵌入数据解析,无需网络请求,也无需修改任何代码。
+对于自定义构建,可以手动注册嵌入式资源:
+
+```typescript
+assets.registerEmbeddedAssets({
+ 'assets/player.png': 'data:image/png;base64,...',
+ 'assets/config.json': 'data:application/json;base64,...',
+});
+```
+
## Addressable 资产
Addressable 资产允许通过逻辑地址、标签或分组加载资源,而非直接使用文件路径。编辑器在构建过程中生成 `AddressableManifest`,将地址和标签映射到资产路径。
@@ -203,6 +243,15 @@ Addressable 资产允许通过逻辑地址、标签或分组加载资源,而
const texture = await assets.load('player-idle');
```
+无需加载即可解析地址到清单条目:
+
+```typescript
+const entry = assets.resolveAddress('player-idle');
+if (entry) {
+ console.log(`类型: ${entry.type},路径: ${entry.path}`);
+}
+```
+
### 按标签加载
加载标记了某个标签的所有资产,返回 `AssetBundle`:
diff --git a/docs/astro/src/content/docs/zh/guides/ui-interaction.mdx b/docs/astro/src/content/docs/zh/guides/ui-interaction.mdx
index 61e3354b8..51ea694a5 100644
--- a/docs/astro/src/content/docs/zh/guides/ui-interaction.mdx
+++ b/docs/astro/src/content/docs/zh/guides/ui-interaction.mdx
@@ -43,9 +43,54 @@ addSystem(defineSystem(
));
```
-**事件类型:** `click`、`press`、`release`、`hover_enter`、`hover_exit`、`focus`、`blur`、`submit`、`change`、`drag_start`、`drag_move`、`drag_end`、`scroll`
+### 事件类型
+
+| 类型 | 说明 | 冒泡 | 触发者 |
+|------|------|------|--------|
+| `click` | 指针在同一实体上按下后释放 | 是 | UIInteraction |
+| `press` | 指针按钮按下 | 是 | UIInteraction |
+| `release` | 指针按钮释放 | 是 | UIInteraction |
+| `hover_enter` | 指针进入实体边界 | 否 | UIInteraction |
+| `hover_exit` | 指针离开实体边界 | 否 | UIInteraction |
+| `focus` | 元素获得键盘焦点(点击或 Tab) | 否 | Focusable |
+| `blur` | 元素失去键盘焦点 | 否 | Focusable |
+| `submit` | 单行 TextInput 中按下 Enter | 否 | TextInput |
+| `change` | Slider、Toggle、TextInput 或 Dropdown 的值改变 | 否 | 各控件 |
+| `drag_start` | 指针移动超过拖拽阈值 | 否 | Draggable |
+| `drag_move` | 拖拽过程中指针移动 | 否 | Draggable |
+| `drag_end` | 拖拽后释放指针 | 否 | Draggable |
+| `scroll` | ScrollView 内容滚动 | 否 | ScrollView |
+
+### UIEvent 结构
+
+每个事件对象包含:
-事件沿实体层级向上冒泡。如果父级的 `Interactable` 设置了 `blockRaycast: true`,冒泡在此停止。
+| 属性 | 类型 | 说明 |
+|------|------|------|
+| `entity` | Entity | 接收事件的实体 |
+| `type` | string | 事件类型(见上表) |
+| `target` | Entity | 触发事件的原始实体 |
+
+### 查询事件
+
+```typescript
+// 查询特定类型的所有事件
+for (const e of events.query('click')) {
+ console.log('点击了:', e.entity);
+}
+
+// 检查特定实体是否有特定事件
+if (events.hasEvent(buttonEntity, 'click')) {
+ handleButton();
+}
+
+// 消费所有事件(返回并清空队列)
+const all = events.drain();
+```
+
+### 事件冒泡
+
+`press`、`release` 和 `click` 事件沿实体层级向上冒泡。如果父级的 `Interactable` 设置了 `blockRaycast: true`,冒泡在此停止。`hover_enter` 和 `hover_exit` **不会**冒泡。
## Focusable
@@ -67,6 +112,31 @@ addSystem(defineSystem(
| `lockX` | boolean | `false` | 锁定水平移动 |
| `lockY` | boolean | `false` | 锁定垂直移动 |
+拖拽激活时,引擎会自动为实体添加 `DragState` 组件:
+
+| 属性 | 类型 | 说明 |
+|------|------|------|
+| `isDragging` | boolean | 正在拖拽 |
+| `startWorldPos` | `{x, y}` | 拖拽开始时的实体位置 |
+| `currentWorldPos` | `{x, y}` | 当前世界位置 |
+| `deltaWorld` | `{x, y}` | 本帧移动量 |
+| `totalDeltaWorld` | `{x, y}` | 从拖拽开始的总移动量 |
+
+## 处理管线
+
+UI 交互系统每帧按固定顺序执行:
+
+| 调度阶段 | 系统 | 作用 |
+|----------|------|------|
+| Last(上一帧) | InputPlugin | 清除单帧输入状态 |
+| PreUpdate | UIInteractionSystem | 命中测试、悬停、按下、释放、点击 |
+| PreUpdate | DragPlugin | 拖拽状态追踪、拖拽事件 |
+| Update | ButtonSystem、TogglePlugin、SliderPlugin 等 | 控件状态更新 |
+
+<Aside type="tip">
+ UIInteraction 上的 `justPressed` 和 `justReleased` 仅在一帧内为 `true`。请在 PreUpdate 或 Update 中读取 — 到 PostUpdate 时已被清除。
+</Aside>
+
## 下一步
- [控件](/microes/zh/guides/ui-widgets/) — 按钮、滑块、开关等
diff --git a/docs/astro/src/content/docs/zh/guides/ui-masking.mdx b/docs/astro/src/content/docs/zh/guides/ui-masking.mdx
index 319d099b3..00e0fc68b 100644
--- a/docs/astro/src/content/docs/zh/guides/ui-masking.mdx
+++ b/docs/astro/src/content/docs/zh/guides/ui-masking.mdx
@@ -7,29 +7,165 @@ import { Aside } from '@astrojs/starlight/components';
## UIMask
-将子实体裁剪到父级 `UIRect` 边界内。
+将所有**子**实体裁剪到父级 `UIRect` 边界内。拥有 `UIMask` 的实体本身不会被裁剪 — 只有其后代会被裁剪。
+
+**前置组件:** 被遮罩的实体必须有 `Transform` 和 `UIRect`。
+
+### 属性
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `enabled` | boolean | `true` | 是否启用裁剪 |
-| `mode` | MaskMode | `Scissor` | `Scissor` (0)、`Stencil` (1) |
+| `mode` | MaskMode | `Scissor` | 遮罩技术(见下文) |
+
+### MaskMode
+
+| 模式 | 值 | 说明 |
+|------|-----|------|
+| `Scissor` | 0 | GPU 裁剪测试 — 快速,仅支持轴对齐矩形 |
+| `Stencil` | 1 | 模板缓冲 — 支持任意形状和嵌套 |
+
+**如何选择:**
+
+- **Scissor** — 适用于简单矩形容器,如滚动视图、面板、卡片列表。速度快但只支持轴对齐矩形。
+- **Stencil** — 需要非矩形遮罩(圆形头像、自定义形状)或需要嵌套遮罩时使用(支持最多 255 层嵌套)。开销稍大。
+
+### 在编辑器中设置
+
+1. 选择或创建一个带 `UIRect` 的 UI 实体(UIRect 定义裁剪范围)
+2. 在 Inspector 中添加 `UIMask` 组件
+3. 选择 `Scissor` 或 `Stencil` 模式
+4. 该实体下添加的所有子实体都会被裁剪到其边界内
+
+### 在代码中设置
+
+```typescript
+import { UIMask, MaskMode } from 'esengine';
-嵌套 `UIMask` 实体会裁剪到所有父级遮罩的交集区域。
+// 创建遮罩容器
+const panel = world.spawn();
+world.insert(panel, UIRect, {
+ anchorMin: { x: 0.1, y: 0.1 },
+ anchorMax: { x: 0.9, y: 0.9 },
+});
+world.insert(panel, UIMask, { enabled: true, mode: MaskMode.Scissor });
+
+// 子内容 — 自动被裁剪
+const content = world.spawn();
+world.setParent(content, panel);
+world.insert(content, Sprite, { texture: myTexture });
+```
+
+### 嵌套遮罩
+
+Scissor 遮罩与父级 Scissor 做交集 — 子级 Scissor 遮罩产生两者的重叠矩形。
+
+Stencil 遮罩支持真正的嵌套:每一层获得独立的模板引用值,子实体根据父级模板进行测试。最多支持 255 层嵌套。
+
+```
+Root (UIMask Stencil)
+ ├── Header (裁剪到 Root)
+ └── Body (UIMask Stencil) ← 嵌套遮罩
+ ├── Item 1 (裁剪到 Body ∩ Root)
+ └── Item 2 (裁剪到 Body ∩ Root)
+```
<Aside type="caution">
- `UIMask` 只裁剪**子**实体——拥有 UIMask 的实体本身不会被裁剪。
+ 同一层级中混用 Scissor 和 Stencil 模式是允许的 — 它们使用独立的 GPU 特性,互不干扰。
</Aside>
+---
+
## SafeArea
-适配设备安全区域(刘海、圆角)。适用于移动端和微信小游戏。
+自动适配设备安全区域(刘海、圆角、状态栏)。该组件通过调整 `UIRect.offsetMin` 和 `UIRect.offsetMax` 来将元素从不安全边缘收缩。
+
+**前置组件:** 实体必须有 `UIRect`。
+
+### 属性
| 属性 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
-| `applyTop` | boolean | `true` | 应用到顶部 |
-| `applyBottom` | boolean | `true` | 应用到底部 |
-| `applyLeft` | boolean | `true` | 应用到左侧 |
-| `applyRight` | boolean | `true` | 应用到右侧 |
+| `applyTop` | boolean | `true` | 从顶部边缘收缩(状态栏、刘海) |
+| `applyBottom` | boolean | `true` | 从底部边缘收缩(Home 指示条) |
+| `applyLeft` | boolean | `true` | 从左侧边缘收缩(横屏刘海) |
+| `applyRight` | boolean | `true` | 从右侧边缘收缩(横屏刘海) |
+
+### 工作原理
+
+1. `SafeAreaPlugin` 在启动时和窗口大小变化时读取设备安全区域边距
+2. 边距根据画布宽高比从屏幕像素缩放到世界单位
+3. 每帧(PreUpdate),插件将缩放后的边距应用到每个带 `SafeArea` 的实体的 `UIRect.offsetMin` / `UIRect.offsetMax`
+
+### 典型用法
+
+创建全屏容器并添加 `SafeArea`,将所有 UI 内容放在其中:
+
+```
+Canvas (全屏)
+ └── SafeArea 容器 (UIRect: 锚点 0,0 → 1,1) ← 在这里添加 SafeArea
+ ├── HUD
+ ├── 分数
+ └── 控制按钮
+```
+
+**在编辑器中:** 在根 UI 面板上添加 `SafeArea`。将锚点设为拉伸(0,0 → 1,1)。所有子元素将在安全区域内布局。
+
+**在代码中:**
+
+```typescript
+import { SafeArea } from 'esengine';
+
+const safeContainer = world.spawn();
+world.insert(safeContainer, UIRect, {
+ anchorMin: { x: 0, y: 0 },
+ anchorMax: { x: 1, y: 1 },
+});
+world.insert(safeContainer, SafeArea, {
+ applyTop: true,
+ applyBottom: true,
+ applyLeft: true,
+ applyRight: true,
+});
+```
+
+### 选择性应用边缘
+
+你可能只需要部分边缘的安全区域。例如,底部导航栏只需要底部安全区:
+
+```typescript
+world.insert(navBar, SafeArea, {
+ applyTop: false,
+ applyBottom: true,
+ applyLeft: true,
+ applyRight: true,
+});
+```
+
+### 平台支持
+
+| 平台 | 边距获取方式 |
+|------|------------|
+| **Web** | CSS `env(safe-area-inset-*)` 通过计算样式变量 `--sat`、`--sab`、`--sal`、`--sar` |
+| **微信小游戏** | `wx.getSystemInfoSync()` 读取 `safeArea` 字段,窗口大小变化时自动更新 |
+| **桌面端** | 返回零边距(无安全区域问题) |
+
+<Aside type="tip">
+ 对于 Web 平台,确保 HTML 中有 `<meta name="viewport" content="viewport-fit=cover">`,这样浏览器才会暴露安全区域边距。否则所有边距都为零。
+</Aside>
+
+### 插件注册
+
+`uiMaskPlugin` 和 `safeAreaPlugin` 在使用 `createWebApp()` 时**自动注册**。手动设置:
+
+```typescript
+import { uiMaskPlugin, safeAreaPlugin } from 'esengine';
+
+const app = App.new()
+ .addPlugin(uiMaskPlugin)
+ .addPlugin(safeAreaPlugin)
+ .run();
+```
## 下一步