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: restructure the manual into fine-grained subchapters (en + zh)

esengine1878fc48ca6c
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index 2b2e55e13..e2994f8b5 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -65,6 +65,9 @@ export default defineConfig({
{ label: 'Components', translations: { 'zh-CN': '组件' }, slug: 'core-concepts/components' },
{ label: 'Systems', translations: { 'zh-CN': '系统' }, slug: 'core-concepts/systems' },
{ label: 'Plugins & Resources', translations: { 'zh-CN': '插件与资源' }, slug: 'core-concepts/plugins-resources' },
+ { label: 'Transforms, Units & Coordinates', translations: { 'zh-CN': '变换、单位与坐标系' }, slug: 'core-concepts/transforms' },
+ { label: 'Screen & Design Resolution', translations: { 'zh-CN': '屏幕与设计分辨率' }, slug: 'core-concepts/screen' },
+ { label: 'App Setup & Lifecycle', translations: { 'zh-CN': '应用设置与生命周期' }, slug: 'core-concepts/app-lifecycle' },
],
},
{
@@ -82,15 +85,12 @@ export default defineConfig({
],
},
{
- label: 'Graphics & UI',
- translations: { 'zh-CN': '图形与 UI' },
+ label: 'Graphics',
+ translations: { 'zh-CN': '图形' },
items: [
{ label: 'Sprites & Rendering', translations: { 'zh-CN': '精灵与渲染' }, slug: 'guides/sprites' },
{ label: 'Video', translations: { 'zh-CN': '视频' }, slug: 'guides/video' },
{ label: 'Tilemaps', translations: { 'zh-CN': '瓦片地图' }, slug: 'guides/tilemap' },
- { label: 'UI', translations: { 'zh-CN': 'UI' }, slug: 'guides/ui' },
- { label: 'UI Components', translations: { 'zh-CN': 'UI 控件' }, slug: 'guides/ui-components' },
- { label: 'UI Controllers', translations: { 'zh-CN': 'UI 控制器' }, slug: 'guides/ui-controllers' },
{ label: 'Particles', translations: { 'zh-CN': '粒子' }, slug: 'guides/particle' },
{ label: 'Post-processing', translations: { 'zh-CN': '后处理' }, slug: 'guides/postprocess' },
{ label: 'Materials & Shaders', translations: { 'zh-CN': '材质与着色器' }, slug: 'guides/material' },
@@ -98,6 +98,21 @@ export default defineConfig({
{ label: 'Custom Drawing', translations: { 'zh-CN': '自定义绘制' }, slug: 'guides/drawing' },
],
},
+ {
+ label: 'UI',
+ translations: { 'zh-CN': 'UI' },
+ items: [
+ { label: 'Overview', translations: { 'zh-CN': '总览' }, slug: 'guides/ui' },
+ { label: 'Layout', translations: { 'zh-CN': '布局' }, slug: 'guides/ui-layout' },
+ { label: 'Text', translations: { 'zh-CN': '文本' }, slug: 'guides/ui-text' },
+ { label: 'Widgets', translations: { 'zh-CN': '控件' }, slug: 'guides/ui-components' },
+ { label: 'Lists & Scrolling', translations: { 'zh-CN': '列表与滚动' }, slug: 'guides/ui-lists' },
+ { label: 'Interaction', translations: { 'zh-CN': '交互' }, slug: 'guides/ui-interaction' },
+ { label: 'Theming', translations: { 'zh-CN': '主题' }, slug: 'guides/ui-theme' },
+ { label: 'Data Binding', translations: { 'zh-CN': '数据绑定' }, slug: 'guides/ui-binding' },
+ { label: 'Controllers', translations: { 'zh-CN': '控制器' }, slug: 'guides/ui-controllers' },
+ ],
+ },
{
label: 'Content & Flow',
translations: { 'zh-CN': '内容与流程' },
@@ -119,6 +134,7 @@ export default defineConfig({
translations: { 'zh-CN': '工具' },
items: [
{ label: 'Math Helpers', translations: { 'zh-CN': '数学辅助' }, slug: 'guides/math' },
+ { label: 'Profiling & Diagnostics', translations: { 'zh-CN': '性能剖析与诊断' }, slug: 'guides/profiling' },
],
},
{
diff --git a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx
new file mode 100644
index 000000000..bc6cc26aa
--- /dev/null
+++ b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx
@@ -0,0 +1,394 @@
+---
+title: App Setup & Lifecycle
+description: How an Estella App boots, which plugins it installs, its public surface, lifecycle events, subsystem observability, side modules, and hot reload.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Everything in Estella runs inside an **`App`** — the container that owns the
+[world](/docs/core-concepts/ecs/), the resources, the system schedules, and the
+frame loop. The editor's play mode, an exported web/desktop game, a WeChat
+MiniGame, and a headless authoritative server all build the *same* `App` class;
+only the factory that assembles it differs. This page is the reference for
+those factories and for the app's runtime surface.
+
+<Aside type="note">
+ In an editor-driven project you rarely construct an `App` yourself — the
+ exported runtime does it for you. Read this page when you embed the engine in
+ your own host page, run a headless server, write a plugin, or want lifecycle
+ and health signals at runtime.
+</Aside>
+
+## `createWebApp(module, options)`
+
+The batteries-included entry point for a browser (or Electron) game. It takes
+the instantiated engine wasm module (`ESEngineModule`), initializes the
+renderer, and installs the full plugin stack:
+
+```typescript
+import { createWebApp } from 'esengine';
+
+const app = createWebApp(module, {
+ wasmBaseUrl: '/engine', // where physics.wasm / spine42.wasm live
+ colorSpace: 'linear',
+ getViewportSize: () => ({ width: innerWidth, height: innerHeight }),
+});
+await app.run();
+```
+
+### `CreateWebAppOptions`
+
+All fields are optional. `CreateWebAppOptions` extends `WebAppOptions` (both
+importable from `esengine`) with `wasmBaseUrl`:
+
+| Option | Type | Default | Meaning |
+|---|---|---|---|
+| `wasmBaseUrl` | `string` | — | Base URL the [side-module](#side-modules) artifacts (`physics.wasm`, `spine38.js`/`.wasm`, …) are served from — usually the directory `esengine.wasm` itself came from. When set (and no explicit `sideModules` is given) it builds a fetch `SideModuleHost` for you. |
+| `sideModules` | `SideModuleHost` | built from `wasmBaseUrl`, else none | The realm's acquirer for optional native modules. Realms that inline their modules (Playable, WeChat) pass a host directly instead of a URL. |
+| `plugins` | `Plugin[]` | `[]` | Extra plugins, appended **after** the default set. |
+| `getViewportSize` | `() => { width, height }` | — | Viewport size callback for the camera system (and the WebGPU init size; `800×600` if absent). |
+| `glContextHandle` | `number` | — | A pre-registered WebGL2 context handle to render into; without it the module creates its own context via `initRenderer()`. |
+| `backend` | `'webgl2' \| 'webgpu'` | `'webgl2'` | `'webgpu'` boots the injected-device path — the host must have acquired a `GPUDevice` and passed it as the module factory's `preinitializedWebGPUDevice` before instantiation. |
+| `canvasSelector` | `string` | `'#canvas'` | CSS selector for the WebGPU swapchain canvas (must be in the DOM). WebGL ignores it. |
+| `colorSpace` | `'gamma' \| 'linear'` | `'gamma'` | Project color space. `'linear'` renders in linear light (sRGB decode on sample, linear blending, explicit encode in the final blit). Must be declared **at app creation** — shaders compile against it. |
+| `ySortLayers` | `number` | `0` | Bitmask of render layers (bits 0–31) that sort by world Y within the layer (top-down occlusion). |
+| `screenFit` | `ScreenScalingData` | off (`scaleMode: -1`) | Project camera fit: letterboxes a design resolution into the actual aspect. Only installed when `scaleMode` is a real mode (≥ 0); `SCREEN_FIT_OFF` (-1) keeps the legacy Canvas-or-raw fit. |
+
+### What it installs
+
+`createWebApp` first wires the core (renderer-facing) plugins, then the full
+content stack, in this order:
+
+1. **Core**: `corePlugin` (render facades), the camera plugin, `assetPlugin`,
+ `prefabsPlugin`, `inputPlugin`, `sceneManagerPlugin` — plus a fresh
+ `RenderPipeline`.
+2. **UI**: `uiPlugins` — the composed UI pipeline (layout, text, text input,
+ masks, render order, interaction, drag, focus, safe area).
+3. **Base content**: `timerPlugin`, `lifecyclePlugin()`, `animationPlugin`,
+ `audioPlugin`, `videoPlugin`, `particlePlugin`, `trailPlugin`,
+ `mesh2dPlugin`, `tilemapPlugin`, `postProcessPlugin`, `timelinePlugin`,
+ `perceptionPlugin`, `fsmPlugin`, `btPlugin`, `navPlugin`,
+ `replicationPlugin`.
+4. **Spine**: a `SpinePlugin` instance (it pulls its per-version wasm runtime
+ from `app.sideModules` on demand — nothing loads unless a scene uses Spine).
+5. **Your `plugins`**, in the order given.
+
+Physics is **not** in the default set: `PhysicsPlugin` needs the physics wasm
+module. The shipped runtime acquires `'physics'` from the side-module host and
+installs the plugin automatically when the project declares physics or the
+scene contains physics components; when composing manually, construct
+`PhysicsPlugin` yourself (it and `loadPhysicsModule` are exported from
+`esengine`; the full API lives on `esengine/physics`).
+
+## Headless apps
+
+`createHeadlessApp(module, options)` builds an app with the **full simulation
+stack and no presentation** — no renderer, no render pipeline, no input device,
+no UI. This is the authoritative-server shape (same wasm module, same gameplay
+code, same fixed-tick loop), also useful in workers and tests:
+
+```typescript
+import { createHeadlessApp, runHeadless } from 'esengine';
+
+const app = createHeadlessApp(module, { plugins: [gameplayPlugin] });
+const stop = runHeadless(app, { fps: 60 });
+// … later
+stop();
+```
+
+`HeadlessAppOptions` has two fields, both optional:
+
+| Option | Type | Meaning |
+|---|---|---|
+| `plugins` | `Plugin[]` | Your gameplay plugins, appended after the base set. |
+| `sideModules` | `SideModuleHost` | Optional-native-module acquirer (physics on the server). |
+
+Included: `assetPlugin`, `prefabsPlugin`, `sceneManagerPlugin`, `timerPlugin`,
+`lifecyclePlugin()`, `audioPlugin` (silent on hosts without a device), and the
+gameplay-AI/replication set (`perceptionPlugin`, `fsmPlugin`, `btPlugin`,
+`navPlugin`, `replicationPlugin`).
+
+Excluded — everything that exists *to be seen*: `corePlugin` (it wires render
+facades that only exist after `initRenderer()`), UI, particles, tilemap
+rendering, post-processing, timeline, Spine, input.
+
+`runHeadless(app, { fps? })` drives the app on a wall-clock `setInterval`
+(there is no `requestAnimationFrame` on a server), default 60 fps. Delta is
+measured, so the fixed-step accumulator keeps simulation cadence exact across
+timer jitter; a slow async tick never piles up re-entrantly. It returns a stop
+function. You can also drive the app manually with `app.tick(dt)`.
+
+<Aside type="caution">
+ `createHeadlessApp` and `runHeadless` are `@beta`: the headless asset story
+ (gameplay data without textures) is still settling and may change these
+ factories' options.
+</Aside>
+
+## The plugin model
+
+A plugin is a plain object that registers systems and resources on the app:
+
+```typescript
+import type { App, Plugin } from 'esengine';
+import { defineResource, defineSystem, Res } from 'esengine';
+
+const Score = defineResource({ value: 0 }, 'Score');
+const scoreSystem = defineSystem([Res(Score)], (score) => { /* … */ });
+
+export const scorePlugin: Plugin = {
+ name: 'score',
+ build(app: App) {
+ app.insertResource(Score, { value: 0 });
+ app.addSystem(scoreSystem);
+ },
+};
+```
+
+| Member | Type | Meaning |
+|---|---|---|
+| `name` | `string?` | Optional but recommended: named plugins auto-register in the [subsystem registry](#subsystem-observability), and systems added inside `build()` inherit the name for liveness reporting. |
+| `dependencies` | `PluginDependency[]?` | Prerequisites, each either a plugin **name** (`string`) or a **resource definition**. `addPlugin` throws if one is missing; `addPlugins` also uses the name edges to sort the batch. |
+| `before` / `after` | `string[]?` | Soft ordering hints against other plugin names, honored when installing a batch via `addPlugins`. |
+| `build(app)` | required | Register systems, resources, and events. Runs immediately on `addPlugin`. |
+| `finish(app)` | optional | Runs once, after **all** plugins have built, when the app first ticks/runs — for wiring that needs the complete set. |
+| `cleanup(app?)` | optional | Runs on `app.quit()`, in reverse install order. |
+
+`PluginDependency = string | ResourceDef<any>` — a name asserts install order;
+a resource def asserts the resource already exists.
+
+Installation: `app.addPlugin(plugin)` (idempotent per instance — adding the
+same object twice is a no-op) or `app.addPlugins([...])`, which topologically
+sorts the batch by `dependencies` / `before` / `after` and throws on a cycle.
+If `build()` throws, the plugin is rolled back and the failure stays visible in
+the subsystem registry as an `error` entry.
+
+**`flushPendingSystems(app)`** — module-level `addSystem` /
+`addStartupSystem` / `defineBehavior` calls (made at import time, outside any
+plugin) queue on the ambient context rather than on a specific app. The
+factories' runtimes drain that queue into the app for you; call
+`flushPendingSystems` yourself when you build a bare `App` manually and still
+want those module-level registrations.
+
+## The `App` surface
+
+The members exported for users, grouped:
+
+### World, resources, module
+
+| Member | Meaning |
+|---|---|
+| `app.world` | The ECS `World` — entities, components, queries. |
+| `app.insertResource(def, value)` / `app.getResource(def)` / `app.hasResource(def)` | The resource store systems read via `Res(...)`. `getResource` on a never-inserted resource installs and returns the def's default value — use `hasResource` to distinguish. |
+| `app.wasmModule` | The connected `ESEngineModule`, or `null` before `connectCpp`. |
+| `app.pipeline` | The `RenderPipeline`, or `null` in headless apps. |
+| `app.subsystems` | The per-app [`SubsystemRegistry`](#subsystem-observability). |
+| `app.sideModules` | The realm's [`SideModuleHost`](#side-modules), or `null` (headless/test apps without one). |
+| `app.getPlugin(Ctor)` | The installed plugin instance of a class, if any. |
+
+### Systems and events
+
+| Member | Meaning |
+|---|---|
+| `app.addSystem(sys)` | Register on `Schedule.Update`. |
+| `app.addStartupSystem(sys)` | Register on `Schedule.Startup` (runs once, before the first frame's schedules). |
+| `app.addSystemToSchedule(schedule, sys, { runBefore?, runAfter?, runIf? })` | Any schedule, with ordering edges and a run condition. |
+| `app.addSystemSet(set)` / `app.addSystemSetToSchedule(schedule, set)` | Register a whole `SystemSet`; members inherit the set's `runIf` and ordering, and other systems can order against the set's name. |
+| `app.removeSystem(systemId)` | Remove by the def's `_id` symbol. |
+| `app.addEvent(eventDef)` | Register an event channel (double-buffered; swapped each frame). |
+
+### The frame loop
+
+| Member | Meaning |
+|---|---|
+| `app.run()` | Start the `requestAnimationFrame` loop. |
+| `app.tick(delta)` | Advance exactly one frame (seconds) — how headless and test hosts drive the app. |
+| `app.quit({ keepRenderer? })` | Stop, run plugin `cleanup` in reverse order, despawn all entities, tear down the renderer (unless `keepRenderer`, used by hot reload). |
+| `app.setFixedTimestep(s)` / `app.getFixedTimestep()` | The `FixedUpdate` cadence. Default `1/60`. |
+| `app.setMaxDeltaTime(s)` | Clamp on a single frame's delta. Default `0.25`. |
+| `app.setMaxFixedSteps(n)` | Cap on fixed-step catch-up per frame. Default `8`. A time budget additionally caps catch-up so a too-heavy sim degrades to slow motion instead of freezing. |
+| `app.setPaused(v)` / `app.isPaused()` | User pause. While paused only `Schedule.Last` runs. |
+| `app.stepFrame()` | Queue exactly one full frame while paused (editor "step"). |
+| `app.setPlaySpeed(x)` / `app.getPlaySpeed()` | Time scale, clamped to `0.1`–`4.0`. Default `1.0`. |
+| `app.setTargetFrameRate(fps)` / `app.getTargetFrameRate()` | Frame cap; `0` (default) = uncapped (vsync). |
+
+Within one frame the schedules run: `First` → the fixed trio
+(`FixedPreUpdate` / `FixedUpdate` / `FixedPostUpdate`, zero or more times from
+the accumulator) → `PreUpdate` → `Update` → `PostUpdate` → `Last`. `Startup`
+systems are flushed before the first frame.
+
+### Errors, physics, stats
+
+| Member | Meaning |
+|---|---|
+| `app.onError(fn)` | Observe any system throw (`(error, systemName)`). |
+| `app.onSystemError(fn)` | Decide per throw: return `'continue'` or `'pause'` (pauses the rest of the frame). |
+| `app.onWasmError(fn)` | Observe errors crossing the wasm bridge. |
+| `app.waitForPhysics()` / `app.isPhysicsReady` | Await / query the async physics wasm init (no-op / `false` without `PhysicsPlugin`). |
+| `app.enableStats()` | Turn on timing collection. |
+| `app.getSystemTimings()` / `app.getPhaseTimings()` / `app.getFrameScopes()` | Per-system / per-schedule / sub-frame CPU timings this frame (`null` when stats are off). |
+| `app.measureFrameScope(name, fn)` | Time `fn` as a named sub-frame scope (a single-branch no-op when stats are off). |
+| `app.getEntityCount()` | Live entity count. |
+
+## Lifecycle events
+
+`lifecyclePlugin(options?)` (installed by default in both factories) publishes
+the **`Lifecycle`** resource — a `LifecycleManager` that tracks page
+visibility/focus and can auto-pause the game:
+
+```typescript
+import { Lifecycle } from 'esengine';
+
+const lifecycle = app.getResource(Lifecycle);
+const off = lifecycle.on((event) => {
+ if (event === 'pause') saveGame();
+});
+```
+
+| Member | Type | Meaning |
+|---|---|---|
+| `visible` | `boolean` | Current page/app visibility. |
+| `focused` | `boolean` | Window focus (tracked; changing it emits no event). |
+| `autoPause` | `boolean` | Whether hiding the page pauses the app. Default `true`; writable at runtime, seeded from `lifecyclePlugin({ autoPause })`. |
+| `on(listener)` / `off(listener)` | — | Subscribe to events; `on` returns an unsubscribe function. |
+
+`LifecycleEvent` is `'show' | 'hide' | 'pause' | 'resume'`, and a
+`LifecycleListener` is `(event: LifecycleEvent) => void`. The semantics:
+
+- **`hide` / `show`** fire on every visibility change (browser
+ `visibilitychange`; `wx.onHide` / `wx.onShow` on WeChat).
+- **`pause`** fires only when the lifecycle actually paused the app: the page
+ hid, `autoPause` is on, and the app wasn't already paused. **`resume`** fires
+ only when the lifecycle un-pauses its *own* pause — a manual
+ `app.setPaused(true)` is never overridden by the page becoming visible.
+- Headless hosts (Node, workers) have no visibility signal; the resource still
+ exists and stays `visible`.
+
+## Subsystem observability
+
+Every app carries a **`SubsystemRegistry`** at `app.subsystems` answering
+"which engine modules are loaded, ready, stepping, or errored". Named plugins
+register automatically; async plugins (physics) drive their own
+`initializing → ready`/`error` transitions.
+
+```typescript
+for (const s of app.subsystems.getStatuses()) {
+ console.log(s.id, s.phase, s.activity, s.lastError ?? '');
+}
+```
+
+- **`SubsystemPhase`** — the recorded lifecycle: `'registered'` →
+ `'initializing'` → `'ready'`, with `'error'` terminal.
+- **`SubsystemActivity`** — liveness, *derived at read time* from watchdog
+ beats (each system run "pets" its owning plugin): `'stepping'` (a beat within
+ the last 400 ms), `'idle'` (ready but stale — e.g. physics frozen in edit
+ mode), `'inactive'` (never beat; liveness unknown). Load ≠ run — this is the
+ distinction the editor's status UI shows.
+- **`SubsystemStatus`** — one entry per subsystem, install order: `id`,
+ `displayName`, `phase`, `activity`, `detail`, `lastError` (retained across
+ later transitions), `dependsOn` (declared plugin-name deps, for cascade
+ context), `phaseAgeMs`.
+- **`SubsystemEvent`** — one recorded transition (`id`, `phase`, `detail?`,
+ `atMs`, `seq`); `recentEvents(limit?)` returns the retained tail (capped at
+ 128).
+- `subscribe(fn)` notifies on phase transitions (not per-beat) and returns an
+ unsubscribe.
+
+The registry is per-app (per realm) — the editor's edit and play realms report
+independently.
+
+## Side modules
+
+Optional native subsystems ship as **standalone wasm modules** loaded on
+demand, so the base engine download stays small: physics (Box2D), the
+per-version Spine runtimes, the Basis Universal texture transcoder, and the
+software video decoder. Each is an emscripten pair — `<file>.js` glue plus
+`<file>.wasm` — acquired uniformly through a `SideModuleHost`; only the
+*transport* differs per realm.
+
+**`SIDE_MODULES`** is the single source of truth mapping ids to artifacts:
+
+| `SideModuleId` | Artifacts | Contents |
+|---|---|---|
+| `'physics'` | `physics.js` / `.wasm` | Box2D physics. |
+| `'spine:3.8'` / `'spine:4.1'` / `'spine:4.2'` | `spine38` / `spine41` / `spine42` `.js`/`.wasm` | One Spine runtime per skeleton format version. |
+| `'basis'` | `basis.js` / `.wasm` | Basis Universal KTX2 transcoder (compressed textures). |
+| `'videodec'` | `videodec.js` / `.wasm` | MPEG-1 software video decoder. |
+
+`SPINE_VERSIONS` is the readonly list `['3.8', '4.1', '4.2']`, and
+`spineModuleId(version)` builds the corresponding id.
+
+A host answers `acquire(id)` with a promise of the instantiated module (cached
+per id, failures cached as `null` so a missing artifact isn't refetched). The
+built-in transports:
+
+- **`createFetchSideModuleHost(baseUrl)`** — fetch the glue and wasm from a
+ base URL (what `wasmBaseUrl` builds); used by the editor, web, and desktop.
+- **`createEmbeddedSideModuleHost(...)`** — modules inlined as base64
+ (Playable ads).
+- **`createWeChatSideModuleHost(...)`** — WeChat's precompiled module
+ factories.
+
+You normally never call `acquire` yourself — set `app.sideModules` (via
+`wasmBaseUrl` or `sideModules`) and the Spine plugin and physics install pull
+from it when needed.
+
+<Aside type="note">
+ The main `esengine` barrel mirrors exactly the physics/spine **wiring**
+ layer — `PhysicsPlugin`, `PhysicsEvents`, `Physics`, `loadPhysicsModule`,
+ `SpinePlugin`, `SpineEvents`, `Spine` — so hosts can register the plugins
+ without a subpath import. The full APIs live on the `esengine/physics` and
+ `esengine/spine` subpaths. See [Physics](/docs/guides/physics/) and
+ [Spine](/docs/guides/spine/).
+</Aside>
+
+## Hot reload
+
+When you edit project code while the editor plays, the editor tries a
+**state-preserving hot swap** before falling back to a full reload. It
+re-imports your bundle inside an isolated probe context via
+**`probeRegistrations(register)`**, which returns a `ProbedRegistrations`:
+
+- `fingerprint` — a digest of the user component **schemas** the bundle
+ declared (shape, not values). Unchanged fingerprint → the live `World` is
+ kept and only system function bodies are swapped in place; changed → full
+ reload.
+- `pending` — the systems the bundle queued, fed to `App.hotSwapSystems`
+ (which rejects the swap — again forcing a full reload — if a user system was
+ added, removed, or renamed).
+
+What your code must respect: **component identity is stable by name**.
+`defineComponent('Health', …)` re-run after a re-import resolves to the *same*
+component identity, so re-imported systems' queries reach the live storage.
+Consequently, renaming a component or behavior is a structural change (full
+reload + state loss for that data), and per-entity `start` hooks run again
+after a reload — write them as idempotent setup (see
+[Scripting](/docs/guides/scripting/)).
+
+## Best practices
+
+- **Prefer the factories.** `createWebApp` / `createHeadlessApp` encode the
+ supported plugin orders; hand-rolling `App.new()` plus a plugin list is for
+ engine embedders.
+- **Name your plugins.** A `name` costs nothing and buys observability: the
+ subsystem registry entry, liveness attribution for the plugin's systems, and
+ usable dependency errors.
+- **Declare `colorSpace` and `backend` up front.** Both are baked in at
+ creation (shader compilation, device injection) — they cannot be toggled on a
+ live app.
+- **Don't fight the lifecycle auto-pause.** Turn it off with
+ `lifecyclePlugin({ autoPause: false })` (or `lifecycle.autoPause = false`)
+ rather than un-pausing in a listener; the manager only ever resumes a pause
+ it made itself.
+- **Route "is X loaded?" through `app.subsystems`.** It distinguishes
+ *loaded* from *running* (`phase` vs `activity`) and retains the last error —
+ better than probing resources.
+
+## See also
+
+- [Plugins & Resources](/docs/core-concepts/plugins-resources/) — reaching
+ subsystem APIs with `Res(...)`.
+- [Systems](/docs/core-concepts/systems/) — schedules and system parameters.
+- [Building & Exporting](/docs/guides/build-export/) — how side-module
+ artifacts ship per target.
+- [Physics](/docs/guides/physics/) and [Spine](/docs/guides/spine/) — the two
+ subpath APIs behind side modules.
diff --git a/docs/astro/src/content/docs/core-concepts/screen.mdx b/docs/astro/src/content/docs/core-concepts/screen.mdx
new file mode 100644
index 000000000..c11e2abfb
--- /dev/null
+++ b/docs/astro/src/content/docs/core-concepts/screen.mdx
@@ -0,0 +1,342 @@
+---
+title: Screen & Design Resolution
+description: How one design resolution maps onto every real screen — the Canvas component, scale modes, the camera fit and ScreenScaling, UI layout pixels, ScreenInfo, safe areas, and pixel-perfect rendering.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+You author a game against **one design resolution** (1920×1080 by default) and the
+engine fits that box onto whatever screen the game actually runs on. This page is
+the complete reference for that pipeline: the units model, the `Canvas` component,
+every scale mode with worked numbers, the project-level `ScreenScaling` fit, why UI
+pixels are stable, reacting to resizes and orientation, device safe areas, and the
+`pixelPerfect` camera flag.
+
+## World units are design pixels
+
+Estella's 2D units model is deliberately simple:
+
+- **1 world unit = 1 design pixel.** A 100×200 texture spawns a 100×200 sprite; a
+ `UINode` sized `px(300)` is 300 design pixels wide.
+- The default scene camera's `orthoSize` is `designResolution.y / 2` = **540** —
+ half the design height — so at the design aspect the camera shows exactly one
+ design box (1920×1080 world units).
+- The world is **Y-up**; screen coordinates are **Y-down** (converted for you by
+ [`CameraView`](/docs/guides/camera/)).
+- `Canvas.pixelsPerUnit` (default `100`) is the **physics scale** — world pixels
+ per Box2D meter — **not** a display scale. Rendering never divides by it.
+
+When the actual screen has a different aspect than the design resolution, a
+**scale mode** decides how the design box is fitted — that scales the *visible
+box*, never your content: sprites keep their pixel sizes, positions stay put.
+
+## The `Canvas` component
+
+One entity per scene carries a `Canvas` — the declaration of the design resolution
+and how it adapts. The editor seeds it when you create a scene; the first `Canvas`
+found is the one the engine uses.
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `designResolution` | Vec2 | `{x: 1920, y: 1080}` | Design (reference) resolution in pixels — the box you author against. |
+| `pixelsPerUnit` | number | `100` | World pixels per physics meter (Box2D + tile-collider scale). Min `1`. Not a display scale. |
+| `scaleMode` | `ScaleMode` | `FixedHeight` | How the design resolution adapts to the actual screen aspect (see below). |
+| `matchWidthOrHeight` | number | `0.5` | `Match`-mode blend, 0–1: `0` = fit width, `1` = fit height. Ignored by the other modes. |
+| `backgroundColor` | Color | `{r:0, g:0, b:0, a:1}` | Background color declared for the letterbox/pillarbox areas outside the design box. |
+
+```typescript
+import { defineSystem, GetWorld, Canvas } from 'esengine';
+
+const readCanvas = defineSystem([GetWorld()], (world) => {
+ const [canvasEntity] = world.getEntitiesWithComponents([Canvas]);
+ if (canvasEntity === undefined) return;
+
+ const canvas = world.get(canvasEntity, Canvas);
+ const designW = canvas.designResolution.x; // 1920
+ const designH = canvas.designResolution.y; // 1080
+});
+```
+
+<Aside type="note">
+ `pixelsPerUnit` feeds physics and tile colliders only: with the default `100`, a
+ 100-pixel crate is one Box2D meter, which keeps physics in the numeric range the
+ solver is tuned for. Changing it re-scales collider sizes and gravity feel — not
+ what anything looks like.
+</Aside>
+
+## Scale modes
+
+The fit math is one pure function, exported as `computeEffectiveOrthoSize`. Given
+the design box and the actual screen aspect it produces the **effective ortho
+half-height** — half the height of the world box the camera will show, in world
+units (design pixels). Two candidate answers exist:
+
+- `orthoForWidth = (designResolution.y / 2) × designAspect / actualAspect` — the
+ half-height at which the design **width** exactly spans the screen.
+- `orthoForHeight = designResolution.y / 2` — the half-height at which the design
+ **height** exactly spans the screen.
+
+Each `ScaleMode` picks between them:
+
+| `ScaleMode` | Value | Effective half-height | Behavior |
+|---|---|---|---|
+| `FixedWidth` | `0` | `orthoForWidth` | The design width always spans the screen exactly. Taller screens reveal extra world above/below; wider screens crop the top/bottom. |
+| `FixedHeight` | `1` (default) | `orthoForHeight` | The design height always spans the screen exactly. Wider screens reveal extra world at the sides; narrower screens crop the sides. |
+| `Expand` | `2` | `max(orthoForWidth, orthoForHeight)` | The **whole design box is always visible**; the shorter-fit axis reveals extra world beyond it. Safe: nothing designed is ever cut off. |
+| `Shrink` | `3` | `min(orthoForWidth, orthoForHeight)` | The **screen is always filled by the design box**; the overflowing axis is cropped. Nothing outside the design box is ever revealed. |
+| `Match` | `4` | `orthoForWidth^(1−t) × orthoForHeight^t` | Geometric blend by `matchWidthOrHeight` (`t`): `0` behaves like `FixedWidth`, `1` like `FixedHeight`, `0.5` splits the difference. |
+
+Two Cocos-style aliases exist on the `ScaleMode` object (they are the *same
+values*, not extra modes): `ScaleMode.ShowAll === ScaleMode.Expand` and
+`ScaleMode.NoBorder === ScaleMode.Shrink`.
+
+```typescript
+import { computeEffectiveOrthoSize, ScaleMode } from 'esengine';
+
+const halfH = computeEffectiveOrthoSize(
+ 540, // baseOrthoSize = designResolution.y / 2
+ 1920 / 1080, // design aspect (≈ 1.778)
+ 1024 / 768, // actual screen aspect (4:3 ≈ 1.333)
+ ScaleMode.Expand,
+ 0.5, // matchWidthOrHeight (Match mode only)
+);
+// halfH === 720 → the camera shows 1920 × 1440 design pixels
+```
+
+### Worked example — 1920×1080 design on a 4:3 screen
+
+On a 1024×768 (4:3) screen, `orthoForWidth = 540 × (16/9)/(4/3) = 720` and
+`orthoForHeight = 540`:
+
+| Mode | Half-height | Visible world box (design px) | Consequence |
+|---|---|---|---|
+| `FixedWidth` | `720` | 1920 × 1440 | Full design width; 180 extra world px revealed above *and* below. |
+| `FixedHeight` | `540` | 1440 × 1080 | Full design height; 240 design px **cut off on each side**. |
+| `Expand` / `ShowAll` | `720` | 1920 × 1440 | Whole design box visible; extra world above/below (same as `FixedWidth` here — on a *wider* screen it instead matches `FixedHeight`). |
+| `Shrink` / `NoBorder` | `540` | 1440 × 1080 | Screen filled, nothing beyond the design box revealed; sides cropped. |
+| `Match` (t = 0.5) | `≈ 623.5` | ≈ 1663 × 1247 | Halfway: mild crop at the sides *and* mild reveal above/below. |
+
+<Aside type="tip">
+ The camera's viewport always fills its screen rectangle — no mode renders literal
+ black bars. "Letterboxing" here means **extra world becomes visible** beyond the
+ design box. With `Expand`, design your backgrounds to bleed past the design
+ frame; whatever you place there is what players on other aspects will see.
+ `Canvas.backgroundColor` declares the color for the areas outside it.
+</Aside>
+
+## How the camera relates
+
+The fit does not run against the camera's authored `orthoSize` — it runs against
+`designResolution.y / 2`. Each frame the camera plugin resolves a **fit source**
+in this order:
+
+1. **`ScreenScaling`** (the project-level fit, below) when its `scaleMode` is a
+ real mode (`≥ 0`) — authoritative, works with no UI at all;
+2. else the scene's **`Canvas`** component, if one exists;
+3. else **no fit** — the camera renders its raw `orthoSize`.
+
+<Aside type="caution">
+ While a fit source is active, the main camera's authored `orthoSize` is **not
+ used** — the visible half-height comes entirely from the design resolution and
+ the scale mode. Zoom by editing/tweening `orthoSize` only takes effect when no
+ fit source is active (no `Canvas` in the scene and `ScreenScaling` off).
+</Aside>
+
+The default scene camera is authored with `orthoSize: 540 = designResolution.y / 2`
+precisely so the unfitted and fitted views agree at the design aspect: whether the
+fit is on or off, a 1920×1080 window shows exactly one design box.
+
+## Project-wide fit: the `ScreenScaling` resource
+
+`ScreenScaling` makes the design-resolution fit a *project* concern instead of a UI
+one — a scene with no `Canvas` (no UI) still letterboxes correctly. It is the
+runtime image of **Project Settings → Display → Camera fit**.
+
+| Field | Type | Default | Description |
+|---|---|---|---|
+| `designWidth` | number | `1920` | Design (reference) resolution width in px. |
+| `designHeight` | number | `1080` | Design (reference) resolution height in px. |
+| `scaleMode` | number | `SCREEN_FIT_OFF` (`-1`) | A real `ScaleMode` (`0`–`4`) turns the project fit **on**; `SCREEN_FIT_OFF` keeps the legacy behavior (Canvas fit when present, else raw `orthoSize`). |
+| `matchWidthOrHeight` | number | `0.5` | `Match`-mode blend 0–1 (`0` = fit width, `1` = fit height); ignored by other modes. |
+
+`DEFAULT_SCREEN_SCALING` is that off-by-default value, and `SCREEN_FIT_OFF` (`-1`)
+is the sentinel. When the project fit is on, it is **authoritative for the
+camera** while UI layout still reads the `Canvas` — so gameplay and UI can fit
+differently.
+
+The shipped runtimes install it from the project config (`createWebApp`'s
+`screenFit` option). Game code can read or override it live — the camera plugin
+re-reads it every frame:
+
+```typescript
+import { defineSystem, Res, ScreenScaling, ScaleMode } from 'esengine';
+
+const enableProjectFit = defineSystem([Res(ScreenScaling)], (fit) => {
+ fit.designWidth = 1280;
+ fit.designHeight = 720;
+ fit.scaleMode = ScaleMode.Expand; // any real mode (≥ 0) switches the fit on
+});
+```
+
+## UI layout: `UINode` pixels are design pixels
+
+UI is laid out inside a world-space rectangle (`uiLayoutRect`), and for scene
+cameras that rectangle **is** the fitted camera extents. Because world units are
+design pixels, `px(300)` on a `UINode` is 300 design pixels on every device — the
+scale mode changes how much *world* is visible around the UI, never the UI's own
+proportions.
+
+The **editor viewport** is the special case: its navigation camera renders the
+world at a free zoom (raw `orthoSize`, no fit — so panning/zooming stays
+predictable). If UI were laid out against those zoomed extents, every element
+would rescale and reflow on each scroll-wheel tick. Instead the editor recovers
+the *fixed* design-resolution box from the `Canvas` and lays UI out there — so the
+layout is identical at any zoom, and the UI still scales visually with the scene
+because it renders through the same zoomed view. The device simulator passes a
+preview aspect into the same math, which is why the letterboxed preview is exactly
+what ships.
+
+Both pure functions — `uiLayoutRect` and `computeEffectiveOrthoSize` — are
+exported for tools and tests.
+
+## Screen size & orientation: `ScreenInfo`
+
+`ScreenInfo` is a small helper class (not auto-installed by the runtimes): you
+construct it, feed it sizes, and it derives orientation and fires callbacks.
+
+| Member | Type | Default | Description |
+|---|---|---|---|
+| `width` | number | `0` | Last reported screen width in px. |
+| `height` | number | `0` | Last reported screen height in px. |
+| `dpr` | number | `1` | Device pixel ratio. |
+| `orientation` | `ScreenOrientation` | `Portrait` | `Landscape` when `width > height`, else `Portrait`. |
+| `onResize` | `((w, h) => void) \| null` | `null` | Called on every `update()`. |
+| `onOrientationChange` | `((o) => void) \| null` | `null` | Called when the derived orientation flips (never on the first `update()`). |
+| `update(width, height, dpr = 1)` | method | — | Feed the current size; recomputes orientation and fires the callbacks. |
+
+```typescript
+import { ScreenInfo, ScreenOrientation } from 'esengine';
+
+const screen = new ScreenInfo();
+screen.onResize = (w, h) => { /* re-position off-canvas HUD, etc. */ };
+screen.onOrientationChange = (o) => {
+ if (o === ScreenOrientation.Portrait) { /* show the "rotate device" hint */ }
+};
+
+const feed = () =>
+ screen.update(window.innerWidth, window.innerHeight, window.devicePixelRatio);
+window.addEventListener('resize', feed);
+feed();
+```
+
+The *shipped* orientation is a project setting, not runtime state: **Project
+Settings → Display → Orientation** writes one value that every export target
+consumes (the WeChat `game.json`, the web/playable rotate hint, the desktop window
+aspect). When unset, it is derived from the design resolution's aspect.
+
+## Safe areas (notches & rounded corners)
+
+Add a `SafeArea` component to an **absolute** `UINode` and the engine keeps that
+node inside the device's safe area by writing its four insets every time the
+insets or screen change. The system ships as part of the standard UI plugin
+(`safeAreaPlugin`, built by `uiPlugin`) — nothing to install in a normal app.
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `applyTop` | boolean | `true` | Push the node's top inset down by the top safe-area inset. |
+| `applyBottom` | boolean | `true` | Same for the bottom inset. |
+| `applyLeft` | boolean | `true` | Same for the left inset. |
+| `applyRight` | boolean | `true` | Same for the right inset. |
+
+Platform insets are converted from device pixels into UI design pixels before
+being written, so the layout stays resolution-independent:
+
+- **WeChat:** read from `wx.getSystemInfoSync().safeArea` automatically.
+- **Web:** read from the `--sat` / `--sab` / `--sal` / `--sar` CSS custom
+ properties on the root element — define them from `env(safe-area-inset-*)` in
+ your host page to opt in (they read as `0` otherwise).
+
+```typescript
+import {
+ defineSystem, GetWorld, spawnUIEntity, SafeArea, UIPositionType,
+} from 'esengine';
+
+const buildHudRoot = defineSystem([GetWorld()], (world) => {
+ // Absolute node; leave width/height auto — the SafeArea system writes the four
+ // insets, so the node stretches to exactly the safe region.
+ const hudRoot = spawnUIEntity({
+ world,
+ node: { position: UIPositionType.Absolute },
+ });
+ world.insert(hudRoot, SafeArea, {
+ applyTop: true, applyBottom: true, applyLeft: true, applyRight: true,
+ });
+ // Parent all HUD widgets under hudRoot — they stay clear of the notch.
+});
+```
+
+## Pixel-perfect rendering
+
+`Camera.pixelPerfect` (default `false`) snaps the camera's position onto the
+**world-space pixel grid** before the view matrix is built, so static pixel art
+lands on the same texels every frame instead of shimmering as the camera drifts by
+sub-pixel amounts. Facts from the implementation:
+
+- Orthographic cameras only (a perspective pixel grid is ill-defined).
+- One grid cell = one *rendered* pixel: `worldPerPixel = 2 × halfHeight /
+ viewportHeightInDevicePixels` — it adapts to the current fit and window size.
+- The snapped position also drives screen↔world conversion, so picking stays
+ consistent with what is drawn.
+- The editor's free navigation view never snaps; the flag applies in play/runtime.
+
+## Project Display settings → runtime
+
+Where each **Project Settings → Display** field lives and lands:
+
+| Editor setting | Project manifest | Runtime effect |
+|---|---|---|
+| Design width / height | `designResolution.width` / `.height` | Seeds new scene `Canvas` components and editor cameras; fills `ScreenScaling.designWidth/Height` (via `createWebApp`'s `screenFit`). |
+| Orientation | `packaging.orientation` (`'portrait'` \| `'landscape'`; absent = derived from the design aspect) | WeChat `game.json`, web/playable rotate hint, desktop window aspect, editor device preview. |
+| Camera fit | `features.rendering.cameraScaleMode` (`'none'`, `'fixed-width'`, `'fixed-height'`, `'expand'`, `'shrink'`, `'match'`; absent = `'none'`) | Mapped to `ScreenScaling.scaleMode` (`'none'` → `SCREEN_FIT_OFF`). |
+| Camera fit match | `features.rendering.cameraMatch` (0–1, default `0.5`) | `ScreenScaling.matchWidthOrHeight`. |
+
+Separately, two `RuntimeConfig` knobs set the **default `scaleMode` for newly
+created `Canvas` components** (they do not touch canvases already saved in a
+scene): `RuntimeConfig.canvasScaleMode` (default `1` = `FixedHeight`) and
+`RuntimeConfig.canvasMatchWidthOrHeight` (default `0.5`). Build configs set them
+by name through `applyBuildRuntimeConfig` — canonical `CanvasScaleMode` names plus
+the `ShowAll` / `NoBorder` aliases; unknown names fall back to `FixedHeight`:
+
+```typescript
+import { applyBuildRuntimeConfig } from 'esengine';
+
+applyBuildRuntimeConfig(app, {
+ canvasScaleMode: 'Expand', // name-based: 'FixedWidth' … 'Match', 'ShowAll', 'NoBorder'
+ canvasMatchWidthOrHeight: 0.5,
+});
+```
+
+## Best practices
+
+- **Author everything at the design resolution** and treat world units as design
+ pixels — never scale content to "fit a screen"; pick a scale mode instead.
+- **`Expand` (ShowAll) for content that must never be cut off** (UI-heavy, puzzle);
+ draw backgrounds that bleed past the design frame. **`Shrink` (NoBorder) for
+ full-bleed art** where cropping the edges is acceptable.
+- **Prefer the project fit** (`ScreenScaling` via Project Settings → Display) over
+ relying on the UI `Canvas` — it works in scenes with no UI and keeps camera and
+ UI concerns separate.
+- **Don't repurpose `pixelsPerUnit`** as a zoom or display scale; it only scales
+ physics meters. Zoom is `orthoSize` (when no fit is active) or design-resolution
+ choice.
+- **Anchor HUD roots with `SafeArea`** on mobile — one absolute root node with
+ `SafeArea` protects the whole HUD from notches.
+- **Enable `pixelPerfect`** only for pixel-art games; it quantizes camera motion,
+ which smooth-scrolling high-res games don't want.
+
+## See also
+
+- [Camera](/docs/guides/camera/) — orthoSize, follow, blending, split-screen.
+- [UI](/docs/guides/ui/) — the flexbox layout that consumes the design-pixel box.
+- [Physics](/docs/guides/physics/) — where `pixelsPerUnit` actually matters.
+- [Editor](/docs/guides/editor/) — the Display settings page and device preview.
diff --git a/docs/astro/src/content/docs/core-concepts/transforms.mdx b/docs/astro/src/content/docs/core-concepts/transforms.mdx
new file mode 100644
index 000000000..6dda154d8
--- /dev/null
+++ b/docs/astro/src/content/docs/core-concepts/transforms.mdx
@@ -0,0 +1,308 @@
+---
+title: Transforms, Units & Coordinates
+description: The Transform component, the world/design-pixel unit system, physics meters, Y-up coordinates, 2D rotation with quaternions, and the parent/child hierarchy.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Every entity that exists somewhere in the world carries a `Transform` — its
+position, rotation, and scale. This page is the foundation the other guides build
+on: what the Transform fields mean, what a "world unit" actually is (a design
+pixel), where meters come in (physics), which way Y points, and how transforms
+compose down a parent/child hierarchy.
+
+## The `Transform` component
+
+`Transform` stores **local** values you write and **world** values the engine
+computes. Local fields are relative to the parent (or to the world origin when
+the entity has no parent); each frame the transform system composes them down the
+hierarchy and writes the results into the world fields.
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `position` | Vec3 | `{0, 0, 0}` | Local position in world units, relative to the parent. `z` breaks draw-order ties within a sorting layer. |
+| `rotation` | Quat | `{w: 1, x: 0, y: 0, z: 0}` | Local rotation as a quaternion (identity = no rotation). In 2D you rotate about Z — see [Rotating in 2D](#rotating-in-2d). |
+| `scale` | Vec3 | `{1, 1, 1}` | Local scale per axis (`1` = original size; negative flips). |
+| `worldPosition` | Vec3 | `{0, 0, 0}` | **Read-only.** Final world-space position, composed by the engine. |
+| `worldRotation` | Quat | identity | **Read-only.** Final world-space rotation. |
+| `worldScale` | Vec3 | `{1, 1, 1}` | **Read-only.** Final world-space scale. |
+
+Write the local fields; read the world fields. The world fields are engine
+outputs — writing them does nothing lasting, because the transform system
+recomputes them from the local fields and the parent chain. For a root entity
+with no parent, world equals local.
+
+```typescript
+import { defineSystem, Query, Mut, Transform } from 'esengine';
+
+const drift = defineSystem([Query(Mut(Transform))], (q) => {
+ for (const [entity, t] of q) {
+ t.position = { x: t.position.x + 1, y: t.position.y, z: t.position.z }; // write local
+ console.log(t.worldPosition.x); // read world
+ }
+});
+```
+
+`position.x/y/z`, `rotation.z`, and `scale.x/y/z` are animatable (the
+[Sequencer](/docs/guides/timeline/) and [tweens](/docs/guides/animation/#tweens)
+can key them), and `position` / `rotation` / `scale` are replicated by
+[networking](/docs/guides/networking/)'s state replication.
+
+<Aside type="note">
+ `LocalTransform` and `WorldTransform` are exported as **aliases of the same
+ component** — `Transform === LocalTransform === WorldTransform`. There is one
+ unified component holding both local and world data; use whichever name reads
+ best in your code.
+</Aside>
+
+<Aside type="tip">
+ The editor's Details panel shows rotation as a single **Z angle in degrees**
+ for convenience, but the stored data is always the quaternion.
+</Aside>
+
+## Coordinate system
+
+- **World space is Y-up**: `+Y` is up, `+X` is right, angle `0` points along
+ `+X`, and positive angles turn counter-clockwise (`Math.atan2(dy, dx)` gives
+ the angle toward a target directly).
+- **`position.z` is draw-order, not perspective**: 2D rendering orders coarsely
+ by each renderer's sorting `layer`; within a layer, use `z` for fine ordering
+ (or a [y-sorted layer](/docs/guides/sprites/#draw-order--sorting-layers) for
+ top-down depth). It does not foreshorten or scale sprites.
+- **Screen space is Y-down**: pointer coordinates (`Input.mouseX/mouseY`, UI hit
+ testing) are pixels from the **top-left** of the canvas, Y increasing
+ downward.
+
+Convert between the two with the `CameraView` resource (see
+[Camera](/docs/guides/camera/#screen--world-coordinates) for the full API):
+
+```typescript
+import { defineSystem, Res, CameraView, Input } from 'esengine';
+
+const pick = defineSystem([Res(CameraView), Res(Input)], (view, input) => {
+ // Screen px (Y-down, top-left origin) -> world units (Y-up). null if no camera.
+ const world = view.screenToWorld(input.mouseX, input.mouseY);
+ if (world) { /* world.x, world.y */ }
+});
+```
+
+## Units — design pixels, world units, and meters
+
+Estella has **one spatial unit** for authoring: the design pixel. And **one
+derived unit** for physics: the meter.
+
+```text
+screen px (Y-down) ── CameraView.screenToWorld ──▶ world units = design px (Y-up)
+world / design px ── ÷ Canvas.pixelsPerUnit (100) ──▶ physics meters (Box2D)
+```
+
+**1 world unit = 1 design pixel.** The default design resolution is 1920×1080
+(`Canvas.designResolution`), and editor scene cameras author
+`orthoSize = designResolution.y / 2 = 540` — the camera sees exactly one design
+resolution's worth of world. The practical consequences:
+
+- A texture dropped into the scene spawns a sprite at its **pixel dimensions**
+ (a 128×128 image is 128×128 world units on screen at default zoom).
+- `UINode` px sizes map **1:1** to design pixels under scene cameras.
+- Distances, offsets, speeds in gameplay code are all in design pixels
+ (px and px/second).
+
+**Physics is metric.** `Canvas.pixelsPerUnit` (default `100`) is the number of
+world pixels per physics **meter** — it scales the Box2D world and tile
+colliders. It is *not* a sprite display scale. The split to remember:
+
+| Physics surface | Unit |
+|---|---|
+| Collider dimensions (`halfExtents`, `radius`, …) | **meters** (divide px by PPU) |
+| Solver-facing methods — forces, impulses, velocities, `setGravity` | **meters** |
+| Spatial queries — `raycast`, `shapeCast*`, `overlapCircle`, `overlapAABB` | **world pixels** (auto-scaled) |
+| `CharacterController.velocity` / `moveCharacter` | **world pixels**/second |
+
+The defaults are exported as constants, so code that needs them never hard-codes
+the numbers:
+
+```typescript
+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT } from 'esengine';
+
+DEFAULT_DESIGN_WIDTH; // 1920
+DEFAULT_DESIGN_HEIGHT; // 1080
+DEFAULT_PIXELS_PER_UNIT; // 100
+
+const radiusMeters = 24 / DEFAULT_PIXELS_PER_UNIT; // a 24 px circle collider
+```
+
+These constants are read from the engine's own Canvas defaults, so they cannot
+drift from the C++ values.
+
+## Rotating in 2D
+
+`Transform.rotation` is a quaternion `{w, x, y, z}`. A pure 2D rotation is a
+rotation about the Z axis, which uses only the `z` and `w` components:
+
+```text
+angle a (radians) -> { w: cos(a/2), x: 0, y: 0, z: sin(a/2) }
+```
+
+The `quat()` factory builds one — **note the argument order: `w` comes first**
+(`quat(w = 1, x = 0, y = 0, z = 0)`), matching the identity default:
+
+```typescript
+import { quat } from 'esengine';
+
+const angle = Math.PI / 4; // 45° CCW
+const rot = quat(Math.cos(angle / 2), 0, 0, Math.sin(angle / 2));
+```
+
+To read the angle back, two equivalent helpers compute `2 * atan2(z, w)`:
+
+| Helper | Signature | Notes |
+|---|---|---|
+| `quaternionToAngle2D` | `(rz, rw) => number` | Z angle in radians from a quaternion's `z`/`w`. |
+| `facingFromQuat` | `(z, w) => number` | Same math; the AI/perception spelling. |
+| `normalizeAngle` | `(a) => number` | Wrap any angle to `(-π, π]` — for shortest-turn deltas. |
+
+A complete example — turrets tracking the cursor:
+
+```typescript
+import {
+ defineSystem, defineTag, Query, Mut, Res,
+ Transform, CameraView, quat, facingFromQuat, normalizeAngle,
+} from 'esengine';
+
+const Turret = defineTag('Turret');
+
+const aim = defineSystem([Query(Mut(Transform)).with(Turret), Res(CameraView)], (q, view) => {
+ const target = view.getWorldMousePosition();
+ if (!target) return;
+ for (const [entity, t] of q) {
+ const angle = Math.atan2(
+ target.y - t.worldPosition.y,
+ target.x - t.worldPosition.x,
+ );
+ t.rotation = quat(Math.cos(angle / 2), 0, 0, Math.sin(angle / 2));
+
+ // Or, to turn gradually: read the current facing and step toward the target.
+ const facing = facingFromQuat(t.rotation.z, t.rotation.w);
+ const delta = normalizeAngle(angle - facing); // shortest signed turn
+ }
+});
+```
+
+To animate a rotation, `TweenTarget.RotationZ` drives the Z angle **in radians**
+(the engine rebuilds the quaternion each step), and the Sequencer keys
+`rotation.z` the same way — see [Animation](/docs/guides/animation/#tweens).
+
+<Aside type="tip">
+ For aiming math without touching rotation at all, `v2.fromAngle(angle, len)`
+ and `v2.rotate(v, angle)` from the [math helpers](/docs/guides/math/) produce
+ direction vectors directly.
+</Aside>
+
+## Parenting & hierarchy
+
+Entities form a tree through the `Parent` and `Children` components, but you
+never write those directly — use the world's hierarchy API:
+
+```typescript
+import { defineSystem, addStartupSystem, GetWorld, Transform } from 'esengine';
+
+const build = defineSystem([GetWorld()], (world) => {
+ const ship = world.spawn('Ship');
+ world.insert(ship, Transform, { position: { x: 400, y: 300, z: 0 } });
+
+ const turret = world.spawn('Turret');
+ world.insert(turret, Transform, { position: { x: 0, y: 24, z: 0 } }); // 24 px above the ship
+ world.setParent(turret, ship);
+});
+addStartupSystem(build);
+```
+
+- `world.setParent(child, parent)` — attach (or re-attach) `child` under
+ `parent`. Maintains **both sides**: the child's `Parent` and the parent's
+ `Children` list. Cycle-safe — parenting an entity to itself or to one of its
+ own descendants is silently ignored.
+- `world.removeParent(entity)` — detach; the entity becomes a root again.
+- `world.despawn(entity)` — despawns the **whole subtree**, children first, so
+ no orphans are left rendering.
+
+For reading the tree, `Parent` holds `{ entity }` (the parent) and `Children`
+holds `{ entities }` (an `Entity[]`) — query them like any component:
+
+```typescript
+import { defineSystem, Query, Parent, Children, Transform } from 'esengine';
+
+const followers = defineSystem([Query(Transform, Parent)], (q) => {
+ for (const [entity, t, parent] of q) { /* parent.entity */ }
+});
+```
+
+### How world transforms compose
+
+Each frame the transform system walks the tree depth-first from the roots. For
+every entity it builds the local matrix as **translate × rotate × scale** (TRS)
+and multiplies by the parent's world matrix:
+
+```text
+world = parentWorld × T(position) × R(rotation) × S(scale)
+```
+
+So a child's `position` is measured in the parent's rotated, scaled frame: a
+child at local `{x: 24, y: 0}` under a parent rotated 90° sits 24 px *above*
+the parent in world space. The decomposed results land in
+`worldPosition` / `worldRotation` / `worldScale`.
+
+### Gotchas
+
+- **Reparenting keeps local values.** `setParent` does not recompute local
+ fields to preserve the world pose — a child at local `{0, 0}` jumps to its
+ new parent's position. If you want the entity to stay put visually, convert
+ its world position into the new parent's frame yourself before reparenting.
+- **Never insert `Parent` directly.** `world.insert(entity, Parent, …)` writes
+ only the child-side link and leaves the parent's `Children` list stale — half
+ the engine (layout, rendering, despawn) walks `Children`. Always
+ `world.setParent`.
+- **Sibling order is not stable across removals.** Detaching a child swap-removes
+ it from `Children`, reordering the remaining siblings. Don't encode meaning in
+ `Children` order; use `position.z` or sorting layers for draw order.
+
+## Scale
+
+`scale` is per-axis. `{2, 2, 1}` doubles an entity uniformly; `{2, 1, 1}`
+stretches it horizontally; negative values mirror (`{-1, 1, 1}` flips
+horizontally — though for sprites, `Sprite.flipX` does this without touching the
+transform).
+
+Scale composes down the hierarchy through `worldScale`: a child under a
+`{2, 2, 1}` parent renders at twice its own scale, and its local `position` is
+stretched by the parent's scale too (local `{x: 10, y: 0}` lands 20 px away in
+world space).
+
+<Aside type="caution">
+ Prefer **uniform** scale (equal x and y) on parents. Non-uniform parent scale
+ combined with child rotation produces skew — the composed matrix is no longer
+ a clean rotation, and physics colliders (which are unscaled meter-space
+ shapes) will no longer match what you see. Zoom a camera with
+ `Camera.orthoSize`, never by scaling its Transform.
+</Aside>
+
+## Best practices
+
+- **Write local, read world.** Treat `worldPosition` / `worldRotation` /
+ `worldScale` as outputs; all authoring goes through `position` / `rotation` /
+ `scale`.
+- **Think in design pixels** for gameplay — positions, speeds, distances —
+ and convert only at the physics boundary (÷ `pixelsPerUnit` for collider
+ dimensions and solver calls).
+- **Use `world.setParent`**, never a hand-written `Parent` insert.
+- **Wrap Transform in `Mut(...)`** in queries that write it, so change
+ detection and the renderer see the update.
+- **Reserve `position.z` for draw-order tie-breaks** within a sorting layer;
+ use layers (or y-sorted layers) for coarse ordering.
+
+## See also
+
+- [Components](/docs/core-concepts/components/) — how components declare and store data.
+- [Camera](/docs/guides/camera/) — orthoSize, follow, and screen ↔ world conversion.
+- [Sprites & Rendering](/docs/guides/sprites/) — sorting layers, y-sort, and draw order.
+- [Physics](/docs/guides/physics/) — the meter-based side of the unit system.
+- [Math Helpers](/docs/guides/math/) — vector and rotation math on the canonical types.
diff --git a/docs/astro/src/content/docs/guides/ai.mdx b/docs/astro/src/content/docs/guides/ai.mdx
index 13ba167ec..7e438996e 100644
--- a/docs/astro/src/content/docs/guides/ai.mdx
+++ b/docs/astro/src/content/docs/guides/ai.mdx
@@ -417,6 +417,112 @@ Because both paradigms resolve leaves from the same registry, you can prototype
enemy as a state machine and later swap in a behavior tree (or run both) without
touching your action/condition code.
+## Advanced: below the components
+
+`Nav`, `NavAgent`, and `Perceiver` — the component layer — cover the common cases.
+The primitives beneath them are exported too, all pure TypeScript with no engine
+or wasm dependency, for when you need a path without an agent or a sight check
+without a `Perceiver`.
+
+### Pathfinding by hand
+
+`findPath` is the A\* the nav plugin uses: uniform-cost search over `NavGrid`
+cells, 4- or 8-connected, with an octile/manhattan heuristic and no corner
+cutting (a diagonal step needs both shared orthogonal cells open). Drop to it
+when you steer movement yourself, draw a path preview, or compute reachability
+for turn-based ranges — or when one grid isn't enough, since the `Nav` resource
+holds a single grid:
+
+```typescript
+import { NavGrid, findPath, pathToWorld } from 'esengine';
+
+const grid = new NavGrid({ width: 32, height: 24, cellSize: 32 });
+
+const path = findPath(
+ grid,
+ grid.worldToCell(hero.x, hero.y), // Cell — integer grid coordinates
+ grid.worldToCell(chest.x, chest.y),
+ { diagonal: false },
+);
+if (path) {
+ const waypoints = pathToWorld(grid, path); // Vec2[] — cell centers, world pixels
+}
+```
+
+`findPath(grid, start, goal, opts?)` returns the `Cell[]` path inclusive of both
+endpoints, or `null` when unreachable. A `Cell` is an integer grid coordinate
+`{ x, y }` (kept distinct from `Vec2` to flag cell space); convert with
+`grid.worldToCell` / `grid.cellToWorld`, or turn a whole path into world-space
+waypoints with `pathToWorld`.
+
+| `PathfindOptions` field | Default | Description |
+|---|---|---|
+| `diagonal` | `true` | Allow 8-connected diagonal moves. |
+| `snapRadius` | `8` | When start/goal lands on a blocked cell, snap to the nearest walkable cell within this ring radius before searching; `0` disables snapping. |
+
+`navGridFromTiles` builds the walkability mask from any tile reader — it is the
+core under `navGridFromTilemapLayer`, which just plugs in `TilemapAPI.getTile`:
+
+```typescript
+import { navGridFromTiles } from 'esengine';
+
+const grid = navGridFromTiles((x, y) => level.tiles[y][x], {
+ width: 32, height: 24, cellSize: 32,
+ blockedTileIds: [WALL_TILE, WATER_TILE],
+});
+```
+
+| `BuildNavGridOptions` field | Description |
+|---|---|
+| `width` / `height` / `cellSize` / `origin?` | Same as the `NavGrid` options (see [Building a grid](#building-a-grid)). |
+| `blockedTileIds?` | Exact set of tile ids that block movement. |
+| `isBlocked?` | Custom predicate over the tile id (`0` = empty); overrides `blockedTileIds`. With neither given, any non-empty tile blocks. |
+
+### Perception internals
+
+The perception plugin is a thin wrapper over four exported functions — useful for
+one-off sight checks from an action, custom senses (memory, hearing, multiple
+targets), or unit tests against a fake world:
+
+- **`senseTarget(ox, oy, facing, tx, ty, range, halfFov, isBlocked?)`** — the pure
+ geometry: a range check, a FOV cone check (`halfFov` is *half* the cone in
+ radians; ≥ π means omnidirectional), then the optional occlusion callback.
+- **`facingFromQuat(z, w)`** — 2D facing angle in radians from a `Transform`
+ rotation quaternion's z/w components.
+- **`makeLosCheck(physics)`** — builds the occlusion callback from a physics
+ raycast: occluded when any hit lands clearly short of the target
+ (`fraction < 0.98` — the last ~2% is the target itself).
+- **`stepPerception(world, isBlocked?)`** — the exact per-frame step the plugin
+ runs in `PreUpdate`: for every `Perceiver`, sense all `PerceptionTarget`s, keep
+ the nearest visible one, and write the `Perception` component.
+
+```typescript
+import { senseTarget, facingFromQuat, Transform, registerCondition } from 'esengine';
+
+// A one-off sight check against a POINT — no PerceptionTarget needed.
+registerCondition('seesShrine', (ctx) => {
+ const tf = ctx.get(Transform);
+ const facing = facingFromQuat(tf.rotation.z, tf.rotation.w);
+ return senseTarget(
+ tf.position.x, tf.position.y, facing,
+ SHRINE.x, SHRINE.y,
+ 300, Math.PI / 3, // 300 px range, 120° cone
+ ).visible;
+});
+```
+
+`senseTarget` returns a `SenseResult`:
+
+| `SenseResult` field | Description |
+|---|---|
+| `visible` | The target is within range, inside the cone, and not occluded. |
+| `distance` | Distance to the target — always set, even when not visible. |
+| `dirX` / `dirY` | Unit direction observer → target; `(0, 0)` when not visible. |
+
+The built-in system wires `makeLosCheck` in only when the physics module is
+loaded; otherwise sensing is range + FOV only — the AI layer has no hard physics
+dependency.
+
## Custom app setup
The perception, FSM, BT, and navigation plugins are part of the default plugin set,
diff --git a/docs/astro/src/content/docs/guides/animation.mdx b/docs/astro/src/content/docs/guides/animation.mdx
index a2092d308..03d4ffe12 100644
--- a/docs/astro/src/content/docs/guides/animation.mdx
+++ b/docs/astro/src/content/docs/guides/animation.mdx
@@ -89,6 +89,40 @@ Re-slicing the grid moves every frame consistently — frames reference grid
cells, not pixel rectangles. Frames that fall outside the current grid are
flagged red in the strip.
+### Clips from code
+
+The `.esanim` document is plain data, so a clip can also be built at runtime:
+`createAnimClip` starts a sheet-sliced clip, you append `{ cell }` frames,
+`parseAnimClipData` resolves it into a runtime `SpriteAnimClip`, and
+`registerClip` makes the name available to every `SpriteAnimator`:
+
+```typescript
+import {
+ defineSystem, Res, Assets, SpriteAnimation,
+ createAnimClip, parseAnimClipData,
+} from 'esengine';
+
+const registerRun = defineSystem([Res(Assets), Res(SpriteAnimation)], async (assets, sprites) => {
+ const tex = await assets.loadTexture('textures/run-sheet.png');
+
+ // A 32×32 grid over the sheet; frames reference grid cells (row-major).
+ const data = createAnimClip('textures/run-sheet.png', 32, 32, tex.width, tex.height);
+ data.fps = 10;
+ for (let cell = 0; cell < 6; cell++) data.frames.push({ cell });
+
+ const handles = new Map([['textures/run-sheet.png', tex.handle]]);
+ sprites.registerClip(parseAnimClipData('run', data, handles));
+ // Any SpriteAnimator can now set clip = 'run'.
+});
+```
+
+| Helper | Description |
+|---|---|
+| `createAnimClip(texture, cellWidth, cellHeight, pageWidth, pageHeight)` | A fresh sheet-sliced `AnimClipAssetData` (fps `12`, `loop: true`, margin/spacing `0`, no frames yet). |
+| `parseAnimClipData(name, data, textureHandles)` | Resolve asset data into a runtime `SpriteAnimClip` — each cell frame gets its texture handle and UV window. |
+| `parseAnimClipAsset(json)` / `serializeAnimClip(data)` | Parse / write the `.esanim` JSON document (the pair round-trips). |
+| `animClipCellRect(sheet, cell)` / `animClipCellUv(sheet, cell)` | Pixel rect / UV window of a grid cell — what a `Sprite` shows for that frame. |
+
### Driving clips from a state machine — no code
The [FSM/BT built-ins](/docs/guides/ai/) drive flipbooks as data. An action's
@@ -177,6 +211,41 @@ tween.cancelAll(entity); // stop everything on an entity
`TweenHandle` has `.then(next)`, `.bezier(...)`, `.pause()`, `.resume()`, and
`.cancel()`.
+### Composition handles
+
+`tween.parallel` returns a `TweenGroup` and `tween.sequence` a `TweenSequence` —
+parent-level handles over their members. Both expose `state` (a `TweenState`),
+`pause()` / `resume()` / `cancel()` that fan out to every member, and
+`onComplete(cb)`:
+
+```typescript
+const popX = tween.to(e, TweenTarget.ScaleX, 1, 1.3, 0.2);
+const popY = tween.to(e, TweenTarget.ScaleY, 1, 1.3, 0.2);
+tween.parallel([popX, popY]).onComplete(() => spawnSparkles());
+
+tween.sequence([
+ () => tween.to(e, TweenTarget.PositionY, 0, 60, 0.3),
+ () => tween.delay(0.2),
+ () => tween.to(e, TweenTarget.PositionY, 60, 0, 0.3),
+]).onComplete(() => landDust());
+```
+
+Always create groups and sequences **through the `Tween` resource** — the
+resource registers them with its internal poller (`TweenCompositionManager`),
+which is what fires `onComplete` and advances a sequence to its next factory. A
+hand-constructed `new TweenGroup(...)` is never polled.
+
+`tween.value(...)` and `tween.delay(...)` return a `ValueTweenHandle` — the same
+control surface (`state`, `.pause()` / `.resume()` / `.cancel()`, `.bezier(...)`)
+plus `.then(next)`, which chains another value tween *or* anything
+pausable/resumable (a group, a sequence). `TweenHandle.then` likewise accepts a
+`ValueTweenHandle`, so property tweens and value tweens mix freely in one chain.
+
+Reach for the shorthand helpers (`tween.parallel` / `tween.sequence` /
+`tween.delay` / handle `.then`) first; the classes are what those calls hand
+back — you only name `TweenGroup` / `TweenSequence` / `ValueTweenHandle` when
+storing a handle to pause, cancel, or observe the composition later.
+
## Animator state machine
For character animation, an **animator controller** holds states, transitions, and
@@ -201,7 +270,7 @@ const drive = defineSystem([Query(Animator), Res(AnimatorController)], (q, anim)
| `Animator` field | Type | Default | Description |
|---|---|---|---|
| `controller` | string | `''` | Registered controller name. |
-| `currentState` | string | `''` | Active state (seeded from the controller's initial state). |
+| `currentState` | string | `''` | Active state, as a `/`-separated path for nested machines (seeded from the controller's initial state). |
| `enabled` | boolean | `true` | Disable to freeze the state machine. |
| `AnimatorController` method | Description |
@@ -215,6 +284,129 @@ const drive = defineSystem([Query(Animator), Res(AnimatorController)], (q, anim)
The controller can drive both sprite **and** [Spine](/docs/guides/spine/)
animations, so one state machine handles a whole character.
+Parameters come in three types (`AnimatorParamType`): `'float'`, `'bool'`, and
+`'trigger'`. Conditions compare them with `gt` / `lt` / `eq` / `neq` (numeric,
+with a `value`), `true` / `false` (bool), or `trigger` (fires once and is
+consumed). There is no separate int type — drive whole numbers through a float
+parameter and `eq` / `neq`.
+
+### Blend trees
+
+A state can carry a 1D **blend** instead of a single clip: a float parameter
+selects between `AnimatorBlendThreshold` stops. Because the sprite channel plays
+one clip at a time, this is a *selection* by threshold — the stop with the
+greatest `value` at or below the parameter wins (below all stops, the first one
+plays) — not a weighted pose blend. Each threshold is
+`{ value, clip, speed?, loop? }`; per-threshold `speed` / `loop` override the
+state's own. The selection re-evaluates every frame, so a rising `speed`
+parameter walks idle→walk→run with no transitions:
+
+```typescript
+import { defineSystem, Res, AnimatorController, type AnimatorControllerDef } from 'esengine';
+
+const movement: AnimatorControllerDef = {
+ parameters: [{ name: 'speed', type: 'float', default: 0 }],
+ initialState: 'move',
+ states: [{
+ name: 'move',
+ blend: {
+ parameter: 'speed',
+ thresholds: [
+ { value: 0, clip: 'idle' },
+ { value: 0.5, clip: 'walk' },
+ { value: 4, clip: 'run', speed: 1.2 },
+ ],
+ },
+ transitions: [],
+ }],
+};
+
+const setup = defineSystem([Res(AnimatorController)], (anim) => {
+ anim.registerController('movement', movement);
+});
+```
+
+The pure helper `selectBlendClip(blend, value)` returns the threshold a value
+selects — handy for tooling or tests.
+
+For skeletal characters, a state can instead carry a `spine` motion
+(`AnimatorSpineMotion`, `{ animation, loop? }`): on entry the controller sets
+that [Spine](/docs/guides/spine/) animation (`loop` defaults `true`) and leaves
+track playback and mixing to the Spine runtime — it never touches
+`SpriteAnimator`. States are exclusive: exactly one of `clip`, `blend`, `spine`,
+or `stateMachine`.
+
+### Sub-state machines
+
+A state carrying a `stateMachine` (`AnimatorSubMachine`) is a **container**: it
+plays no motion of its own. On entry the machine descends into the sub-machine's
+`initialState`; the container's own `transitions` are the *exit edges*,
+evaluated from every leaf inside it. A sub-machine can declare its own
+`anyStateTransitions`, checked from all of its sub-states. `Animator.currentState`
+holds the full `/`-separated path (`STATE_PATH_SEP`), e.g. `locomotion/run`:
+
+```typescript
+import { defineSystem, Res, AnimatorController, type AnimatorControllerDef } from 'esengine';
+
+const player: AnimatorControllerDef = {
+ parameters: [
+ { name: 'speed', type: 'float', default: 0 },
+ { name: 'jump', type: 'trigger' },
+ ],
+ initialState: 'locomotion',
+ states: [
+ {
+ name: 'locomotion', // container: no motion of its own
+ stateMachine: {
+ initialState: 'idle',
+ states: [
+ { name: 'idle', clip: 'idle', transitions: [
+ { to: 'run', conditions: [{ param: 'speed', op: 'gt', value: 0.1 }] },
+ ] },
+ { name: 'run', clip: 'run', transitions: [
+ { to: 'idle', conditions: [{ param: 'speed', op: 'lt', value: 0.1 }] },
+ ] },
+ ],
+ },
+ // Exit edges — leave the whole machine from idle OR run.
+ transitions: [{ to: 'jump', conditions: [{ param: 'jump', op: 'trigger' }] }],
+ },
+ { name: 'jump', clip: 'jump', loop: false, transitions: [
+ { to: 'locomotion', conditions: [], hasExitTime: true }, // back in at idle
+ ] },
+ ],
+};
+
+const setup = defineSystem([Res(AnimatorController)], (anim) => {
+ anim.registerController('player', player);
+});
+```
+
+Entering `locomotion` lands on `locomotion/idle`; the jump trigger exits from
+either leaf; when the one-shot jump clip ends, `hasExitTime` re-enters the
+container at its initial state. Transition priority, highest first: top-level
+any-state → each enclosing machine's any-state (outermost in) → the leaf's own
+transitions → container exit edges (innermost out).
+
+The path machinery is exposed as pure functions (an `AnimatorScope` is the shape
+shared by the top-level controller and every sub-machine):
+
+```typescript
+import { enterStatePath, leafStateOf, evaluateAnimatorPath } from 'esengine';
+
+enterStatePath(player, 'locomotion'); // ['locomotion', 'idle']
+leafStateOf(player, 'locomotion/run')?.clip; // 'run'
+evaluateAnimatorPath(player, 'locomotion/idle', { speed: 3 }, new Set());
+// → { nextPath: 'locomotion/run', consumedTriggers: [] }
+```
+
+| Helper | Description |
+|---|---|
+| `enterStatePath(scope, name)` | Descend from a state to its concrete leaf; returns the path segments. |
+| `leafStateOf(def, path)` | The motion-bearing leaf state of a path, or `null`. |
+| `evaluateAnimatorPath(def, path, params, triggers, clipFinished?)` | One pure evaluation step over a path → `{ nextPath, consumedTriggers }`. |
+| `STATE_PATH_SEP` | The path separator, `'/'`. |
+
## Choosing the right tool
<Aside type="tip">
diff --git a/docs/astro/src/content/docs/guides/assets.mdx b/docs/astro/src/content/docs/guides/assets.mdx
index e25be3317..3d200405c 100644
--- a/docs/astro/src/content/docs/guides/assets.mdx
+++ b/docs/astro/src/content/docs/guides/assets.mdx
@@ -146,22 +146,49 @@ entities normally.
The texture budget defaults to **64 MB** (`RuntimeConfig.textureCacheBudget`,
also settable as `textureCacheBudget` in the build config); decoded audio has
its own **32 MB** mirror (`audioCacheBudget` — see the
-[audio guide](/docs/guides/audio/)). Size the texture budget for your game with
-`setTextureBudget`, and watch residency with `getResourceStats`:
+[audio guide](/docs/guides/audio/)).
+
+## Texture memory & budgets
+
+Textures are the budget that matters — they dominate GPU memory. The engine
+applies `RuntimeConfig.textureCacheBudget` at startup; size it for your game
+with `setTextureBudget` (the single game-facing surface over the C++ pool —
+there is no parallel TS-side budget to drift from it), and watch residency with
+`getResourceStats`:
```typescript
-import { setTextureBudget, getResourceStats } from 'esengine';
+import { setTextureBudget, getResourceStats, trimTextureCache } from 'esengine';
setTextureBudget(256 * 1024 * 1024); // 256 MB texture budget
-const stats = getResourceStats();
+const stats = getResourceStats(); // null before the engine initializes
// stats.textureBytes — resident texture bytes (held + evictable)
-// stats.textureBudget — the current budget
+// stats.textureBudget — the current budget (0 = eviction off)
// stats.textureEvictableCount — warm-cache entries awaiting revive/evict
+// …plus shaderCount / textureCount / vertexBufferCount / indexBufferCount
+// and cacheHits / cacheMisses
+
+const freed = trimTextureCache(); // drop every evictable texture now
```
-Setting the budget to `0` disables the warm cache — every texture frees the
-moment its last reference is released.
+The "GC" here is the LRU described above: once `textureBytes` exceeds
+`textureBudget`, the C++ pool evicts the least-recently-used **unreferenced**
+textures until it fits — held textures are never touched. `setTextureBudget(0)`
+disables the warm cache entirely (every texture frees the moment its last
+reference is released), and `trimTextureCache()` frees all evictable entries at
+once, returning the count — the engine calls it on OS memory warnings; call it
+yourself before a known memory spike.
+
+Two small helpers round out the surface: `getTextureDimensions(handle)` returns
+a texture's `{ width, height }` (cached on the TS side after the first query),
+and `evictTextureDimensions(handle)` drops that cached entry — the asset system
+does this when a texture is truly freed, so you only need it if you destroy and
+recreate textures around the asset system's back.
+
+For watching these numbers frame-over-frame in the editor and at runtime, see
+[Profiling](/docs/guides/profiling/). Per-texture **sampling/filtering**
+parameters (pixel-art nearest vs. smooth linear) are covered in the
+[Sprites guide](/docs/guides/sprites/).
## Best practices
diff --git a/docs/astro/src/content/docs/guides/audio.mdx b/docs/astro/src/content/docs/guides/audio.mdx
index 7bfcf8a77..7b58b3b02 100644
--- a/docs/astro/src/content/docs/guides/audio.mdx
+++ b/docs/astro/src/content/docs/guides/audio.mdx
@@ -171,6 +171,83 @@ Settings**: `Compress` and `Bitrate` control the cook's WAV → MP3 transcode
pass through untouched. MP3 has a small encoder delay — turn `Compress` off on
clips that must loop seamlessly.
+## Under the facade
+
+`Audio` is a facade over three exported classes the Web Audio backend assembles —
+`AudioMixer`, `AudioBus`, and `AudioPool`. You rarely construct them inside a
+game (on the WeChat backend they don't exist at all, which is why the bus APIs
+degrade to no-ops there), but they're public for two real jobs: **custom buses
+beyond the built-in four**, and **standalone audio pipelines** — an audition
+tool, a custom `PlatformAudioBackend`, tests — built on your own `AudioContext`.
+
+Custom buses need no class at all — the facade covers them:
+
+```typescript
+audio.ensureBus('ambience'); // create under master (idempotent)
+audio.ensureBus('footsteps', 'sfx'); // or under an existing bus
+audio.setBusVolume('ambience', 0.5);
+audio.playSFX('assets/wind.ogg', { bus: 'ambience' }); // or AudioSource.bus
+```
+
+`ensureBus(name, parent?)` creates the bus if it's missing (under `parent`,
+defaulting to `master`) and returns `false` on backends without a mixer graph;
+every by-name facade call (`setBusVolume`, `muteBus`, `setBusEffects`,
+`setBusDucking`) then reaches it.
+
+### `AudioBus`
+
+One mixer strip: `input → [effect inserts…] → duck → gain(volume) → parent`.
+Sources and child buses connect to `input`; `node` is the **output** gain — what
+volume/mute act on and where parents (or an `AnalyserNode` for a VU meter) tap.
+The duck stage is a separate gain, so sidechain ducking never fights the user's
+volume setting. Constructed with an `AudioBusConfig`:
+
+| `AudioBusConfig` | Type | Default | Description |
+|---|---|---|---|
+| `name` | string | – | Bus name. |
+| `volume` | number | `1` | Initial volume, clamped 0..1. |
+| `muted` | boolean | `false` | Start muted. |
+| `parent` | string | `'master'` | Parent bus name (consumed by `AudioMixer.createBus`). |
+
+| Member | Description |
+|---|---|
+| `input` / `node` | Entry `GainNode` / output `GainNode` (analyser taps connect from `node`). |
+| `volume` | 0..1; changes are smoothed over ~15 ms so they never click. |
+| `muted` | Ramps the output to 0 and back without losing `volume`. |
+| `effects` / `setEffects(defs)` | Read / idempotently replace the DSP insert chain (`BusEffectDef[]`). |
+| `duckTo(level, timeConstant)` | Ramp the duck stage toward `level` (the mixer's ducking drives this). |
+| `connect(dest)` / `addChild(bus)` | Wire the output into a parent bus or a raw `AudioNode`. |
+
+### `AudioMixer`
+
+Owns the bus tree. Constructing one builds `master → { music, sfx, ui, voice }`
+wired to `context.destination`, with volumes from `AudioMixerConfig`
+(`masterVolume` / `musicVolume` / `sfxVolume` / `uiVolume` / `voiceVolume` —
+music defaults to `0.8`, the rest to `1`):
+
+```typescript
+import { AudioMixer } from 'esengine';
+
+const mixer = new AudioMixer(new AudioContext(), { musicVolume: 0.6 });
+const ambience = mixer.createBus({ name: 'ambience' }); // under master
+```
+
+| Method | Description |
+|---|---|
+| `master` / `music` / `sfx` / `ui` / `voice` | The built-in buses, as readonly fields. |
+| `getBus(name)` / `busNames()` | Look up a bus / list every name (creation order, `master` first). |
+| `createBus(config)` | Create and wire a bus under `config.parent` (default `master`). |
+| `setDucking(target, rule \| null)` / `getDucking(target)` | Install or clear a sidechain `BusDuckRule` (`trigger`, `amount`, `attack`, `release`, `threshold`). |
+| `updateDucking()` | Per-frame: measure each trigger's RMS and ramp its target's duck stage (the audio system calls this for the engine's mixer). |
+
+### `AudioPool`
+
+The voice pool behind one-shots: pre-built `gain → panner` node pairs
+(`PooledAudioNode`) that are `acquire()`d per play and `release()`d when the
+sound ends, growing past the initial 16 on demand; `activeCount` and `capacity`
+report usage. Reach for it when you build custom playback on your own
+`AudioContext` and want to avoid per-play node churn.
+
## Spatial audio
Set `AudioSource.spatial = true` and give your listener entity (usually the camera
@@ -204,6 +281,28 @@ const setupSpatial = defineSystem([Commands()], (cmds) => {
`AudioListener` has a single field, `enabled` (default `true`) — keep exactly one
enabled listener in the scene.
+Estella's spatial pipeline is honest 2D: each frame, the audio system takes the
+source's and the listener's world positions, computes the distance, and drives
+the playing handle with `volume × attenuation` plus an **x-axis stereo pan**
+(`(sourceX − listenerX) / maxDistance`, clamped to ±1). There is no HRTF,
+doppler, or occlusion. A spatial source playing with no enabled listener warns
+once and measures from the world origin.
+
+The curve math is exported as pure functions for tools and tests —
+`calculateAttenuation(distance, config)` with a `SpatialAudioConfig`
+(`model`, `refDistance`, `maxDistance`, `rolloff` — the system fills it from
+`AudioSource.minDistance`/`maxDistance`/`rolloff`), and
+`calculatePanning(sourceX, sourceY, listenerX, listenerY, maxDistance)`:
+
+```typescript
+import { calculateAttenuation, calculatePanning, AttenuationModel } from 'esengine';
+
+const gain = calculateAttenuation(250, {
+ model: AttenuationModel.Inverse, refDistance: 100, maxDistance: 1000, rolloff: 1,
+}); // 0.4 — refDistance / distance
+const pan = calculatePanning(600, 0, 0, 0, 1000); // 0.6 — to the right
+```
+
## Best practices
- **Preload** clips you'll play in performance-critical moments (`preload` /
diff --git a/docs/astro/src/content/docs/guides/build-export.mdx b/docs/astro/src/content/docs/guides/build-export.mdx
index 75cd7ecc8..fe8cdbcd2 100644
--- a/docs/astro/src/content/docs/guides/build-export.mdx
+++ b/docs/astro/src/content/docs/guides/build-export.mdx
@@ -87,6 +87,36 @@ module for each engine feature the game uses (`physics-wechat`, `spine-wechat`,
`basis-wechat` for compressed textures) — see
[WeChat MiniGame](/docs/guides/wechat/).
+## Side modules
+
+Optional engine features ship as separate WebAssembly **side modules** — an
+emscripten `<file>.js` glue plus `<file>.wasm` per module — loaded on demand so
+the base engine stays small:
+
+| Module | Artifacts | Loaded when |
+|---|---|---|
+| Physics (Box2D) | `physics.js` / `physics.wasm` | The project declares physics or a scene uses physics components. |
+| Spine | `spine38` / `spine41` / `spine42` `.js`/`.wasm` | A scene uses a Spine skeleton of that format version. |
+| Basis transcoder | `basis.js` / `basis.wasm` | The build shipped KTX2-compressed textures. |
+| Video decoder | `videodec.js` / `videodec.wasm` | The wasm video path decodes a clip. |
+
+- **Web / Desktop** — the artifacts sit as loose files next to `esengine.wasm`;
+ the runtime fetches them from `wasmBaseUrl` (the directory the engine itself
+ was loaded from) via a fetch side-module host.
+- **Playable** — nothing external is allowed, so the exporter inlines the
+ modules as base64 into the single HTML file; the boot code
+ (`initPlayableRuntime`) is handed an embedded side-module host instead of a
+ URL.
+- **WeChat** — side modules are packaged as WeChat-precompiled module
+ factories (that's why each feature needs its `*-wechat` runtime build,
+ above).
+
+The editor's own play mode boots through the same shipping runtime
+(`initPlayRealmRuntime`), fetching side modules over the editor origin — so
+play == ship covers these modules too. See
+[App Setup & Lifecycle](/docs/core-concepts/app-lifecycle/#side-modules) for the
+runtime API.
+
## Build config & source maps
- **Development** — an unminified build; pair it with source maps for debuggable
diff --git a/docs/astro/src/content/docs/guides/camera.mdx b/docs/astro/src/content/docs/guides/camera.mdx
index 6dc501328..dc903b804 100644
--- a/docs/astro/src/content/docs/guides/camera.mdx
+++ b/docs/astro/src/content/docs/guides/camera.mdx
@@ -79,6 +79,31 @@ const zoomIn = defineSystem([Res(Tween)], (tween) => {
Use `Perspective` only for pseudo-3D layered scenes; leave 2D games on
`Orthographic` so sizes stay constant with depth.
+## Design-resolution fit
+
+In a shipped game the main camera usually does **not** render its raw `orthoSize`.
+Each frame the engine resolves a *fit source* and, when one is active, letterboxes
+the project's design resolution (default 1920×1080) into the actual screen aspect —
+the visible half-height is computed from `designResolution.y / 2` and a scale mode,
+so world units stay design pixels on every device. The fit source is, in order:
+
+1. the **`ScreenScaling`** resource (Project Settings → Display → Camera fit), when
+ its `scaleMode` is a real mode (`≥ 0`);
+2. else the scene's **`Canvas`** component, if one exists;
+3. else none — the camera renders its raw `orthoSize`.
+
+<Aside type="caution">
+ While a fit source is active, the camera's authored `orthoSize` is **not used** —
+ the visible area comes from the design resolution and the scale mode. Zooming via
+ `orthoSize` (including the tween above) only takes effect with no `Canvas` in the
+ scene and the project fit off.
+</Aside>
+
+The default `orthoSize` of `540` is exactly `designResolution.y / 2`, so the fitted
+and unfitted views agree at the design aspect. Scale modes, worked letterbox
+examples, and the `ScreenScaling` fields are covered in
+[Screen & Design Resolution](/docs/core-concepts/screen/).
+
## Follow a target
Add a `FollowTarget` to the camera and point it at an entity. The follow is a
@@ -108,6 +133,11 @@ const follow = defineSystem([Query(Camera), Commands()], (cameras, cmds) => {
| `deadzone` | number | `0` | Radius (world units) the target may roam before the camera moves. |
| `damping` | number | `0.25` | Smoothing time-constant in seconds (larger = slower; `0` = snap). |
+The data shape is exported as the `FollowTargetData` type. The follow system writes
+the camera's `Transform` directly (so the director blends already-followed views)
+and runs in **play mode only** — the editor's navigation view is never dragged
+around by it.
+
## Screen ↔ world coordinates
Read the `CameraView` resource to convert between the two spaces — for placing
@@ -143,6 +173,18 @@ import { shakeCamera } from 'esengine';
shakeCamera(app, { amplitude: 12, rotation: 0, frequency: 22, duration: 0.4 });
```
+Both `shakeCamera` and `setViewTarget` accept either the `App` (host code) or the
+`CameraDirector` resource state — inside a system, pass what `Res(CameraDirector)`
+gives you:
+
+```typescript
+import { defineSystem, Res, Input, CameraDirector, shakeCamera } from 'esengine';
+
+const shakeOnHit = defineSystem([Res(Input), Res(CameraDirector)], (input, director) => {
+ if (input.isKeyPressed('Space')) shakeCamera(director, { amplitude: 16 });
+});
+```
+
| Option | Default | Description |
|---|---|---|
| `amplitude` | `12` | Peak positional offset (world units). |
@@ -168,6 +210,76 @@ setViewTarget(app, cutsceneCamera, { time: 1.5, curve: BlendCurve.EaseInOut });
(or no prior view) is an instant cut. Position, zoom, and rotation interpolate;
discrete fields (projection, viewport) snap at the midpoint.
+## The camera director
+
+`setViewTarget` and `shakeCamera` are the API of the **camera director** — a
+per-app resource (`CameraDirector`) that resolves *one* main point of view each
+frame from the full-frame camera candidates: the committed view target (or the
+active/priority camera), blended toward a new target while a transition is in
+flight, with shakes applied on top of the rendered view only. Its state
+(`CameraDirectorState`) is readable; treat it as **read-only** and mutate through
+`setViewTarget` / `shakeCamera`:
+
+| Field | Type | Default | Description |
+|---|---|---|---|
+| `target` | number | `-1` | Committed view-target entity; `-1` = fall back to the `isActive` / highest-`priority` pick. |
+| `blending` | boolean | `false` | A view-target blend is currently in flight. |
+| `duration` / `curve` | number | `0` / `EaseInOut` | Length (seconds) and easing of the active blend. |
+| `currentMain` | `CameraPOV \| null` | `null` | The last resolved main POV, **pre-shake** — also what screen↔world conversion uses. |
+| `shakes` | `ActiveShake[]` | `[]` | Active transient shakes (pushed by `shakeCamera`, dropped when they decay out). |
+
+The remaining fields (`hasPending`, `pendingTarget`, `pendingTime`, `pendingCurve`,
+`from`, `startTime`, `shakeSeq`) are the director's internal request/blend
+bookkeeping written by `setViewTarget`.
+
+```typescript
+import { defineSystem, Res, CameraDirector } from 'esengine';
+
+const watchDirector = defineSystem([Res(CameraDirector)], (director) => {
+ if (director.blending) { /* e.g. suppress player input during the hand-off */ }
+ const pov = director.currentMain; // CameraPOV | null — the view being rendered
+ if (pov) { /* pov.x, pov.y, pov.orthoSize, ... */ }
+});
+```
+
+### `CameraPOV`
+
+A `CameraPOV` is a camera's *authored view parameters* as one plain snapshot —
+the unit the director blends and the shape stored in `currentMain`:
+
+| Field | Type | Description |
+|---|---|---|
+| `entity` | number | Source camera entity, or `-1` for a synthetic POV (the editor view). |
+| `isActive` | boolean | The authoritative "this is the main camera" flag. |
+| `x` / `y` / `z` | number | Camera position (world units). |
+| `rotation` | number | Z rotation in radians. |
+| `projection` | number | A `ProjectionType` value. |
+| `orthoSize` | number | Authored ortho half-height (world units). |
+| `fov` | number | Field of view in degrees (Perspective). |
+| `near` / `far` | number | Clip distances. |
+| `viewport` | `{x, y, z, w}` | Screen rect in 0–1 (`z`/`w` are width/height). |
+| `clearFlags` | number | A `ClearFlags` value. |
+| `priority` | number | Tie-breaker among active cameras. |
+| `pixelPerfect` | boolean | Pixel-grid snapping flag. |
+
+During a blend, continuous fields (position, `rotation` via the shortest angular
+path, `orthoSize`, `fov`, `near`/`far`) interpolate; discrete fields (`projection`,
+`pixelPerfect`) flip at the midpoint, and `viewport` / `clearFlags` / `priority`
+take the target's values.
+
+## Matching the canvas aspect
+
+`updateCameraAspectRatio(world, aspect)` stamps `aspectRatio` onto **every**
+`Camera` component in the world. The shipped runtimes call it at boot with the
+real canvas's `width / height`, keeping the authored field in sync with the actual
+surface (rendering itself derives aspect from the live viewport each frame):
+
+```typescript
+import { updateCameraAspectRatio } from 'esengine';
+
+updateCameraAspectRatio(app.world, canvas.width / canvas.height);
+```
+
## Multiple cameras & split-screen
With several `Camera` entities, `isActive` + `priority` decide which is live. Give
@@ -192,6 +304,8 @@ split-screen, left and right halves:
## See also
+- [Screen & Design Resolution](/docs/core-concepts/screen/) — the design-resolution
+ fit, scale modes, `ScreenScaling`, and `pixelPerfect` in depth.
- [Animation](/docs/guides/animation/) — tween `orthoSize` for smooth zooms.
- [Input](/docs/guides/input/) — `screenToWorld` with the mouse for picking.
- [UI](/docs/guides/ui/) — UI renders in screen space, independent of the camera.
diff --git a/docs/astro/src/content/docs/guides/drawing.mdx b/docs/astro/src/content/docs/guides/drawing.mdx
index 3ff6e6852..901e5e667 100644
--- a/docs/astro/src/content/docs/guides/drawing.mdx
+++ b/docs/astro/src/content/docs/guides/drawing.mdx
@@ -1,6 +1,6 @@
---
title: Custom Drawing
-description: Draw beyond components — immediate-mode primitives with Draw, vector paths with Graphics, custom triangle meshes with Mesh2D, and offscreen render textures.
+description: Draw beyond components — immediate-mode primitives with Draw, vector paths with Graphics, custom triangle meshes with Mesh2D and the Geometry API, and offscreen render textures.
---
import { Aside } from '@astrojs/starlight/components';
@@ -9,6 +9,18 @@ Most visuals are components — [sprites](/docs/guides/sprites/), tilemaps,
particles. When you need something they can't express — debug overlays, procedural
shapes, custom geometry — the engine exposes its drawing layer directly.
+## Which API to use
+
+| API | Model | Reach for it when |
+|---|---|---|
+| `Draw` | **Immediate**, global — commands batch and clear every frame. | Debug overlays, gizmos, anything redrawn from scratch each frame. |
+| `Graphics` | **Retained** path recorder — build once, replay through `Draw` with `flush()`. | Vector shapes with paths/béziers/arcs you don't want to re-tessellate per frame. |
+| `ShapeRenderer` / `Mesh2D` | **Components** — entities with sorting layers, materials, editor gizmos. | Shapes/meshes that are part of the scene (see [Sprites](/docs/guides/sprites/)). |
+
+Rule of thumb: if the visual belongs to the *scene* (sorted, saved, inspectable),
+make it a component; if it belongs to a *frame* (debug, HUD-ish overlays,
+procedural effects), draw it in a callback.
+
## Draw callbacks
Register a callback and it runs inside the render pass every frame, with the
@@ -46,6 +58,7 @@ cleared every frame, so call it each frame you want the shape visible:
| `circle(center, radius, color, filled?, segments?)` / `circleOutline(…)` | A circle (default `32` segments). |
| `texture(pos, size, textureHandle, tint?)` | A textured quad. |
| `textureRotated(pos, size, rotation, textureHandle, tint?)` | Same, rotated (radians). |
+| `drawMesh(geometry, shader, transform)` / `drawMeshWithMaterial(geometry, material, transform?)` | A custom mesh by handle (see the `Geometry` API below). |
| `setLayer(layer)` / `setDepth(depth)` | Sorting of subsequent commands. |
| `setBlendMode(mode)` / `setDepthTest(on)` | Blend / depth state for subsequent commands. |
| `getDrawCallCount()` / `getPrimitiveCount()` | Frame stats. |
@@ -101,13 +114,92 @@ automatically; to **mutate it at runtime**, go through the `Meshes2D` resource
`getGeometry` / `clearGeometry` round it out. Direct writes to the `geometry`
field alone are not change-detected.
+## Custom geometry: the `Geometry` API
+
+Where `Mesh2D` is the *component* path, `Geometry` is the *immediate* one: it
+uploads an indexed vertex buffer and hands back a **handle** you draw yourself —
+paired with a [material](/docs/guides/material/) via
+`Draw.drawMeshWithMaterial(geometry, material, transform?)` (or a raw shader via
+`Draw.drawMesh(geometry, shader, transform)`).
+
+```typescript
+import { Geometry, Draw, Material, registerDrawCallback } from 'esengine';
+
+const quad = Geometry.createQuad(120, 120); // 1 unit ≙ 1 design px
+const mat = Material.create({ shader }); // a compileShader material
+
+registerDrawCallback('custom-mesh', () => {
+ Draw.drawMeshWithMaterial(quad, mat); // identity transform
+});
+```
+
+### `GeometryOptions`
+
+| Field | Default | Description |
+|---|---|---|
+| `vertices` | — | Interleaved vertex data as one `Float32Array` (max 64K floats per upload). |
+| `layout` | — | `VertexAttributeDescriptor[]` — one `{ name, type }` per attribute, in buffer order. |
+| `indices` | — | `Uint16Array` or `Uint32Array` triangle list (max 16K indices per upload). |
+| `dynamic` | `false` | Allocate for frequent updates via `updateVertices`. |
+
+`DataType` names each attribute's shape: `Float`, `Float2`, `Float3`, `Float4`,
+`Int`, `Int2`, `Int3`, `Int4`.
+
+### Methods & helpers
+
+| Method | Does |
+|---|---|
+| `create(options)` | Uploads the mesh; returns a `GeometryHandle` (throws on failure or oversized data). |
+| `updateVertices(handle, vertices, offset?)` | Rewrites vertex data on a `dynamic` geometry (offset in floats). |
+| `release(handle)` / `isValid(handle)` | Free / probe a handle. |
+| `createQuad(width?, height?)` | A centered quad (defaults 1×1), layout `a_position` + `a_texCoord`. |
+| `createCircle(radius?, segments?)` | A triangle-fan circle (defaults 1, 32), same layout. |
+| `createPolygon(points)` | A fan-triangulated polygon from `{x, y}` points, UVs from its bounding box. |
+
+The helper meshes all use the two-attribute `Float2` position + `Float2` UV
+layout, so they pair directly with fragment-only `.esshader` materials.
+
## Offscreen targets: `RenderTexture`
-For advanced setups — minimaps, portraits, mirrors — `RenderTexture.create({
-width, height })` allocates an offscreen target; wrap draw commands in
-`RenderTexture.begin(rt, viewProjection)` / `end()` to render into it, and
-`release(rt)` when done. This is a low-level surface (you supply the
-view-projection matrix yourself) — see the TypeScript API reference for details.
+For minimaps, portraits, mirrors — and as the backing of
+[cache-as-bitmap](/docs/guides/sprites/) — `RenderTexture` allocates an offscreen
+render target. Wrap draw commands in `begin`/`end` to render into it; the
+resulting `textureId` is an ordinary texture handle usable anywhere (a
+`Sprite.texture`, `Draw.texture`, a material texture param):
+
+```typescript
+import { RenderTexture, Draw } from 'esengine';
+
+const rt = RenderTexture.create({ width: 256, height: 256, filter: 'linear' });
+
+RenderTexture.begin(rt, viewProjection); // an ortho view-projection you supply
+Draw.circle({ x: 0, y: 0 }, 80, { r: 1, g: 0.5, b: 0, a: 1 });
+RenderTexture.end();
+
+sprite.texture = rt.textureId;
+```
+
+### `RenderTextureOptions`
+
+| Field | Default | Description |
+|---|---|---|
+| `width` / `height` | — | Target size in pixels (required). |
+| `depth` | `true` | Attach a depth buffer — turn off for pure 2D compositing to save memory. |
+| `filter` | `'nearest'` | Sampling filter when the result is drawn: `'nearest'` or `'linear'`. |
+
+### Methods
+
+| Method | Does |
+|---|---|
+| `create(options)` | Allocates the target; returns a handle with `textureId`, `width`, `height`. |
+| `begin(rt, viewProjection)` | Redirects subsequent draws into the target (you supply the matrix). |
+| `end()` | Ends offscreen rendering, back to the screen. |
+| `resize(rt, width, height)` | Releases and re-creates — returns a **new** handle (the `textureId` changes). |
+| `getDepthTexture(rt)` | The depth attachment as a sampleable texture handle. |
+| `release(rt)` | Frees the target and its textures. |
+
+This is a low-level surface: it doesn't render the scene for you — it redirects
+whatever you draw between `begin`/`end`, under a view-projection matrix you build.
## See also
diff --git a/docs/astro/src/content/docs/guides/input.mdx b/docs/astro/src/content/docs/guides/input.mdx
index 6155845a6..735a4f0e5 100644
--- a/docs/astro/src/content/docs/guides/input.mdx
+++ b/docs/astro/src/content/docs/guides/input.mdx
@@ -126,6 +126,40 @@ bindings, and multiple bindings sum (then clamp), so keyboard and gamepad coexis
| `Keys2D(up, down, left, right)` | axis2d | Four keys → a 2D direction. |
| `Stick('left' \| 'right', pad?)` | axis2d | A gamepad stick (up = +y, matching `Keys2D`). |
+### The data model
+
+Those constructors are just sugar over plain, serializable data — `Binding` is a
+tagged union, and an action is a `type` plus its binding list:
+
+```typescript
+import { type Binding, type ActionDef } from 'esengine';
+
+const jump: ActionDef = {
+ type: 'button', // 'button' | 'axis' | 'axis2d'
+ bindings: [
+ { kind: 'key', code: 'Space' }, // Key('Space')
+ { kind: 'gpButton', button: 0 }, // GpButton(GamepadButton.South)
+ ],
+};
+```
+
+| `Binding` kind | Fields | Constructor |
+|---|---|---|
+| `key` | `code` | `Key` |
+| `mouse` | `button` | `MouseButton` |
+| `gpButton` | `button`, `pad?` | `GpButton` |
+| `gpAxis` | `axis`, `pad?`, `scale?` | `GpAxis` |
+| `keys1d` | `neg`, `pos` | `Keys1D` |
+| `keys2d` | `up`, `down`, `left`, `right` | `Keys2D` |
+| `stick` | `stick: 'left' \| 'right'`, `pad?` | `Stick` |
+
+Because bindings are data, this one model is also the **rebind and persistence
+format**: `toJSON()` / `loadJSON()` round-trip the bindings alone (per-action
+`Binding[]`), while `toAsset()` serializes the full map — action types included —
+as an `InputMapAsset` (`{ version, actions }`), the content of an `.inputmap`
+file. `loadJSON` ignores actions the map doesn't define, so stale saved data for
+a removed action never resurrects it.
+
### Rebinding & persistence
Bindings are plain serializable data, so a controls screen stays small:
@@ -138,6 +172,12 @@ Controls.save('controls'); // persist to platform Storage
Controls.load('controls'); // re-apply saved bindings (if any)
```
+`rebind` / `listenForBinding` take a `ListenOptions` choosing which device
+families the capture listens to: `keyboard` and `gamepad` default **on**,
+`mouse` defaults **off** — so the click that pressed the "rebind" button isn't
+itself captured. Axis sources are never captured; rebinding targets discrete
+inputs.
+
`getBindings` / `setBindings` inspect and edit bindings programmatically, and
`cancelListen()` aborts a pending capture (it resolves with `null`).
@@ -173,6 +213,65 @@ A tap is a touch under 0.3 s with less than 10 px of travel; a swipe needs ≥ 5
at ≥ 200 px/s; pinch reports the frame-to-frame scale of a two-finger spread with
its center point.
+## Input routing (layers)
+
+Before a raw platform event lands in the `Input` resource, it passes through the
+**`InputRouter`** — a chain of responsibility with three tiers:
+
+1. **Editor** — tools (gizmos, marquee drags) get first claim.
+2. **UI** — widgets and dialogs claim what falls through.
+3. **Game** — implicit: the `Input` resource itself. Gameplay only ever sees
+ events no upstream handler consumed.
+
+A handler callback returns `true` to **consume** the event — it then neither
+updates `Input` nor reaches later tiers. Returning `false` / nothing lets it fall
+through. Because consumption is per-event (not a global "editor is active" flag),
+a tool can claim exactly what it cares about: a marquee drag consumes pointer
+moves while pressed but lets the wheel scroll through to the camera; a modal
+consumes Escape but ignores the arrow keys.
+
+The engine's UI plugin already occupies the UI tier — that is what makes
+`isPointerOverUI()` and click-through prevention work. You write a handler when
+building tools or embedding the engine in a host app:
+
+```typescript
+import { inputRouter, type InputHandler } from 'esengine';
+
+const modalHandler: InputHandler = {
+ onKeyDown(code, mods) {
+ if (code === 'Escape') { closeModal(); return true; } // consumed
+ },
+ onPointerDown(button, x, y, mods) {
+ return isInsideModal(x, y); // claim clicks on the modal, pass the rest
+ },
+};
+
+const release = inputRouter.setUIHandler(modalHandler);
+// when the modal closes:
+release();
+```
+
+`inputRouter` is a module-level singleton; `setEditorHandler` / `setUIHandler`
+install one handler per tier and return an unregister thunk (unregistering only
+removes *your* handler, never a newer one). All `InputHandler` methods are
+optional:
+
+| `InputHandler` method | Signature |
+|---|---|
+| `onKeyDown` / `onKeyUp` | `(code, mods)` |
+| `onPointerMove` | `(x, y, mods)` |
+| `onPointerDown` | `(button, x, y, mods)` |
+| `onPointerUp` | `(button, mods)` |
+| `onWheel` | `(deltaX, deltaY, mods)` |
+| `onTouchStart` / `onTouchMove` | `(id, x, y)` |
+| `onTouchEnd` / `onTouchCancel` | `(id)` |
+
+`mods` is a **`Modifiers`** snapshot — `{ shift, ctrl, alt, meta }` — tracked by
+the router from key events (also readable any time as `inputRouter.currentMods`).
+On the key-up edge that releases a modifier, handlers still see it as held,
+matching DOM `event.shiftKey` semantics. A handler that throws is treated as not
+consuming, so a broken tool can't swallow all input.
+
## Reference
| Group | Methods |
diff --git a/docs/astro/src/content/docs/guides/material.mdx b/docs/astro/src/content/docs/guides/material.mdx
index a9a0a19fd..385c465e7 100644
--- a/docs/astro/src/content/docs/guides/material.mdx
+++ b/docs/astro/src/content/docs/guides/material.mdx
@@ -144,6 +144,120 @@ const v = Material.getUniform(tintMat, 'u_intensity');
| `setUniform(material, name, value)` | Set a reflected parameter at runtime. |
| `getUniform(material, name)` | Read a parameter's current value. |
+### `MaterialOptions`
+
+`Material.create(options)` takes the full render state, not just shader + uniforms:
+
+| Field | Default | Description |
+|---|---|---|
+| `shader` | — | Shader handle from `compileShader` / `createShader` (required). |
+| `uniforms` | — | Initial parameter values by name; textures via `Material.tex(textureId)`. |
+| `blendMode` | `BlendMode.Normal` | How the material composites (`Normal`, `Additive`, `Multiply`, …). |
+| `depthTest` | `false` | Test against the depth buffer. |
+| `depthWrite` | `true` | Write to the depth buffer. |
+| `cull` | `CullMode.None` | Triangle culling mode. |
+| `switches` | `{}` | Enabled `#pragma switch` names — the static permutation this material was compiled for. |
+
+Each state field also has a runtime setter — `setBlendMode`, `setDepthTest`,
+`setDepthWrite`, `setCull` — and `Material.createInstance(source)` builds a cheap
+variant that inherits everything from a parent material and stores only the diffs
+you set on it.
+
+### `CullMode`
+
+| Value | Meaning |
+|---|---|
+| `CullMode.None` | Draw both faces (the 2D default). |
+| `CullMode.Back` | Cull back faces. |
+| `CullMode.Front` | Cull front faces. |
+
+### `ShaderSources`
+
+For the raw `createShader` path, `ShaderSources` ships ready-made ES 3.0 GLSL
+using the batch vertex layout (`vec3` position + `vec4` color + `vec2` texCoord,
+with `u_projection` / `u_model` uniforms) — pair a vertex with its fragment:
+
+| Source | Stage | What it does |
+|---|---|---|
+| `ShaderSources.SPRITE_VERTEX` | vertex | Passes position, color, and UV through. |
+| `ShaderSources.SPRITE_FRAGMENT` | fragment | `texture(u_texture, uv) × v_color`. |
+| `ShaderSources.COLOR_VERTEX` | vertex | Position + color only (no UV). |
+| `ShaderSources.COLOR_FRAGMENT` | fragment | Flat vertex color. |
+
+These are **not** the `.esshader` templates — no `#pragma param` reflection; use
+them as starting points for `Material.createShader(vertex, fragment)` meshes.
+
+## Building graphs in code
+
+The editor's material graph is not a separate pipeline — it's a **visual frontend
+that generates a `.esshader`**. `compileMaterialGraph(graph)` walks the node DAG
+from the output and emits the same shader source you'd write by hand (both the
+GLSL fragment and its WGSL twin), so a graph material runs on either backend and
+its const/texture nodes become ordinary reflected `#pragma param`s. That means you
+can author graphs entirely in code — the graph is plain data:
+
+```typescript
+import { compileMaterialGraph, Material, type MaterialGraph } from 'esengine';
+
+const graph: MaterialGraph = {
+ name: 'TintedSprite',
+ output: 'out', // id of the output node
+ nodes: [
+ { id: 'tex', type: 'textureSample', params: { name: 'u_albedo', default: 'white' } },
+ { id: 'tint', type: 'constColor', params: { name: 'u_tint', value: [1, 0.6, 0.2, 1] } },
+ { id: 'mul', type: 'multiply', inputs: { a: 'tex', b: 'tint' } },
+ { id: 'out', type: 'output', inputs: { color: 'mul' } },
+ ],
+};
+
+const shader = Material.compileShader(compileMaterialGraph(graph));
+const mat = Material.create({ shader });
+Material.setUniform(mat, 'u_tint', [1, 0, 0, 1]); // graph params are ordinary params
+```
+
+`compileMaterialGraph` throws on a cycle, a missing node or input, or an `output`
+root that isn't an output node.
+
+### Node types
+
+`GraphNodeType` covers inputs, params, and math (`NODE_SPECS` holds each type's
+ports and editable literals — the same schema the editor's palette reads):
+
+| Node | Output | What |
+|---|---|---|
+| `uv` / `screenUV` | `vec2` | Texture UV / canvas-normalized screen UV (0–1, y-up). |
+| `vertexColor` | `vec4` | The sprite's per-instance tint. |
+| `time` | `float` | Engine frame clock in seconds. |
+| `constFloat` / `constColor` | `float` / `vec4` | A reflected material param (`params: { name, value }`). |
+| `textureSample` | `vec4` | Samples a texture param at a UV (`params: { name, default }`). |
+| `multiply` / `add` / `lerp` | widened / `vec4` | Arithmetic; scalars broadcast against vectors. |
+| `oneMinus` / `saturate` / `sin` | input type | `1 − x` / clamp 0–1 / sine. |
+| `smoothstep` | input type | `smoothstep(edge0, edge1, x)` — edges are node literals. |
+| `noise` | `float` | Procedural value noise over a UV (`scale` literal). |
+| `panner` | `vec2` | `uv + time × speed` — scrolling UVs (`speedX` / `speedY` literals). |
+
+### Editing operations
+
+For tooling (or generating graphs procedurally), the SDK exports pure operations —
+each returns a **new** graph, leaving the input untouched:
+
+| Function | Does |
+|---|---|
+| `newMaterialGraph()` | A starter graph: one white `textureSample` wired to `output`. |
+| `addNode(g, type, x, y)` | Adds a node with sensible default params; returns `{ graph, id }`. |
+| `connect(g, fromId, toId, toSlot)` | Wires an edge; returns `g` **unchanged** if it would create a cycle or the slot is unknown. |
+| `disconnect(g, toId, toSlot)` | Clears an input connection. |
+| `moveNode(g, id, x, y)` | Canvas layout only — the compiler ignores positions. |
+| `removeNode(g, id)` | Removes a node and every edge touching it (the `output` node can't be removed). |
+
+## Custom geometry
+
+Materials aren't limited to component renderers: the **`Geometry`** API
+(`Geometry.create` with a `GeometryOptions` vertex layout, plus `createQuad` /
+`createCircle` / `createPolygon` helpers) builds handle-based meshes you draw
+immediately with `Draw.drawMeshWithMaterial(geometry, material)` — the full
+reference lives in [Custom Drawing](/docs/guides/drawing/).
+
## Best practices
- **Compile shaders once** at startup and reuse the handle — never in a per-frame
diff --git a/docs/astro/src/content/docs/guides/math.mdx b/docs/astro/src/content/docs/guides/math.mdx
index e8873bce0..59c5ade0e 100644
--- a/docs/astro/src/content/docs/guides/math.mdx
+++ b/docs/astro/src/content/docs/guides/math.mdx
@@ -8,7 +8,9 @@ import { Aside } from '@astrojs/starlight/components';
The SDK ships small math namespaces — `v2` / `v3` (vectors), `col` (colors), and
`scalar` (numbers) — that operate on the same canonical types your components use
(`{x, y}` vectors, `{r, g, b, a}` colors in 0..1). Every helper is **pure**: it
-returns a new value and never mutates its inputs.
+returns a new value and never mutates its inputs. For what the numbers *mean* —
+world units, design pixels, physics meters, and the Y-up coordinate system — see
+[Transforms, Units & Coordinates](/docs/core-concepts/transforms/).
## Vectors
@@ -71,6 +73,37 @@ scalar.deg2rad(90); // degrees -> radians
Also: `clamp`, `inverseLerp`, `rad2deg`, `approximately`, `mod`, `sign`.
+## Rotation helpers
+
+`Transform.rotation` is a quaternion; in 2D you only ever rotate about Z, and a
+handful of exports cover the angle ↔ quaternion round trip:
+
+```typescript
+import { quat, quaternionToAngle2D, facingFromQuat, normalizeAngle } from 'esengine';
+
+// Angle -> quaternion. NOTE: the factory takes w FIRST — quat(w, x, y, z).
+const a = Math.PI / 3;
+const rot = quat(Math.cos(a / 2), 0, 0, Math.sin(a / 2));
+
+// Quaternion -> angle (radians), from the z/w components.
+const facing = quaternionToAngle2D(rot.z, rot.w); // Math.PI / 3
+facingFromQuat(rot.z, rot.w); // same math, the AI/perception spelling
+
+// Wrap to (-π, π] — the shortest signed turn from facing toward a target angle.
+const delta = normalizeAngle(targetAngle - facing);
+```
+
+| Helper | Description |
+|---|---|
+| `quat(w?, x?, y?, z?)` | Quaternion factory; no arguments gives the identity `{w: 1, x: 0, y: 0, z: 0}`. |
+| `quaternionToAngle2D(rz, rw)` | Z angle in radians from a quaternion's `z`/`w` (`2 * atan2(z, w)`). |
+| `facingFromQuat(z, w)` | Identical math under its AI/perception name. |
+| `normalizeAngle(a)` | Wrap any angle to `(-π, π]` for shortest-turn comparisons. |
+
+For direction *vectors* instead of rotations, stay in `v2`: `fromAngle` /
+`angle` / `rotate`. A full worked example (turrets facing the cursor) is in
+[Transforms, Units & Coordinates](/docs/core-concepts/transforms/#rotating-in-2d).
+
<Aside type="tip">
Results use the same canonical types as components, so they drop straight in —
e.g. `transform.position = v2.add(transform.position, step)` or
@@ -78,3 +111,11 @@ Also: `clamp`, `inverseLerp`, `rad2deg`, `approximately`, `mod`, `sign`.
the helpers allocate a new object per call, hoist them out of hot inner loops
where you're counting allocations.
</Aside>
+
+## See also
+
+- [Transforms, Units & Coordinates](/docs/core-concepts/transforms/) — what the
+ numbers mean: world units = design pixels, physics meters, Y-up, and rotating
+ entities with quaternions.
+- [Physics](/docs/guides/physics/) — the meter-based unit surface these helpers
+ feed into.
diff --git a/docs/astro/src/content/docs/guides/physics.mdx b/docs/astro/src/content/docs/guides/physics.mdx
index 2bb300127..33e364a5d 100644
--- a/docs/astro/src/content/docs/guides/physics.mdx
+++ b/docs/astro/src/content/docs/guides/physics.mdx
@@ -28,11 +28,38 @@ app.addPlugin(new PhysicsPlugin('physics.js', { gravity: { x: 0, y: -9.81 } }));
main `esengine` barrel.
</Aside>
+## Units
+
+Box2D simulates in **meters**; the rest of the engine works in **world pixels**.
+The conversion factor is the live **pixels-per-unit** (PPU) — `Canvas.pixelsPerUnit`,
+`100` pixels per meter by default. Every part of the physics API sits on a fixed
+side of that boundary:
+
+| Surface | Units |
+|---|---|
+| Collider component dimensions — `halfExtents`, `radius`, `offset`, … | **Meters.** |
+| Solver-facing methods — `applyForce` / `applyImpulse`, `setLinearVelocity` / `getLinearVelocity`, `setGravity`, … | **Meters** (m/s, m/s²). |
+| Spatial queries — `raycast`, `shapeCast*`, `overlapCircle` / `overlapAABB`, `moveCharacter` | **World pixels**, scaled by the live PPU. |
+| `CharacterController.velocity`, `MotorJoint.linearVelocity` | World pixels per second. |
+
+`physics.getPixelsPerUnit()` returns the live PPU (pushed from the `Canvas` each
+frame), so conversions never hard-code `100`:
+
+```typescript
+const ppu = physics.getPixelsPerUnit(); // world pixels per meter
+const speedPx = physics.getLinearVelocity(e).x * ppu; // m/s → px/s
+physics.applyImpulse(e, { x: 0, y: jumpPx / ppu }); // px/s → m/s
+```
+
+Mixing the two spaces — passing pixels to `applyForce`, or meters to `raycast` —
+is the most common physics bug. When in doubt: **components and solver = meters;
+queries and the character controller = pixels.**
+
## Bodies & colliders
Attach a `RigidBody` plus one collider shape. **Collider dimensions are in meters,
-not pixels** — divide pixel sizes by your pixels-per-unit (PPU). Spawn from a system
-that takes `Commands()`:
+not pixels** — divide pixel sizes by your pixels-per-unit (see [Units](#units)).
+Spawn from a system that takes `Commands()`:
```typescript
import {
@@ -40,7 +67,7 @@ import {
RigidBody, BodyType, CircleCollider,
} from 'esengine';
-const PPU = 100;
+const PPU = 100; // = Canvas.pixelsPerUnit; read the live value via physics.getPixelsPerUnit()
const spawnBall = defineSystem([Commands()], (cmds) => {
cmds.spawn()
@@ -113,7 +140,9 @@ dedicated layers so the mask narrows what each sensor considers.
## Moving bodies — forces & velocity
-Read the `Physics` resource to drive bodies. Every method takes the world entity:
+Read the `Physics` resource — a `PhysicsAPI` instance — to drive bodies. These
+methods talk to the solver directly, so they are all in **meters** (m/s, m/s² —
+see [Units](#units)). Every method takes the world entity:
```typescript
import { defineSystem, Query, Res, RigidBody } from 'esengine';
@@ -138,6 +167,14 @@ const move = defineSystem([Query(RigidBody), Res(Physics)], (q, physics) => {
| `getMass(e)` / `getInertia(e)` / `getCenterOfMass(e)` / `getMassData(e)` | Mass properties. |
| `setAwake(e, awake)` / `isAwake(e)` | Sleeping-body control. |
+`getMassData(e)` bundles the mass properties into one `MassData`:
+
+| `MassData` field | Type | Description |
+|---|---|---|
+| `mass` | number | Body mass (from collider `density` × area). |
+| `inertia` | number | Rotational inertia about the center of mass. |
+| `centerOfMass` | `Vec2` | Center of mass in the body's **local frame**, in pixels (× PPU). |
+
## Spatial queries
Queries take **pixel-space** arguments and auto-scale by the live PPU. Each accepts
@@ -162,6 +199,15 @@ const swept = physics.shapeCastCircle(/* … */); // sweep a shape
| `overlapAABB(min, max, maskBits?)` | `Entity[]` | Colliders overlapping a box. |
| `shapeCastCircle` / `shapeCastBox` / `shapeCastCapsule` | hit | Sweep a shape and get what it would hit. |
+Casts return `RaycastHit`s (`ShapeCastHit` is the same shape):
+
+| `RaycastHit` field | Type | Description |
+|---|---|---|
+| `entity` | `Entity` | The entity owning the collider that was hit. |
+| `point` | `Vec2` | Hit point, world pixels. |
+| `normal` | `Vec2` | Surface normal at the hit point (unit vector). |
+| `fraction` | number | Fraction of the cast distance at the hit, `0..1` — results sort by it, nearest first. |
+
## Collision & sensor events
The `PhysicsEvents` resource carries this frame's contacts. Set `isSensor: true` on a
@@ -223,7 +269,7 @@ its own power:
```typescript
// A conveyor: drive the crate toward +x at a fixed speed.
-world.spawn(MotorJoint, {
+world.insert(crate, MotorJoint, {
connectedEntity: anchor,
linearVelocity: { x: 200, y: 0 }, // world px/s
maxVelocityForce: 500, // newtons available to reach it
@@ -250,12 +296,11 @@ cost when no one-way platforms exist):
```typescript
import { OneWayPlatform } from 'esengine/physics';
-world.spawn(
- Transform, { position: { x: 0, y: 0 } },
- RigidBody, { bodyType: BodyType.Static },
- BoxCollider, { halfExtents: { x: 2, y: 0.2 } },
- OneWayPlatform, { normal: { x: 0, y: 1 } }, // solid top: land from above, pass from below
-);
+const platform = world.spawn('ledge');
+world.insert(platform, Transform, { position: { x: 0, y: 0 } });
+world.insert(platform, RigidBody, { bodyType: BodyType.Static });
+world.insert(platform, BoxCollider, { halfExtents: { x: 2, y: 0.2 } });
+world.insert(platform, OneWayPlatform, { normal: { x: 0, y: 1 } }); // solid top: land from above, pass from below
```
`normal` is the solid-side direction in world space; `{ x: 0, y: 1 }` (the default)
@@ -326,14 +371,49 @@ the component for the standalone `moveAndSlide` resolver (`esengine/physics`); t
native mover the live controller uses does its own iteration and gap handling, so it
ignores them. Stair/slope floor-snap (`snapLength`) is a planned mover addition.</Aside>
+## Debug draw
+
+The physics plugin installs a **`PhysicsDebugDraw`** resource — an in-game overlay
+that strokes collider outlines, velocity vectors, and contact points through the
+[`Draw`](/docs/guides/drawing/) API. It ships disabled; flip `enabled` from any
+system to see exactly what the solver sees:
+
+```typescript
+import { defineSystem, Res, Input } from 'esengine';
+import { PhysicsDebugDraw } from 'esengine/physics';
+
+const toggleDebug = defineSystem([Res(Input), Res(PhysicsDebugDraw)], (input, dbg) => {
+ if (input.isKeyPressed('F1')) dbg.enabled = !dbg.enabled;
+});
+```
+
+| `PhysicsDebugDrawConfig` field | Default | Draws |
+|---|---|---|
+| `enabled` | `false` | Master switch for the whole overlay. |
+| `showColliders` | `true` | Collider outlines, color-coded by body: blue = static, green = dynamic, cyan = kinematic; sensors are yellow. |
+| `showVelocity` | `false` | A red arrow per dynamic body along its linear velocity. |
+| `showContacts` | `false` | A red dot at each contact that began this frame. |
+
+The overlay draws in **world pixels** at each body's live transform (scaled by the
+live PPU), so what you see is exactly where the queries agree the collider is.
+`setupPhysicsDebugDraw(app, Physics, PhysicsEvents)` is the wiring `PhysicsPlugin`
+runs for you — it inserts the resource and registers the draw callback; call it (or
+the underlying per-frame `drawPhysicsDebug(app, Physics, PhysicsEvents)`) only from
+a custom host that bypasses the plugin.
+
+<Aside type="note">This is the runtime overlay. The **editor viewport** has its own
+collider/joint gizmos under the Physics Show Flag (see
+[Joints — in the editor](#in-the-editor)); the two are independent.</Aside>
+
## Best practices
- **Fixed timestep**: apply continuous forces and read `PhysicsEvents` *every frame*,
since physics substeps independently of the frame delta.
- **`bullet: true`** on fast, thin bodies (bullets, thin platforms) to avoid tunneling.
- **`fixedRotation: true`** for characters so they don't topple.
-- **Colliders in meters** (÷ PPU), but **queries and the character controller in
- pixels** — mixing the two is the most common bug.
+- **Colliders and the solver in meters, queries and the character controller in
+ pixels** — mixing the two is the most common bug; convert with
+ `physics.getPixelsPerUnit()` (see [Units](#units)).
- **Sensors for triggers**: `isSensor: true` gives enter/exit events with no physical push.
- **Filter with layers** (`categoryBits` / `maskBits`) instead of checking entity types
in event handlers.
diff --git a/docs/astro/src/content/docs/guides/profiling.mdx b/docs/astro/src/content/docs/guides/profiling.mdx
new file mode 100644
index 000000000..e34ead849
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/profiling.mdx
@@ -0,0 +1,386 @@
+---
+title: Profiling & Diagnostics
+description: Frame stats and the in-game overlay, structured logging, frame capture, GL debugging, GPU resource budgets, and subsystem health.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Estella ships its diagnostics as ordinary SDK surface: a **`Stats` resource** your
+systems can read, an **in-game overlay**, a structured **logger** with pluggable
+sinks, a **frame capture** that records every draw call (and can replay the frame
+up to any one of them), **GL error checking**, GPU **resource residency stats**,
+and a per-app **subsystem health registry**. This guide covers each piece.
+
+## Frame stats — `statsPlugin`
+
+Add `statsPlugin` and the engine collects per-frame performance data into the
+`Stats` resource every frame (in the `Last` schedule, after everything else ran):
+
+```typescript
+import { statsPlugin } from 'esengine';
+
+app.addPlugin(statsPlugin);
+```
+
+`statsPlugin` is a ready-made instance with defaults. For options, construct
+`StatsPlugin` yourself:
+
+```typescript
+import { StatsPlugin } from 'esengine';
+
+app.addPlugin(new StatsPlugin({ overlay: true, position: 'top-right' }));
+```
+
+| `StatsPluginOptions` | Type | Default | Description |
+|---|---|---|---|
+| `overlay` | boolean | `true` | Show the DOM overlay (skipped automatically where there's no `document`). |
+| `position` | `StatsPosition` | `'bottom-left'` | Overlay corner: `'top-left'` / `'top-right'` / `'bottom-left'` / `'bottom-right'`. |
+| `container` | HTMLElement | `document.body` | Element the overlay panel is appended to. |
+
+The plugin also calls `app.enableStats()`, which turns on per-system and
+per-phase timing collection (off otherwise, so shipped games don't pay for it).
+
+### Reading `Stats` from a system
+
+`Stats` is a normal resource — inject it with `Res(Stats)`:
+
+```typescript
+import { defineSystem, addSystem, Res, Stats } from 'esengine';
+
+const watchPerf = defineSystem([Res(Stats)], (stats) => {
+ if (stats.fps > 0 && stats.fps < 30) {
+ console.warn(`slow frame: ${stats.frameTimeMs.toFixed(1)}ms, ${stats.drawCalls} draw calls`);
+ }
+});
+addSystem(watchPerf);
+```
+
+`FrameStats` fields (FPS and frame time are a 60-frame sliding-window average;
+the render counters are the current frame's):
+
+| `FrameStats` field | Type | Description |
+|---|---|---|
+| `fps` | number | Frames per second, averaged over the last 60 frames. |
+| `frameTimeMs` | number | Average frame time in milliseconds over the same window. |
+| `entityCount` | number | Live entities in the world. |
+| `systemTimings` | `Map<string, number>` | CPU ms per system this frame, keyed by system name. |
+| `phaseTimings` | `Map<string, number>` | CPU ms per schedule phase this frame. |
+| `drawCalls` | number | GPU draw calls issued this frame. |
+| `triangles` | number | Triangles submitted this frame. |
+| `sprites` | number | Sprites rendered this frame. |
+| `text` | number | Text entities rendered this frame. |
+| `spine` | number | Spine skeletons rendered this frame. |
+| `meshes` | number | Meshes rendered this frame. |
+| `culled` | number | Entities culled (not submitted) this frame. |
+
+## The stats overlay
+
+With `overlay: true` (the default) the plugin renders a small fixed-position
+monospace panel: FPS + frame time, draw calls / triangles / sprites / culled,
+entity count, and the **top 5 systems** ranked by their worst frame — each as
+`avg / max ms`. The panel re-renders at most every 500&nbsp;ms, accumulating
+system timings in between, so it costs next to nothing and a one-frame spike
+still shows up in the `max` column.
+
+You can also drive a `StatsOverlay` yourself — for example to bind it to a
+debug hotkey:
+
+```typescript
+import { StatsOverlay, defineSystem, addSystem, Res, Stats } from 'esengine';
+
+const overlay = new StatsOverlay(document.body, 'top-right');
+
+const feedOverlay = defineSystem([Res(Stats)], (stats) => {
+ overlay.update(stats);
+});
+addSystem(feedOverlay);
+
+// overlay.hide() / overlay.show() to toggle, overlay.dispose() to remove it.
+```
+
+<Aside type="note">
+ The overlay is DOM-based, so it exists on web and desktop but not in
+ DOM-less environments; `statsPlugin` skips creating it there automatically.
+ The `Stats` resource itself works everywhere.
+</Aside>
+
+## Renderer counters — `Renderer.getStats()`
+
+The render counters in `FrameStats` come from `Renderer.getStats()`, which you
+can also call directly (no stats plugin needed) — it returns a `RenderStats`
+with the same seven fields: `drawCalls`, `triangles`, `sprites`, `text`,
+`spine`, `meshes`, `culled`.
+
+```typescript
+import { Renderer } from 'esengine';
+
+const rs = Renderer.getStats();
+console.log(`${rs.drawCalls} draw calls, ${rs.triangles} triangles`);
+```
+
+## Building your own tooling
+
+Two small utilities back the plugin and are exported for custom tooling:
+
+- **`StatsCollector`** — the 60-frame sliding window behind `fps` /
+ `frameTimeMs`. Feed it delta times with `pushFrame(deltaSeconds)` and read
+ `getFps()` / `getFrameTimeMs()`; `reset()` clears the window.
+- **`FrameHistory`** — a ring buffer of `FrameSnapshot`s (default capacity
+ 300, ~5&nbsp;seconds at 60&nbsp;fps) for building frame-time graphs.
+ `push(frameTimeMs, phaseTimings, systemTimings?)` deep-copies the maps so
+ snapshots stay valid; `getLatest()` returns the newest snapshot, `getAll()`
+ the whole window oldest-first, and `count` / `reset()` do what they say.
+
+| `FrameSnapshot` field | Description |
+|---|---|
+| `frameTimeMs` | The frame's total CPU time. |
+| `phaseTimings` | Per-phase ms (copied at push time). |
+| `systemTimings` | Per-system ms (copied at push time). |
+
+## Logging
+
+The SDK routes its own diagnostics through a structured logger instead of raw
+`console.*`, and your game code can use the same channel. Every message has a
+**level**, a free-form **category** string (`'physics'`, `'net'`, your own
+`'gameplay'`…), a message, and optional structured `data`:
+
+```typescript
+import { log, setLogLevel, LogLevel } from 'esengine';
+
+setLogLevel(LogLevel.Debug); // default is LogLevel.Info
+
+log.debug('gameplay', 'Wave spawned', { wave: 3, enemies: 12 });
+log.info('save', 'Game saved');
+log.warn('net', 'High latency', { rttMs: 240 });
+log.error('boot', 'Asset manifest failed', err); // Error keeps its stack
+```
+
+`LogLevel` is `Debug < Info < Warn < Error`; `setLogLevel` sets the minimum
+level — anything below it is dropped before reaching any handler. The
+standalone `debug` / `info` / `warn` / `error` functions are also exported and
+forward to the same default logger; `getLogger()` returns it if you need the
+`Logger` instance itself.
+
+By default one console handler is installed: it formats
+`[time] [LEVEL] [category] message` and picks the matching `console` method
+per level, passing `Error` data through as a real argument so the browser
+renders the stack trace.
+
+### Custom log sinks
+
+A **`LogHandler`** receives every accepted message as a structured `LogEntry`
+— the hook for an in-game console, a file writer, or crash-report
+breadcrumbs. A handler that throws is caught and reported, never breaking the
+app:
+
+```typescript
+import { getLogger, LogLevel, type LogEntry, type LogHandler } from 'esengine';
+
+class Breadcrumbs implements LogHandler {
+ entries: LogEntry[] = [];
+ handle(entry: LogEntry): void {
+ if (entry.level >= LogLevel.Warn) {
+ this.entries.push(entry);
+ if (this.entries.length > 100) this.entries.shift();
+ }
+ }
+}
+
+const crumbs = new Breadcrumbs();
+getLogger().addHandler(crumbs);
+// getLogger().removeHandler(crumbs) to detach,
+// getLogger().clearHandlers() to remove every handler (console one included).
+```
+
+| `LogEntry` field | Type | Description |
+|---|---|---|
+| `timestamp` | number | `Date.now()` at log time (epoch ms). |
+| `level` | `LogLevel` | `Debug` / `Info` / `Warn` / `Error`. |
+| `category` | string | The channel string the caller passed. |
+| `message` | string | The message. |
+| `data` | unknown | Optional payload (object, `Error`, …). |
+
+## Frame capture — every draw call, explained
+
+When "why is this 40 draw calls?" needs an answer, capture a frame. Arm the
+capture, let one frame render, then read back a record for **every draw call**
+— what it drew, with which texture/material/shader and state, and crucially
+**why the previous batch broke**:
+
+```typescript
+import { Renderer, RenderType, FlushReason } from 'esengine';
+
+Renderer.captureNextFrame(); // arm: the NEXT rendered frame records
+
+// …one frame later:
+if (Renderer.hasCapturedData()) {
+ const capture = Renderer.getCapturedData(); // FrameCaptureData | null
+ for (const dc of capture!.drawCalls) {
+ console.log(
+ `#${dc.index} ${RenderType[dc.type]} tex=${dc.textureId} ` +
+ `tris=${dc.triangleCount} entities=${dc.entityCount} ` +
+ `flush=${FlushReason[dc.flushReason]}`
+ );
+ }
+ console.log(`${capture!.cameraCount} camera pass(es)`);
+}
+```
+
+`FrameCaptureData` is `{ drawCalls: DrawCallInfo[], cameraCount }`. Each
+`DrawCallInfo`:
+
+| `DrawCallInfo` field | Description |
+|---|---|
+| `index` | Draw call index within the frame (submission order). |
+| `cameraIndex` | Which camera pass issued it. |
+| `stage` | Render stage (`RenderStage`: Background / Opaque / Transparent / Overlay). |
+| `type` | What kind of content (`RenderType`, below). |
+| `blendMode` | Blend mode id in effect. |
+| `textureId` / `materialId` / `shaderId` | GPU resources bound for the call. |
+| `vertexCount` / `triangleCount` | Geometry submitted. |
+| `entityCount` / `entityOffset` / `entities` | The entity ids batched into this call. |
+| `layer` | Render layer of the batch. |
+| `flushReason` | Why this batch ended (`FlushReason`, below). |
+| `scissorX/Y/W/H`, `scissorEnabled` | Scissor rect state (UI masks). |
+| `stencilWrite` / `stencilTest` / `stencilRef` | Stencil state (mask writers/readers). |
+| `textureSlotUsage` | Texture slots the batch consumed. |
+
+`RenderType` tells you what a call drew: `Sprite`, `Spine`, `Mesh`,
+`ExternalMesh`, `Text`, `Particle`, `Shape`, `UIElement`.
+
+`FlushReason` is the batching story — each value names the state change that
+forced a new draw call, i.e. what to fix to batch better:
+
+| `FlushReason` | Meaning |
+|---|---|
+| `BatchFull` | Vertex batch hit capacity — a "good" flush; lots of content. |
+| `TextureSlotsFull` | Ran out of texture slots — atlas more textures together. |
+| `ScissorChange` | Scissor rect changed (a `UIMask` boundary). |
+| `StencilChange` | Stencil state changed (mask write/test boundary). |
+| `MaterialChange` | Material switched — group entities by material. |
+| `BlendModeChange` | Blend mode switched — interleaved additive/normal content. |
+| `StageEnd` | Render stage boundary. |
+| `TypeChange` | Content type switched (e.g. sprites → text → sprites). |
+| `FrameEnd` | Final flush of the frame. |
+
+### Replaying to a draw call
+
+A capture can be **replayed up to any draw call** to see the frame being built
+— this is what the editor's frame inspector does. `replayToDrawCall(i)`
+re-renders draw calls `0…i` into a snapshot; `getSnapshotImageData()` resolves
+with its pixels once the GPU readback lands (immediate on WebGL, a later tick
+on WebGPU):
+
+```typescript
+import { Renderer } from 'esengine';
+
+Renderer.replayToDrawCall(5); // draw calls 0..5 only
+const img = await Renderer.getSnapshotImageData(); // ImageData | null
+if (img) ctx2d.putImageData(img, 0, 0); // e.g. into a debug canvas
+```
+
+## GL debugging — `GLDebug`
+
+`GLDebug` toggles GL error checking inside the wasm renderer — off by default
+because checking has a cost:
+
+```typescript
+import { GLDebug } from 'esengine';
+
+GLDebug.enable(); // check GL errors at key points
+const errors = GLDebug.check('after-spawn'); // explicit check; returns error count
+GLDebug.diagnose(); // dump renderer diagnostics to the console
+GLDebug.disable();
+```
+
+`check(context)` runs an immediate error check and returns the number of GL
+errors found, tagging any log output with your `context` string so you can
+bisect where in the frame an error appears.
+
+## GPU resource budgets & residency
+
+Released textures stay resident in a byte-budgeted warm cache (the full model
+is in the [assets guide](/docs/guides/assets/#lifetime--reference-counting)).
+The diagnostics side of it:
+
+```typescript
+import { getResourceStats, setTextureBudget, trimTextureCache } from 'esengine';
+
+setTextureBudget(256 * 1024 * 1024); // resize the budget (0 = no warm cache)
+
+const stats = getResourceStats(); // ResourceStats | null before engine init
+if (stats && stats.textureBytes > stats.textureBudget * 0.9) {
+ const freed = trimTextureCache(); // drop every evictable texture now
+ console.log(`freed ${freed} cached textures`);
+}
+```
+
+| `ResourceStats` field | Description |
+|---|---|
+| `shaderCount` | Live compiled shaders. |
+| `textureCount` | Live GPU textures. |
+| `vertexBufferCount` / `indexBufferCount` | Live GPU buffers. |
+| `cacheHits` / `cacheMisses` | Resource-cache hit/miss counters. |
+| `textureBytes` | Resident texture bytes (RGBA8 estimate) — held + evictable. |
+| `textureBudget` | The current resident-byte budget (`0` = eviction off). |
+| `textureEvictableCount` | Cached refcount-0 textures awaiting revive or eviction. |
+
+`trimTextureCache()` frees every evictable entry immediately and returns how
+many textures it freed — the engine calls it on OS memory warnings; call it
+yourself before a known memory spike. Held (referenced) textures and the
+budget are untouched.
+
+`evictTextureDimensions(handle)` drops the SDK-side cached width/height for
+one texture handle so the next `getTextureDimensions` query re-reads it from
+the engine — only relevant to tooling that replaces texture contents under an
+existing handle.
+
+## Subsystem health
+
+Every `App` carries a `SubsystemRegistry` at `app.subsystems` that tracks each
+engine subsystem's lifecycle phase (`registered` → `initializing` → `ready`,
+`error` terminal) and derived liveness (`stepping` / `idle` / `inactive`) — the
+"is physics actually running?" question:
+
+```typescript
+for (const s of app.subsystems.getStatuses()) {
+ console.log(`${s.displayName}: ${s.phase} (${s.activity})`, s.lastError ?? '');
+}
+```
+
+`recentEvents()` returns the recent lifecycle transitions and `subscribe(fn)`
+notifies on phase changes. The full lifecycle model is covered in
+[App & Lifecycle](/docs/core-concepts/app-lifecycle/).
+
+## In the editor
+
+The desktop editor builds its profiling UI on these same surfaces: the
+**Profiler panel** shows a live frame-time graph with per-phase and per-system
+breakdowns (click a frame to inspect it), and the viewport has a small perf
+overlay for an at-a-glance FPS readout. For in-game builds, `statsPlugin` above
+is the equivalent.
+
+## Best practices
+
+- **Ship without `statsPlugin`** (or gate it behind a debug flag) — timing
+ collection is off by default for a reason; add it while profiling.
+- **Blame before optimizing** — read `systemTimings` / `phaseTimings` to find
+ *which* system is slow before touching code; the overlay's `max` column
+ catches one-frame spikes an average hides.
+- **Capture a frame to fix draw calls** — `flushReason` names the exact state
+ change that broke each batch (`TextureSlotsFull` → atlas; `MaterialChange` →
+ group by material).
+- **Log with categories, not `console.log`** — structured entries let a
+ handler filter by channel and level, and `setLogLevel(LogLevel.Debug)` turns
+ verbosity on without code changes.
+- **Leave `GLDebug` off in production** — per-call GL error checking is
+ expensive; enable it only while hunting a rendering bug.
+- **Watch `textureBytes` against `textureBudget`** on memory-constrained
+ targets, and `trimTextureCache()` before known spikes.
+
+## See also
+
+- [Assets](/docs/guides/assets/) — the texture warm cache and budget the resource stats observe.
+- [App & Lifecycle](/docs/core-concepts/app-lifecycle/) — plugins, schedules, and the subsystem registry.
+- [Systems](/docs/core-concepts/systems/) — schedules and system names (the keys in `systemTimings`).
+- [Editor](/docs/guides/editor/) — the desktop editor, including its Profiler panel.
diff --git a/docs/astro/src/content/docs/guides/scene.mdx b/docs/astro/src/content/docs/guides/scene.mdx
index 46d7571f1..d2eb3704d 100644
--- a/docs/astro/src/content/docs/guides/scene.mdx
+++ b/docs/astro/src/content/docs/guides/scene.mdx
@@ -22,6 +22,52 @@ const goToLevel2 = defineSystem([Res(SceneManager)], async (scenes) => {
});
```
+## Scene transitions
+
+`switchTo` and `unload` take `TransitionOptions`. With `transition: 'fade'` the
+switch fades through a solid color in three phases: the overlay ramps to opaque
+over the first half of `duration`, **holds opaque while the old scene unloads and
+the new one loads** (a slow load extends the hold instead of flashing), then
+ramps back over the second half. The awaited promise resolves only after the
+fade-in completes — and rejects if the load failed. A `switchTo` issued while a
+transition is in flight is ignored with a warning; `isTransitioning()` tells you.
+
+| Option | Type | Default | Description |
+|---|---|---|---|
+| `transition` | `'none' \| 'fade'` | `'none'` | Hard cut, or fade through `color`. |
+| `duration` | number | `0.3` | Total fade time in seconds — half out, half in (`RuntimeConfig.sceneTransitionDuration`). |
+| `color` | `Color` | opaque black | Overlay color (`RuntimeConfig.sceneTransitionColor`; the build config takes a hex string). |
+| `onStart` / `onComplete` | callback | – | Fired when the fade starts / after the fade-in finishes. |
+| `keepPersistent` | boolean | `true` | Keep entities marked via `SceneContext.setPersistent` alive through the unload. |
+
+`transitionTo` is a one-call convenience over the same machinery, configured
+with a `TransitionConfig` (`type: 'fade'`, `duration`, optional `color`). It
+accepts the `App` (bootstrap code, menu glue) or the SceneManager resource
+state — inside a system, pass what `Res(SceneManager)` gives you. A menu →
+level flow:
+
+```typescript
+import { transitionTo, type TransitionConfig } from 'esengine';
+
+const fadeToBlack: TransitionConfig = {
+ type: 'fade',
+ duration: 0.5,
+ color: { r: 0, g: 0, b: 0, a: 1 },
+};
+
+async function onPlayClicked() {
+ await transitionTo(app, 'levels/level1', fadeToBlack); // menu → level
+}
+```
+
+<Aside type="note">
+ All of this ships with `sceneManagerPlugin`, which the default app bootstrap
+ already registers: it inserts the `SceneManager` and `SceneStreaming`
+ resources, loads the initial scene at startup, and advances transitions and
+ streaming every frame. You only add it yourself when assembling an `App` from
+ individual plugins.
+</Aside>
+
## Additive scenes
Load a scene **on top** of the current one — a HUD, a pause menu, a streamed region
@@ -57,6 +103,28 @@ cells instead of unloading: entities stay in memory, disabled and hidden, so
re-entering is instant at the cost of memory. Cell scenes are ordinary project
scenes referenced by name (see below).
+Under the resource sits `SceneStreamingController` — pure orchestration over the
+`SceneManager` primitives (`loadAdditive` / `unload` / `sleep` / `wake`); it owns
+no loading itself. Distances are measured to the **cell edge** (center distance
+minus `radius`), so a large cell starts loading while its center is still far
+away. Loads and unloads are async, and the controller keeps them safe: a cell
+with a load or unload in flight is never issued twice, and if the focus has
+already left by the time a load resolves, the cell is dropped again instead of
+leaking. With no cells registered, `update()` is a no-op.
+
+| `SceneStreamingController` | Description |
+|---|---|
+| `configure({ loadRadius, unloadRadius, policy? })` | Set the radii (`unloadRadius` is clamped up to `loadRadius`) and the out-of-range policy — `'unload'` (default) or `'sleep'`. |
+| `register(cell)` / `unregister(scene)` / `clear()` | Manage the cell set (`{ scene, x, y, radius }`). |
+| `setFocus(x, y)` | Drive the focus point directly (call each frame). |
+| `setFocusEntity(entity)` / `getFocusEntity()` | Follow an entity instead — the streaming system reads its `Transform` each tick (play mode only). |
+| `getActive()` | Scene names the controller currently holds in-range. |
+| `update()` | Reconcile resident cells against the focus (`sceneManagerPlugin` calls this every frame). |
+
+The threshold math is also exported on its own as the pure
+`computeStreaming(cells, focusX, focusY, loadRadius, unloadRadius, active)` —
+useful for tests or a custom scheduler.
+
## Scenes in a build
Every scene in the project's scenes folder ships with an export and registers as a
@@ -86,6 +154,96 @@ ship the startup scene only. See
| `isPaused(name)` / `isSleeping(name)` | The suspension states above. |
| `isTransitioning()` | `true` during a `switchTo` transition. |
+## Serialization & migration
+
+The scene file format is a public surface: `SceneData` is plain JSON, and the
+primitives the editor and runtime use to read and write it are exported for game
+code. You reach for them to save a **snapshot of the live world** (a checkpoint
+richer than the [save-game API](/docs/guides/save/)), to load player-generated
+or downloaded scenes, or to ship components whose state doesn't fit their plain
+fields.
+
+`serializeScene(world, name?)` walks the live world and produces a `SceneData`
+that round-trips through the loaders — hierarchy is collapsed into each entity
+record's `parent`/`children` fields, and runtime-only projection entities (tile
+colliders and the like, which their systems re-derive) are excluded.
+`loadSceneWithAssets(world, data, options?)` preloads every referenced asset,
+then spawns; the sync `loadSceneData(world, data)` spawns without asset
+resolution. Both return a map from serialized entity ids to live entities, and
+`findEntityByName(world, name)` finds an entity afterwards:
+
+```typescript
+import { defineSystem, GetWorld, Res, Assets, serializeScene,
+ loadSceneWithAssets, findEntityByName, MissingAssetsError } from 'esengine';
+
+const checkpoint = defineSystem([GetWorld(), Res(Assets)], async (world, assets) => {
+ // Save: snapshot the live world as ordinary scene JSON.
+ const data = serializeScene(world, 'checkpoint');
+ localStorage.setItem('checkpoint', JSON.stringify(data));
+
+ // Load: preload assets, then spawn. Old saves are migrated automatically.
+ try {
+ await loadSceneWithAssets(world, JSON.parse(localStorage.getItem('checkpoint')!), {
+ assets,
+ abortOnMissingAssets: true, // throw instead of spawning with holes
+ onMissingAssets: (missing) => { // called once per load (list may be empty)
+ for (const m of missing) console.warn(`${m.ref}: ${m.reason}`);
+ },
+ });
+ } catch (e) {
+ if (e instanceof MissingAssetsError) { /* "content missing" UI — e.missing */ }
+ }
+
+ const player = findEntityByName(world, 'Player');
+});
+```
+
+`SceneLoadOptions`:
+
+| Option | Description |
+|---|---|
+| `assets` | The `Assets` resource; enables asset preloading (and prefab-instance expansion) before spawn. |
+| `assetBaseUrl` | Base URL to resolve asset paths against. |
+| `onProgress` | `(loaded, total)` preload progress callback. |
+| `onMissingAssets` | Called once with every ref that failed to resolve or load (`MissingAsset[]` — `ref`, optional `type`, and `reason: 'unresolved' \| 'load-failed'`). Fires even when the list is empty. |
+| `abortOnMissingAssets` | Default `false` — missing assets get handle `0` and the scene loads anyway. `true` throws `MissingAssetsError` after preloading, before anything spawns. |
+| `collectAssets` | Bookkeeping sets the load adds acquired asset keys to, so the caller (normally the scene manager) can release them on unload. |
+
+**Versioning.** Scene files carry a `version` (currently
+`SCENE_FORMAT_VERSION = '1.0'`). `migrateSceneData(raw)` upgrades any older
+shape to the current one: it never mutates its input (it returns a migrated deep
+copy), is idempotent, drops component types retired by engine upgrades, and
+**rejects data newer than the engine**. Every loader runs it internally — call
+it yourself only to inspect `migrated` / `fromVersion` (say, to prompt a re-save
+of an upgraded file):
+
+```typescript
+import { migrateSceneData } from 'esengine';
+
+const { data, migrated, fromVersion } = migrateSceneData(raw);
+if (migrated) console.log(`upgraded scene from format ${fromVersion}`);
+```
+
+**Out-of-band component state.** A component whose full state doesn't fit its
+plain field record — a tilemap layer's tile chunks live in a C++ blob — registers
+a `SceneComponentCodec` so the generic (de)serializer can carry it without
+component-specific knowledge:
+
+```typescript
+import { registerSceneComponentCodec } from 'esengine';
+
+registerSceneComponentCodec('MyVoxelChunk', {
+ exportData(entity, data) { data.chunks = myStore.serialize(entity); },
+ outOfBandFields: ['chunks'], // stripped before the component insert
+ importData(entity, outOfBand) { myStore.restore(entity, outOfBand.chunks); },
+});
+```
+
+`exportData` writes the extra state into the record on save; the listed
+`outOfBandFields` are stripped from the record before the component is inserted
+on load, then handed to `importData` afterwards. Registration is idempotent —
+the owning plugin (see `tilemapPlugin`) does it at startup.
+
## Best practices
- **`await` scene calls** — they're async; a switch that isn't awaited races with the
diff --git a/docs/astro/src/content/docs/guides/scripting.mdx b/docs/astro/src/content/docs/guides/scripting.mdx
index 39ed74d84..4904b9f07 100644
--- a/docs/astro/src/content/docs/guides/scripting.mdx
+++ b/docs/astro/src/content/docs/guides/scripting.mdx
@@ -204,7 +204,18 @@ programming model used by the [Gameplay AI](/docs/guides/ai/) layer's actions an
behavior-tree leaves, so moving logic between a behavior and an AI action is
straightforward.
-<Aside type="note">
- On hot reload, per-entity `start` runs again for live entities — matching Estella's
- fast-restart semantics, so treat `start` as idempotent setup.
-</Aside>
+## Hot reload
+
+While the editor plays, saving your code triggers a **state-preserving hot
+swap** when it can: if your components' shapes are unchanged and no system was
+added, removed, or renamed, the live world is kept and only your function
+bodies are replaced. Otherwise the editor falls back to a full reload. What
+that asks of your code:
+
+- **Component and behavior names are identity.** Renaming one is a structural
+ change — expect a full reload and fresh state for that data.
+- On any reload, per-entity `start` runs again for live entities — matching
+ Estella's fast-restart semantics, so treat `start` as idempotent setup.
+
+The mechanism (probe context, schema fingerprint, `App.hotSwapSystems`) is
+documented in [App Setup & Lifecycle](/docs/core-concepts/app-lifecycle/#hot-reload).
diff --git a/docs/astro/src/content/docs/guides/sprites.mdx b/docs/astro/src/content/docs/guides/sprites.mdx
index b5a4d83dc..2e813ef4e 100644
--- a/docs/astro/src/content/docs/guides/sprites.mdx
+++ b/docs/astro/src/content/docs/guides/sprites.mdx
@@ -1,6 +1,6 @@
---
title: Sprites & Rendering
-description: Draw 2D images with the Sprite component — textures, tint and transparency, size and pivot, flipping, sorting layers and draw order, parallax — plus ShapeRenderer primitives, sprite filters, motion trails, and world-space bitmap text.
+description: Draw 2D images with the Sprite component — textures, tint and transparency, size and pivot, flipping, sorting layers and draw order, parallax — plus texture filtering, hit-testing, cache-as-bitmap, ShapeRenderer primitives, sprite filters, motion trails, and world-space bitmap text.
---
import { Aside } from '@astrojs/starlight/components';
@@ -70,6 +70,23 @@ Scale on the `Transform` multiplies on top of it. `pivot` is the normalized anch
bottom-left corner, `{0.5, 0}` pins the bottom-center (handy for characters standing on
the ground).
+## Units & coordinates
+
+World units are **design pixels**. Dropping a texture into the viewport spawns a
+sprite at the texture's pixel dimensions (`size = { tex.width, tex.height }`), and
+the editor's cameras are authored so one world unit is one design pixel
+(`orthoSize = designHeight / 2`). So `Sprite.size` is in design pixels, and `pivot`
+is a normalized fraction of that size. The world is **Y-up** — positive Y is up on
+screen — which is why `pivot: {0, 0}` is the **bottom-left** corner, not the top-left.
+
+<Aside type="note">
+ `Canvas.pixelsPerUnit` (default `100`) does **not** scale sprites — it's the
+ **physics meter scale**: how many design pixels make one Box2D meter (see
+ [Physics](/docs/guides/physics/)). A sprite's displayed size is `size` ×
+ `Transform` scale, nothing else. The full units-and-spaces picture is in
+ [Transforms](/docs/core-concepts/transforms/).
+</Aside>
+
## Draw order & sorting layers
When sprites overlap, draw order decides what's on top. Order is set by the **sorting
@@ -110,6 +127,39 @@ front of it — no manual `layer` or z juggling.
- **Scrolling**: animate `uvOffset` over time to scroll a texture (water, conveyor
belts), and set `tileSize` to repeat it across a large sprite.
+## Texture filtering & wrapping
+
+How a texture is sampled is set **per texture handle**, not per sprite:
+
+| Enum | Values | Meaning |
+|---|---|---|
+| `TextureFilter` | `Nearest`, `Linear` | Nearest = hard texel edges (pixel art); Linear = smooth interpolation (default). |
+| `TextureWrap` | `Repeat`, `ClampToEdge`, `MirroredRepeat` | What UVs outside 0–1 sample — tiling repeats, clamp stretches the edge pixel. |
+
+```typescript
+import { TextureFilter, TextureWrap, setTextureFilter, setTextureWrap, setTextureParams } from 'esengine';
+
+setTextureFilter(tex.handle, TextureFilter.Nearest); // crisp pixel art
+setTextureWrap(tex.handle, TextureWrap.Repeat); // tile outside 0–1 UVs
+
+// The two helpers above each reset the *other* params to their defaults
+// (ClampToEdge / Linear). To set filter and wrap together, use the full form:
+setTextureParams(tex.handle, TextureFilter.Nearest, TextureFilter.Nearest,
+ TextureWrap.Repeat, TextureWrap.Repeat);
+```
+
+`setTextureParams(textureId, minFilter, magFilter, wrapS, wrapT)` is the complete
+surface — separate minification/magnification filters and per-axis wrap. `Repeat`
+is what makes `tileSize` tiling and UV-scroll effects seamless.
+
+<Aside type="tip">
+ For pixel art, `TextureFilter.Nearest` is half the story: it keeps **texels**
+ crisp, but a camera at a fractional position still lands sprites between screen
+ pixels and shimmers as it moves. Pair it with the camera's `pixelPerfect` flag,
+ which snaps the (orthographic) camera to the pixel grid — see
+ [Camera](/docs/guides/camera/).
+</Aside>
+
## Parallax backgrounds
`parallax` scales how much a sprite moves relative to the camera: `1` moves with the
@@ -213,6 +263,100 @@ numbers, name tags, retro UI. Point `font` at a **BMFont** asset (`.fnt` text or
For screen-space UI text (layout, wrapping, SDF sharpness), use the UI `Text`
widget instead — see [UI](/docs/guides/ui/).
+## Hit-testing sprites
+
+"Did the click land on this sprite?" is two steps: convert the screen point to
+world space, then test it against the sprite's rectangle. The `CameraView`
+resource does the first (see [Camera](/docs/guides/camera/)); for the second the
+SDK exports pivot-aware point tests:
+
+| Function | Tests |
+|---|---|
+| `pointInWorldRect(px, py, worldX, worldY, worldW, worldH, pivotX, pivotY)` | An axis-aligned rectangle placed by position + pivot (a sprite's exact footprint when unrotated). |
+| `pointInOBB(…, rotationZ, rotationW)` | The same rectangle **rotated** — pass the transform quaternion's `z`/`w`; falls back to the rect test when unrotated. |
+| `pointInHitArea(px, py, area)` | A custom `HitAreaShape` — `rect`, `circle`, or `polygon`. |
+
+```typescript
+import { defineSystem, Query, Res, CameraView, Input, Transform, Sprite, pointInOBB } from 'esengine';
+
+const clickSprites = defineSystem(
+ [Query(Transform, Sprite), Res(CameraView), Res(Input)],
+ (q, view, input) => {
+ if (!input.isMouseButtonPressed(0)) return;
+ const p = view.screenToWorld(input.mouseX, input.mouseY);
+ if (!p) return;
+ for (const [entity, t, s] of q) {
+ const w = s.size.x * t.worldScale.x, h = s.size.y * t.worldScale.y;
+ if (pointInOBB(p.x, p.y, t.worldPosition.x, t.worldPosition.y,
+ w, h, s.pivot.x, s.pivot.y,
+ t.worldRotation.z, t.worldRotation.w)) {
+ console.log('hit', entity);
+ }
+ }
+ });
+```
+
+For sprites whose clickable region isn't their rectangle — an irregular character,
+a donut-shaped button — describe the region as a `HitAreaShape` in sprite-local
+coordinates and test the localized point:
+
+```typescript
+import { pointInHitArea, type HitAreaShape } from 'esengine';
+
+const hull: HitAreaShape = { type: 'polygon', points: [0, 0, 64, 0, 64, 48, 32, 64, 0, 48] };
+// For an unrotated sprite, localize by subtracting its origin:
+const hit = pointInHitArea(p.x - t.worldPosition.x, p.y - t.worldPosition.y, hull);
+```
+
+`screenToWorld` is also exported standalone (it takes an inverse view-projection
+matrix and a viewport rectangle) for code that manages its own camera math — the
+`CameraView` resource is the same function with the active camera filled in. For
+interactive **UI**, don't hand-roll any of this: `Interactable` + `UIEvents` do
+picking for you (see [UI](/docs/guides/ui/)).
+
+## Cache as bitmap
+
+**`CacheAsBitmap`** supports rendering an entity's expensive content **once** into
+an offscreen texture and drawing that single quad afterwards — the classic
+cache-as-bitmap trade: GPU memory (`width × height` RGBA) for per-frame draw cost.
+It pays when content is costly to draw every frame (many vector paths, lots of
+text or shapes) but **rarely changes**; it does nothing for you if the content
+changes every frame — you'd re-render the cache each time *and* pay the extra blit.
+
+| Field | Default | Description |
+|---|---|---|
+| `enabled` | `true` | Whether caching is active for this entity. |
+| `dirty` | `true` | Set `true` to request a re-render of the cache. |
+| `width` / `height` | `256` | Cache texture size in pixels. |
+
+The component is the **bookkeeping half** — the SDK does not ship a system that
+walks the scene and caches subtrees automatically. You drive the refresh with the
+exported helpers: a per-entity cache store (`getCacheForEntity`,
+`setCacheForEntity`, `removeCacheForEntity`, `clearAllCaches`) and `CacheBitmap`,
+a thin render-target wrapper (`create`, `beginDraw`/`endDraw`, `resize`,
+`release`):
+
+```typescript
+import { CacheBitmap, getCacheForEntity, setCacheForEntity, Draw } from 'esengine';
+
+// Refresh (only when dirty):
+let cache = getCacheForEntity(entity);
+if (!cache) {
+ cache = CacheBitmap.create(512, 256);
+ setCacheForEntity(entity, cache);
+}
+CacheBitmap.beginDraw(cache, viewProjection); // an ortho matrix framing the content
+// … draw the expensive content once, with Draw / Graphics …
+CacheBitmap.endDraw();
+
+// Every frame thereafter: one textured quad instead of the whole redraw.
+Draw.texture(pos, { x: 512, y: 256 }, cache.textureId);
+```
+
+`cache.textureId` is an ordinary texture handle — it also works as a
+`Sprite.texture`. Under the hood this is a [RenderTexture](/docs/guides/drawing/)
+without a depth buffer.
+
## In the editor
- **Create → Sprite** adds a sprite entity, or **drag an image** from the Content
diff --git a/docs/astro/src/content/docs/guides/timeline.mdx b/docs/astro/src/content/docs/guides/timeline.mdx
index 22912c2bc..7f6b6ac1e 100644
--- a/docs/astro/src/content/docs/guides/timeline.mdx
+++ b/docs/astro/src/content/docs/guides/timeline.mdx
@@ -84,13 +84,98 @@ These methods write through to the `TimelinePlayer` flags — `timeline.play(e)`
A timeline is a set of tracks evaluated together each frame:
-| Track | Drives |
+| Track | `TrackType` | Drives |
+|---|---|---|
+| Property | `Property` | Keyframed component fields — position / rotation / scale and any numeric dot-path. |
+| Sprite frames | `AnimFrames` | Swap sprite-sheet frames over time. |
+| Sprite clip | `SpriteAnim` | Start a named `anim-clip` at a time. |
+| Audio | `Audio` | Fire one-shot sounds at keyframes. |
+| Activation | `Activation` | Toggle entities on/off over ranges. |
+| Spine | `Spine` | Play Spine animations as clips. |
+| Marker | `Marker` | Named time markers. |
+| Custom event | `CustomEvent` | Named events with a payload, for your own systems. |
+
+## Timelines from code
+
+An `.estimeline` document is plain data — the `TimelineAsset` type plus the
+`TrackType` / `InterpType` / `WrapMode` constants let you build one entirely in
+code. Register it with `registerTimelineAsset(path, asset)`, and any
+`TimelinePlayer` whose `timeline` names that same path plays it like an authored
+asset:
+
+```typescript
+import {
+ defineSystem, Commands, registerTimelineAsset, TimelinePlayer,
+ TrackType, InterpType, WrapMode, type TimelineAsset,
+} from 'esengine';
+
+const slideIn: TimelineAsset = {
+ version: '1.1',
+ type: 'timeline',
+ duration: 2,
+ wrapMode: WrapMode.Once,
+ tracks: [{
+ type: TrackType.Property,
+ name: 'Slide in',
+ childPath: '', // '' = the player entity itself
+ component: 'Transform',
+ channels: [{
+ property: 'position.x',
+ keyframes: [
+ { time: 0, value: -200, inTangent: 0, outTangent: 0, interpolation: InterpType.EaseOut },
+ { time: 2, value: 0, inTangent: 0, outTangent: 0 },
+ ],
+ }],
+ }],
+};
+
+const attach = defineSystem([Commands()], (cmds) => {
+ registerTimelineAsset('code/slide-in', slideIn);
+ cmds.spawn().insert(TimelinePlayer, {
+ timeline: 'code/slide-in',
+ playing: true,
+ wrapMode: 'once',
+ });
+});
+```
+
+A `Keyframe` is `{ time, value, inTangent, outTangent, interpolation? }`. The
+segment *starting* at a keyframe uses that keyframe's `interpolation`:
+`Hermite` (the default — tangent-driven curves), `Linear`, `Step`, `EaseIn`,
+`EaseOut`, or `EaseInOut`. A property track resolves its target entity by
+`childPath` (child names separated by `/`; empty = the player entity) and writes
+the channel's dot-path field on the named component.
+
+### Wrap modes
+
+Playback uses the **player component's** `wrapMode` string; the numeric
+`WrapMode` constant lives on the asset and in the pure evaluation API. The
+mapping and behavior:
+
+| `WrapMode` | Player string | Behavior past the end |
+|---|---|---|
+| `WrapMode.Once` (`0`) | `'once'` | Clamp at `duration`, stop, latch `finished`. |
+| `WrapMode.Loop` (`1`) | `'loop'` | Wrap around (`time % duration`). |
+| `WrapMode.PingPong` (`2`) | `'pingPong'` | Play forward then backward each cycle. |
+
+`applyWrapMode(time, duration, mode)` is the pure mapping itself — it returns
+`{ time, stopped }` for an absolute clock time.
+
+### Sampling and serializing
+
+The evaluator is pure TypeScript, shared by playback and the editor's scrub —
+you can call it yourself:
+
+| Function | Description |
|---|---|
-| Transform | Position / rotation / scale keyframes (hermite / linear / step). |
-| Sprite frames | Swap sprite-sheet frames over time. |
-| Audio | Fire one-shot sounds at keyframes. |
-| Activation | Toggle entities on/off. |
-| Spine | Play Spine animations as clips. |
+| `sampleTimelineInWorld(asset, time, world, rootEntity, opts?)` | Evaluate every property track at `time` and write the results into the world (the scrub operation). |
+| `sampleTimeline(asset, time, rootEntity, deps, opts?)` | Same, with injected `SampleDeps` (world / component lookup / child resolver) — for tests and tooling. |
+| `evaluateChannel(channel, time)` | Value of one property channel at `time`; endpoints clamp. |
+| `serializeTimelineAsset(asset)` | The asset as a JSON-ready object (the `.estimeline` document shape). |
+| `serializeTimelineToJson(asset, indent?)` | Pretty-printed `.estimeline` JSON string (indent defaults `2`). |
+
+Sampling covers property tracks; event-like tracks (audio, markers, custom
+events) fire edge-detected during playback, not on a sample.
## Best practices
diff --git a/docs/astro/src/content/docs/guides/ui-binding.mdx b/docs/astro/src/content/docs/guides/ui-binding.mdx
new file mode 100644
index 000000000..d97e30c1a
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-binding.mdx
@@ -0,0 +1,221 @@
+---
+title: Data Binding
+description: Reactive signals into component fields — signal/derived/bind, two-way widget binding with bindWidgetValue, and when to use binding vs controllers vs systems.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Data binding drives UI from game state **declaratively**: a *signal* holds a
+value, a *binding* writes it into a component field — applied immediately and
+on every change. It replaces the imperative "read the component, mutate the
+field, insert it back" loop, and it is **push-based**: subscribers run inside
+`set`, so there is no per-frame polling.
+
+## Signals — `signal()`
+
+`signal(initial)` creates a writable reactive value:
+
+```typescript
+import { signal } from 'esengine';
+
+const score = signal(0);
+
+score.get(); // → 0
+score.set(10); // notifies subscribers
+score.update((n) => n + 1); // set via the previous value
+const off = score.subscribe((n) => console.log('score is', n));
+off(); // unsubscribe
+```
+
+| `Signal<T>` member | Contract |
+|---|---|
+| `get()` | The current value. |
+| `set(value)` | Store + notify — but **only if the value actually changed** (`Object.is`); an unchanged write is free. |
+| `update(fn)` | `set(fn(previous))`. |
+| `subscribe(fn)` | Called on every change; returns an unsubscribe function. |
+
+`ReadonlySignal<T>` is the `get` + `subscribe` half — what `derived` returns
+and what `bind` accepts, so a consumer can't write back into a source it
+should only read.
+
+## Derived values — `derived()`
+
+`derived(sources, compute)` is a read-only signal computed from other signals;
+it recomputes (and notifies, again only on real change) whenever any source
+changes:
+
+```typescript
+import { signal, derived } from 'esengine';
+
+const health = signal(75);
+const maxHealth = signal(100);
+const healthFrac = derived([health, maxHealth], () => health.get() / maxHealth.get());
+```
+
+<Aside type="caution">
+ A `derived`'s subscriptions to its sources live for the process — use it for
+ **app-lifetime** derivations (score text, health fractions), not something
+ you mint per short-lived entity.
+</Aside>
+
+## One-way binding — `bind()`
+
+`bind(world, entity, Component, field, source)` drives one component field
+from a `ReadonlySignal`:
+
+```typescript
+import { signal, derived, bind, Text } from 'esengine';
+
+const score = signal(0);
+bind(world, scoreLabel, Text, 'content',
+ derived([score], () => `Score: ${score.get()}`));
+
+score.set(1200); // the label now reads "Score: 1200"
+```
+
+The contract, from the source:
+
+- The field is **seeded immediately** with the signal's current value, then
+ tracks every change.
+- Writes are **guarded** — skipped if the entity is gone or lost the
+ component — and go through `world.insert` (a full component write, like any
+ other mutation).
+- The binding **auto-disposes when the entity despawns**; it also returns a
+ manual dispose to unbind early.
+- Types line up end to end: `bind(world, e, Text, 'content', source)` requires
+ `source` to be a `ReadonlySignal<string>` because `Text.content` is a string.
+
+Any reflected field works the same way — `UIVisual.color` from a
+`ReadonlySignal<Color>`, `Text.color`, a `UINode` dimension, etc.
+
+## Two-way widget binding — `bindWidgetValue()`
+
+Value widgets (slider, toggle, dropdown) need traffic in both directions:
+signal writes flow **down** into the widget's value field, and user input
+flows **up** from the widget's `change` event into the signal.
+`bindWidgetValue` wires both:
+
+```typescript
+bindWidgetValue(world, events, entity, Component, field, signal, payloadKey?)
+```
+
+- **Down**: a `bind` writes the signal into the field; the widget's behavior
+ system observes the component and updates visuals + emits `change`.
+- **Up**: the widget's `change` event writes its payload value back into the
+ signal.
+- **No loops**: the signal is the loop breaker — `Signal.set` and the
+ down-binding both no-op on equal values, so a round trip settles in one hop.
+- Returns a dispose that tears down both directions (the down-binding also
+ auto-disposes on despawn).
+
+`payloadKey` names the value inside the `change` payload and defaults to the
+field name:
+
+| Widget | Component / field | `payloadKey` |
+|---|---|---|
+| Slider | `UISlider.value` | `'value'` (the default) |
+| Toggle | `UIToggle.isOn` | `'isOn'` (the default) |
+| Dropdown | `UIDropdown.selectedIndex` | `'index'` (pass explicitly) |
+
+A volume row — slider and label, both bound to one signal:
+
+```typescript
+import {
+ defineSystem, addStartupSystem, GetWorld, Res, UIEvents,
+ spawnUIEntity, createSlider, px,
+ signal, derived, bind, bindWidgetValue,
+ UISlider, Text,
+} from 'esengine';
+
+const buildVolumeRow = defineSystem([GetWorld(), Res(UIEvents)], (world, events) => {
+ const volume = signal(0.8);
+
+ // The slider: dragging it (or arrow keys while focused) writes `volume` up.
+ const slider = createSlider({
+ world, events,
+ node: { width: px(240), height: px(20) },
+ min: 0, max: 1, value: volume.get(),
+ });
+ bindWidgetValue(world, events, slider.entity, UISlider, 'value', volume);
+
+ // The label: follows the same signal down.
+ const label = spawnUIEntity({ world, text: { content: '' } });
+ bind(world, label, Text, 'content',
+ derived([volume], () => `${Math.round(volume.get() * 100)}%`));
+
+ // Game code sets the signal; the slider fill+handle AND the label follow.
+ volume.set(0.5);
+});
+
+addStartupSystem(buildVolumeRow);
+```
+
+Because the down edge writes the *component* and the widget's behavior system
+is the single writer of the visuals, every writer — the pointer, the binding,
+`setValue` on the handle, the editor inspector — moves the fill and handle and
+fires `change` identically.
+
+## Binding controller pages
+
+`bindControllerPage(world, entity, controller, source)` drives a
+[UI controller's](/docs/guides/ui-controllers/) current page from a
+`ReadonlySignal<string>` — the declarative path to a data-driven tab bar. Set
+the signal, the page switches, every geared element reflows:
+
+```typescript
+import { signal, bindControllerPage } from 'esengine';
+
+const activeTab = signal('home');
+bindControllerPage(world, root, 'tab', activeTab);
+activeTab.set('shop');
+```
+
+Same lifecycle as `bind`: seeded now, auto-disposed on despawn, manual dispose
+returned. Unknown controllers/pages are ignored rather than throwing.
+
+## Binding and lists
+
+A [ListView](/docs/guides/ui-lists/) is *already* data-driven — it renders
+from a `DataSource` (e.g. `ArrayDataSource`) with fine-grained
+insert/remove/update notifications, which virtualization needs and a single
+value signal can't express. So: **collections go in a `DataSource`, scalar UI
+state goes in signals**, and the two compose — an item template's `bind`
+callback can read signals, and a signal (say, a selected id) can live next to
+the data source that owns the rows.
+
+## Binding vs controllers vs systems
+
+Three ways to get game state onto the screen — pick by the shape of the state:
+
+| State shape | Use | Why |
+|---|---|---|
+| A **value** — score, health, a name, a slider position | `signal` + `bind` / `bindWidgetValue` | Push on change, no polling; two-way for value widgets. |
+| A **named state** out of a finite set — tab, open/closed, button state | [Controller + gears](/docs/guides/ui-controllers/) | Many elements reflow from one page switch; editor-authorable; tweens. Bridge from data with `bindControllerPage`. |
+| A **collection** — inventory rows, leaderboard | `DataSource` + [ListView](/docs/guides/ui-lists/) | Fine-grained change notifications drive virtualization. |
+| A **per-frame** value derived from simulation — cooldown sweep, follow-the-player markers | A plain [system](/docs/guides/scripting/) writing components | The value changes every frame anyway; a query is the natural reader. |
+
+Rule of thumb: if you're about to write a system that only copies a variable
+into a component when it changes, that's a `bind`. If you're about to hand-set
+colors on five entities whenever a mode changes, that's a controller.
+
+## Best practices
+
+- **One signal per fact.** Derive presentation strings with `derived` instead
+ of storing formatted text.
+- **Let despawn clean up.** Bindings tied to an entity dispose themselves;
+ keep the returned dispose only when you unbind *before* the entity dies.
+- **Two-way only at the widget edge.** `bindWidgetValue` for the slider;
+ everything else reads the signal one-way.
+- **Don't fight the equality break.** Signals compare with `Object.is` — for
+ object values, `set` a *new* object; mutating the old one in place notifies
+ no one.
+- **Keep game logic out of subscribers.** Subscribers run synchronously inside
+ `set`; heavy work there stalls the setter. Bind UI, simulate in systems.
+
+## See also
+
+- [UI](/docs/guides/ui/) — the component model bindings write into.
+- [UI Components](/docs/guides/ui-components/) — the value widgets (`createSlider`, `createToggle`, `createDropdown`).
+- [UI Controllers](/docs/guides/ui-controllers/) — named page state + gears; `bindControllerPage` bridges signals into it.
+- [UI Lists](/docs/guides/ui-lists/) — `DataSource`-driven virtualized lists.
+- [Theming](/docs/guides/ui-theme/) — design tokens and live re-theming.
diff --git a/docs/astro/src/content/docs/guides/ui-components.mdx b/docs/astro/src/content/docs/guides/ui-components.mdx
index a269c05e8..82e6ba77d 100644
--- a/docs/astro/src/content/docs/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/guides/ui-components.mdx
@@ -1,6 +1,6 @@
---
title: UI Components
-description: The built-in widget factories — Button, Toggle, Slider, Progress, Dropdown, Dialog, and ListView — plus text input, drag & drop, keyboard focus, mobile safe areas, and theming.
+description: The built-in widget factories — Button, Toggle, Slider, Progress, Dropdown, Dialog, and Text input — their options, handles, and state components, plus the editor prefabs.
---
import { Aside } from '@astrojs/starlight/components';
@@ -13,10 +13,12 @@ always with `entity` and `dispose()`, plus imperative methods to read and drive
Interactive widgets need the world and the UI event queue — `world` from `GetWorld()`
and `events` from `Res(UIEvents)`, exactly as in the [UI guide](/docs/guides/ui/). They
-all accept `parent?`, a `node?` ([`UINode`](/docs/guides/ui/#uinode--the-layout-box)
-layout), and visual overrides. Interactive widgets are **keyboard-reachable by
-default**: they carry a `Focusable`, so Tab reaches them, Enter/Space clicks them, and
-arrow keys drive sliders — opt out with `focusable: false`.
+all accept `parent?`, a `node?` ([`UINode`](/docs/guides/ui-layout/) layout — **default:
+fill the parent**), and visual overrides; visual defaults come from the active
+[theme](/docs/guides/ui-theme/)'s roles and re-resolve on a live theme swap.
+Interactive widgets are **keyboard-reachable by default**: they carry a `Focusable`,
+so Tab reaches them, Enter/Space clicks them, and arrow keys drive sliders — opt out
+with `focusable: false`.
<Aside type="tip">
These are a convenient starting point, not a closed set — a widget is just an entity
@@ -53,19 +55,23 @@ const btn = createButton({
});
```
-| Option | Description |
-|---|---|
-| `text` | Label — a string or a `TextInit`. Omit for no label. |
-| `states` | Map of state name (`normal` / `hover` / `pressed` / `disabled` / `focused`) → color / sprite / scale override. Omit to use the active theme's control roles. |
-| `background` | Background visual (default: solid white). |
-| `fadeDuration` | Tween time for color/scale state changes (default `0` = snap; sprite swaps always snap). |
-| `disabled` | Start disabled. |
-| `focusable` / `tabIndex` | Keyboard reachability (default `true` / `0`). |
-| `onClick(entity)` | Click callback. |
+| Option | Default | Description |
+|---|---|---|
+| `node` | fill the parent | The button's `UINode` layout. |
+| `text` | none | Label — a string or a `TextInit`. Omit for no label. The label color/size default to the theme's `text` role and label type size. |
+| `states` | theme control roles | Map of state name (`normal` / `hover` / `pressed` / `disabled` / `focused`) → color / sprite / scale override. Custom names (e.g. `'loading'`) are allowed. |
+| `background` | solid white | Background visual (a `UIVisualInit`). |
+| `fadeDuration` | `0` (snap) | Tween time for color/scale state changes; sprite swaps always snap. |
+| `disabled` | `false` | Start disabled. |
+| `focusable` / `tabIndex` | `true` / `0` | Keyboard reachability and Tab order. |
+| `onClick(entity)` | — | Click callback (gated on the enabled state). |
**Handle:** `entity`, `setDisabled(disabled)`, `dispose()`.
-Flip a custom state later with `setButtonState(world, handle.entity, 'loading')`.
+The theme-default states are also exported as `themeButtonStates()` — spread and
+override them instead of restating all five. Flip a custom state later with
+`setButtonState(world, handle.entity, 'loading')`; the pointer driver leaves any
+non-canonical page alone until you switch back.
## Toggle
@@ -86,12 +92,15 @@ const toggle = createToggle({
toggle.setIsOn(false); // programmatic change (fires onChange)
```
-| Option | Description |
-|---|---|
-| `interactionStates` | Frame visual states (like the button's `states`; theme defaults when omitted). |
-| `check` | The on-state indicator: `{ node?, color?, sprite? }`, shown when on (theme accent by default). |
-| `isOn` | Initial state. |
-| `onChange(isOn, entity)` | Fires on toggle. |
+| Option | Default | Description |
+|---|---|---|
+| `node` / `background` | fill the parent / solid white | Frame layout + background, as in `createButton`. |
+| `interactionStates` | theme control roles | Frame visual states (like the button's `states`). |
+| `check` | theme `primary` fill | The on-state indicator: `{ node?, color?, sprite? }`, a child shown when on. Fills the frame by default — inset it via `check.node`. |
+| `isOn` | `false` | Initial state. |
+| `disabled` | `false` | Start disabled. |
+| `focusable` / `tabIndex` | `true` / `0` | Keyboard reachability. |
+| `onChange(isOn, entity)` | — | Fires on toggle. |
**Handle:** `isOn()`, `setIsOn(value)`, `setDisabled(disabled)`, `entity`, `dispose()`.
@@ -121,17 +130,19 @@ const slider = createSlider({
slider.setValue(75);
```
-| Option | Description |
-|---|---|
-| `min` / `max` / `value` | Range and initial value. |
-| `step` | Quantization step (`0` = continuous). Also the keyboard nudge. |
-| `handleWidth` | Thumb width in pixels (default `12`). |
-| `disabled` / `focusable` / `tabIndex` | Interactivity + keyboard reachability. |
-| `trackVisual` / `fillVisual` / `handleVisual` | Per-part visuals. |
-| `onChange(value, entity)` | Fires on value change — from input, `setValue`, or any other writer. |
-
-**Handle:** `getValue()`, `setValue(v)`, `dispose()`, plus `trackEntity` /
-`fillEntity` / `handleEntity`.
+| Option | Default | Description |
+|---|---|---|
+| `node` | fill the parent | The track's `UINode` layout. |
+| `min` / `max` | `0` / `1` | The range. |
+| `value` | `min` | Initial value (clamped and step-quantized). |
+| `step` | `0` (continuous) | Quantization step. Also the keyboard nudge. |
+| `handleWidth` | `12` | Thumb width in pixels. |
+| `disabled` / `focusable` / `tabIndex` | `false` / `true` / `0` | Interactivity + keyboard reachability. |
+| `trackVisual` / `fillVisual` / `handleVisual` | theme `track` / `primary` / `onPrimary` | Per-part visuals. |
+| `onChange(value, entity)` | — | Fires on value change — from input, `setValue`, or any other writer. |
+
+**Handle:** `getValue()`, `setValue(v)`, `dispose()`, plus `entity` /
+`trackEntity` (the same entity) / `fillEntity` / `handleEntity`.
<Aside type="note">
The state lives in a **`UISlider` component** on the track entity; the behavior
@@ -143,6 +154,7 @@ slider.setValue(75);
## Progress
`createProgress(opts)` is a non-interactive fill bar. Returns a `ProgressHandle`.
+It takes no `events` — nothing to interact with.
```typescript
import { createProgress } from 'esengine';
@@ -160,14 +172,16 @@ bar.setValue(0.6); // 0..1
const ring = createProgress({ world, parent, radial: true, value: 0.75 });
```
-| Option | Description |
-|---|---|
-| `value` | Initial progress, `0..1`. |
-| `direction` | Linear fill growth: `'right'` (default), `'left'`, `'up'`, `'down'`. |
-| `radial` | Radial gauge instead of a bar — a clockwise wedge sweeping the full circle. Ignores `direction`. |
-| `background` / `fill` | Track and fill visuals. |
+| Option | Default | Description |
+|---|---|---|
+| `node` | fill the parent | The track's `UINode` layout. |
+| `value` | `0` | Initial progress, `0..1` (clamped). |
+| `direction` | `'right'` | Linear fill growth: `'right'`, `'left'`, `'up'`, `'down'`. |
+| `radial` | `false` | Radial gauge instead of a bar — a clockwise wedge sweeping the full circle. Ignores `direction`. |
+| `background` | theme `track` | Track visual (a `UIVisualInit`). |
+| `fill` | theme `primary` | The filled bar: `{ color?, sprite? }`. |
-**Handle:** `value()`, `setValue(v)`, `dispose()`, plus `fillEntity`.
+**Handle:** `value()`, `setValue(v)`, `dispose()`, plus `entity` / `fillEntity`.
<Aside type="note">
**One fill primitive.** A progress bar is a single [`UIVisual`](/docs/guides/ui/) in
@@ -203,18 +217,20 @@ createDropdown({
});
```
-| Option | Description |
-|---|---|
-| `options` | The list of selectable values. |
-| `selectedIndex` | Initial selection. |
-| `optionToLabel(option, i)` | Map a non-string option to its display text. |
-| `buttonStates` | Colors for the main button (option rows use theme roles). |
-| `optionHeight` | Row height in pixels (default `32`). |
-| `disabled` / `focusable` / `tabIndex` | Interactivity + keyboard reachability. |
-| `onSelect(index, option, entity)` | Fires on selection. |
+| Option | Default | Description |
+|---|---|---|
+| `node` | fill the parent | The main button's `UINode` layout. |
+| `options` | — | The list of selectable values. Required. |
+| `selectedIndex` | `0` | Initial selection. |
+| `optionToLabel(option, i)` | `String(option)` | Map a non-string option to its display text. |
+| `buttonStates` | theme control roles | `{ normal?, hover?, pressed? }` colors for the main button (option rows use theme roles). |
+| `optionHeight` | `32` | Row height in pixels. |
+| `disabled` / `focusable` / `tabIndex` | `false` / `true` / `0` | Interactivity + keyboard reachability. |
+| `onSelect(index, option, entity)` | — | Fires on selection. |
**Handle:** `getSelected()`, `getSelectedIndex()`, `setSelectedIndex(i)`,
-`open()`, `close()`, `isOpen()`, `dispose()`.
+`open()`, `close()`, `isOpen()`, `dispose()`, plus `entity` / `labelEntity`
+(the child `Text` showing the current selection).
<Aside type="note">
Labels + selection live in a **`UIDropdown` component**; the behavior system owns
@@ -247,13 +263,13 @@ dialog.open();
dialog.close();
```
-| Option | Description |
-|---|---|
-| `backdropNode` / `backdropVisual` | The full-viewport scrim behind the panel. |
-| `panelNode` / `panelVisual` | The modal panel (default: 400×300, centered). |
-| `startHidden` | Start closed (default `true`). |
-| `closeOnEscape` / `closeOnBackdrop` | The standard dismissals — Escape, and a click on the scrim (not the panel). Both default `true`. |
-| `onOpenChange(open)` | Fires on every open/close, whoever initiated it. |
+| Option | Default | Description |
+|---|---|---|
+| `backdropNode` / `backdropVisual` | fill the parent / theme `backdrop` scrim | The full-viewport scrim behind the panel. It blocks pointer hits but is not focusable. |
+| `panelNode` / `panelVisual` | 400×300 centered / theme `surface` | The modal panel. The panel swallows clicks so only true scrim clicks dismiss. |
+| `startHidden` | `true` | Start closed. |
+| `closeOnEscape` / `closeOnBackdrop` | `true` / `true` | The standard dismissals — Escape, and a click on the scrim (not the panel). |
+| `onOpenChange(open)` | — | Fires on every open/close, whoever initiated it. |
While a dialog is open it also **traps the Tab ring**: only focusables inside the
open dialog's subtree participate (the scrim already blocks pointer focus outside).
@@ -267,120 +283,11 @@ backdrop root) / `panelEntity`.
prefab closes on Escape / scrim clicks without any code hookup.
</Aside>
-## Lists & collections
-
-For long, scrollable, **data-driven** lists — inventories, leaderboards, chat logs —
-`createListView` builds a **virtualized** list (or grid): only the items near the
-viewport are ever mounted, so a 10 000-row list stays cheap. One call composes a data
-source, a layout, item recycling, scrolling, and clipping.
-
-```typescript
-import { createListView, uiPlugin, arrayDataSource, spawnUIEntity, px } from 'esengine';
-
-const list = createListView<Player>({
- world, host: uiPlugin, parent,
- viewportSize: { x: 320, y: 480 }, // the visible window, in pixels
- data: arrayDataSource(players), // any DataSource<T>, or a raw array
- layout: { itemHeight: 56 }, // a column list
- item: {
- create: (world, parent) => spawnUIEntity({ world, parent, node: { height: px(56) } }),
- bind: (entity, player, index) => { /* fill the row's Text / Sprite from `player` */ },
- },
-});
-```
-
-`host` is the plugin that ticks virtualization and routes scroll input — pass the
-`uiPlugin` your app was built with. `item.create` builds one row entity; `item.bind`
-fills it from the data. `bind` runs every time a row is reused for a different index,
-so keep it a pure "apply this data" function.
-
-**Layout** is a column, a row, or a grid:
-
-| `layout` | Result |
-|---|---|
-| `{ itemHeight }` | A vertical list — a fixed row height, or a **`(index) => number`** for [auto-height rows](#auto-height-rows). |
-| `{ itemWidth, direction: 'row' }` | A horizontal list. |
-| `{ columns, itemSize }` | A grid (a *TileView*). |
-
-**Updating** the list means mutating its data source — an `ArrayDataSource` notifies
-the view, which re-syncs on the next frame:
-
-```typescript
-list.data.append([newPlayer]); // add
-list.data.remove(3); // remove index 3
-list.data.update(0, updatedPlayer); // replace one
-list.data.setItems(freshList); // replace all
-```
-
-**Handle:** `data` (mutate it to change the list) · `scrollToIndex(i)` · `refresh()` ·
-`mountedCount()` (never grows with the data — handy in tests) · `dispose()`, plus
-`scroll` and `view` as escape hatches to the underlying `ScrollContainer` / `ListView`.
-
-<Aside type="note">
- Scrolling works out of the box: mouse wheel over the viewport, pointer **drag with
- a kinetic fling** — the platform layer funnels the primary touch into the pointer
- stream, so touch scrolling rides the same path — and an **auto-fading overlay
- scrollbar** per scrollable axis (opt out with `showScrollbar: false` on the
- ScrollContainer). Tune it with `dragScroll: false` or
- `decelerationRate` (fling velocity left after 1s; default `0.135`, the ScrollRect
- standard). For heterogeneous rows, pass a map of item type → template instead of one
- `item`, and give the data source a `getItemType(i)`.
-</Aside>
-
-### Auto-height rows
-
-Pass a **function** for `itemHeight` to size each row to its content — perfect for a
-chat log where a bubble grows with its wrapped text. The list caches the measurement
-and re-flows on data or viewport changes:
-
-```typescript
-import { measureText } from 'esengine';
-
-createListView<Message>({
- world, host: uiPlugin, parent,
- viewportSize: { x: 360, y: 480 },
- data: messages,
- layout: {
- itemHeight: (i) => measureText(messages.getItem(i).text, {
- fontSize: 14, maxWidth: 320,
- }).height + 16, // wrapped text height + vertical padding
- spacing: 8,
- },
- item: { /* create / bind */ },
-});
-```
-
-`measureText(text, { fontSize, maxWidth?, bold?, italic?, letterSpacing?, lineHeight? })`
-returns `{ width, lineCount, height }` measured off the **same Canvas2D metrics the glyph
-atlas draws from**, so a measured height matches what actually renders — no more clipped
-or overflowing rows. (A DOM-less host falls back to an average-glyph estimate.)
-
-### Free-form scrolling
-
-For a scrollable panel of **arbitrary content** (a settings page, a long form) — no
-virtualization, no data source — use `createScrollView` and parent anything under its
-`content` frame:
-
-```typescript
-import { createScrollView, uiPlugin } from 'esengine';
-
-const panel = createScrollView({
- world, host: uiPlugin, parent,
- viewportSize: { x: 320, y: 480 },
- contentSize: { x: 320, y: 1200 },
-});
-// build your content under panel.content …
-panel.scrollTo({ x: 0, y: 300 });
-```
-
-Wheel, drag/touch, and the kinetic fling work exactly as in the list view; call
-`setContentSize()` after the content grows.
-
## Text input
`createTextInput(opts)` builds an editable field — background, caret, placeholder,
and IME plumbing included — with theme-role colors that re-resolve on a theme swap.
-Returns a `TextInputHandle` (`getValue()` / `setValue(v)` / `entity` / `dispose()`).
+Returns a `TextInputHandle`: `getValue()` / `setValue(v)` / `entity` / `dispose()`.
```typescript
import { createTextInput } from 'esengine';
@@ -393,8 +300,25 @@ const name = createTextInput({
});
```
+| Option | Default | Description |
+|---|---|---|
+| `node` | 220×32 | The field's `UINode` layout (the one factory that doesn't default to fill-parent). |
+| `value` / `placeholder` | `''` | Content / hint shown while empty. |
+| `maxLength` | `0` | Character cap (`0` = unlimited). |
+| `multiline` | `false` | Enter inserts a newline instead of submitting. |
+| `password` | `false` | Mask the characters. |
+| `readOnly` | `false` | Focusable but not editable. |
+| `fontSize` / `fontFamily` | theme label size / `'Arial'` | Text style. |
+| `color` / `backgroundColor` / `placeholderColor` | theme `text` / `control` / faded `text` | Color overrides — theme roles when omitted. |
+| `padding` | `6` | Inner horizontal padding in px. |
+| `renderMode` | `Auto` | Glyph pipeline for the field text — `Auto` (crisp bitmap when unscaled, SDF once scaled), always `Bitmap`, or always `Sdf`. |
+| `disabled` / `tabIndex` | `false` / `0` | Interactivity + Tab order. Text fields are always focusable — that is what they are for. |
+| `onChange(value, entity)` | — | Fires on every edit. |
+| `onSubmit(value, entity)` | — | Fires on Enter (single-line). |
+
The factory is sugar over the `TextInput` **component** — insert that directly on any
-UI entity for full manual control:
+UI entity for full manual control (same fields as above, plus the live `focused` /
+`cursorPos` state):
```typescript
import { spawnUIEntity, TextInput, px } from 'esengine';
@@ -406,16 +330,6 @@ events.on(field, 'change', () => { /* value edited */ });
events.on(field, 'submit', () => save(world.get(field, TextInput).value)); // Enter
```
-| Field | Default | Description |
-|---|---|---|
-| `value` / `placeholder` | `''` | Content / hint shown while empty. |
-| `maxLength` | `0` | Character cap (`0` = unlimited). |
-| `multiline` | `false` | Enter inserts a newline instead of submitting. |
-| `password` | `false` | Mask the characters. |
-| `readOnly` | `false` | Focusable but not editable. |
-| `fontSize` / `fontFamily` | `16` / `Arial` | Text style — `color`, `placeholderColor`, `backgroundColor`, and `padding` (`6`) round out the look. |
-| `renderMode` | `Auto` | Glyph pipeline for the field text — `Auto` (crisp bitmap when unscaled, SDF once scaled), always `Bitmap`, or always `Sdf`. |
-
Click (or Tab to) the field to focus it; **Escape** blurs, **Enter** fires
`submit` on single-line fields. A value longer than the box **clips to it and scrolls
horizontally** so the caret stays in view as you type.
@@ -425,87 +339,46 @@ horizontally** so the caret stays in view as you type.
hidden native textarea for IME support) — it's inert in the editor's edit view.
</Aside>
-## Data binding
-
-Widget values are plain component fields, so the [signal](/docs/guides/ui/) layer
-binds to them directly — and `bindWidgetValue` makes it **two-way**: the signal
-drives the component, and the widget's `change` event writes back.
+## Lists & scrolling
-```typescript
-import { signal, bindWidgetValue, UISlider, UIToggle } from 'esengine';
+Virtualized data-driven lists and grids (`createListView`), free-form scrollable
+panels (`createScrollView`), data sources, layout providers, auto-height rows, and
+the kinetic-scroll / scrollbar machinery have their own chapter:
+**[Lists & Scrolling](/docs/guides/ui-lists/)**.
-const volume = signal(50);
-bindWidgetValue(world, events, slider.entity, UISlider, 'value', volume);
-const muted = signal(false);
-bindWidgetValue(world, events, toggle.entity, UIToggle, 'isOn', muted);
-
-volume.set(80); // moves the slider
-// dragging the slider ↦ volume.get() follows
-```
+## Data binding
-The signal's equality guard breaks the loop, so a round trip settles in one hop.
+Widget values are plain component fields (`UISlider.value`, `UIToggle.isOn`, …), so
+the signal layer binds to them directly — and `bindWidgetValue` makes it two-way.
+See **[UI Binding](/docs/guides/ui-binding/)**.
## Drag & drop
-Add `Draggable` to any interactable UI entity and pointer drags move it — its
-absolute `UINode` insets when it has one, otherwise its `Transform`:
-
-```typescript
-world.insert(entity, Draggable, { dragThreshold: 5, lockY: true });
-events.on(entity, 'drag_start', () => { /* also 'drag_move' and 'drag_end' */ });
-```
-
-`lockX` / `lockY` constrain the axis and `constraintMin` / `constraintMax` clamp
-the range; the auto-inserted `DragState` component exposes the live drag
-(`isDragging`, `deltaWorld`, `totalDeltaWorld`, …). There's no built-in
-drop-target concept — decide what the drop hit in your `drag_end` handler.
+Add `Draggable` to any interactable UI entity and pointer drags move it, with
+`drag_start` / `drag_move` / `drag_end` events and a live `DragState` component.
+Axis locks and range clamps included. See
+**[UI Interaction](/docs/guides/ui-interaction/)**.
## Keyboard focus
-Entities with a `Focusable` component participate in keyboard focus: **click**
-focuses, **Tab / Shift+Tab** cycles (ordered by `tabIndex` ascending, skipping
-disabled widgets, wrapping at the ends), **Enter / Space** activates the focused
-control (a synthesized `click`; text fields keep those keys for editing), sliders
-take the **arrow keys**, and **Escape** or a click on empty space clears focus.
-Widget factories add `Focusable` automatically (`focusable: false` opts out); a
-focused control shows its `focused` interaction page (theme hover color by
-default). The `FocusManager` resource exposes `focusedEntity` plus
-`focus(entity)` / `blur()` for programmatic control, and focused entities
-receive `focus` / `blur` events on the UI event bus.
+Entities with a `Focusable` participate in keyboard focus: Tab / Shift+Tab cycle
+by `tabIndex`, Enter/Space activate, sliders take the arrow keys, and a focused
+control shows its `focused` interaction page. Widget factories add `Focusable`
+automatically (`focusable: false` opts out); the `FocusManager` resource gives
+programmatic control. Details in **[UI Interaction](/docs/guides/ui-interaction/)**.
## Safe area (mobile notches)
Add `SafeArea` to a full-screen, absolutely-positioned `UINode` container and its
-insets track the platform safe area — device notches, rounded corners, the WeChat
-capsule — so children laid out inside never hide under hardware. `applyTop` /
-`applyBottom` / `applyLeft` / `applyRight` (all default `true`) pick which edges
-apply.
+insets track the platform safe area — notches, rounded corners, the WeChat capsule —
+with per-edge opt-outs. See **[Screen & Resolution](/docs/core-concepts/screen/)**.
## Theming
-Widget colors come from a shared token set: `getTheme()` / `setTheme(tokens)`
-with roles like `surface`, `control`, `controlHover`, `primary`, `onPrimary`,
-`track`, and `backdrop` (`DARK_TOKENS` / `LIGHT_TOKENS` are built in). `setTheme`
-affects widgets constructed afterwards; **`switchTheme(world, tokens)`** also
-live-restyles everything already on screen — widgets record which theme *role*
-each color came from (a `ThemeStyle` component, carried into prefabs too), so a
-swap re-resolves hues while preserving each color's alpha.
-
-### The project theme
-
-A project declares its widget palette once, in **Project Settings → UI**: pick
-the base theme (**dark** is the default, **light** is built in), then override
-any **color role** in the **Theme Colors** group — a full color picker per
-role, with unset rows showing the inherited base value and a reset that clears
-the override. Overrides are stored in `project.esproject` as
-`features.ui.colors` (role → `#rrggbb[aa]` hex) and validated against the
-theme's role list.
-
-The resolved theme (base + overrides) applies **everywhere, identically**: the
-edit viewport previews it live as you change a setting, Play uses it, and every
-export target — web, desktop, WeChat, playable — resolves it at boot before
-re-theming widgets. Brand the accent by overriding `primary` (+ `primaryHover`
-/ `primaryActive`); `onPrimary` is the content drawn on top of it.
+Widget colors come from a shared token set with roles like `surface`, `control`,
+`primary`, and `track`; `switchTheme(world, tokens)` live-restyles everything on
+screen, and a project declares its palette once in **Project Settings → UI**.
+See **[UI Theme](/docs/guides/ui-theme/)**.
## Editor prefabs
@@ -520,3 +393,27 @@ drag), and an empty-canvas drop lands at the root as before. The anchor picker
edits **per axis** and keeps the widget exactly where it was — changing the
horizontal anchor never disturbs the vertical layout, and vice versa. See
[The Editor](/docs/guides/editor/).
+
+## Best practices
+
+- **Prefer the state components over handle juggling.** `UIToggle.isOn`,
+ `UISlider.value`, `UIDropdown.selectedIndex` are the single source of truth —
+ write them (or bind them) and the visuals follow; the handle methods are just
+ typed sugar over the same writes.
+- **Let the theme own colors.** Omit `states` / visuals to get theme roles that
+ re-resolve on a live swap; hard-code colors only for deliberately off-theme art.
+- **Put dialog content under `panelEntity`**, never beside it — that's what makes
+ open/close a single `display` write for the whole subtree.
+- **Dispose handles you created at runtime** — `dispose()` despawns the widget's
+ entities and detaches its event subscriptions.
+- **Keep keyboard reachability on.** Only pass `focusable: false` for decorative
+ or duplicate controls; the Tab ring is your accessibility story.
+
+## See also
+
+- [UI](/docs/guides/ui/) — the component model: `UINode`, `Text`, `UIVisual`, interaction.
+- [Lists & Scrolling](/docs/guides/ui-lists/) — `createListView`, `createScrollView`, virtualization.
+- [UI Controllers](/docs/guides/ui-controllers/) — shared "page" state + declarative per-page field bindings.
+- [UI Binding](/docs/guides/ui-binding/) — signals and two-way widget binding.
+- [UI Interaction](/docs/guides/ui-interaction/) — focus, drag & drop, pointer events.
+- [UI Theme](/docs/guides/ui-theme/) — tokens, roles, live theme swaps, the project theme.
diff --git a/docs/astro/src/content/docs/guides/ui-interaction.mdx b/docs/astro/src/content/docs/guides/ui-interaction.mdx
new file mode 100644
index 000000000..45bcf943f
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-interaction.mdx
@@ -0,0 +1,281 @@
+---
+title: UI Interaction
+description: The complete UI interaction reference — hit-testing with Interactable/UIInteraction, the UIEvents bubbling bus, drag & drop, keyboard focus, manual picking helpers, and how UI layers over game input.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Pointer input flows through one pipeline every frame: the hit-test finds the
+topmost `Interactable` node under the cursor, writes per-frame state into
+`UIInteraction`, and emits bubbling events on the `UIEvents` bus. Drag and
+keyboard-focus systems layer on top. All of it ships in the default `uiPlugin`
+— nothing to install — and the interaction systems run in **play mode**.
+
+## Hit-testing: `Interactable` + `UIInteraction`
+
+Add `Interactable` to make a node hit-testable:
+
+| `Interactable` field | Default | Description |
+|---|---|---|
+| `enabled` | `true` | Master switch — a disabled node is skipped by hit-testing, events, and the Tab ring. |
+| `blockRaycast` | `true` | The node occludes nodes behind it (and stops the event-bubbling walk above it). |
+| `raycastTarget` | `true` | The node itself can be the hit result. |
+
+Each frame the hit-test writes pointer state into `UIInteraction` on the hit
+entity. It is created on demand (**transient** — never authored, never saved)
+and is **read-only for your logic**: query it, never mutate it.
+
+| `UIInteraction` field | Description |
+|---|---|
+| `hovered` | The pointer is over the node. |
+| `pressed` | The primary button is held down on the node. |
+| `justPressed` | Became pressed this frame (one-frame edge). |
+| `justReleased` | Released this frame on the node that was pressed (one-frame edge — a click). |
+
+```typescript
+import { defineSystem, Query, Interactable, UIInteraction } from 'esengine';
+
+const onTiles = defineSystem([Query(Interactable, UIInteraction)], (q) => {
+ for (const [entity, _gate, state] of q) {
+ if (state.justReleased) { /* this node was clicked */ }
+ }
+});
+```
+
+While any UI node is hit, `input.isPointerOverUI()` is `true` — the standard
+guard that keeps a button click from also firing a world click.
+
+## The `UIEvents` bus
+
+The `UIEvents` resource is a pub/sub queue with DOM-like bubbling. Widgets and
+the interaction systems emit the standard set; the type space is **open** —
+emit any string you like (a ListView emits `'item_selected'`).
+
+| `UIEventType` constant | String | Emitted when | Bubbles |
+|---|---|---|---|
+| `Click` | `'click'` | Press and release on the same node. Keyboard Enter/Space also emits it (on the target only, no bubble). | Yes |
+| `Press` / `Release` | `'press'` / `'release'` | Primary button down / up on a node. | Yes |
+| `HoverEnter` / `HoverExit` | `'hover_enter'` / `'hover_exit'` | The hit node changed. | No |
+| `Focus` / `Blur` | `'focus'` / `'blur'` | Keyboard focus moved (see [Focus](#focus--keyboard)). | No |
+| `Change` | `'change'` | A widget's value changed (toggle, slider, dropdown…). | No |
+| `Submit` | `'submit'` | A text input confirmed (Enter). | No |
+| `DragStart` / `DragMove` / `DragEnd` | `'drag_start'` / `'drag_move'` / `'drag_end'` | The drag system (see [Drag](#drag--drop)). | No |
+| `Scroll` / `Select` / `Deselect` | `'scroll'` / `'select'` / `'deselect'` | Scroll views and list selection. | No |
+
+Bubbling events climb the parent chain, revisiting every **enabled**
+`Interactable` ancestor; an ancestor with `blockRaycast` ends the walk, and any
+handler can call `stopPropagation()`. Each `UIEvent` carries:
+
+| `UIEvent` field | Description |
+|---|---|
+| `type` | The event string. |
+| `target` | The entity where the event originated. |
+| `currentTarget` | The entity currently handling it (differs from `target` while bubbling). |
+| `data` | Optional payload (e.g. `{ index }` on a dropdown `change`). |
+| `stopPropagation()` / `propagationStopped` | Halt bubbling. |
+| `preventDefault()` / `defaultPrevented` | Ask the emitter to skip its default action. |
+
+Subscribe per entity or globally — `on` returns an unsubscribe function, and
+handlers for a despawned entity are pruned automatically:
+
+```typescript
+import { defineSystem, addStartupSystem, Res, UIEvents } from 'esengine';
+
+const wireMenu = defineSystem([Res(UIEvents)], (events) => {
+ events.on(buttonEntity, 'click', (e) => { /* one widget */ });
+ events.on('click', (e) => console.log('clicked', e.target)); // any entity
+});
+addStartupSystem(wireMenu);
+```
+
+A system can also read the frame's queue without subscribing:
+`events.query('click')` inspects pending events non-destructively (the
+interaction plugin drains the queue at the start of each frame).
+
+## `makeWidgetInteractable` — wiring custom widgets
+
+Every built-in widget factory shares one interaction assembly, exported for
+your own widgets:
+
+```typescript
+import { makeWidgetInteractable } from 'esengine';
+
+makeWidgetInteractable(world, myWidgetRoot, { tabIndex: 2 });
+```
+
+It inserts a raycast-blocking `Interactable` plus — by default — a `Focusable`,
+so the widget is clickable **and** keyboard-reachable (Tab to it, Enter/Space
+activates). Options: `disabled` (start with `Interactable.enabled = false`),
+`focusable` (default `true`), `tabIndex` (default `0` = document order). It
+deliberately does *not* insert `UIInteraction` — that stays transient. For
+hover/press **visuals**, bind fields to the built-in interaction controller
+pages — see [UI Controllers](/docs/guides/ui-controllers/).
+
+## Drag & drop
+
+Add `Draggable` to an `Interactable` node and the drag system handles the rest:
+press, move past the threshold, and the entity follows the pointer — nudging
+the `UINode` absolute insets when it has one (so the position survives the next
+layout pass), else translating the `Transform`.
+
+| `Draggable` field | Default | Description |
+|---|---|---|
+| `enabled` | `true` | Master switch. |
+| `dragThreshold` | `5` | Screen px of travel before the drag starts (keeps clicks clickable). |
+| `lockX` / `lockY` | `false` | Freeze an axis (a horizontal-only slider card). |
+| `constraintMin` / `constraintMax` | `null` | World-space clamp corners, or `null` for unbounded. |
+
+While dragging, the transient `DragState` component carries the live geometry
+(all world-space):
+
+| `DragState` field | Description |
+|---|---|
+| `isDragging` | Past the threshold and still held. |
+| `startWorldPos` | Entity position when the press landed. |
+| `currentWorldPos` | Entity position now. |
+| `deltaWorld` | Movement since last frame. |
+| `totalDeltaWorld` | Movement since the drag started. |
+| `pointerStartWorld` | Pointer position when the press landed. |
+
+The system emits `drag_start` / `drag_move` / `drag_end` on the bus. A
+drag-a-card-to-a-slot flow is those three events plus a drop test:
+
+```typescript
+import {
+ defineSystem, addStartupSystem, GetWorld, Res, UIEvents,
+ spawnUIEntity, Draggable, DragState, UIPositionType, px,
+} from 'esengine';
+
+const buildCard = defineSystem([GetWorld(), Res(UIEvents)], (world, events) => {
+ const card = spawnUIEntity({
+ world,
+ node: { width: px(90), height: px(120), position: UIPositionType.Absolute },
+ visual: { color: { r: 0.85, g: 0.75, b: 0.4, a: 1 } },
+ });
+ world.insert(card, Draggable, { dragThreshold: 4 });
+
+ events.on(card, 'drag_end', () => {
+ const state = world.get(card, DragState);
+ // Drop test: snap into the slot if released over it, else return to hand.
+ if (overDropSlot(state.currentWorldPos)) { /* snap the card in */ }
+ });
+});
+addStartupSystem(buildCard);
+```
+
+<Aside type="note">
+ When several draggables overlap under the pointer, the system picks the one
+ with the highest render layer, breaking ties by hierarchy depth — the card on
+ top is the one you grab.
+</Aside>
+
+## Focus & keyboard
+
+Keyboard accessibility is **on by default**: `focusPlugin` ships inside
+`uiPlugin`, and every widget factory adds a `Focusable` (via
+`makeWidgetInteractable`). The `FocusManager` resource tracks the single
+focused entity; `Focusable.isFocused` mirrors it per entity, and `focus` /
+`blur` events fire on every move.
+
+| Interaction | Behavior |
+|---|---|
+| Click a focusable | Focuses it. |
+| Click empty space / press `Escape` | Clears focus. |
+| `Tab` / `Shift+Tab` | Cycles the focus ring — sorted by `tabIndex` (ties in discovery order), skipping disabled `Interactable`s and anything hidden by `display: none` up its tree. |
+| `Enter` / `Space` on the focused control | Emits `click` — activates buttons, toggles, dropdowns. Text inputs keep these keys for editing. |
+| Open `UIDialog` | **Focus trap**: while a modal dialog is open, only focusables inside it participate in the Tab ring (the scrim already blocks pointer focus outside). |
+| Focused dropdown | `ArrowDown` / `ArrowUp` step the selection (popup open or closed, the native `<select>` convention); `Enter` confirms, `Escape` dismisses an open popup. |
+
+```typescript
+import { defineSystem, Res, FocusManager } from 'esengine';
+
+const focusDebug = defineSystem([Res(FocusManager)], (focus) => {
+ if (focus.focusedEntity !== null) { /* draw a focus ring, play a tick… */ }
+});
+```
+
+<Aside type="note">
+ Gamepad navigation is not built into the focus system — the ring is driven by
+ `Tab` / `Enter` / `Space` / `Escape` and the arrow keys. For gamepad menus,
+ drive selection yourself from an [input map](/docs/guides/input/) and call
+ widget state directly.
+</Aside>
+
+## Manual picking
+
+When game code needs its own picking — a custom cursor, tooltips over arbitrary
+UI, an editor tool — the hit-test helpers are exported. They talk to the C++
+core, so they take the wasm module and registry:
+
+```typescript
+import { uiPickWorld, UICameraInfo, Res, GetWorld, defineSystem } from 'esengine';
+
+const tooltip = defineSystem([GetWorld(), Res(UICameraInfo)], (world, camera) => {
+ if (!camera.valid) return;
+ const hit = uiPickWorld(
+ module, registry, // app.wasmModule / world.getCppRegistry()
+ camera.worldMouseX, camera.worldMouseY, // cursor already projected to world
+ );
+ if (hit !== null) { /* show tooltip for `hit` */ }
+});
+```
+
+| Helper | Returns | Use |
+|---|---|---|
+| `uiHitTestWorld(module, registry, x, y, …)` | Topmost **interactable** entity or `null` | The runtime raycast — same rules the interaction system uses. |
+| `uiPickWorld(module, registry, x, y)` | Topmost UI entity or `null` | Editor-style pick, ignores `Interactable`. |
+| `uiPickAllWorld(module, registry, x, y)` | All UI entities under the point, most specific first | Pick-through menus, debug overlays. |
+| `screenToUiWorld(camera, glX, glY)` | `{ x, y }` world point | Project a GL-oriented screen point through the UI camera. |
+| `uiWorldToScreen(camera, x, y)` | `{ x, y }` screen point | The inverse — place DOM/screen effects over a UI node. |
+
+For the common case you rarely need these: `UICameraInfo.worldMouseX/Y` is the
+cursor already in world space, and `input.isPointerOverUI()` answers "is the
+pointer on UI at all".
+
+## UI input vs game input
+
+Raw platform events pass through the `InputRouter` before they reach the
+`Input` resource — a chain of responsibility with three tiers:
+
+1. **Editor** — viewport tools (only in the editor host).
+2. **UI** — text inputs and other UI internals that must claim raw events.
+3. **Game** — implicit: whatever no upstream tier consumed lands in the `Input`
+ resource your systems poll.
+
+A handler (`InputHandler`) implements any of `onKeyDown`, `onKeyUp`,
+`onPointerMove`, `onPointerDown`, `onPointerUp`, `onWheel`, and the touch
+callbacks, each receiving the current `Modifiers` (`shift` / `ctrl` / `alt` /
+`meta`); returning `true` **consumes** the event — it never updates `Input` and
+never reaches later tiers. Register with `inputRouter.setUIHandler(handler)` /
+`setEditorHandler(handler)`; each returns an unregister thunk, and each tier
+holds a single handler.
+
+In a game you normally never touch the router: pointer-over-UI arbitration is
+already handled at the polling level — hit UI sets `input.pointerOverUI`, and
+gameplay guards with `isPointerOverUI()`. Reach for a router handler only when
+a system must claim *raw* events before the `Input` resource sees them at all
+(a modal that swallows Escape, a minigame capturing all keys).
+
+## Best practices
+
+- **Read, never write, `UIInteraction`** — it is engine-owned per-frame state;
+ drive logic from it or from `UIEvents`.
+- **Prefer the bus for widgets, the query for grids** — `events.on(entity,
+ 'click', …)` reads best per widget; a `Query(Interactable, UIInteraction)`
+ scales to boards of uniform tiles.
+- **Guard world clicks with `input.isPointerOverUI()`** so UI clicks don't leak
+ into gameplay.
+- **Use `makeWidgetInteractable` for custom widgets** — you get hit-testing and
+ keyboard reachability in one call, consistent with the built-ins.
+- **Keep `dragThreshold` non-zero** on anything that is also clickable, or
+ every click risks becoming a 0-px drag.
+- **Set `tabIndex` sparingly** — document order is usually the right Tab order;
+ reserve explicit indices for jumps.
+
+## See also
+
+- [UI](/docs/guides/ui/) — the component model overview.
+- [UI Components](/docs/guides/ui-components/) — widget factories with events pre-wired.
+- [UI Controllers](/docs/guides/ui-controllers/) — hover/press **visual** states driven by the interaction controller.
+- [UI Binding](/docs/guides/ui-binding/) — two-way widget-value binding over `change` events.
+- [Input](/docs/guides/input/) — the `Input` resource, input maps, and gestures below the UI layer.
diff --git a/docs/astro/src/content/docs/guides/ui-layout.mdx b/docs/astro/src/content/docs/guides/ui-layout.mdx
new file mode 100644
index 000000000..738133304
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-layout.mdx
@@ -0,0 +1,340 @@
+---
+title: UI Layout
+description: The UI layout reference — design-pixel units, px/percent/auto dimensions, the full UINode and FlexContainer tables, absolute positioning and auto-centering, anchor presets, and layout recipes.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+UI geometry is a CSS box model solved by a single-pass flexbox engine (Yoga) in
+the C++ core, every frame, against the camera's UI box. This page is the deep
+reference: units, the `Dimension` type, every `UINode` and `FlexContainer`
+field, absolute positioning, anchor presets, and recipes. For the component
+model overview start at [UI](/docs/guides/ui/).
+
+## Units: design pixels
+
+Every `px` in UI layout is a **design pixel** — a unit of the project's design
+resolution (Project Settings → Display), not a device pixel. Scene cameras bake
+the design-resolution fit into their extents, so inside the UI layout box
+**1 world unit = 1 design px** and a `px(320)` panel is 320 design px wide on
+every device; the canvas scale mode decides how that design box fits the real
+screen (letterbox, expand, match). The editor's free-zoom view lays UI out
+against the same fixed design box, so zooming the viewport never reflows your
+interface. See [Screen & Resolution](/docs/core-concepts/screen/) and
+[Camera](/docs/guides/camera/).
+
+## Dimensions: `px`, `percent`, `auto`
+
+Every length field is a `Dimension` — `{ value, unit }` — built with three
+helpers:
+
+```typescript
+import { px, percent, auto, isAuto, DimensionUnit } from 'esengine';
+
+px(320) // 320 design pixels
+percent(50) // 50% of the parent's corresponding axis (0..100, not 0..1)
+auto() // content-/layout-driven; value is ignored
+isAuto(d) // true when d is the auto length
+```
+
+- **`px(n)`** — absolute design pixels (`DimensionUnit.Px`).
+- **`percent(n)`** — percentage **of the parent's corresponding axis**: a
+ `width: percent(50)` is half the parent's width, `height: percent(50)` half
+ its height. The scale is 0–100, mirroring CSS `%`.
+- **`auto()`** — "let layout decide". What that means depends on the field:
+
+| Field | `auto()` means |
+|---|---|
+| `width` / `height` | Content-driven (text measure, children) or stretched by the container; a **root** node fills the camera box on any `auto` axis. |
+| `minWidth/Height`, `maxWidth/Height` | No constraint. |
+| `flexBasis` | Use `width`/`height`, else content size. |
+| `insetLeft/Top/Right/Bottom` | That edge is unconstrained (see [Absolute positioning](#absolute-positioning)). |
+| `marginLeft/Top/Right/Bottom` | The margin absorbs free space (CSS `margin: auto`); on an `Absolute` node, all-`auto` margins + insets center the axis. |
+
+## `UINode` — the box
+
+`UINode` holds the per-item layout fields (container-level fields live on
+`FlexContainer`). Defaults below are the component defaults from the SDK source.
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `position` | `UIPositionType` | `Relative` | `Relative` = in the flex flow; `Absolute` = out of flow, placed by insets. |
+| `display` | `UIDisplay` | `Flex` | `None` removes this node **and its whole subtree** from layout, rendering, and hit-testing — the hierarchical show/hide. Contrast `UIVisual.enabled`, which hides only this entity's visual. |
+| `width` / `height` | `Dimension` | `auto()` | Box size; `auto` = content-/flex-driven. |
+| `minWidth` / `minHeight` | `Dimension` | `auto()` | Lower size bounds; `auto` = unconstrained. |
+| `maxWidth` / `maxHeight` | `Dimension` | `auto()` | Upper size bounds; `auto` = unconstrained. |
+| `flexGrow` | number | `0` | Share of the container's free main-axis space to absorb (`0` = don't grow). |
+| `flexShrink` | number | `1` | Shrink factor when space is tight (`0` = never shrink). |
+| `flexBasis` | `Dimension` | `auto()` | Base main-axis size before grow/shrink; `auto` = use `width`/`height` or content. |
+| `alignSelf` | `AlignSelf` | `Auto` | Per-item cross-axis override (`Auto` / `Start` / `Center` / `End` / `Stretch`); `Auto` inherits the container's `alignItems`. |
+| `marginLeft/Top/Right/Bottom` | `Dimension` | `px(0)` | Outer spacing; `auto()` absorbs free space (CSS auto margin). |
+| `insetLeft/Top/Right/Bottom` | `Dimension` | `auto()` | Offset from the parent's edges when `position` is `Absolute` (CSS `left/top/right/bottom`); `auto` = edge unconstrained. |
+
+<Aside type="caution">
+ The layout pass **writes `Transform.position`** on every UI entity each frame
+ (center-based, pivot 0.5, y-up). Don't hand-position UI entities through
+ `Transform` — move them with insets/margins instead. (Tweens coordinate with
+ layout through per-axis override flags, so animating UI position with the
+ tween API is fine.)
+</Aside>
+
+## `FlexContainer` — laying out children
+
+Add a `FlexContainer` to a node to lay out its children. The mental model is
+CSS flexbox — each field maps 1:1 to a CSS property:
+
+| Property | Type | Default | CSS | Description |
+|---|---|---|---|---|
+| `direction` | `FlexDirection` | `Row` | `flex-direction` | `Row` / `Column` / `RowReverse` / `ColumnReverse` — the main axis. |
+| `wrap` | `FlexWrap` | `NoWrap` | `flex-wrap` | `NoWrap` / `Wrap`. |
+| `justifyContent` | `JustifyContent` | `Start` | `justify-content` | Main-axis distribution: `Start` / `Center` / `End` / `SpaceBetween` / `SpaceAround` / `SpaceEvenly`. |
+| `alignItems` | `AlignItems` | `Stretch` | `align-items` | Cross-axis alignment: `Start` / `Center` / `End` / `Stretch`. |
+| `alignContent` | `AlignContent` | `Start` | `align-content` | Wrapped-line distribution: `Start` / `Center` / `End` / `Stretch` / `SpaceBetween` / `SpaceAround`. |
+| `gap` | `Vec2` | `{x: 0, y: 0}` | `column-gap` / `row-gap` | Space between children, plain design px (`x` = column gap, `y` = row gap). |
+| `padding` | `Padding` | `{0,0,0,0}` | `padding` | Inner spacing (`left/top/right/bottom`), plain design px. |
+
+<Aside type="note">
+ `gap` and `padding` are plain numbers (design px), not `Dimension`s.
+</Aside>
+
+```typescript
+import { FlexContainer, FlexDirection, JustifyContent, AlignItems } from 'esengine';
+
+world.insert(panel, FlexContainer, {
+ direction: FlexDirection.Column,
+ justifyContent: JustifyContent.Center,
+ alignItems: AlignItems.Center,
+ gap: { x: 0, y: 12 },
+ padding: { left: 16, top: 16, right: 16, bottom: 16 },
+});
+```
+
+## Absolute positioning
+
+`position: Absolute` takes a node out of the flex flow; the four insets place
+it against the parent's box, exactly like CSS `left/top/right/bottom`:
+
+- **One edge pinned** — `insetTop: px(16), insetRight: px(16)` puts the box 16px
+ from the top-right corner; the `auto` edges stay unconstrained and the
+ authored `width`/`height` apply.
+- **Both edges pinned + `auto` size** — the insets drive the size: `insetLeft:
+ px(0), insetRight: px(0)` with `width: auto()` stretches the box across the
+ parent. All four insets at `px(0)` = fill the parent (that's what
+ `spawnUIEntity`'s `node: { fill: true }` writes).
+- **Percent insets** resolve against the parent's corresponding axis, like
+ every other `Dimension`.
+
+### Centering with `auto`
+
+An `Absolute` node **centers an axis when both its insets *and* both its
+margins on that axis are `auto`** — the engine reads that combination as
+"center this out-of-flow node in the parent box". This is a per-node rule the
+engine adds on top of Yoga (Yoga's absolute-position centering keys off the
+parent's `justifyContent`, so it couldn't differ per sibling), and it's the one
+anchor a pivot-less CSS box can't otherwise express. Each axis resolves
+independently, so you can center horizontally while pinning the top edge.
+
+<Aside type="caution">
+ `UINode`'s margins **default to `px(0)`**, not `auto` — so a fresh `Absolute`
+ node with all-`auto` insets is *not* centered until you also set the margins
+ to `auto()`. The `Center` anchor preset writes exactly this combination for
+ you (next section).
+</Aside>
+
+```typescript
+import { spawnUIEntity, UIPositionType, px, auto } from 'esengine';
+
+// Dead-center 320×220 panel: insets AND margins all auto on both axes.
+const panel = spawnUIEntity({
+ world,
+ node: {
+ position: UIPositionType.Absolute,
+ width: px(320), height: px(220),
+ marginLeft: auto(), marginRight: auto(),
+ marginTop: auto(), marginBottom: auto(),
+ },
+ visual: { color: { r: 0.08, g: 0.10, b: 0.16, a: 0.95 } },
+});
+```
+
+## Anchor presets in code
+
+The editor's anchor picker — and the same API in code — is a set of **shortcuts
+that write the box fields above**. An anchor is *not* stored state: the
+`position`/inset/margin fields remain the single source of truth, so a preset
+and the live layout can never desync. Each axis is one of four modes:
+
+| `AnchorAxis` | Writes (per axis) |
+|---|---|
+| `Start` | Near inset `px(0)`, far inset `auto`, margins `px(0)` — pin the left/top edge. |
+| `Center` | Both insets **and** both margins `auto` — engine-centered (see above). |
+| `End` | Far inset `px(0)`, near inset `auto`, margins `px(0)` — pin the right/bottom edge. |
+| `Stretch` | Both insets `px(0)`, margins `px(0)`, **size `auto`** — the insets drive the size. |
+
+`anchorPresetFields({ h, v })` resolves a preset to the fields to write. It
+always sets `position: Absolute` plus the four insets and four margins;
+`width`/`height` are included **only** for a `Stretch` axis, so a non-stretch
+axis preserves the size you authored. `ANCHOR_AXES` lists the four modes in
+grid order (for building a preset picker UI).
+
+```typescript
+import {
+ UINode, AnchorAxis, anchorPresetFields, detectAnchor, detectAnchorAxes,
+} from 'esengine';
+
+// Anchor a badge to the top-right corner.
+const node = world.get(badge, UINode);
+Object.assign(node, anchorPresetFields({ h: AnchorAxis.End, v: AnchorAxis.Start }));
+node.insetRight = { ...node.insetRight, value: 16 }; // 16px in from the right
+node.insetTop = { ...node.insetTop, value: 16 };
+world.insert(badge, UINode, node);
+
+detectAnchor(node); // → { h: AnchorAxis.End, v: AnchorAxis.Start }
+detectAnchorAxes(node); // → per-axis; an axis is null when hand-tuned
+```
+
+`detectAnchor(node)` classifies a `UINode` back to the preset it matches — it
+round-trips with `anchorPresetFields` — and returns `null` for `Relative` nodes
+or boxes that aren't a clean preset. `detectAnchorAxes(node)` classifies each
+axis independently (`h`/`v`, each `AnchorAxis | null`), so a box with one
+hand-tuned axis still reads — and can keep — the other.
+
+## Layout timing and `UILayoutGeneration`
+
+The layout runs in `PreUpdate` (before your `Update` systems) and re-solves in
+`PostUpdate` after scroll/list mutations, so gameplay systems always see
+current geometry. Each solve increments the **`UILayoutGeneration`** resource —
+a monotonic counter you can watch to invalidate anything you cache off computed
+UI geometry (the built-in pointer hit-testing uses it exactly this way):
+
+```typescript
+import { defineSystem, Res, UILayoutGeneration } from 'esengine';
+
+let seen = -1;
+const trackLayout = defineSystem([Res(UILayoutGeneration)], (gen) => {
+ if (gen.generation === seen) return; // layout unchanged since last frame
+ seen = gen.generation;
+ // Layout re-solved: re-read computed UI geometry, rebuild cached rects…
+});
+```
+
+## Recipes
+
+### Full-screen scrim
+
+```typescript
+import { spawnUIEntity } from 'esengine';
+
+const scrim = spawnUIEntity({
+ world,
+ node: { fill: true }, // Absolute + all four insets px(0)
+ visual: { color: { r: 0, g: 0, b: 0, a: 0.6 } },
+});
+```
+
+### Center a panel
+
+Two equivalent tools: give the **parent** a centering `FlexContainer`
+(`justifyContent: Center, alignItems: Center` — the quickstart pattern in
+[UI](/docs/guides/ui/)), or make the panel itself `Absolute` with all-`auto`
+insets **and** margins (the [Center anchor](#centering-with-auto) — no parent
+container needed).
+
+### HUD corner badge
+
+```typescript
+import { spawnUIEntity, UIPositionType, px } from 'esengine';
+
+const badge = spawnUIEntity({
+ world, parent: hudRoot,
+ node: {
+ position: UIPositionType.Absolute,
+ insetTop: px(16), insetRight: px(16), // other edges stay auto
+ width: px(48), height: px(48),
+ },
+ visual: { color: { r: 0.9, g: 0.2, b: 0.2, a: 1 } },
+});
+```
+
+### Responsive column
+
+Percent width with a pixel cap — fluid on phones, capped on wide screens.
+`min`/`max` aren't in the `spawnUIEntity` init, so set them on the component:
+
+```typescript
+import { spawnUIEntity, UINode, px, percent } from 'esengine';
+
+const column = spawnUIEntity({ world, parent: root, node: { width: percent(90) } });
+const n = world.get(column, UINode);
+n.maxWidth = px(480);
+world.insert(column, UINode, n);
+```
+
+### Stretch children / spacer
+
+`alignItems` defaults to `Stretch`, so children of a `Row` already fill its
+height. Along the main axis, use `flexGrow` — a grow-only spacer pushes
+siblings apart:
+
+```typescript
+import { spawnUIEntity, FlexContainer, FlexDirection, px, percent } from 'esengine';
+
+const toolbar = spawnUIEntity({ world, node: { height: px(48), width: percent(100) } });
+world.insert(toolbar, FlexContainer, {
+ direction: FlexDirection.Row,
+ gap: { x: 8, y: 0 }, padding: { left: 8, top: 4, right: 8, bottom: 4 },
+});
+
+spawnUIEntity({ world, parent: toolbar, text: { content: 'Title' } });
+spawnUIEntity({ world, parent: toolbar, node: { flexGrow: 1 } }); // spacer
+spawnUIEntity({ world, parent: toolbar, text: { content: '99:59' } });
+```
+
+## Low-level builders
+
+`spawnUIEntity` composes three pure builders you can also use directly when
+inserting components yourself — each fills a sparse init out to a complete
+component literal:
+
+- **`buildUINode(init)`** — a full `UINodeData`. `fill: true` is the common
+ widget case: `Absolute` + all insets `px(0)`. Without `fill`, the default is
+ `Relative` with `auto` size — note that `spawnUIEntity` with **no** `node`
+ init produces this relative auto box, not a parent-filling one.
+- **`buildUIVisual(init)`** — a full `UIVisualData` (default: solid white).
+- **`buildText(init)`** — a full `TextData` with *widget-flavored* defaults
+ (14px, centered, no wrap) — deliberately different from the `Text`
+ component's own defaults (24px, left/top, wrap), which target free-standing
+ labels.
+- **`setUIVisible(world, entity, visible)`** — toggles `UIVisual.enabled`
+ (no-op without a `UIVisual`). For hiding a whole subtree, set
+ `UINode.display` to `UIDisplay.None` instead.
+
+```typescript
+import { UINode, UIVisual, buildUINode, buildUIVisual, px } from 'esengine';
+
+const e = world.spawn();
+world.insert(e, UINode, buildUINode({ width: px(200), height: px(40) }));
+world.insert(e, UIVisual, buildUIVisual({ color: { r: 0.2, g: 0.2, b: 0.25, a: 1 } }));
+```
+
+## Best practices
+
+- **Flex first** — express layout with containers, `flexGrow`, and `percent`;
+ reach for `Absolute` only for overlays, badges, and floating panels.
+- **Anchor with presets** — `anchorPresetFields` writes the correct
+ inset/margin combination (especially `Center`'s all-`auto` rule) so you don't
+ have to remember it.
+- **Never position UI via `Transform`** — the layout pass overwrites it every
+ frame; move boxes with insets and margins.
+- **Cap fluid sizes** — pair `percent` widths with `maxWidth: px(...)` for
+ wide-screen sanity.
+- **Hide subtrees with `display: None`**, single visuals with
+ `UIVisual.enabled`.
+
+## See also
+
+- [UI](/docs/guides/ui/) — the component model overview and quickstart.
+- [UI Text](/docs/guides/ui-text/) — how `Text` measures and aligns inside the box.
+- [UI Interaction](/docs/guides/ui-interaction/) — hit-testing the laid-out boxes.
+- [UI Components](/docs/guides/ui-components/) — widgets built on these primitives (incl. mobile safe areas).
+- [Camera](/docs/guides/camera/) — cameras, canvas scale modes, and the UI box.
diff --git a/docs/astro/src/content/docs/guides/ui-lists.mdx b/docs/astro/src/content/docs/guides/ui-lists.mdx
new file mode 100644
index 000000000..3b3c2a107
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-lists.mdx
@@ -0,0 +1,507 @@
+---
+title: Lists & Scrolling
+description: Virtualized data-driven lists and grids with createListView — data sources, layout providers, entity recycling, auto-height rows — plus free-form scrolling with createScrollView, kinetic fling, and scrollbars.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Long, scrollable content in Estella is built from two factories on top of the
+[UI](/docs/guides/ui/) component model:
+
+- **`createListView`** — a **virtualized**, data-driven list or grid. Only the
+ items near the viewport are ever mounted, so a 10 000-row inventory,
+ leaderboard, or chat log stays as cheap as a 10-row one.
+- **`createScrollView`** — a clipped, scrollable panel for **arbitrary
+ content** (a settings page, a long form). No virtualization, no data source —
+ just parent your entities under it.
+
+Both compose the same primitives: a Scissor [`UIMask`](#clipping--uimask)
+viewport, a content frame translated by a [`ScrollContainer`](#the-scrolling-model),
+and wheel / drag / kinetic-fling input routed by the UI plugin.
+
+## `createListView`
+
+One call composes a data source, a layout, item recycling, scrolling, and
+clipping:
+
+```typescript
+import { createListView, uiPlugin, arrayDataSource, spawnUIEntity, px } from 'esengine';
+
+const list = createListView<Player>({
+ world, host: uiPlugin, parent,
+ viewportSize: { x: 320, y: 480 }, // the visible window, in pixels
+ data: arrayDataSource(players), // any DataSource<T>, or a raw array
+ layout: { itemHeight: 56 }, // a column list
+ item: {
+ create: (world, parent) => spawnUIEntity({ world, parent, node: { height: px(56) } }),
+ bind: (entity, player, index) => { /* fill the row's Text / Sprite from `player` */ },
+ },
+});
+```
+
+`host` is the plugin that ticks virtualization and routes scroll input — pass
+the `uiPlugin` your app was built with (the granular `uiBehaviorPlugin` also
+satisfies it).
+
+### Options
+
+| Option | Default | Description |
+|---|---|---|
+| `world` / `host` | — | The ECS world and the ticking plugin (`uiPlugin`). Required. |
+| `parent` | root | Parent entity for the viewport. |
+| `viewportSize` | — | Pixel size of the visible window. Required — the scroll math needs it up front. |
+| `node` | sized to `viewportSize` | Extra `UINode` props for the viewport box. |
+| `background` | transparent | Viewport visual. The default is an invisible **hit-target** — it must exist so the wheel and drag land on the list. |
+| `data` | — | A `DataSource<T>`, or a raw array (wrapped in an `ArrayDataSource` — the array is **copied**, so mutate the source afterwards, not your original array). |
+| `layout` | — | Layout sugar (`itemHeight` / `itemWidth` / `columns`, below) or a full [`LayoutProvider`](#layout-providers). |
+| `item` | — | One [item template](#the-item-template), or a map of item type → template for heterogeneous rows. |
+| `direction` | from layout | Scroll axis: `'vertical'` \| `'horizontal'` \| `'both'`. Column and grid layouts default to vertical, row layouts to horizontal. |
+| `recycleBuffer` | `2` | Extra indices kept mounted on each side of the visible range. For grids, think in rows: `columns * 2` keeps two extra rows. |
+| `wheelSpeed` | `1` | Wheel delta multiplier. |
+| `dragScroll` | `true` | Pointer/touch drag scrolling with a kinetic fling. |
+| `decelerationRate` | `0.135` | Fling velocity fraction left after 1 s of coasting. |
+| `onItemBound` | — | `(entity, data, index)` called after every bind — for ad-hoc per-item tweaks. |
+
+**Layout sugar** (`ListLayoutSpec`) covers the three common shapes:
+
+| `layout` | Result |
+|---|---|
+| `{ itemHeight, spacing? }` | A vertical list — a fixed row height, or a **`(index) => number`** function for [auto-height rows](#auto-height-rows). |
+| `{ itemWidth, direction: 'row', spacing? }` | A horizontal list; items span the viewport height. |
+| `{ columns, itemSize, spacing? }` | A grid (a *TileView*); `spacing` is a `Vec2` here. |
+
+### The item template
+
+An item template is a **create / bind** pair (`ListItemTemplate<T>`):
+
+```typescript
+item: {
+ // Build ONE row entity. Runs only when the pool has no free row to reuse.
+ create: (world, parent) => spawnUIEntity({ world, parent, text: { content: '' } }),
+ // Apply data to a row. Runs on every (re)bind — keep it a pure "apply this data".
+ bind: (entity, player, index) => setRowText(world, entity, player.name),
+}
+```
+
+- `create` builds the row's entity subtree once — spawn children, insert
+ components, wire interaction here. Use `spawnUIEntity` so the row carries a
+ `UINode`.
+- `bind` fills the row from the data. It runs **every time** the row is
+ (re)used — when it scrolls in, when its data updates, and again for every
+ mounted row on each scroll step — so it must be **idempotent and cheap**.
+
+**Recycling rules.** Rows are pooled entities, not fresh spawns:
+
+- A reused row still holds **everything the previous bind wrote** — reset every
+ field you ever set (text, colors, the visibility of conditional children).
+ If a field is only set for *some* items, `bind` must also clear it for the
+ others.
+- Never spawn children or add components inside `bind` — that accumulates on
+ every reuse. Structure belongs in `create`.
+- Don't key external state by the row **entity** — the entity↔index mapping
+ changes as you scroll. Key by the data (or re-derive in `bind`).
+- Guard your writes: `bind` re-runs for all mounted rows on every scroll step,
+ so skip component writes when the value hasn't changed (an early-return
+ `if (text.content === next) return;` keeps scrolling allocation-free).
+- The list **owns each row's box**: on every bind the row's `UINode` is set to
+ `Absolute` and its inset + `width`/`height` are overwritten with the layout
+ rect. Size row *content* with children inside the row, not by writing the row
+ node itself.
+- Off-screen rows are hidden (via `setUIVisible`), not despawned; they are
+ reused or despawned with the list.
+
+**Heterogeneous rows** — pass a map of item type → template, and give the data
+source a `getItemType(index)`:
+
+```typescript
+item: {
+ header: { create: makeHeader, bind: bindHeader },
+ message: { create: makeMessage, bind: bindMessage },
+},
+```
+
+Every type `getItemType` returns must have a matching template. When a data
+reset changes an index's type, the old row is released and a row of the right
+template is bound in its place.
+
+<Aside type="note">
+ There is **no built-in selection model** — a row is an ordinary entity tree.
+ Make rows clickable (a `createButton` inside `create`, or an `Interactable` +
+ a `click` handler), store the selected id **in your data**, and let `bind`
+ render the selected look. State that lives in the data survives recycling by
+ construction.
+</Aside>
+
+### The handle
+
+`createListView` returns a `ListViewHandle<T>`:
+
+| Member | Description |
+|---|---|
+| `entity` | The viewport entity (the clipped window; position it in your UI tree). |
+| `content` | The scrolling content frame the rows are parented to. |
+| `data` | The `DataSource<T>` — mutate it to update the list. |
+| `refresh()` | Force a re-sync of mounted rows on the next frame (after out-of-band data changes). |
+| `scrollToIndex(i)` | Scroll so item `i` sits at the top-left of the viewport (clamped to the range). |
+| `mountedCount()` | Number of row entities currently mounted — never grows with the data; handy in tests. |
+| `scroll` / `view` | Escape hatches to the underlying `ScrollContainer` / `ListView` driver. |
+| `dispose()` | Unregister, release rows, drop scroll/data subscriptions, despawn the viewport. |
+
+## Data sources
+
+A list reads its items through the `DataSource<T>` interface:
+
+```typescript
+interface DataSource<T> {
+ getCount(): number;
+ getItem(index: number): T;
+ getItemType?(index: number): string; // default 'default'
+ getItemId?(index: number, item: T): string | number; // stable identity
+ subscribe?(listener: (change: DataSourceChange) => void): () => void;
+}
+```
+
+`subscribe` is what makes the list live: on any change notification the view
+marks itself dirty and re-syncs on the next frame — you never call `refresh()`
+for changes that go through the data source.
+
+### `ArrayDataSource`
+
+The built-in array-backed source (`arrayDataSource(items)` is the shorthand
+constructor). Every mutator updates the array **and** notifies subscribers in
+one call:
+
+| Method | Change emitted | Description |
+|---|---|---|
+| `setItems(items)` | `reset` | Replace all items. |
+| `append(items)` | `insert` | Add items at the end. |
+| `insert(index, items)` | `insert` | Insert at `index` (clamped into range). |
+| `remove(index, count = 1)` | `remove` | Remove `count` items at `index`. |
+| `update(index, item)` | `update` | Replace one item. |
+| `getCount()` / `getItem(i)` | — | Reads (`getItem` throws on out-of-range). |
+| `subscribe(fn)` | — | Listen to changes; returns an unsubscribe function. |
+
+```typescript
+list.data.append([newPlayer]); // add
+list.data.remove(3); // remove index 3
+list.data.update(0, updatedPlayer); // replace one
+list.data.setItems(freshList); // replace all
+```
+
+<Aside type="caution">
+ The constructor **copies** the array you pass in. Mutating your original array
+ afterwards changes nothing on screen — go through the mutators above. If you
+ must mutate shared state the source can't see, call `list.refresh()` (and
+ know that a measured layout won't re-measure that way — see below).
+</Aside>
+
+### Writing a custom `DataSource`
+
+Implement the interface directly when the data doesn't live in an array — a
+ring buffer, a query result, a network-paged collection:
+
+```typescript
+import type { DataSource, DataSourceChange } from 'esengine';
+
+class LogSource implements DataSource<string> {
+ private lines: string[] = [];
+ private listeners = new Set<(c: DataSourceChange) => void>();
+
+ getCount() { return this.lines.length; }
+ getItem(i: number) { return this.lines[i]; }
+ subscribe(fn: (c: DataSourceChange) => void) {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+
+ push(line: string) {
+ const at = this.lines.length;
+ this.lines.push(line);
+ for (const fn of this.listeners) fn({ type: 'insert', index: at, count: 1 });
+ }
+}
+```
+
+`getCount` + `getItem` are the required minimum; without `subscribe` the list
+still works, but you must call `refresh()` after every change.
+
+## Layout providers
+
+The `layout` option accepts a full `LayoutProvider` — the pure math object
+behind the sugar. A provider answers three questions: total content size, the
+rect of item `i`, and which index range a viewport rect can see. Three
+implementations ship:
+
+| Provider | Use when | Options |
+|---|---|---|
+| `LinearLayoutProvider` | Fixed-size rows or columns. | `itemSize: Vec2` (required), `direction: 'row' \| 'column'` (default `'column'`), `spacing` (default `0`). |
+| `GridLayoutProvider` | Fixed-size cells in N columns; scrolls vertically. | `columns` (required, min 1), `itemSize: Vec2` (required), `spacing: Vec2` (default `{0, 0}`). |
+| `MeasuredLinearLayoutProvider` | Rows whose main-axis size varies per item (chat bubbles, mixed content). | `crossSize` (required), `mainSizeOf: (index) => number` (required), `direction` (default `'column'`), `spacing` (default `0`). |
+
+```typescript
+import { createListView, GridLayoutProvider, uiPlugin } from 'esengine';
+
+createListView<Item>({
+ world, host: uiPlugin, parent,
+ viewportSize: { x: 320, y: 480 },
+ data: items,
+ layout: new GridLayoutProvider({ columns: 4, itemSize: { x: 72, y: 72 }, spacing: { x: 8, y: 8 } }),
+ item: { create: makeCell, bind: bindCell },
+});
+```
+
+The sugar specs map straight onto these: `{ itemHeight: 56 }` builds a
+`LinearLayoutProvider` with the viewport width as the cross size;
+`{ itemHeight: (i) => … }` builds a `MeasuredLinearLayoutProvider`;
+`{ columns, itemSize }` builds a `GridLayoutProvider`.
+
+**Auto-height mechanics.** `MeasuredLinearLayoutProvider` prefix-sums the item
+offsets and caches them; item lookup and visibility queries then read the
+cache. The cache rebuilds when the item count changes and whenever the list
+invalidates it — which the list does on **every data-source change** and on
+**viewport resizes** (a width-dependent measure like wrapped text re-flows).
+A rebuild calls `mainSizeOf` once for every item, so keep the measure cheap or
+memoize it per item.
+
+### Auto-height rows
+
+Pass a **function** for `itemHeight` to size each row to its content — perfect
+for a chat log where a bubble grows with its wrapped text:
+
+```typescript
+import { measureText } from 'esengine';
+
+createListView<Message>({
+ world, host: uiPlugin, parent,
+ viewportSize: { x: 360, y: 480 },
+ data: messages,
+ layout: {
+ itemHeight: (i) => measureText(messages.getItem(i).text, {
+ fontSize: 14, maxWidth: 320,
+ }).height + 16, // wrapped text height + vertical padding
+ spacing: 8,
+ },
+ item: { /* create / bind */ },
+});
+```
+
+`measureText(text, { fontSize, maxWidth?, fontFamily?, bold?, italic?, letterSpacing?, lineHeight? })`
+returns `{ width, lineCount, height }` measured off the **same Canvas2D metrics
+the glyph atlas draws from**, so a measured height matches what actually renders
+— no clipped or overflowing rows. `lineHeight` defaults to `fontSize * 1.2`,
+the `Text` default ratio; omit `maxWidth` for a single unwrapped line. (A
+DOM-less host falls back to an average-glyph estimate.)
+
+## How virtualization works
+
+Each frame, the host plugin ticks every registered list; a tick is a no-op
+unless something marked the list dirty (a scroll, a data change, a viewport
+resize). A dirty update:
+
+1. asks the layout provider for the **visible index range** at the current
+ scroll offset,
+2. widens it by `recycleBuffer` indices on each side,
+3. **releases** mounted rows that fell outside the range into an entity pool
+ (hidden, not despawned),
+4. **acquires** rows for indices that entered the range — from the pool when
+ one is free, else via the template's `create` — and **binds** every row in
+ the range.
+
+The result: work per frame is `O(mounted)`, and `mounted ≈ visible +
+2 × recycleBuffer` regardless of data size. `mountedCount()` exposes that
+number — assert it stays flat in tests. Data mutations are just as bounded: an
+`append` to a list scrolled far from the end binds nothing at all.
+
+**Do:**
+
+- Keep `bind` cheap, idempotent, and change-guarded — it is the per-scroll hot
+ path.
+- Route every data change through the data source (or call `refresh()`).
+- Use `getItemType` + a template map instead of one template full of `if`s.
+- For advanced pooling control (e.g. pre-warming rows to avoid a first-scroll
+ spike), the `ViewPool` primitive is public — compose your own `ListView`
+ driver with it.
+
+**Don't:**
+
+- Don't spawn/insert in `bind`, and don't assume a fresh entity — see the
+ [recycling rules](#the-item-template).
+- Don't cache entity references per data index across frames.
+- Don't drive per-row animation from `bind` — bind writes state; animate with a
+ system or tween targeting the row's components.
+- Don't give a measured list an expensive `mainSizeOf` — it runs for **all**
+ items on every data change.
+
+## Free-form scrolling — `createScrollView`
+
+For a scrollable panel of arbitrary content — no virtualization, no data
+source — use `createScrollView` and parent anything under its `content` frame:
+
+```typescript
+import { createScrollView, uiPlugin } from 'esengine';
+
+const panel = createScrollView({
+ world, host: uiPlugin, parent,
+ viewportSize: { x: 320, y: 480 },
+ contentSize: { x: 320, y: 1200 },
+});
+// build your content under panel.content …
+panel.scrollTo({ x: 0, y: 300 });
+```
+
+| Option | Default | Description |
+|---|---|---|
+| `world` / `host` | — | The world and the input-routing plugin (`uiPlugin`). Required. |
+| `parent` | root | Parent entity for the viewport. |
+| `viewportSize` | — | Pixel size of the visible window. Required. |
+| `contentSize` | — | Pixel size of the scrollable content frame. Required — sizes are explicit because the scroll math needs them up front. |
+| `node` / `background` | sized box / transparent hit-target | As in `createListView`. |
+| `direction` | `'vertical'` | Scroll axis: `'vertical'` \| `'horizontal'` \| `'both'`. |
+| `wheelSpeed` | `1` | Wheel delta multiplier. |
+| `dragScroll` | `true` | Drag/touch scrolling with kinetic fling. |
+| `decelerationRate` | `0.135` | Fling decay (fraction left after 1 s). |
+| `onScroll` | — | `(offset)` fired on every offset change. |
+
+**Handle** (`ScrollViewHandle`): `entity` (the clipped viewport) · `content`
+(parent your content here) · `scrollTo(offset)` · `setContentSize(size)` —
+call it after the content grows or shrinks, it resizes the frame *and* the
+scroll range · `scroll` (the underlying `ScrollContainer`) · `dispose()`.
+
+## The scrolling model
+
+Both factories drive a **`ScrollContainer`** — a pure scroll-state model with
+no input or ECS knowledge. It clamps the offset to `[0, contentSize −
+viewportSize]` per axis (a `'vertical'` container pins `x` to 0 and vice
+versa), and notifies `onScroll` listeners on any change. The factories
+subscribe to it and translate the content frame by `-offset`; the UI plugin
+feeds it input:
+
+- **Wheel** — deltas over the hovered viewport, scaled by `wheelSpeed`.
+- **Drag / touch** — with `dragScroll: true` (default), a pointer grab drags
+ the content; the platform layer funnels the primary touch into the pointer
+ stream, so touch scrolling rides the same path.
+- **Kinetic fling** — on release, the sampled velocity coasts and decays
+ exponentially: `decelerationRate` is the velocity fraction left after one
+ second (default `0.135`, the ScrollRect standard — lower stops sooner). The
+ underlying `KineticScroll` model is public too, with a rest-velocity floor
+ (`4` px/s) and an EMA sample rate (`12`/s) for custom compositions.
+
+Programmatic scrolling goes through the handle (`scrollToIndex`, `scrollTo`)
+or the container itself: `list.scroll.scrollBy({ x: 0, y: 120 })`.
+
+### Scrollbars
+
+Every attached scroll container gets an **auto-fading overlay scrollbar** per
+scrollable axis: a slim thumb appears while the offset moves, then fades out
+after ~0.8 s of stillness. Thumb length tracks the viewport/content ratio,
+it's out of flow (no layout impact), not interactable (no input surface), and
+theme-tagged with the `text` role so it re-skins on a live theme swap. The
+factories always leave scrollbars on; opting out (`showScrollbar: false`) is a
+`ScrollContainer` construction option, for manual compositions.
+
+## Clipping — `UIMask`
+
+The viewport entity of both factories carries a `UIMask` in **Scissor** mode:
+children render only inside the viewport's axis-aligned rectangle, which is
+what actually hides the off-screen part of the content frame. Scissor is a
+render-state rectangle — effectively free, but axis-aligned; a **Stencil**
+mask (`MaskMode.Stencil`) clips correctly under rotation. You can put a
+`UIMask` on any UI node the same way:
+
+```typescript
+import { UIMask, MaskMode } from 'esengine';
+
+world.insert(panel, UIMask, { enabled: true, mode: MaskMode.Scissor });
+```
+
+## A complete chat log
+
+The pieces together — a virtualized message log with measured bubble rows and
+a composer that appends to the data source (`examples/chat` in the repo is the
+full two-sided version):
+
+```typescript
+import {
+ defineSystem, addStartupSystem, GetWorld, Res, UIEvents,
+ createListView, createTextInput, uiPlugin, ArrayDataSource,
+ spawnUIEntity, measureText, px, Text, UIPositionType,
+} from 'esengine';
+import type { World, Entity } from 'esengine';
+
+interface Message { from: 'me' | 'them'; text: string; }
+
+const W = 360, PAD = 8, FONT = 14;
+const messages = new ArrayDataSource<Message>([]);
+
+const rowHeight = (i: number) =>
+ measureText(messages.getItem(i).text, { fontSize: FONT, maxWidth: W - 2 * PAD }).height + 2 * PAD;
+
+function setRowText(world: World, row: Entity, content: string): void {
+ const t = world.get(row, Text);
+ if (t.content === content) return; // change-guard: bind is the hot path
+ t.content = content;
+ world.insert(row, Text, t);
+}
+
+const buildChat = defineSystem([GetWorld(), Res(UIEvents)], (world, events) => {
+ const list = createListView<Message>({
+ world, host: uiPlugin,
+ viewportSize: { x: W, y: 480 },
+ data: messages,
+ layout: { itemHeight: rowHeight, spacing: 6 },
+ item: {
+ create: (w, parent) => spawnUIEntity({
+ world: w, parent,
+ // The row box is owned by the list; the bubble look lives on the row itself.
+ visual: { color: { r: 0.15, g: 0.17, b: 0.22, a: 1 } },
+ text: { content: '', fontSize: FONT, wordWrap: true },
+ }),
+ bind: (row, msg) => setRowText(world, row, `${msg.from}: ${msg.text}`),
+ },
+ });
+
+ createTextInput({
+ world, events,
+ node: { position: UIPositionType.Absolute, insetLeft: px(0), insetBottom: px(0), width: px(W), height: px(32) },
+ placeholder: 'Type a message and press Enter…',
+ onSubmit: (text, entity) => {
+ if (!text.trim()) return;
+ messages.append([{ from: 'me', text }]); // notifies the list
+ list.scrollToIndex(messages.getCount() - 1); // keep the newest in view
+ },
+ });
+});
+
+addStartupSystem(buildChat);
+```
+
+The `append` notifies the list (dirty → re-sync next frame) **and** re-clamps
+the scroll range; `scrollToIndex` then lands on the new last row. Because the
+layout is measured, the append also invalidates the offset cache, so the new
+bubble's wrapped height is measured before anything is placed.
+
+## Best practices
+
+- **Virtualize anything data-shaped.** If the content is "N of the same thing",
+ reach for `createListView` even at modest N — you get recycling, scrolling,
+ clipping, and live data updates in one call. `createScrollView` is for
+ *heterogeneous* content.
+- **The data source is the single source of truth.** Selection, highlight,
+ badges — model them in the data and render them in `bind`; never stash list
+ state on row entities.
+- **Guard writes in `bind`.** Early-return when the value is unchanged; `bind`
+ runs for every mounted row on every scroll step.
+- **Measure once, reuse.** For auto-height rows, share one measure function
+ between `itemHeight` and the row's own text layout (same `fontSize`,
+ `maxWidth`) so the box and the glyphs always agree.
+- **Dispose what you create.** `dispose()` unregisters from the plugin,
+ releases rows, and drops subscriptions — leaking a list keeps it ticking.
+
+## See also
+
+- [UI](/docs/guides/ui/) — the component model these factories are built on.
+- [UI Components](/docs/guides/ui-components/) — the other widget factories (Button, Dialog, Text input, …).
+- [UI Layout](/docs/guides/ui-layout/) — `UINode` boxes, flexbox, and dimensions.
+- [UI Binding](/docs/guides/ui-binding/) — signals and two-way widget binding.
+- [UI Interaction](/docs/guides/ui-interaction/) — pointer events, focus, drag & drop.
+- [UI Theme](/docs/guides/ui-theme/) — the token roles the scrollbar and defaults draw from.
diff --git a/docs/astro/src/content/docs/guides/ui-text.mdx b/docs/astro/src/content/docs/guides/ui-text.mdx
new file mode 100644
index 000000000..c2e15493e
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-text.mdx
@@ -0,0 +1,250 @@
+---
+title: Text
+description: The complete Text reference — the Bitmap/SDF glyph pipelines, every Text property, alignment with and without a layout box, rich-text markup, measureText, custom fonts, and localization.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+The `Text` component draws strings from a dynamic glyph atlas. Give the entity a
+`UINode` and the text lays out inside the flexbox box (wrapped, aligned, sorted
+with sibling UI); without a box it renders as a free world-space label anchored
+to the entity origin. Spawn one in code with `spawnUIEntity({ text: … })` or add
+`Text` in the inspector.
+
+```typescript
+import { defineSystem, addStartupSystem, GetWorld, spawnUIEntity, TextAlign, px } from 'esengine';
+
+const buildHud = defineSystem([GetWorld()], (world) => {
+ spawnUIEntity({
+ world,
+ node: { width: px(240), height: px(40) },
+ text: { content: 'Score: 0', fontSize: 24, align: TextAlign.Left },
+ });
+});
+addStartupSystem(buildHud);
+```
+
+## The two glyph pipelines
+
+Every glyph is rasterized once into a shared atlas and drawn as textured quads.
+`renderMode` picks **how** it is rasterized, per Text:
+
+- **`Bitmap`** — glyphs rasterize with Canvas2D at the **effective on-screen
+ pixel size**: device pixels × the canvas design-resolution fit are folded into
+ rasterization, so quads blit 1:1 with native antialiasing and font hinting.
+ DOM-crisp at any window size — the sharpest choice for **static** UI.
+- **`Sdf`** — each glyph rasterizes once into a signed-distance field and the
+ shader lays a **~1px screen-space coverage ramp** on the edge (the
+ msdfgen/TextMeshPro technique). The edge stays crisp under **dynamic**
+ scaling — animated zoom, scale tweens, world-space labels — where a bitmap
+ would blur or shimmer.
+- **`Auto`** (default) — bitmap while the entity's own world scale is 1 (within
+ ±2%; the canvas fit is already compensated in the bitmap path), SDF the moment
+ the entity scales. DOM-crisp static UI *and* zoom-stable animated text with no
+ configuration.
+
+So a pulsing "LEVEL UP!" banner needs nothing special — `Auto` switches it to
+SDF while it scales:
+
+```typescript
+import {
+ defineSystem, Query, Mut, Res, Time, Transform, Text,
+} from 'esengine';
+
+// Tween the banner's scale; Auto routes the text to the SDF pipeline
+// while scale ≠ 1, so the glyph edges stay crisp mid-zoom.
+const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, time) => {
+ for (const [, tr] of q) {
+ const s = 1 + 0.25 * Math.sin(time.elapsed * 4);
+ tr.scale.x = s;
+ tr.scale.y = s;
+ }
+});
+```
+
+Force `Sdf` when text is *born* scaled or lives in world space at arbitrary
+camera zoom; force `Bitmap` when you know the text never scales and want
+hinting even under tiny per-frame scale noise.
+
+## `Text` properties
+
+Defaults below are the component defaults (what the inspector shows).
+
+| Property | Type | Default | Description |
+|---|---|---|---|
+| `content` | string | `''` | The string to display. `\n` hard-breaks lines. |
+| `i18nKey` | string | `''` | Localization key. Non-empty ⇒ `content` becomes **derived**: resolved from the Localization catalogs every frame (see [below](#localization)). |
+| `fontFamily` | string | `'Arial'` | Font family, resolved by the platform's Canvas2D (see [Custom fonts](#custom-fonts)). |
+| `fontSize` | number | `24` | Size in **design px** — the same units as `UINode` `px()` sizes. The design-resolution fit and device pixel ratio are compensated at rasterization. |
+| `color` | Color | `{1,1,1,1}` | Fill color (per-channel `0..1`). |
+| `align` | `TextAlign` | `Left` | Horizontal alignment: `Left` / `Center` / `Right`. |
+| `verticalAlign` | `TextVerticalAlign` | `Top` | Vertical alignment: `Top` / `Middle` / `Bottom`. |
+| `wordWrap` | boolean | `true` | Wrap lines at the box width (needs a `UINode` box). |
+| `overflow` | `TextOverflow` | `Visible` | `Visible` / `Clip` / `Ellipsis`. Currently the renderer always draws `Visible`; clip overflow with a [`UIMask`](/docs/guides/ui/) on the box. |
+| `lineHeight` | number | `1.2` | Line spacing as a **ratio of `fontSize`** (baseline-to-baseline = `lineHeight × fontSize`). |
+| `bold` / `italic` | boolean | `false` | Base font style (rich-text `<b>`/`<i>` layer on top). |
+| `strokeColor` | Color | `{0,0,0,1}` | Outline color. |
+| `strokeWidth` | number | `0` | Outline width in px; `0` disables. Drawn as recolored glyph copies fanned out in 8 directions. |
+| `shadowColor` | Color | `{0,0,0,1}` | Drop-shadow color. |
+| `shadowOffsetX` / `shadowOffsetY` | number | `0` | Shadow offset in px. The shadow draws only when the color has alpha and at least one offset is non-zero. |
+| `shadowBlur` | number | `0` | Reserved — the current renderer draws the shadow as a hard-edged offset copy and does not apply blur. |
+| `richText` | boolean | `false` | Parse inline [rich-text markup](#rich-text). |
+| `renderMode` | `TextRenderMode` | `Auto` | Glyph pipeline: `Auto` / `Bitmap` / `Sdf` (see above). |
+| `enabled` | boolean | `true` | Render toggle (the editor's eye icon uses it too). |
+
+<Aside type="note">
+ The code-composition path has widget-friendly defaults that differ from the
+ component's: `spawnUIEntity({ text: … })` / `buildText()` default to
+ `fontSize: 14`, `align: Center`, `verticalAlign: Middle`, `wordWrap: false`.
+ Pass fields explicitly where it matters.
+</Aside>
+
+## Alignment — with and without a box
+
+One rule covers both cases: **`align` / `verticalAlign` position the text block
+within its box, and a missing box collapses to a zero-size box at the entity
+origin** — so the same fields *anchor* a free label instead of silently doing
+nothing.
+
+- **With a `UINode` box** (the entity has a `UINode` with a non-zero laid-out
+ size): each line aligns horizontally within the box width — independent of
+ `wordWrap`, which only decides whether lines *break* at that width — and
+ `verticalAlign` distributes the block's vertical slack (`Middle` splits it,
+ `Bottom` pushes the block down).
+- **Without a box** (no `UINode`, or a 0×0 one): the block anchors to the entity
+ origin. `align: Left` puts the left edge at the origin, `Center` centers the
+ block on it, `Right` ends at it; `verticalAlign` anchors top/middle/bottom
+ edge the same way. This is what you want for world-space labels — damage
+ numbers, nameplates — where "center on the entity" is one field, not math.
+
+## Rich text
+
+Set `richText: true` and mark up `content` with inline tags. Styles nest as a
+stack; a closing tag pops the innermost style. Anything that does not parse as a
+known tag renders literally (so a stray `<` cannot eat your text).
+
+| Markup | Effect |
+|---|---|
+| `<b>…</b>` | Bold run. |
+| `<i>…</i>` | Italic run. |
+| `<color=#RRGGBB>…</color>` | Colored run; `#RRGGBBAA` adds alpha. |
+| `<font size=32>…</font>` | Run at another font size (`size="32"` also parses); the shared baseline is kept. |
+| `<img src="…" width=24 height=24 />` | Inline image segment — parsed today, **not yet rendered** (see below). |
+
+```typescript
+import { defineSystem, addStartupSystem, GetWorld, spawnUIEntity, px } from 'esengine';
+
+const buildToast = defineSystem([GetWorld()], (world) => {
+ spawnUIEntity({
+ world,
+ node: { width: px(360), height: px(48) },
+ text: {
+ content: 'Found <color=#ffd75a><b>Iron Sword</b></color> <font size=12>(rare)</font>',
+ fontSize: 18,
+ richText: true,
+ },
+ });
+});
+addStartupSystem(buildToast);
+```
+
+The parser is exported as `parseRichText(input)`, returning `RichTextRun[]` — a
+`TextSegment` (`text`, `bold`, `italic`, `color`, `fontSize`) or `ImageSegment`
+per run — if you want to drive a custom pipeline from the same markup.
+
+<Aside type="caution">
+ `<img src="…" width=N height=N valign=baseline|middle|top|bottom offsetX=N
+ offsetY=N scale=N tint=#RRGGBB />` parses into an `ImageSegment` (the tag must
+ be self-closing and needs `src`), but the built-in text renderer currently
+ **skips image runs** — inline sprites in text do not draw yet. Compose an
+ image next to the text with flexbox instead.
+</Aside>
+
+## Measuring text
+
+`measureText(text, opts)` answers "how big will this string render?" without
+spawning an entity — for layout that must size to content up front, e.g. a
+ListView `itemHeight(index)` for wrapped chat bubbles. It measures through the
+same Canvas2D source and the same wrap algorithm the renderer uses, so measured
+wraps match rendered ones. On a headless host (no DOM) it falls back to an
+average-glyph estimate.
+
+```typescript
+import { measureText, px, spawnUIEntity, defineSystem, addStartupSystem, GetWorld } from 'esengine';
+
+const buildBubble = defineSystem([GetWorld()], (world) => {
+ const message = 'You have been invited to join the guild "Night Watch".';
+ const m = measureText(message, { fontSize: 16, maxWidth: 260 });
+ spawnUIEntity({
+ world,
+ node: { width: px(280), height: px(m.height + 20) }, // pad the measured height
+ visual: { color: { r: 0.13, g: 0.15, b: 0.2, a: 1 } },
+ text: { content: message, fontSize: 16, wordWrap: true },
+ });
+});
+addStartupSystem(buildBubble);
+```
+
+| `MeasureTextOptions` | Default | Description |
+|---|---|---|
+| `fontSize` | — (required) | Size in display px. |
+| `fontFamily` | `'Arial'` | Font family. |
+| `bold` / `italic` | `false` | Style (affects advances). |
+| `letterSpacing` | `0` | Extra px between glyphs. |
+| `maxWidth` | — | Word-wrap width; `0`/omitted = single line. |
+| `lineHeight` | `fontSize × 1.2` | Line height in display px (note: **px**, not the component's ratio). |
+
+| `TextMetrics` | Description |
+|---|---|
+| `width` | Width of the widest line, display px. |
+| `lineCount` | Lines after wrapping plus explicit `\n`. |
+| `height` | `lineCount × lineHeight` — the height to size a box to. |
+
+## Custom fonts
+
+`fontFamily` is resolved by the platform's **Canvas2D** when glyphs rasterize —
+any family the host page can resolve works: system fonts, or a web font the page
+loads (CSS `@font-face` or the `FontFace` API). The SDK does not fetch font
+files for the `Text` component itself; make sure a web font is loaded before the
+text first renders, or its glyphs rasterize with the fallback font.
+
+Separately, **bitmap font assets** (`.fnt` / `.bmfont`) load through the asset
+pipeline — `Assets.loadFont(ref)` resolves the `.fnt`, loads its page texture,
+and returns a `FontResult` (`{ handle }`). They drive the **`BitmapText`**
+component: a world-space text renderer whose `font` field references the loaded
+asset (assign the font asset in the inspector), with `text`, `color`,
+`fontSize`, `align`, `spacing`, `parallax`, and `layer` fields. Use `BitmapText`
+for pre-baked score/damage glyph art; use `Text` for UI.
+
+## Localization
+
+Set `i18nKey` instead of hand-writing `content`: while a Localization resource
+exists (install `localizationPlugin`), a per-frame system resolves the key
+through the catalogs and writes the result into `content` — so `setLocale`
+re-flows every bound label on the next frame. A missing key resolves to the key
+itself (visible and greppable), and with no Localization resource the authored
+`content` stands. See [Localization](/docs/guides/localization/).
+
+## Best practices
+
+- **Leave `renderMode` on `Auto`** — hand-pick `Sdf` only for text that is born
+ scaled, `Bitmap` only to pin hinting on text you know never scales.
+- **Give UI text a `UINode` box** so wrapping and alignment have a width to work
+ against; go boxless only for world-space labels anchored to an entity.
+- **`fontSize` is design px** — size text in the same units as your `px()`
+ layout and let the engine handle DPR and the design-resolution fit.
+- **Measure before you size** — `measureText` uses the renderer's own wrap, so
+ content-sized boxes (chat rows, tooltips) come out exact.
+- **Bind labels with `i18nKey`**, not by writing translated strings into
+ `content` — locale switches then re-flow for free.
+- **Prefer markup over entity-splitting** for emphasis: one rich Text beats
+ three plain ones glued with flexbox.
+
+## See also
+
+- [UI](/docs/guides/ui/) — the component model overview.
+- [UI Layout](/docs/guides/ui-layout/) — the `UINode` box that text aligns and wraps within.
+- [UI Components](/docs/guides/ui-components/) — `createTextInput` for editable text.
+- [UI Theme](/docs/guides/ui-theme/) — themed text color roles and type scale.
+- [UI Binding](/docs/guides/ui-binding/) — drive `content` from reactive signals.
+- [Localization](/docs/guides/localization/) — catalogs, locales, and `i18nKey` resolution.
diff --git a/docs/astro/src/content/docs/guides/ui-theme.mdx b/docs/astro/src/content/docs/guides/ui-theme.mdx
new file mode 100644
index 000000000..59c3b1f8a
--- /dev/null
+++ b/docs/astro/src/content/docs/guides/ui-theme.mdx
@@ -0,0 +1,234 @@
+---
+title: Theming
+description: The ThemeTokens design-token model — semantic color/text roles, dark/light palettes, live theme swap with switchTheme, project-level overrides, and theming custom widgets.
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+The widget layer never hard-codes colors. Every built-in widget resolves its
+defaults from **design tokens** — a palette of *semantic roles*
+(`surface`, `control`, `primary`, `text`, …) plus a type scale — so one place
+defines the look, the same widget code renders correctly under the dark or the
+light palette, and a whole UI re-skins by swapping the token set.
+
+Three layers make that work:
+
+1. **`ThemeTokens`** — the token model: color roles + type scale, with the
+ built-in `DARK_TOKENS` / `LIGHT_TOKENS` sets.
+2. **`ThemeStyle`** — a component that records *which role* an entity's colors
+ came from, so already-built widgets can re-resolve.
+3. **`switchTheme`** — the live swap: set the active tokens *and* restyle every
+ `ThemeStyle`-tagged entity in the world.
+
+## The token model — `ThemeTokens`
+
+```typescript
+interface ThemeTokens {
+ colors: ThemeColors; // semantic color roles
+ type: ThemeType; // font-size scale
+}
+```
+
+### Color roles (`ThemeColors`)
+
+Every role, in display order (this is also the runtime list `THEME_COLOR_ROLES`
+— the array a theme editor or config validator iterates):
+
+| Role | Purpose |
+|---|---|
+| `surface` | Dialog / panel background. |
+| `surfaceElevated` | Raised surface — popup / dropdown list background. |
+| `control` | Interactive control resting fill (button, option). |
+| `controlHover` | Control fill while hovered. |
+| `controlActive` | Control fill while pressed. |
+| `track` | Slider / progress track. |
+| `primary` | Accent — slider fill, progress fill, selected option. |
+| `primaryHover` | Accent while hovered. |
+| `primaryActive` | Accent while pressed. |
+| `onPrimary` | Content/handle drawn *on top of* `primary` (e.g. the slider thumb). |
+| `text` | Default foreground (label text / icon) on `surface` / `control`. |
+| `backdrop` | Modal scrim behind dialogs. |
+
+### Type scale (`ThemeType`)
+
+Font sizes in px, shared between the light and dark sets:
+
+| Step | Default | Used for |
+|---|---|---|
+| `label` | `14` | Control / label text (buttons, options). |
+| `body` | `15` | Body / default text. |
+| `title` | `20` | Headings (dialog titles). |
+
+### Built-in token sets
+
+- **`DARK_TOKENS`** — the built-in default.
+- **`LIGHT_TOKENS`** — the same roles on light surfaces with dark text.
+
+The active set is read with `getTheme()` (or the `themeColors()` /
+`themeType()` shorthands) and replaced with `setTheme(tokens)` — but note that
+`setTheme` alone only affects widgets constructed *afterwards*; for a live
+swap use [`switchTheme`](#live-theme-swap--switchtheme) below.
+
+## How widgets consume tokens
+
+Widget factories resolve tokens **at build time**: `createButton` reads
+`themeColors().control` / `controlHover` / `controlActive` for its state pages
+and `themeColors().text` + `themeType().label` for its label; `createSlider`
+reads `track` / `primary` / `onPrimary` for track, fill, and handle; and so on.
+The resolved values are baked into ordinary components (`UIVisual`, `Text`,
+`$interaction` color gears) — there is no per-frame theme lookup.
+
+Because the values are baked, each factory *also* tags the entities it themed
+with a **`ThemeStyle`** component recording which role each color came from:
+
+| `ThemeStyle` field | Records the role driving… |
+|---|---|
+| `visual` | …this entity's `UIVisual.color`. |
+| `text` | …this entity's `Text.color`. |
+| `states` | …each `$interaction` color-gear page (page name → role), e.g. a button's `{ normal: 'control', hover: 'controlHover', … }`. |
+| `input` | …a `TextInput`'s `background` / `text` / `placeholder` colors. |
+
+`markThemed(world, entity, style)` inserts the tag. Role tags are authoring
+data — they **persist into prefabs and scenes**, so an editor-placed widget
+re-themes exactly like a code-constructed one.
+
+## Live theme swap — `switchTheme`
+
+`switchTheme(world, tokens)` sets the active tokens **and** calls
+`applyThemeToWorld(world)`, which walks every `ThemeStyle`-tagged entity and
+re-resolves its role bindings — `UIVisual.color`, `Text.color`, `TextInput`
+colors, and each `$interaction` color-gear page — against the new palette:
+
+```typescript
+import { switchTheme, getTheme, DARK_TOKENS, LIGHT_TOKENS } from 'esengine';
+
+// e.g. from a settings toggle:
+switchTheme(world, getTheme() === DARK_TOKENS ? LIGHT_TOKENS : DARK_TOKENS);
+```
+
+Semantics worth knowing:
+
+- **Alpha is preserved** — only the hue re-themes. A dimmed `disabled` state
+ keeps its transparency, and any translucency you set survives the swap.
+- **Prefab-authored colors re-resolve too**: a widget instanced from a prefab
+ carries its baked colors *and* its `ThemeStyle` tags, so
+ `applyThemeToWorld` restyles it the same as a live-constructed one.
+- Entities *without* a `ThemeStyle` tag are untouched — explicit colors stay
+ yours (see [overrides](#per-widget-overrides-vs-tokens)).
+
+## Project-level theme
+
+You normally don't call `switchTheme` for the *base* look — the project
+declares it. **Project Settings → UI** in the editor writes two fields under
+`features.ui` in the project manifest (`project.esproject`):
+
+| Setting | Manifest field | Meaning |
+|---|---|---|
+| Theme | `features.ui.theme` | `'light'`, or absent for the dark default. |
+| Theme colors | `features.ui.colors` | Partial re-skin: color role → `#rrggbb[aa]` hex. Only known roles (the `THEME_COLOR_ROLES` list) with valid hex persist; an absent role inherits the base theme. |
+
+Two shared functions carry those settings to every runtime:
+
+- **`parseThemeOverrides(colors)`** — converts the JSON hex map into
+ `ThemeOverrides` (unknown roles and malformed hex are dropped).
+- **`resolveThemeTokens(base, overrides?)`** — merges a base name
+ (`'dark' | 'light'`) with the partial overrides into effective
+ `ThemeTokens`, so a project that overrides `primary` alone re-tints the
+ accent while inheriting everything else.
+
+```typescript
+import { resolveThemeTokens, parseThemeOverrides, switchTheme } from 'esengine';
+
+const overrides = parseThemeOverrides({ primary: '#e5484d' });
+switchTheme(world, resolveThemeTokens('dark', overrides));
+```
+
+The flow end to end: the **editor** previews the effective theme live in the
+edit viewport (it runs exactly `switchTheme(world, resolveThemeTokens(...))`
+on the edit world — WYSIWYG for the settings panel, with per-role color
+pickers whose placeholders show the inherited base value). On **export**, the
+theme and colors are cooked into the shipped game config, and every runtime
+boots the scene and then applies
+`switchTheme(world, resolveThemeTokens(theme, overrides))` — prefabs bake
+dark values, so the post-load swap is what re-resolves every `ThemeStyle` tag.
+
+<Aside type="note">
+ Dark is expressed by *absence*: only `'light'` and non-empty color overrides
+ persist in the manifest. A project with no `features.ui` block ships the
+ default `DARK_TOKENS` untouched.
+</Aside>
+
+## Per-widget overrides vs tokens
+
+Every factory lets you pass explicit colors — and doing so **opts that field
+out of theming**. The rule is consistent: a theme-defaulted field gets a
+`ThemeStyle` tag and re-resolves on swap; a caller-supplied color gets *no*
+tag and is yours forever.
+
+- `createButton({ states: {...} })` — custom state colors don't re-theme;
+ omit `states` to get `themeButtonStates()` (the canonical
+ `control`-role states), which do.
+- `createButton({ text: { color } })` — an explicit label color skips the
+ `text`-role tag; omit `color` and the label follows the theme.
+- `createSlider({ trackVisual / fillVisual / handleVisual })` — same story per
+ part.
+
+Prefer tokens for anything that should follow dark/light; reserve explicit
+colors for genuinely fixed branding (a red "record" dot stays red in both
+themes).
+
+## Theming custom widgets
+
+To make your own composition behave like a built-in widget, do what the
+factories do: resolve from `themeColors()` / `themeType()` at build, then
+`markThemed` each entity with the roles you used.
+
+```typescript
+import type { World, Entity } from 'esengine';
+import { spawnUIEntity, markThemed, themeColors, themeType, px } from 'esengine';
+
+function createBadge(world: World, parent: Entity, label: string): Entity {
+ const c = themeColors();
+
+ const badge = spawnUIEntity({
+ world, parent,
+ node: { width: px(64), height: px(24) },
+ visual: { color: c.primary },
+ });
+ markThemed(world, badge, { visual: 'primary' });
+
+ const text = spawnUIEntity({
+ world, parent: badge,
+ text: { content: label, color: c.onPrimary, fontSize: themeType().label },
+ });
+ markThemed(world, text, { text: 'onPrimary' });
+
+ return badge;
+}
+```
+
+Now `switchTheme` re-tints the badge with everything else. For an interactive
+widget with `$interaction` color gears, tag the page→role map instead:
+`markThemed(world, entity, { states: { normal: 'control', hover: 'controlHover', pressed: 'controlActive' } })`.
+
+## Best practices
+
+- **Roles, not colors.** Reach for `themeColors().primary`, not a literal —
+ and tag it with `markThemed` so it survives a swap.
+- **Declare the base theme in Project Settings**, not in code —
+ the editor preview, and every export target then agree.
+- **Re-tint via overrides**: overriding `primary` (+ `primaryHover` /
+ `primaryActive`) in `features.ui.colors` re-brands the accent across every
+ widget with zero code.
+- **Only intentional constants opt out.** Passing an explicit color is a
+ contract that this element does *not* follow the theme — make sure that's
+ what you mean.
+- **Swap with `switchTheme`, not `setTheme`.** Bare `setTheme` only affects
+ widgets built afterwards; `switchTheme` also restyles what's on screen.
+
+## See also
+
+- [UI](/docs/guides/ui/) — the component model the tokens color.
+- [UI Components](/docs/guides/ui-components/) — the widget factories that consume tokens.
+- [UI Controllers](/docs/guides/ui-controllers/) — the `$interaction` gears that theme state colors ride on.
+- [Data Binding](/docs/guides/ui-binding/) — reactive values into component fields.
diff --git a/docs/astro/src/content/docs/guides/ui.mdx b/docs/astro/src/content/docs/guides/ui.mdx
index 139965217..a1ee0631a 100644
--- a/docs/astro/src/content/docs/guides/ui.mdx
+++ b/docs/astro/src/content/docs/guides/ui.mdx
@@ -1,6 +1,6 @@
---
title: UI
-description: The complete UI reference — the flexbox component model (UINode/FlexContainer), text, visuals, widgets, and interaction handling.
+description: The UI system overview — the flexbox component model, a pause-menu quickstart, how layout/visuals/interaction/widgets fit together, and a map of the UI guides.
---
import { Aside } from '@astrojs/starlight/components';
@@ -10,19 +10,22 @@ interface from UI components — visually in the editor or in code — and handl
interaction from your systems. There is **no `RectTransform`**: `UINode` is real
flexbox, sized with `px` / `percent` / `auto` plus `Absolute` insets.
+This page is the overview: the component model, a quickstart, and a map of the
+detailed UI guides. Deep reference for each area lives in its own chapter.
+
## The components
-| Component | Role |
-|---|---|
-| `UINode` | The layout box; holds the per-item flex fields (size, grow/shrink, margin, inset). |
-| `FlexContainer` | Lays a node's children out with flexbox (direction, justify, align, gap, padding). |
-| `Text` | Text via an SDF glyph atlas (content, font, color, align, stroke, shadow, rich text). |
-| `UIVisual` | The fill — solid color, texture, 9-slice, tiled, or filled. |
-| `UIMask` | Clips its children. |
-| `Interactable` | Marks a node hit-testable so it can be hovered/clicked. |
-| `UIInteraction` | Engine-written per-frame pointer state (read-only for your logic). |
+| Component | Role | Guide |
+|---|---|---|
+| `UINode` | The layout box; holds the per-item flex fields (size, grow/shrink, margin, inset). | [UI Layout](/docs/guides/ui-layout/) |
+| `FlexContainer` | Lays a node's children out with flexbox (direction, justify, align, gap, padding). | [UI Layout](/docs/guides/ui-layout/) |
+| `Text` | Text via a dynamic glyph atlas (content, font, color, align, stroke, shadow, rich text). | [UI Text](/docs/guides/ui-text/) |
+| `UIVisual` | The fill — solid color, texture, 9-slice, tiled, or filled. | below |
+| `UIMask` | Clips its children. | below |
+| `Interactable` | Marks a node hit-testable so it can be hovered/clicked. | [UI Interaction](/docs/guides/ui-interaction/) |
+| `UIInteraction` | Engine-written per-frame pointer state (read-only for your logic). | [UI Interaction](/docs/guides/ui-interaction/) |
-## Build a UI in code
+## Quickstart: a pause menu
A complete pause menu — a centered column panel with a title and a button — built
once from a **startup system**:
@@ -70,84 +73,37 @@ addStartupSystem(buildPauseMenu);
```
`spawnUIEntity({ world, parent?, node?, visual?, text? })` returns the entity; pass
-`parent` to nest. Sizes use the dimension helpers `px`, `percent`, `auto`. The other
-widget factories work the same way: `createToggle`, `createSlider`, `createProgress`,
-`createDialog`, `createDropdown`.
-
-<Aside type="tip">
- In the editor you build the same tree visually: add `UINode` entities, nest them,
- and add `FlexContainer` / `Text` / `UIVisual` / `Interactable` in the inspector.
-</Aside>
-
-## `UINode` — the layout box
-
-Per-item sizing and placement live here (dimensions are built with `px()` /
-`percent()` / `auto()`).
-
-| Property | Type | Default | Description |
-|---|---|---|---|
-| `position` | `UIPositionType` | `Relative` | `Relative` (in flow) or `Absolute` (placed by inset). |
-| `width` / `height` | Dimension | `auto` | Box size; `auto` = content-/flex-driven. |
-| `minWidth` / `minHeight` | Dimension | `auto` | Lower size bounds. |
-| `maxWidth` / `maxHeight` | Dimension | `auto` | Upper size bounds. |
-| `flexGrow` | number | `0` | Share of free space to absorb. |
-| `flexShrink` | number | `1` | Shrink factor when space is tight. |
-| `flexBasis` | Dimension | `auto` | Base size before grow/shrink. |
-| `alignSelf` | `AlignSelf` | `Auto` | Per-item cross-axis alignment override. |
-| `marginLeft/Top/Right/Bottom` | Dimension | `0` | Outer spacing. |
-| `insetLeft/Top/Right/Bottom` | Dimension | `auto` | Edge offsets when `Absolute`. |
-
-## `FlexContainer` — layout
-
-Add a `FlexContainer` to a node to lay out its children. The enums mirror CSS.
-
-| Property | Type | Default | Description |
-|---|---|---|---|
-| `direction` | `FlexDirection` | `Row` | `Row` / `Column` / `RowReverse` / `ColumnReverse`. |
-| `wrap` | `FlexWrap` | `NoWrap` | `NoWrap` / `Wrap`. |
-| `justifyContent` | `JustifyContent` | `Start` | Main-axis distribution (`Start`…`SpaceEvenly`). |
-| `alignItems` | `AlignItems` | `Stretch` | Cross-axis alignment (`Start` / `Center` / `End` / `Stretch`). |
-| `alignContent` | `AlignContent` | `Start` | Wrapped-line distribution. |
-| `gap` | Vec2 | `{0, 0}` | Space between children (x = column gap, y = row gap). |
-| `padding` | Padding | `{0,0,0,0}` | Inner spacing (`left/top/right/bottom`). |
-
-## `Text`
-
-Text draws from a dynamic glyph atlas with **two pipelines**, chosen per Text by
-`renderMode`:
-
-- **`Bitmap`** — glyphs rasterize at the **effective on-screen pixel size**
- (device pixels × the canvas design-resolution fit) with Canvas-native
- antialiasing and font hinting, and blit 1:1 — DOM-crisp at any window size.
-- **`Sdf`** — each glyph rasterizes once into a signed-distance field and the
- shader lays a **1px screen-space coverage ramp** on the edge (the
- msdfgen/TextMeshPro technique), so text stays crisp under **dynamic** scaling
- — animated zoom, scale tweens, world-space labels.
-- **`Auto`** (default) — bitmap while the entity itself is unscaled (the canvas
- fit is already compensated in the bitmap), SDF the moment the entity scales.
- DOM-crisp static UI *and* zoom-stable animated text, no configuration.
-
-| Property | Type | Default | Description |
-|---|---|---|---|
-| `content` | string | `''` | The string to display. |
-| `fontFamily` | string | `'Arial'` | Font family. |
-| `fontSize` | number | `24` | Size in pixels. |
-| `color` | Color | `{1,1,1,1}` | Text color. |
-| `align` | `TextAlign` | `Left` | Horizontal alignment. |
-| `verticalAlign` | `TextVerticalAlign` | `Top` | Vertical alignment. |
-| `wordWrap` | boolean | `true` | Wrap at the box width. |
-| `overflow` | `TextOverflow` | `Visible` | Overflow handling. |
-| `lineHeight` | number | — | Line spacing multiplier. |
-| `bold` / `italic` | boolean | `false` | Font style. |
-| `strokeColor` / `strokeWidth` | Color / number | — | Outline. |
-| `shadowColor` / `shadowBlur` / `shadowOffsetX` / `shadowOffsetY` | — | Drop shadow. |
-| `richText` | boolean | `false` | Parse inline rich-text markup. |
-| `renderMode` | `TextRenderMode` | `Auto` | Glyph pipeline: `Auto` / `Bitmap` / `Sdf` (see above). |
-| `enabled` | boolean | `true` | Render toggle (the editor's eye uses it too). |
-
-## `UIVisual` — the fill
-
-`UIVisual` draws the node's background. `visualType` selects the mode:
+`parent` to nest. Sizes use the dimension helpers `px`, `percent`, `auto` — all
+in **design pixels** (see [UI Layout](/docs/guides/ui-layout/#units-design-pixels)).
+The other widget factories work the same way: `createToggle`, `createSlider`,
+`createProgress`, `createDialog`, `createDropdown` — see
+[UI Components](/docs/guides/ui-components/).
+
+## How the pieces fit
+
+Each layer builds on the one before it:
+
+1. **Layout** — `UINode` boxes, solved by the flexbox engine; `FlexContainer`
+ arranges children, `Absolute` insets place overlays.
+ → [UI Layout](/docs/guides/ui-layout/)
+2. **Visuals & text** — `UIVisual` fills the box, `UIMask` clips, `Text` draws
+ crisp glyphs. → [UI Text](/docs/guides/ui-text/)
+3. **Interaction** — `Interactable` makes a box hit-testable; the engine writes
+ pointer state into `UIInteraction` and emits bubbling `UIEvents`; drag & drop
+ and keyboard focus sit on top. → [UI Interaction](/docs/guides/ui-interaction/)
+4. **Widgets** — factories (`createButton`, `createSlider`, …) compose the three
+ layers into ready-made controls; `createListView` adds virtualized lists.
+ → [UI Components](/docs/guides/ui-components/), [UI Lists](/docs/guides/ui-lists/)
+5. **Controllers** — a named "page" state per UI root with per-page field
+ bindings (tabs, button states, show/hide) — no code.
+ → [UI Controllers](/docs/guides/ui-controllers/)
+6. **Theme & binding** — design tokens skin every widget (live-switchable), and
+ reactive signals keep UI in sync with game state.
+ → [UI Theme](/docs/guides/ui-theme/), [UI Binding](/docs/guides/ui-binding/)
+
+### `UIVisual` and `UIMask`
+
+`UIVisual` draws the node's background; `visualType` selects the mode:
| `UIVisualType` | Uses | Description |
|---|---|---|
@@ -156,49 +112,50 @@ Text draws from a dynamic glyph atlas with **two pipelines**, chosen per Text by
| `Image` | `texture`, `uvOffset`, `uvScale` | Textured quad / sprite region. |
| `NineSlice` | `sliceBorder` | Scalable panel with fixed corners. |
| `Tiled` | `tileSize` | Texture repeated across the box. |
-| `Filled` | `fillAmount`, `fillMethod`, `fillOrigin` | Cropped fill (health/progress bars). |
+| `Filled` | `fillAmount`, `fillMethod`, `fillOrigin` | Cropped fill (health/progress bars, cooldown rings). |
-## Handling interaction
+`UIVisual.enabled` hides this entity's visual only; `UINode.display = None`
+removes the node **and its whole subtree** from layout, rendering, and
+hit-testing. Add `UIMask` to a node to clip its children to the box.
-`createButton` gives you `onClick` directly. For custom widgets, the hit-test system
-writes per-frame pointer state into `UIInteraction` on any entity with an
-`Interactable`. It is **read-only** — query it, never mutate it:
+## Editor or code
-```typescript
-import { defineSystem, Query, Interactable, UIInteraction } from 'esengine';
+Both author the **same components** — there is no separate editor format:
-const onTiles = defineSystem([Query(Interactable, UIInteraction)], (q) => {
- for (const [entity, _gate, state] of q) {
- if (state.justReleased) { /* this node was clicked */ }
- }
-});
-```
+- **Editor** — *Create… → UI* drops widget prefabs (Button, Toggle, Slider,
+ Dialog, …); nest by dragging, edit every field in Details, place with the
+ per-axis anchor picker, and preview against the project's design resolution
+ and device presets. See [The Editor](/docs/guides/editor/).
+- **Code** — `spawnUIEntity` + the widget factories, from a startup system as
+ above. Anything the editor writes, code can write too.
-| `UIInteraction` field | Description |
-|---|---|
-| `hovered` | The pointer is over the node. |
-| `pressed` | The pointer is held down on the node. |
-| `justPressed` | Became pressed this frame. |
-| `justReleased` | Released this frame (a click). |
+## Where to go next
-For bubbling events — `click`, `hover_enter`, `change`, `submit`, `drag` up the
-parent chain — read the `UIEvents` resource (the UI event bus).
+| You want to… | Open |
+|---|---|
+| Size and place boxes — `px`/`percent`/`auto`, flexbox, absolute insets, anchors | [UI Layout](/docs/guides/ui-layout/) |
+| Draw text — fonts, SDF/bitmap crispness, wrapping, rich text | [UI Text](/docs/guides/ui-text/) |
+| React to pointer & keyboard — clicks, `UIEvents`, drag & drop, focus | [UI Interaction](/docs/guides/ui-interaction/) |
+| Use ready-made controls — button, toggle, slider, dialog, dropdown, input | [UI Components](/docs/guides/ui-components/) |
+| Show scrolling data — virtualized lists and grids | [UI Lists](/docs/guides/ui-lists/) |
+| Skin everything — design tokens, project theme, live switching | [UI Theme](/docs/guides/ui-theme/) |
+| Keep UI in sync with game state — signals, `bind`, two-way widget binding | [UI Binding](/docs/guides/ui-binding/) |
+| Share state across elements — tabs, radio groups, page-driven visuals | [UI Controllers](/docs/guides/ui-controllers/) |
## Best practices
- **Flex, not absolute** — lay out with `FlexContainer` + `flexGrow`; reserve
`Absolute` insets for overlays and badges.
-- **Size with `percent` / `auto`** for resolution independence; hard `px` only where
- a fixed size is intended.
+- **Size with `percent` / `auto`** for resolution independence; hard `px` only
+ where a fixed size is intended.
- **Drive logic from `UIInteraction` or `UIEvents`**, never by mutating them.
-- **Reuse the widget factories** (`createButton`, `createSlider`, …) for consistent
- state visuals instead of wiring hover/press by hand.
+- **Reuse the widget factories** for consistent state visuals instead of wiring
+ hover/press by hand.
- **9-slice panels** (`NineSlice`) keep borders crisp at any size.
## See also
-- [UI Components](/docs/guides/ui-components/) — the built-in widget factories.
-- [UI Controllers](/docs/guides/ui-controllers/) — shared "page" state + declarative per-page field bindings (tabs, button states, show/hide).
- [Input](/docs/guides/input/) — raw keyboard/mouse/touch below the UI layer.
- [Localization](/docs/guides/localization/) — bind `Text.content` to translated keys.
- [Animation](/docs/guides/animation/) — tween UI color/position for juice.
+- [The Editor](/docs/guides/editor/) — visual authoring, prefabs, anchor picker.
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx
new file mode 100644
index 000000000..224aeeb05
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/app-lifecycle.mdx
@@ -0,0 +1,352 @@
+---
+title: 应用设置与生命周期
+description: Estella 的 App 如何启动、默认安装哪些插件、它的公开接口、生命周期事件、子系统可观测性、侧模块与热重载。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Estella 里的一切都跑在一个 **`App`** 之中——它是持有[世界](/docs/zh-cn/core-concepts/ecs/)、
+资源、系统调度与帧循环的容器。编辑器的播放模式、导出的 Web/桌面游戏、微信小游戏、
+以及无头(headless)权威服务器,构建的都是*同一个* `App` 类;不同的只是组装它的工厂。
+本页是这些工厂与应用运行时接口的参考手册。
+
+<Aside type="note">
+ 在编辑器驱动的项目里你几乎不用亲手构造 `App`——导出的运行时会替你完成。
+ 当你要把引擎嵌入自己的宿主页面、运行无头服务器、编写插件、或想在运行时拿到
+ 生命周期与健康信号时,再来读这一页。
+</Aside>
+
+## `createWebApp(module, options)`
+
+面向浏览器(或 Electron)游戏的"全家桶"入口。它接收已实例化的引擎 wasm 模块
+(`ESEngineModule`),初始化渲染器,并安装完整插件栈:
+
+```typescript
+import { createWebApp } from 'esengine';
+
+const app = createWebApp(module, {
+ wasmBaseUrl: '/engine', // where physics.wasm / spine42.wasm live
+ colorSpace: 'linear',
+ getViewportSize: () => ({ width: innerWidth, height: innerHeight }),
+});
+await app.run();
+```
+
+### `CreateWebAppOptions`
+
+所有字段都是可选的。`CreateWebAppOptions` 在 `WebAppOptions` 之上(两者都可从
+`esengine` 导入)多了一个 `wasmBaseUrl`:
+
+| 选项 | 类型 | 默认 | 含义 |
+|---|---|---|---|
+| `wasmBaseUrl` | `string` | — | [侧模块](#侧模块)产物(`physics.wasm`、`spine38.js`/`.wasm`……)的服务基址——通常就是 `esengine.wasm` 所在目录。设置后(且未显式给出 `sideModules`)会自动构建一个 fetch 传输的 `SideModuleHost`。 |
+| `sideModules` | `SideModuleHost` | 由 `wasmBaseUrl` 构建,否则无 | 该 realm 的可选原生模块获取器。内联模块的 realm(Playable、微信)直接传 host 而不是 URL。 |
+| `plugins` | `Plugin[]` | `[]` | 额外插件,追加在默认集合**之后**。 |
+| `getViewportSize` | `() => { width, height }` | — | 视口尺寸回调,供相机系统使用(也是 WebGPU 初始化尺寸;缺省时为 `800×600`)。 |
+| `glContextHandle` | `number` | — | 预注册的 WebGL2 上下文句柄;不传则模块通过 `initRenderer()` 自建上下文。 |
+| `backend` | `'webgl2' \| 'webgpu'` | `'webgl2'` | `'webgpu'` 走注入设备路径——宿主必须先取得 `GPUDevice` 并在实例化前作为模块工厂的 `preinitializedWebGPUDevice` 传入。 |
+| `canvasSelector` | `string` | `'#canvas'` | WebGPU 交换链画布的 CSS 选择器(必须已在 DOM 中)。WebGL 忽略它。 |
+| `colorSpace` | `'gamma' \| 'linear'` | `'gamma'` | 项目色彩空间。`'linear'` 在线性光下渲染(采样时 sRGB 解码、线性混合、最终 blit 显式编码)。必须**在创建应用时**声明——着色器按它编译。 |
+| `ySortLayers` | `number` | `0` | 渲染层位掩码(bit 0–31):层内按世界 Y 排序(俯视遮挡)。 |
+| `screenFit` | `ScreenScalingData` | 关(`scaleMode: -1`) | 项目相机适配:把设计分辨率 letterbox 进实际宽高比。仅当 `scaleMode` 为真实模式(≥ 0)时安装;`SCREEN_FIT_OFF`(-1)保持旧行为(有 Canvas 用 Canvas 适配,否则用原始 orthoSize)。 |
+
+### 它安装什么
+
+`createWebApp` 先接线核心(面向渲染器的)插件,再装完整内容栈,顺序如下:
+
+1. **核心**:`corePlugin`(渲染 facade)、相机插件、`assetPlugin`、
+ `prefabsPlugin`、`inputPlugin`、`sceneManagerPlugin`——外加一个新的
+ `RenderPipeline`。
+2. **UI**:`uiPlugins`——组合好的 UI 管线(布局、文本、文本输入、遮罩、
+ 渲染排序、交互、拖拽、焦点、安全区)。
+3. **基础内容**:`timerPlugin`、`lifecyclePlugin()`、`animationPlugin`、
+ `audioPlugin`、`videoPlugin`、`particlePlugin`、`trailPlugin`、
+ `mesh2dPlugin`、`tilemapPlugin`、`postProcessPlugin`、`timelinePlugin`、
+ `perceptionPlugin`、`fsmPlugin`、`btPlugin`、`navPlugin`、
+ `replicationPlugin`。
+4. **Spine**:一个 `SpinePlugin` 实例(按需从 `app.sideModules` 拉取对应版本
+ 的 wasm 运行时——场景不用 Spine 就什么也不加载)。
+5. **你的 `plugins`**,按给出顺序。
+
+物理**不在**默认集合里:`PhysicsPlugin` 需要物理 wasm 模块。发行运行时会在项目
+声明了物理、或场景含有物理组件时,自动从侧模块 host 获取 `'physics'` 并安装插件;
+手动组装时请自己构造 `PhysicsPlugin`(它和 `loadPhysicsModule` 都从 `esengine`
+导出;完整 API 在 `esengine/physics` 子路径上)。
+
+## 无头应用
+
+`createHeadlessApp(module, options)` 构建一个**只有完整模拟栈、没有任何呈现**的
+应用——没有渲染器、没有渲染管线、没有输入设备、没有 UI。这就是权威服务器的形态
+(同一个 wasm 模块、同一份玩法代码、同一个固定步循环),也适用于 worker 和测试:
+
+```typescript
+import { createHeadlessApp, runHeadless } from 'esengine';
+
+const app = createHeadlessApp(module, { plugins: [gameplayPlugin] });
+const stop = runHeadless(app, { fps: 60 });
+// … later
+stop();
+```
+
+`HeadlessAppOptions` 只有两个字段,均可选:
+
+| 选项 | 类型 | 含义 |
+|---|---|---|
+| `plugins` | `Plugin[]` | 你的玩法插件,追加在基础集合之后。 |
+| `sideModules` | `SideModuleHost` | 可选原生模块获取器(服务器上的物理)。 |
+
+包含:`assetPlugin`、`prefabsPlugin`、`sceneManagerPlugin`、`timerPlugin`、
+`lifecyclePlugin()`、`audioPlugin`(无音频设备的宿主上静音),以及游戏 AI /
+复制集合(`perceptionPlugin`、`fsmPlugin`、`btPlugin`、`navPlugin`、
+`replicationPlugin`)。
+
+不包含——一切*为了被看见*而存在的东西:`corePlugin`(它接线的渲染 facade 只在
+`initRenderer()` 之后才存在)、UI、粒子、tilemap 渲染、后处理、时间轴、Spine、
+输入。
+
+`runHeadless(app, { fps? })` 用挂钟 `setInterval` 驱动应用(服务器上没有
+`requestAnimationFrame`),默认 60 fps。delta 是实测的,所以固定步累加器能在
+定时器抖动下保持模拟节奏精确;慢的异步 tick 不会重入堆积。它返回一个停止函数。
+你也可以用 `app.tick(dt)` 手动驱动。
+
+<Aside type="caution">
+ `createHeadlessApp` 和 `runHeadless` 是 `@beta`:无头资产方案(不带纹理的
+ 玩法数据)仍在收敛,这些工厂的选项可能变化。
+</Aside>
+
+## 插件模型
+
+插件就是一个在应用上注册系统与资源的普通对象:
+
+```typescript
+import type { App, Plugin } from 'esengine';
+import { defineResource, defineSystem, Res } from 'esengine';
+
+const Score = defineResource({ value: 0 }, 'Score');
+const scoreSystem = defineSystem([Res(Score)], (score) => { /* … */ });
+
+export const scorePlugin: Plugin = {
+ name: 'score',
+ build(app: App) {
+ app.insertResource(Score, { value: 0 });
+ app.addSystem(scoreSystem);
+ },
+};
+```
+
+| 成员 | 类型 | 含义 |
+|---|---|---|
+| `name` | `string?` | 可选但推荐:具名插件会自动注册进[子系统注册表](#子系统可观测性),且 `build()` 里添加的系统继承该名字用于存活性归因。 |
+| `dependencies` | `PluginDependency[]?` | 前置条件,每项是插件**名**(`string`)或**资源定义**。缺失时 `addPlugin` 抛错;`addPlugins` 还会用名字边为整批排序。 |
+| `before` / `after` | `string[]?` | 相对其他插件名的软排序提示,在 `addPlugins` 批量安装时生效。 |
+| `build(app)` | 必需 | 注册系统、资源与事件。`addPlugin` 时立即执行。 |
+| `finish(app)` | 可选 | 在**所有**插件 build 完、应用首次 tick/run 时执行一次——用于需要完整集合的接线。 |
+| `cleanup(app?)` | 可选 | `app.quit()` 时按安装逆序执行。 |
+
+`PluginDependency = string | ResourceDef<any>`——名字断言安装顺序;资源定义
+断言该资源已存在。
+
+安装:`app.addPlugin(plugin)`(按实例幂等——同一对象加两次是 no-op),或
+`app.addPlugins([...])`——后者按 `dependencies` / `before` / `after` 对整批做
+拓扑排序,遇环抛错。若 `build()` 抛错,插件会被回滚,失败以 `error` 条目的形式
+留在子系统注册表里可见。
+
+**`flushPendingSystems(app)`**——模块级的 `addSystem` / `addStartupSystem` /
+`defineBehavior` 调用(在 import 时、任何插件之外发生)排队在环境上下文里,而
+不是某个具体应用上。工厂对应的运行时会替你把队列灌进应用;当你手动搭一个裸
+`App` 又想要这些模块级注册时,自己调用 `flushPendingSystems`。
+
+## `App` 的接口
+
+面向用户导出的成员,分组如下:
+
+### 世界、资源、模块
+
+| 成员 | 含义 |
+|---|---|
+| `app.world` | ECS `World`——实体、组件、查询。 |
+| `app.insertResource(def, value)` / `app.getResource(def)` / `app.hasResource(def)` | 系统经 `Res(...)` 读取的资源存储。对从未插入过的资源,`getResource` 会安装并返回其定义的默认值——用 `hasResource` 区分。 |
+| `app.wasmModule` | 已连接的 `ESEngineModule`,`connectCpp` 之前为 `null`。 |
+| `app.pipeline` | `RenderPipeline`,无头应用里为 `null`。 |
+| `app.subsystems` | 该应用专属的 [`SubsystemRegistry`](#子系统可观测性)。 |
+| `app.sideModules` | 该 realm 的 [`SideModuleHost`](#侧模块),或 `null`(没有它的无头/测试应用)。 |
+| `app.getPlugin(Ctor)` | 已安装的某个类插件实例(若有)。 |
+
+### 系统与事件
+
+| 成员 | 含义 |
+|---|---|
+| `app.addSystem(sys)` | 注册到 `Schedule.Update`。 |
+| `app.addStartupSystem(sys)` | 注册到 `Schedule.Startup`(只跑一次,在首帧各调度之前)。 |
+| `app.addSystemToSchedule(schedule, sys, { runBefore?, runAfter?, runIf? })` | 任意调度,带排序边和运行条件。 |
+| `app.addSystemSet(set)` / `app.addSystemSetToSchedule(schedule, set)` | 注册整个 `SystemSet`;成员继承集合的 `runIf` 与排序,其他系统可用集合名对其排序。 |
+| `app.removeSystem(systemId)` | 按系统定义的 `_id` symbol 移除。 |
+| `app.addEvent(eventDef)` | 注册事件通道(双缓冲;每帧交换)。 |
+
+### 帧循环
+
+| 成员 | 含义 |
+|---|---|
+| `app.run()` | 启动 `requestAnimationFrame` 循环。 |
+| `app.tick(delta)` | 恰好推进一帧(秒)——无头与测试宿主的驱动方式。 |
+| `app.quit({ keepRenderer? })` | 停止、按逆序执行插件 `cleanup`、销毁所有实体、拆掉渲染器(`keepRenderer` 时跳过,热重载用)。 |
+| `app.setFixedTimestep(s)` / `app.getFixedTimestep()` | `FixedUpdate` 节奏。默认 `1/60`。 |
+| `app.setMaxDeltaTime(s)` | 单帧 delta 的钳制上限。默认 `0.25`。 |
+| `app.setMaxFixedSteps(n)` | 每帧固定步追赶的上限。默认 `8`。此外还有时间预算封顶追赶,过重的模拟会退化为慢动作而不是卡死。 |
+| `app.setPaused(v)` / `app.isPaused()` | 用户暂停。暂停期间只有 `Schedule.Last` 运行。 |
+| `app.stepFrame()` | 在暂停时排入恰好一整帧(编辑器"步进")。 |
+| `app.setPlaySpeed(x)` / `app.getPlaySpeed()` | 时间缩放,钳制在 `0.1`–`4.0`。默认 `1.0`。 |
+| `app.setTargetFrameRate(fps)` / `app.getTargetFrameRate()` | 帧率上限;`0`(默认)= 不封顶(vsync)。 |
+
+一帧之内调度的运行顺序是:`First` → 固定三件套(`FixedPreUpdate` /
+`FixedUpdate` / `FixedPostUpdate`,由累加器决定跑零到多次)→ `PreUpdate` →
+`Update` → `PostUpdate` → `Last`。`Startup` 系统在首帧之前冲刷。
+
+### 错误、物理、统计
+
+| 成员 | 含义 |
+|---|---|
+| `app.onError(fn)` | 观察任何系统抛错(`(error, systemName)`)。 |
+| `app.onSystemError(fn)` | 逐次抛错决策:返回 `'continue'` 或 `'pause'`(暂停本帧余下部分)。 |
+| `app.onWasmError(fn)` | 观察跨 wasm 桥的错误。 |
+| `app.waitForPhysics()` / `app.isPhysicsReady` | 等待 / 查询异步的物理 wasm 初始化(没装 `PhysicsPlugin` 时为 no-op / `false`)。 |
+| `app.enableStats()` | 开启计时采集。 |
+| `app.getSystemTimings()` / `app.getPhaseTimings()` / `app.getFrameScopes()` | 本帧的逐系统 / 逐调度 / 子帧 CPU 计时(统计关闭时为 `null`)。 |
+| `app.measureFrameScope(name, fn)` | 把 `fn` 作为具名子帧作用域计时(统计关闭时只花一次分支的 no-op)。 |
+| `app.getEntityCount()` | 存活实体数。 |
+
+## 生命周期事件
+
+`lifecyclePlugin(options?)`(两个工厂都默认安装)发布 **`Lifecycle`** 资源——
+一个跟踪页面可见性/焦点、并能自动暂停游戏的 `LifecycleManager`:
+
+```typescript
+import { Lifecycle } from 'esengine';
+
+const lifecycle = app.getResource(Lifecycle);
+const off = lifecycle.on((event) => {
+ if (event === 'pause') saveGame();
+});
+```
+
+| 成员 | 类型 | 含义 |
+|---|---|---|
+| `visible` | `boolean` | 当前页面/应用可见性。 |
+| `focused` | `boolean` | 窗口焦点(会跟踪;变化不发事件)。 |
+| `autoPause` | `boolean` | 页面隐藏时是否暂停应用。默认 `true`;运行时可写,初值来自 `lifecyclePlugin({ autoPause })`。 |
+| `on(listener)` / `off(listener)` | — | 订阅事件;`on` 返回退订函数。 |
+
+`LifecycleEvent` 是 `'show' | 'hide' | 'pause' | 'resume'`,`LifecycleListener`
+是 `(event: LifecycleEvent) => void`。语义如下:
+
+- **`hide` / `show`** 在每次可见性变化时触发(浏览器的 `visibilitychange`;
+ 微信上的 `wx.onHide` / `wx.onShow`)。
+- **`pause`** 只在生命周期真的暂停了应用时触发:页面隐藏、`autoPause` 开着、
+ 且应用并非已暂停。**`resume`** 只在生命周期解除*它自己*的暂停时触发——手动
+ `app.setPaused(true)` 绝不会被页面重新可见而覆盖。
+- 无头宿主(Node、worker)没有可见性信号;资源仍然存在,保持 `visible`。
+
+## 子系统可观测性
+
+每个应用都在 `app.subsystems` 挂着一个 **`SubsystemRegistry`**,回答"哪些引擎
+模块已加载、就绪、在推进、或出错了"。具名插件自动注册;异步插件(物理)自己
+驱动 `initializing → ready`/`error` 的转移。
+
+```typescript
+for (const s of app.subsystems.getStatuses()) {
+ console.log(s.id, s.phase, s.activity, s.lastError ?? '');
+}
+```
+
+- **`SubsystemPhase`**——记录的生命周期:`'registered'` → `'initializing'` →
+ `'ready'`,`'error'` 为终态。
+- **`SubsystemActivity`**——存活性,*读取时*由看门狗心跳推导(每次系统运行会
+ "喂"其所属插件):`'stepping'`(400 ms 内有心跳)、`'idle'`(就绪但心跳过期
+ ——例如编辑态被冻结的物理)、`'inactive'`(从未有过心跳;存活性未知)。
+ 加载 ≠ 运行——这正是编辑器状态 UI 展示的区分。
+- **`SubsystemStatus`**——每个子系统一条,按安装顺序:`id`、`displayName`、
+ `phase`、`activity`、`detail`、`lastError`(后续转移后仍保留)、`dependsOn`
+ (声明的插件名依赖,用于级联上下文)、`phaseAgeMs`。
+- **`SubsystemEvent`**——一次记录下的转移(`id`、`phase`、`detail?`、`atMs`、
+ `seq`);`recentEvents(limit?)` 返回保留的尾部(上限 128 条)。
+- `subscribe(fn)` 在相位转移时通知(不逐心跳),返回退订函数。
+
+注册表是按应用(按 realm)的——编辑器的编辑与播放 realm 各自独立上报。
+
+## 侧模块
+
+可选的原生子系统以**独立 wasm 模块**按需加载,让基础引擎下载体积保持小:物理
+(Box2D)、逐版本的 Spine 运行时、Basis Universal 纹理转码器、软件视频解码器。
+每个都是一对 emscripten 产物——`<file>.js` 胶水加 `<file>.wasm`——统一经由
+`SideModuleHost` 获取;各 realm 之间只有*传输方式*不同。
+
+**`SIDE_MODULES`** 是 id 到产物映射的单一权威源:
+
+| `SideModuleId` | 产物 | 内容 |
+|---|---|---|
+| `'physics'` | `physics.js` / `.wasm` | Box2D 物理。 |
+| `'spine:3.8'` / `'spine:4.1'` / `'spine:4.2'` | `spine38` / `spine41` / `spine42` 的 `.js`/`.wasm` | 每个骨骼格式版本一份 Spine 运行时。 |
+| `'basis'` | `basis.js` / `.wasm` | Basis Universal KTX2 转码器(压缩纹理)。 |
+| `'videodec'` | `videodec.js` / `.wasm` | MPEG-1 软件视频解码器。 |
+
+`SPINE_VERSIONS` 是只读列表 `['3.8', '4.1', '4.2']`,`spineModuleId(version)`
+构造对应的 id。
+
+host 用 `acquire(id)` 应答,返回已实例化模块的 promise(按 id 缓存,失败也以
+`null` 缓存,缺失的产物不会被反复重新拉取)。内置传输:
+
+- **`createFetchSideModuleHost(baseUrl)`**——从基址 fetch 胶水与 wasm
+ (`wasmBaseUrl` 构建的就是它);编辑器、Web 与桌面使用。
+- **`createEmbeddedSideModuleHost(...)`**——模块以 base64 内联(Playable 广告)。
+- **`createWeChatSideModuleHost(...)`**——微信的预编译模块工厂。
+
+你通常永远不用自己调 `acquire`——设置好 `app.sideModules`(经 `wasmBaseUrl`
+或 `sideModules`),Spine 插件和物理安装会在需要时从中拉取。
+
+<Aside type="note">
+ 主 `esengine` barrel 恰好镜像了物理/Spine 的**接线**层——`PhysicsPlugin`、
+ `PhysicsEvents`、`Physics`、`loadPhysicsModule`、`SpinePlugin`、
+ `SpineEvents`、`Spine`——宿主无需子路径导入即可注册这些插件。完整 API 在
+ `esengine/physics` 与 `esengine/spine` 子路径上。见[物理](/docs/zh-cn/guides/physics/)
+ 与 [Spine](/docs/zh-cn/guides/spine/)。
+</Aside>
+
+## 热重载
+
+当你在编辑器播放时修改项目代码,编辑器会先尝试**保状态热替换**,失败才退回
+整体重载。它通过 **`probeRegistrations(register)`** 在隔离的探针上下文里重新
+import 你的 bundle,返回一个 `ProbedRegistrations`:
+
+- `fingerprint`——bundle 声明的用户组件**模式**摘要(形状,不含值)。指纹不变
+ → 保留存活的 `World`,只原位替换系统函数体;变了 → 整体重载。
+- `pending`——bundle 排队的系统,喂给 `App.hotSwapSystems`(若有用户系统被
+ 增、删或改名,替换会被拒绝——同样强制整体重载)。
+
+你的代码需要遵守的:**组件身份按名字稳定**。重新 import 后再次运行的
+`defineComponent('Health', …)` 解析到*同一个*组件身份,因此重新导入的系统的
+查询能命中存活的存储。相应地,给组件或 behavior 改名是结构性变更(整体重载 +
+该数据的状态丢失),且重载后每实体的 `start` 钩子会再次运行——请把它写成幂等
+的初始化(见[脚本](/docs/zh-cn/guides/scripting/))。
+
+## 最佳实践
+
+- **优先用工厂。**`createWebApp` / `createHeadlessApp` 编码了受支持的插件顺序;
+ 手搓 `App.new()` 加插件列表是引擎嵌入方的事。
+- **给插件起名。**一个 `name` 零成本却买来可观测性:子系统注册表条目、插件系统
+ 的存活性归因、可用的依赖报错。
+- **前置声明 `colorSpace` 和 `backend`。**两者都在创建时固化(着色器编译、设备
+ 注入)——不能在存活应用上切换。
+- **别和生命周期自动暂停较劲。**用 `lifecyclePlugin({ autoPause: false })`(或
+ `lifecycle.autoPause = false`)关掉它,而不是在监听器里解除暂停;manager 只会
+ 解除它自己造成的暂停。
+- **"X 加载了吗?"走 `app.subsystems`。**它区分*已加载*与*在运行*(`phase` 与
+ `activity`),并保留最后一次错误——比探测资源更靠谱。
+
+## 另请参阅
+
+- [插件与资源](/docs/zh-cn/core-concepts/plugins-resources/)——用 `Res(...)`
+ 触达子系统 API。
+- [系统](/docs/zh-cn/core-concepts/systems/)——调度与系统参数。
+- [构建与导出](/docs/zh-cn/guides/build-export/)——侧模块产物在各目标如何发布。
+- [物理](/docs/zh-cn/guides/physics/)与 [Spine](/docs/zh-cn/guides/spine/)——
+ 侧模块背后的两个子路径 API。
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/screen.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/screen.mdx
new file mode 100644
index 000000000..ea7a28998
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/screen.mdx
@@ -0,0 +1,306 @@
+---
+title: 屏幕与设计分辨率
+description: 一个设计分辨率如何映射到每一块真实屏幕——Canvas 组件、缩放模式、相机适配与 ScreenScaling、UI 布局像素、ScreenInfo、安全区与像素完美渲染。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+你按**一个设计分辨率**(默认 1920×1080)制作游戏,引擎负责把这个盒子适配到游戏实际运行的
+任何屏幕上。本页是这条管线的完整参考:单位模型、`Canvas` 组件、每个缩放模式及实际数字、
+项目级 `ScreenScaling` 适配、UI 像素为何稳定、响应尺寸与方向变化、设备安全区,以及相机的
+`pixelPerfect` 开关。
+
+## 世界单位就是设计像素
+
+Estella 的 2D 单位模型刻意保持简单:
+
+- **1 世界单位 = 1 设计像素。**一张 100×200 纹理生成一个 100×200 的精灵;`px(300)` 的
+ `UINode` 宽 300 设计像素。
+- 默认场景相机的 `orthoSize` 是 `designResolution.y / 2` = **540**——设计高度的一半——
+ 所以在设计宽高比下,相机恰好显示一个设计盒(1920×1080 世界单位)。
+- 世界是 **Y 向上**;屏幕坐标是 **Y 向下**(由
+ [`CameraView`](/docs/zh-cn/guides/camera/) 为你转换)。
+- `Canvas.pixelsPerUnit`(默认 `100`)是**物理缩放**——每 Box2D 米的世界像素数——
+ **不是**显示缩放。渲染从不除以它。
+
+当实际屏幕的宽高比与设计分辨率不同,由**缩放模式**决定如何适配设计盒——它缩放的是
+*可见盒*,而不是你的内容:精灵保持像素尺寸,位置一动不动。
+
+## `Canvas` 组件
+
+每个场景有一个实体携带 `Canvas`——设计分辨率及其适配方式的声明。编辑器建场景时会自动种下它;
+引擎使用找到的第一个 `Canvas`。
+
+| 属性 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `designResolution` | Vec2 | `{x: 1920, y: 1080}` | 设计(参考)分辨率,像素——你制作时对照的盒子。 |
+| `pixelsPerUnit` | number | `100` | 每物理米的世界像素数(Box2D + 瓦片碰撞体缩放)。最小 `1`。不是显示缩放。 |
+| `scaleMode` | `ScaleMode` | `FixedHeight` | 设计分辨率如何适配实际屏幕宽高比(见下)。 |
+| `matchWidthOrHeight` | number | `0.5` | `Match` 模式的混合值,0–1:`0` = 适配宽度,`1` = 适配高度。其余模式忽略。 |
+| `backgroundColor` | Color | `{r:0, g:0, b:0, a:1}` | 为设计盒之外的 letterbox/pillarbox 区域声明的背景色。 |
+
+```typescript
+import { defineSystem, GetWorld, Canvas } from 'esengine';
+
+const readCanvas = defineSystem([GetWorld()], (world) => {
+ const [canvasEntity] = world.getEntitiesWithComponents([Canvas]);
+ if (canvasEntity === undefined) return;
+
+ const canvas = world.get(canvasEntity, Canvas);
+ const designW = canvas.designResolution.x; // 1920
+ const designH = canvas.designResolution.y; // 1080
+});
+```
+
+<Aside type="note">
+ `pixelsPerUnit` 只喂给物理和瓦片碰撞体:默认 `100` 时,一个 100 像素的箱子就是一个
+ Box2D 米,让物理保持在求解器调优的数值范围内。改它会重新缩放碰撞体尺寸和重力手感——
+ 而不是任何东西的外观。
+</Aside>
+
+## 缩放模式
+
+适配数学是一个纯函数,导出为 `computeEffectiveOrthoSize`。给定设计盒与实际屏幕宽高比,
+它产出**有效正交半高**——相机将显示的世界盒高度的一半,单位是世界单位(设计像素)。
+存在两个候选答案:
+
+- `orthoForWidth = (designResolution.y / 2) × designAspect / actualAspect`——让设计
+ **宽度**恰好铺满屏幕的半高。
+- `orthoForHeight = designResolution.y / 2`——让设计**高度**恰好铺满屏幕的半高。
+
+每个 `ScaleMode` 在二者之间选择:
+
+| `ScaleMode` | 值 | 有效半高 | 行为 |
+|---|---|---|---|
+| `FixedWidth` | `0` | `orthoForWidth` | 设计宽度总是恰好铺满屏幕。更高的屏幕在上下露出额外世界;更宽的屏幕裁掉上下。 |
+| `FixedHeight` | `1`(默认) | `orthoForHeight` | 设计高度总是恰好铺满屏幕。更宽的屏幕在两侧露出额外世界;更窄的屏幕裁掉两侧。 |
+| `Expand` | `2` | `max(orthoForWidth, orthoForHeight)` | **整个设计盒始终可见**;适配更松的轴在盒外露出额外世界。安全:设计内的东西永不被裁。 |
+| `Shrink` | `3` | `min(orthoForWidth, orthoForHeight)` | **屏幕始终被设计盒填满**;溢出的轴被裁剪。永不露出设计盒之外的内容。 |
+| `Match` | `4` | `orthoForWidth^(1−t) × orthoForHeight^t` | 按 `matchWidthOrHeight`(`t`)几何混合:`0` 表现同 `FixedWidth`,`1` 同 `FixedHeight`,`0.5` 取中。 |
+
+`ScaleMode` 对象上还有两个 Cocos 风格的别名(是*相同的值*,不是额外模式):
+`ScaleMode.ShowAll === ScaleMode.Expand`、`ScaleMode.NoBorder === ScaleMode.Shrink`。
+
+```typescript
+import { computeEffectiveOrthoSize, ScaleMode } from 'esengine';
+
+const halfH = computeEffectiveOrthoSize(
+ 540, // baseOrthoSize = designResolution.y / 2
+ 1920 / 1080, // design aspect (≈ 1.778)
+ 1024 / 768, // actual screen aspect (4:3 ≈ 1.333)
+ ScaleMode.Expand,
+ 0.5, // matchWidthOrHeight (Match mode only)
+);
+// halfH === 720 → the camera shows 1920 × 1440 design pixels
+```
+
+### 实际例子——1920×1080 设计放到 4:3 屏幕
+
+在 1024×768(4:3)屏幕上,`orthoForWidth = 540 × (16/9)/(4/3) = 720`,
+`orthoForHeight = 540`:
+
+| 模式 | 半高 | 可见世界盒(设计像素) | 后果 |
+|---|---|---|---|
+| `FixedWidth` | `720` | 1920 × 1440 | 完整设计宽度;上*和*下各露出 180 额外世界像素。 |
+| `FixedHeight` | `540` | 1440 × 1080 | 完整设计高度;**左右各裁掉** 240 设计像素。 |
+| `Expand` / `ShowAll` | `720` | 1920 × 1440 | 整个设计盒可见;上下露出额外世界(此屏幕上等同 `FixedWidth`——在*更宽*的屏幕上则等同 `FixedHeight`)。 |
+| `Shrink` / `NoBorder` | `540` | 1440 × 1080 | 屏幕填满,不露出设计盒之外的内容;两侧被裁。 |
+| `Match`(t = 0.5) | `≈ 623.5` | ≈ 1663 × 1247 | 折中:两侧轻微裁剪,*同时*上下轻微露出。 |
+
+<Aside type="tip">
+ 相机视口总是填满其屏幕矩形——没有模式会渲染真正的黑边。这里的"letterbox"意味着
+ **设计盒之外的额外世界变得可见**。用 `Expand` 时,把背景画到设计框之外去;你放在那里的
+ 东西,就是其他宽高比玩家看到的东西。`Canvas.backgroundColor` 为盒外区域声明颜色。
+</Aside>
+
+## 相机如何参与
+
+适配并不作用于相机自己写的 `orthoSize`——它作用于 `designResolution.y / 2`。相机插件
+每帧按此顺序解析**适配源**:
+
+1. **`ScreenScaling`**(项目级适配,见下),当其 `scaleMode` 是真实模式(`≥ 0`)时——
+ 权威,完全不需要 UI;
+2. 否则,场景的 **`Canvas`** 组件(若存在);
+3. 否则**无适配**——相机按原始 `orthoSize` 渲染。
+
+<Aside type="caution">
+ 适配源生效期间,主相机自己写的 `orthoSize` **不会被使用**——可见半高完全来自设计分辨率
+ 与缩放模式。通过编辑/tween `orthoSize` 缩放,只在没有适配源时生效(场景无 `Canvas`
+ 且项目适配关闭)。
+</Aside>
+
+默认场景相机写的正是 `orthoSize: 540 = designResolution.y / 2`,所以有无适配的视图在设计
+宽高比下一致:无论适配开关,1920×1080 的窗口都恰好显示一个设计盒。
+
+## 项目级适配:`ScreenScaling` 资源
+
+`ScreenScaling` 把设计分辨率适配变成*项目*概念而非 UI 概念——没有 `Canvas`(没有 UI)的
+场景照样正确 letterbox。它是**项目设置 → 显示 → 相机适配**的运行时映像。
+
+| 字段 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `designWidth` | number | `1920` | 设计(参考)分辨率宽度,像素。 |
+| `designHeight` | number | `1080` | 设计(参考)分辨率高度,像素。 |
+| `scaleMode` | number | `SCREEN_FIT_OFF`(`-1`) | 真实的 `ScaleMode`(`0`–`4`)**开启**项目适配;`SCREEN_FIT_OFF` 保持旧行为(有 Canvas 用 Canvas 适配,否则原始 `orthoSize`)。 |
+| `matchWidthOrHeight` | number | `0.5` | `Match` 模式混合值 0–1(`0` = 适配宽度,`1` = 适配高度);其余模式忽略。 |
+
+`DEFAULT_SCREEN_SCALING` 就是这个默认关闭的值,`SCREEN_FIT_OFF`(`-1`)是哨兵值。项目
+适配开启时,它**对相机是权威的**,而 UI 布局仍读 `Canvas`——所以玩法与 UI 可以按不同方式
+适配。
+
+各发布运行时从项目配置安装它(`createWebApp` 的 `screenFit` 选项)。游戏代码可以实时读取
+或覆盖——相机插件每帧重读:
+
+```typescript
+import { defineSystem, Res, ScreenScaling, ScaleMode } from 'esengine';
+
+const enableProjectFit = defineSystem([Res(ScreenScaling)], (fit) => {
+ fit.designWidth = 1280;
+ fit.designHeight = 720;
+ fit.scaleMode = ScaleMode.Expand; // any real mode (≥ 0) switches the fit on
+});
+```
+
+## UI 布局:`UINode` 像素就是设计像素
+
+UI 在一个世界空间矩形(`uiLayoutRect`)内布局,对场景相机而言,这个矩形**就是**适配后的
+相机范围。因为世界单位是设计像素,`UINode` 上的 `px(300)` 在任何设备上都是 300 设计像素——
+缩放模式改变的是 UI 周围可见多少*世界*,而绝不改变 UI 自身的比例。
+
+**编辑器视口**是特例:它的导航相机以自由缩放渲染世界(原始 `orthoSize`,无适配——平移/缩放
+才可预测)。如果 UI 按那个被缩放的范围布局,每滚一格滚轮,所有元素都会重新缩放和重排。
+编辑器改为从 `Canvas` 恢复*固定的*设计分辨率盒,并在那里布局 UI——布局在任何缩放级别都完全
+一致,而 UI 仍随场景视觉缩放,因为它通过同一个缩放后的视图渲染。设备模拟器把预览宽高比传进
+同一套数学,这就是 letterbox 预览与实机发布完全一致的原因。
+
+两个纯函数——`uiLayoutRect` 与 `computeEffectiveOrthoSize`——都已导出,供工具与测试使用。
+
+## 屏幕尺寸与方向:`ScreenInfo`
+
+`ScreenInfo` 是一个小工具类(运行时不会自动安装):你构造它、喂给它尺寸,它推导方向并触发
+回调。
+
+| 成员 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `width` | number | `0` | 最后上报的屏幕宽度,像素。 |
+| `height` | number | `0` | 最后上报的屏幕高度,像素。 |
+| `dpr` | number | `1` | 设备像素比。 |
+| `orientation` | `ScreenOrientation` | `Portrait` | `width > height` 时为 `Landscape`,否则 `Portrait`。 |
+| `onResize` | `((w, h) => void) \| null` | `null` | 每次 `update()` 都调用。 |
+| `onOrientationChange` | `((o) => void) \| null` | `null` | 推导出的方向翻转时调用(首次 `update()` 从不触发)。 |
+| `update(width, height, dpr = 1)` | 方法 | — | 喂入当前尺寸;重算方向并触发回调。 |
+
+```typescript
+import { ScreenInfo, ScreenOrientation } from 'esengine';
+
+const screen = new ScreenInfo();
+screen.onResize = (w, h) => { /* re-position off-canvas HUD, etc. */ };
+screen.onOrientationChange = (o) => {
+ if (o === ScreenOrientation.Portrait) { /* show the "rotate device" hint */ }
+};
+
+const feed = () =>
+ screen.update(window.innerWidth, window.innerHeight, window.devicePixelRatio);
+window.addEventListener('resize', feed);
+feed();
+```
+
+*发布*的方向是项目设置而非运行时状态:**项目设置 → 显示 → 方向**写一个值,所有导出目标
+共同消费(微信 `game.json`、web/playable 的旋转提示、桌面窗口宽高比)。未设置时,由设计
+分辨率的宽高比推导。
+
+## 安全区(刘海与圆角)
+
+给一个 **absolute** 的 `UINode` 加上 `SafeArea` 组件,引擎会在插入区或屏幕变化时写入该
+节点的四个 inset,把它保持在设备安全区内。该系统随标准 UI 插件一同发布
+(`safeAreaPlugin`,由 `uiPlugin` 构建)——普通应用无需安装。
+
+| 属性 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `applyTop` | boolean | `true` | 按顶部安全区 inset 下推节点的顶部 inset。 |
+| `applyBottom` | boolean | `true` | 底部 inset 同理。 |
+| `applyLeft` | boolean | `true` | 左侧 inset 同理。 |
+| `applyRight` | boolean | `true` | 右侧 inset 同理。 |
+
+平台 inset 在写入前会从设备像素换算到 UI 设计像素,布局保持分辨率无关:
+
+- **微信:**自动从 `wx.getSystemInfoSync().safeArea` 读取。
+- **Web:**从根元素上的 `--sat` / `--sab` / `--sal` / `--sar` CSS 自定义属性读取——
+ 在宿主页面里用 `env(safe-area-inset-*)` 定义它们即可启用(否则读到 `0`)。
+
+```typescript
+import {
+ defineSystem, GetWorld, spawnUIEntity, SafeArea, UIPositionType,
+} from 'esengine';
+
+const buildHudRoot = defineSystem([GetWorld()], (world) => {
+ // Absolute node; leave width/height auto — the SafeArea system writes the four
+ // insets, so the node stretches to exactly the safe region.
+ const hudRoot = spawnUIEntity({
+ world,
+ node: { position: UIPositionType.Absolute },
+ });
+ world.insert(hudRoot, SafeArea, {
+ applyTop: true, applyBottom: true, applyLeft: true, applyRight: true,
+ });
+ // Parent all HUD widgets under hudRoot — they stay clear of the notch.
+});
+```
+
+## 像素完美渲染
+
+`Camera.pixelPerfect`(默认 `false`)在构建视图矩阵前把相机位置吸附到**世界空间像素网格**
+上,让静态像素画每帧落在相同的纹素上,而不会随相机的亚像素漂移而闪烁。实现层面的事实:
+
+- 仅限正交相机(透视下像素网格无定义)。
+- 一个格子 = 一个*渲染*像素:`worldPerPixel = 2 × halfHeight /
+ viewportHeightInDevicePixels`——随当前适配和窗口尺寸自适应。
+- 吸附后的位置同时驱动屏幕↔世界转换,拾取与所见保持一致。
+- 编辑器的自由导航视图从不吸附;该开关在 play/运行时生效。
+
+## 项目显示设置 → 运行时
+
+**项目设置 → 显示**的每个字段存在哪里、落到哪里:
+
+| 编辑器设置 | 项目 manifest | 运行时效果 |
+|---|---|---|
+| 设计宽度 / 高度 | `designResolution.width` / `.height` | 为新场景的 `Canvas` 组件与编辑器相机播种;填充 `ScreenScaling.designWidth/Height`(经 `createWebApp` 的 `screenFit`)。 |
+| 方向 | `packaging.orientation`(`'portrait'` \| `'landscape'`;缺省 = 由设计宽高比推导) | 微信 `game.json`、web/playable 旋转提示、桌面窗口宽高比、编辑器设备预览。 |
+| 相机适配 | `features.rendering.cameraScaleMode`(`'none'`、`'fixed-width'`、`'fixed-height'`、`'expand'`、`'shrink'`、`'match'`;缺省 = `'none'`) | 映射到 `ScreenScaling.scaleMode`(`'none'` → `SCREEN_FIT_OFF`)。 |
+| 相机适配 match | `features.rendering.cameraMatch`(0–1,默认 `0.5`) | `ScreenScaling.matchWidthOrHeight`。 |
+
+另外,两个 `RuntimeConfig` 旋钮设置**新建 `Canvas` 组件的默认 `scaleMode`**(不影响场景中
+已保存的 canvas):`RuntimeConfig.canvasScaleMode`(默认 `1` = `FixedHeight`)与
+`RuntimeConfig.canvasMatchWidthOrHeight`(默认 `0.5`)。构建配置通过
+`applyBuildRuntimeConfig` 按名字设置——规范的 `CanvasScaleMode` 名字加上 `ShowAll` /
+`NoBorder` 别名;未知名字回退到 `FixedHeight`:
+
+```typescript
+import { applyBuildRuntimeConfig } from 'esengine';
+
+applyBuildRuntimeConfig(app, {
+ canvasScaleMode: 'Expand', // name-based: 'FixedWidth' … 'Match', 'ShowAll', 'NoBorder'
+ canvasMatchWidthOrHeight: 0.5,
+});
+```
+
+## 最佳实践
+
+- **一切按设计分辨率制作**,把世界单位当设计像素——绝不为了"适配屏幕"而缩放内容;
+ 改选缩放模式。
+- **绝不能被裁的内容用 `Expand`(ShowAll)**(重 UI、解谜);把背景画出设计框外。
+ **全屏出血的美术用 `Shrink`(NoBorder)**,可接受边缘裁剪时。
+- **优先用项目适配**(项目设置 → 显示的 `ScreenScaling`)而非依赖 UI `Canvas`——它在无
+ UI 的场景也工作,并让相机与 UI 关注点分离。
+- **别把 `pixelsPerUnit` 挪用**为缩放或显示比例;它只缩放物理米。缩放是 `orthoSize`
+ (无适配时)或设计分辨率的选择。
+- 移动端**用 `SafeArea` 锚定 HUD 根节点**——一个带 `SafeArea` 的 absolute 根节点保护
+ 整个 HUD 远离刘海。
+- **只为像素画游戏开启 `pixelPerfect`**;它量化相机运动,平滑滚动的高清游戏不需要。
+
+## 参见
+
+- [相机](/docs/zh-cn/guides/camera/) —— orthoSize、跟随、混合、分屏。
+- [UI](/docs/zh-cn/guides/ui/) —— 消费设计像素盒的 flexbox 布局。
+- [物理](/docs/zh-cn/guides/physics/) —— `pixelsPerUnit` 真正起作用的地方。
+- [编辑器](/docs/zh-cn/guides/editor/) —— 显示设置页与设备预览。
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/transforms.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/transforms.mdx
new file mode 100644
index 000000000..b4d52b720
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/transforms.mdx
@@ -0,0 +1,279 @@
+---
+title: 变换、单位与坐标系
+description: Transform 组件、世界单位/设计像素单位制、物理米制、Y 轴向上的坐标系、用四元数做 2D 旋转,以及父子层级。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+每个存在于世界中的实体都带有一个 `Transform`——它的位置、旋转与缩放。本页是其他指南
+的地基:Transform 各字段的含义、"世界单位"到底是什么(设计像素)、米制从哪里出现
+(物理)、Y 轴指向哪边,以及变换如何沿父子层级复合。
+
+## `Transform` 组件
+
+`Transform` 同时存储你写入的**局部(local)**值和引擎计算出的**世界(world)**值。
+局部字段相对于父实体(没有父实体时相对于世界原点);每一帧变换系统沿层级向下复合,
+把结果写进世界字段。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|---|---|---|---|
+| `position` | Vec3 | `{0, 0, 0}` | 局部位置,单位是世界单位,相对于父实体。`z` 用于在同一排序层内细分绘制顺序。 |
+| `rotation` | Quat | `{w: 1, x: 0, y: 0, z: 0}` | 局部旋转,四元数表示(单位四元数 = 无旋转)。2D 下绕 Z 轴旋转——见 [2D 旋转](#2d-旋转)。 |
+| `scale` | Vec3 | `{1, 1, 1}` | 逐轴局部缩放(`1` = 原始尺寸;负值翻转)。 |
+| `worldPosition` | Vec3 | `{0, 0, 0}` | **只读。**最终世界空间位置,由引擎复合得出。 |
+| `worldRotation` | Quat | 单位四元数 | **只读。**最终世界空间旋转。 |
+| `worldScale` | Vec3 | `{1, 1, 1}` | **只读。**最终世界空间缩放。 |
+
+写局部字段,读世界字段。世界字段是引擎的输出——写它们不会有持久效果,因为变换系统
+每帧都会根据局部字段和父链重新计算。没有父实体的根实体,世界值等于局部值。
+
+```typescript
+import { defineSystem, Query, Mut, Transform } from 'esengine';
+
+const drift = defineSystem([Query(Mut(Transform))], (q) => {
+ for (const [entity, t] of q) {
+ t.position = { x: t.position.x + 1, y: t.position.y, z: t.position.z }; // write local
+ console.log(t.worldPosition.x); // read world
+ }
+});
+```
+
+`position.x/y/z`、`rotation.z`、`scale.x/y/z` 是可动画字段([Sequencer](/docs/zh-cn/guides/timeline/)
+和[补间](/docs/zh-cn/guides/animation/#补间tween)可以打关键帧),而 `position` /
+`rotation` / `scale` 会被[网络](/docs/zh-cn/guides/networking/)的状态复制同步。
+
+<Aside type="note">
+ `LocalTransform` 和 `WorldTransform` 是**同一个组件的别名导出**——
+ `Transform === LocalTransform === WorldTransform`。局部与世界数据都在这一个统一
+ 组件里;代码里用哪个名字读起来顺就用哪个。
+</Aside>
+
+<Aside type="tip">
+ 编辑器的 Details 面板为了方便,把旋转显示为单个**以度为单位的 Z 角度**,但底层
+ 存储的数据始终是四元数。
+</Aside>
+
+## 坐标系
+
+- **世界空间 Y 轴向上**:`+Y` 朝上,`+X` 朝右,角度 `0` 指向 `+X`,正角度逆时针
+ (`Math.atan2(dy, dx)` 可直接得到指向目标的角度)。
+- **`position.z` 是绘制顺序,不是透视**:2D 渲染先按各渲染器的排序层 `layer` 粗排;
+ 同一层内用 `z` 做精细排序(俯视角深度请用
+ [y 排序层](/docs/zh-cn/guides/sprites/#绘制顺序与排序层))。它不会使精灵产生
+ 透视缩放。
+- **屏幕空间 Y 轴向下**:指针坐标(`Input.mouseX/mouseY`、UI 命中测试)是从画布
+ **左上角**起算的像素,Y 向下增大。
+
+用 `CameraView` 资源在两个空间之间转换(完整 API 见
+[相机](/docs/zh-cn/guides/camera/#屏幕--世界坐标)):
+
+```typescript
+import { defineSystem, Res, CameraView, Input } from 'esengine';
+
+const pick = defineSystem([Res(CameraView), Res(Input)], (view, input) => {
+ // Screen px (Y-down, top-left origin) -> world units (Y-up). null if no camera.
+ const world = view.screenToWorld(input.mouseX, input.mouseY);
+ if (world) { /* world.x, world.y */ }
+});
+```
+
+## 单位——设计像素、世界单位与米
+
+Estella 只有**一种创作用空间单位**:设计像素。以及**一种派生单位**给物理用:米。
+
+```text
+screen px (Y-down) ── CameraView.screenToWorld ──▶ world units = design px (Y-up)
+world / design px ── ÷ Canvas.pixelsPerUnit (100) ──▶ physics meters (Box2D)
+```
+
+**1 世界单位 = 1 设计像素。**默认设计分辨率是 1920×1080(`Canvas.designResolution`),
+编辑器场景相机的创作默认 `orthoSize = designResolution.y / 2 = 540`——相机恰好看到
+一个设计分辨率大小的世界。实际含义:
+
+- 把纹理拖进场景会按其**像素尺寸**生成精灵(128×128 的图片在默认缩放下就是
+ 128×128 个世界单位)。
+- `UINode` 的 px 尺寸在场景相机下与设计像素 **1:1** 对应。
+- 玩法代码里的距离、偏移、速度都以设计像素计(px 与 px/秒)。
+
+**物理是米制的。**`Canvas.pixelsPerUnit`(默认 `100`)是每物理**米**对应的世界像素
+数——它缩放 Box2D 世界和瓦片碰撞体。它*不是*精灵的显示缩放。需要记住的分界:
+
+| 物理接口 | 单位 |
+|---|---|
+| 碰撞体尺寸(`halfExtents`、`radius` 等) | **米**(像素 ÷ PPU) |
+| 面向求解器的方法——力、冲量、速度、`setGravity` | **米** |
+| 空间查询——`raycast`、`shapeCast*`、`overlapCircle`、`overlapAABB` | **世界像素**(自动换算) |
+| `CharacterController.velocity` / `moveCharacter` | **世界像素**/秒 |
+
+这些默认值以常量导出,需要它们的代码不必硬编码数字:
+
+```typescript
+import { DEFAULT_DESIGN_WIDTH, DEFAULT_DESIGN_HEIGHT, DEFAULT_PIXELS_PER_UNIT } from 'esengine';
+
+DEFAULT_DESIGN_WIDTH; // 1920
+DEFAULT_DESIGN_HEIGHT; // 1080
+DEFAULT_PIXELS_PER_UNIT; // 100
+
+const radiusMeters = 24 / DEFAULT_PIXELS_PER_UNIT; // a 24 px circle collider
+```
+
+这些常量直接读取引擎自身的 Canvas 默认值,因此不会与 C++ 数值漂移。
+
+## 2D 旋转
+
+`Transform.rotation` 是四元数 `{w, x, y, z}`。纯 2D 旋转就是绕 Z 轴的旋转,只用到
+`z` 和 `w` 两个分量:
+
+```text
+angle a (radians) -> { w: cos(a/2), x: 0, y: 0, z: sin(a/2) }
+```
+
+用 `quat()` 工厂函数构造——**注意参数顺序:`w` 在最前**
+(`quat(w = 1, x = 0, y = 0, z = 0)`),与单位四元数默认值一致:
+
+```typescript
+import { quat } from 'esengine';
+
+const angle = Math.PI / 4; // 45° CCW
+const rot = quat(Math.cos(angle / 2), 0, 0, Math.sin(angle / 2));
+```
+
+反向读回角度,有两个等价的辅助函数,都计算 `2 * atan2(z, w)`:
+
+| 辅助函数 | 签名 | 说明 |
+|---|---|---|
+| `quaternionToAngle2D` | `(rz, rw) => number` | 由四元数的 `z`/`w` 求 Z 角度(弧度)。 |
+| `facingFromQuat` | `(z, w) => number` | 同样的数学;AI/感知模块的写法。 |
+| `normalizeAngle` | `(a) => number` | 把任意角度归一到 `(-π, π]`——用于最短转向差值。 |
+
+完整示例——炮塔跟踪光标:
+
+```typescript
+import {
+ defineSystem, defineTag, Query, Mut, Res,
+ Transform, CameraView, quat, facingFromQuat, normalizeAngle,
+} from 'esengine';
+
+const Turret = defineTag('Turret');
+
+const aim = defineSystem([Query(Mut(Transform)).with(Turret), Res(CameraView)], (q, view) => {
+ const target = view.getWorldMousePosition();
+ if (!target) return;
+ for (const [entity, t] of q) {
+ const angle = Math.atan2(
+ target.y - t.worldPosition.y,
+ target.x - t.worldPosition.x,
+ );
+ t.rotation = quat(Math.cos(angle / 2), 0, 0, Math.sin(angle / 2));
+
+ // Or, to turn gradually: read the current facing and step toward the target.
+ const facing = facingFromQuat(t.rotation.z, t.rotation.w);
+ const delta = normalizeAngle(angle - facing); // shortest signed turn
+ }
+});
+```
+
+想动画化旋转,`TweenTarget.RotationZ` 以**弧度**驱动 Z 角度(引擎每步重建四元数),
+Sequencer 给 `rotation.z` 打关键帧也是同样的语义——见
+[动画](/docs/zh-cn/guides/animation/#补间tween)。
+
+<Aside type="tip">
+ 如果只需要瞄准数学而完全不碰旋转,[数学辅助](/docs/zh-cn/guides/math/)里的
+ `v2.fromAngle(angle, len)` 和 `v2.rotate(v, angle)` 可以直接产出方向向量。
+</Aside>
+
+## 父子层级
+
+实体通过 `Parent` 和 `Children` 组件构成一棵树,但你永远不要直接写这两个组件——
+用 world 的层级 API:
+
+```typescript
+import { defineSystem, addStartupSystem, GetWorld, Transform } from 'esengine';
+
+const build = defineSystem([GetWorld()], (world) => {
+ const ship = world.spawn('Ship');
+ world.insert(ship, Transform, { position: { x: 400, y: 300, z: 0 } });
+
+ const turret = world.spawn('Turret');
+ world.insert(turret, Transform, { position: { x: 0, y: 24, z: 0 } }); // 24 px above the ship
+ world.setParent(turret, ship);
+});
+addStartupSystem(build);
+```
+
+- `world.setParent(child, parent)`——把 `child` 挂到(或改挂到)`parent` 下。
+ **双侧维护**:既写子实体的 `Parent`,也更新父实体的 `Children` 列表。防环——
+ 把实体挂到自己或自己的后代下会被静默忽略。
+- `world.removeParent(entity)`——脱离父实体,实体重新成为根。
+- `world.despawn(entity)`——销毁**整棵子树**,先子后父,不会留下孤儿继续渲染。
+
+读取树结构时,`Parent` 持有 `{ entity }`(父实体),`Children` 持有 `{ entities }`
+(一个 `Entity[]`)——像普通组件一样查询:
+
+```typescript
+import { defineSystem, Query, Parent, Children, Transform } from 'esengine';
+
+const followers = defineSystem([Query(Transform, Parent)], (q) => {
+ for (const [entity, t, parent] of q) { /* parent.entity */ }
+});
+```
+
+### 世界变换如何复合
+
+每一帧变换系统从各个根开始深度优先遍历。对每个实体,先按
+**translate × rotate × scale**(TRS)构建局部矩阵,再乘上父实体的世界矩阵:
+
+```text
+world = parentWorld × T(position) × R(rotation) × S(scale)
+```
+
+所以子实体的 `position` 是在父实体旋转、缩放后的坐标系里度量的:父实体旋转 90° 时,
+局部位于 `{x: 24, y: 0}` 的子实体在世界空间里出现在父实体*上方* 24 px 处。分解后的
+结果写入 `worldPosition` / `worldRotation` / `worldScale`。
+
+### 易错点
+
+- **改挂父级保留局部值。**`setParent` 不会为保持世界位姿而重算局部字段——局部为
+ `{0, 0}` 的子实体会跳到新父实体的位置。想让实体在视觉上原地不动,请在改挂前自行
+ 把它的世界位置换算进新父实体的坐标系。
+- **绝不要直接插入 `Parent`。**`world.insert(entity, Parent, …)` 只写子侧链接,
+ 父实体的 `Children` 列表会失去同步——而引擎的一半(布局、渲染、销毁)都在遍历
+ `Children`。永远用 `world.setParent`。
+- **兄弟顺序在移除后不稳定。**摘除一个子实体是对 `Children` 做 swap-remove,会打乱
+ 剩余兄弟的次序。不要在 `Children` 顺序里编码含义;绘制顺序用 `position.z` 或
+ 排序层表达。
+
+## 缩放
+
+`scale` 逐轴生效。`{2, 2, 1}` 均匀放大一倍;`{2, 1, 1}` 水平拉伸;负值镜像
+(`{-1, 1, 1}` 水平翻转——不过对精灵而言,`Sprite.flipX` 不动变换就能做到)。
+
+缩放通过 `worldScale` 沿层级向下复合:挂在 `{2, 2, 1}` 父实体下的子实体以自身缩放
+的两倍渲染,其局部 `position` 也会被父实体的缩放拉伸(局部 `{x: 10, y: 0}` 在世界
+空间落在 20 px 之外)。
+
+<Aside type="caution">
+ 父实体上尽量用**均匀**缩放(x、y 相等)。非均匀的父缩放叠加子旋转会产生剪切
+ (skew)——复合矩阵不再是干净的旋转,而物理碰撞体(不受缩放影响的米制形状)也
+ 将与你看到的画面不再吻合。相机缩放请用 `Camera.orthoSize`,绝不要缩放相机的
+ Transform。
+</Aside>
+
+## 最佳实践
+
+- **写局部,读世界。**把 `worldPosition` / `worldRotation` / `worldScale` 当作输出;
+ 所有创作性修改都走 `position` / `rotation` / `scale`。
+- **玩法逻辑用设计像素思考**——位置、速度、距离——只在物理边界处换算
+ (碰撞体尺寸与求解器调用 ÷ `pixelsPerUnit`)。
+- **用 `world.setParent`**,不要手写 `Parent` 插入。
+- 写 Transform 的查询里**用 `Mut(...)` 包裹**,让变更检测和渲染器看到更新。
+- **`position.z` 只用于同一排序层内的先后细分**;粗粒度排序用排序层
+ (或 y 排序层)。
+
+## 另请参阅
+
+- [组件](/docs/zh-cn/core-concepts/components/)——组件如何声明与存储数据。
+- [相机](/docs/zh-cn/guides/camera/)——orthoSize、跟随与屏幕 ↔ 世界转换。
+- [精灵与渲染](/docs/zh-cn/guides/sprites/)——排序层、y 排序与绘制顺序。
+- [物理](/docs/zh-cn/guides/physics/)——单位制中以米为单位的那一侧。
+- [数学辅助](/docs/zh-cn/guides/math/)——在规范类型上做向量与旋转数学。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ai.mdx b/docs/astro/src/content/docs/zh-cn/guides/ai.mdx
index 786eae496..d86d38a30 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/ai.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/ai.mdx
@@ -384,6 +384,105 @@ registerAction('takeDamage', (ctx) => {
`registerFsm`/`registerBt` 调用。因为两种范式都从同一份注册表解析叶子,你可以先把一个敌人
原型成状态机,之后再换成行为树(或两者都跑),而不用动你的动作/条件代码。
+## 进阶:组件层之下
+
+`Nav`、`NavAgent`、`Perceiver`——组件层——覆盖了常见场景。它们底下的原语同样被导出,
+全是不依赖引擎/wasm 的纯 TypeScript,供你在不要 agent 的情况下求一条路径、
+或在没有 `Perceiver` 时做一次视线检查。
+
+### 手动寻路
+
+`findPath` 就是导航插件用的那个 A\*:在 `NavGrid` 格子上做均匀代价搜索,4 连通或
+8 连通,octile/曼哈顿启发式,且不切角(走对角线要求两个共享的正交格子都可通行)。
+当你要自己驱动移动、画路径预览、或计算可达性(回合制的移动范围)时下沉到它——
+或者当一张网格不够用时,因为 `Nav` 资源只持有一张网格:
+
+```typescript
+import { NavGrid, findPath, pathToWorld } from 'esengine';
+
+const grid = new NavGrid({ width: 32, height: 24, cellSize: 32 });
+
+const path = findPath(
+ grid,
+ grid.worldToCell(hero.x, hero.y), // Cell — integer grid coordinates
+ grid.worldToCell(chest.x, chest.y),
+ { diagonal: false },
+);
+if (path) {
+ const waypoints = pathToWorld(grid, path); // Vec2[] — cell centers, world pixels
+}
+```
+
+`findPath(grid, start, goal, opts?)` 返回含首尾两端的 `Cell[]` 路径,不可达时返回
+`null`。`Cell` 是整数网格坐标 `{ x, y }`(与 `Vec2` 刻意区分,以标示格子空间);用
+`grid.worldToCell` / `grid.cellToWorld` 互转,或用 `pathToWorld` 把整条路径转成
+世界空间路点。
+
+| `PathfindOptions` 字段 | 默认 | 说明 |
+|---|---|---|
+| `diagonal` | `true` | 允许 8 连通的对角移动。 |
+| `snapRadius` | `8` | 起点/终点落在被阻挡格子上时,先在此环半径内吸附到最近的可走格子再搜索;`0` 关闭吸附。 |
+
+`navGridFromTiles` 从任意瓦片读取器构建可走掩码——它是 `navGridFromTilemapLayer`
+底下的核心,后者只是接上了 `TilemapAPI.getTile`:
+
+```typescript
+import { navGridFromTiles } from 'esengine';
+
+const grid = navGridFromTiles((x, y) => level.tiles[y][x], {
+ width: 32, height: 24, cellSize: 32,
+ blockedTileIds: [WALL_TILE, WATER_TILE],
+});
+```
+
+| `BuildNavGridOptions` 字段 | 说明 |
+|---|---|
+| `width` / `height` / `cellSize` / `origin?` | 与 `NavGrid` 选项相同(见[构建网格](#构建网格))。 |
+| `blockedTileIds?` | 阻挡移动的瓦片 id 的精确集合。 |
+| `isBlocked?` | 针对瓦片 id 的自定义谓词(`0` = 空);覆盖 `blockedTileIds`。二者都不给时,任何非空瓦片都阻挡。 |
+
+### 感知内幕
+
+感知插件是四个导出函数之上的薄封装——适合在动作里做一次性视线检查、做自定义感官
+(记忆、听觉、多目标),或对着一个假 world 做单元测试:
+
+- **`senseTarget(ox, oy, facing, tx, ty, range, halfFov, isBlocked?)`**——纯几何:
+ 先查距离,再查视野锥(`halfFov` 是锥角的*一半*,弧度;≥ π 表示全向),最后走可选的
+ 遮挡回调。
+- **`facingFromQuat(z, w)`**——从 `Transform` 旋转四元数的 z/w 分量求 2D 朝向角
+ (弧度)。
+- **`makeLosCheck(physics)`**——用物理射线构建遮挡回调:任何命中明显落在目标之前
+ (`fraction < 0.98`——最后约 2% 是目标自己)即视为遮挡。
+- **`stepPerception(world, isBlocked?)`**——插件每帧在 `PreUpdate` 跑的那一步:
+ 对每个 `Perceiver`,感知全部 `PerceptionTarget`,留下最近的可见者,写入
+ `Perception` 组件。
+
+```typescript
+import { senseTarget, facingFromQuat, Transform, registerCondition } from 'esengine';
+
+// A one-off sight check against a POINT — no PerceptionTarget needed.
+registerCondition('seesShrine', (ctx) => {
+ const tf = ctx.get(Transform);
+ const facing = facingFromQuat(tf.rotation.z, tf.rotation.w);
+ return senseTarget(
+ tf.position.x, tf.position.y, facing,
+ SHRINE.x, SHRINE.y,
+ 300, Math.PI / 3, // 300 px range, 120° cone
+ ).visible;
+});
+```
+
+`senseTarget` 返回一个 `SenseResult`:
+
+| `SenseResult` 字段 | 说明 |
+|---|---|
+| `visible` | 目标在范围内、在锥内、且未被遮挡。 |
+| `distance` | 到目标的距离——即使不可见也总是被设置。 |
+| `dirX` / `dirY` | 观察者 → 目标的单位方向;不可见时为 `(0, 0)`。 |
+
+内置系统只在物理模块已加载时才接入 `makeLosCheck`;否则感知只做距离 + 视野锥——
+AI 层没有对物理的硬依赖。
+
## 自定义应用
感知、FSM、BT、导航这四个插件是默认插件集的一部分,所以**编辑器和 `esengine` Web 运行时会替你
diff --git a/docs/astro/src/content/docs/zh-cn/guides/animation.mdx b/docs/astro/src/content/docs/zh-cn/guides/animation.mdx
index 9232f30c4..d4856765b 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/animation.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/animation.mdx
@@ -80,6 +80,39 @@ const jump = defineSystem([Query(Mut(SpriteAnimator)), Res(SpriteAnimation)], (q
重新切片时所有帧一致跟随——帧引用的是网格格子,不是像素矩形。
超出当前网格的帧会在帧条中标红。
+### 用代码创建剪辑
+
+`.esanim` 文档就是普通数据,所以剪辑也可以在运行时构建:`createAnimClip` 建一个
+按网格切片的剪辑,追加 `{ cell }` 帧,`parseAnimClipData` 把它解析成运行时的
+`SpriteAnimClip`,再用 `registerClip` 注册,任何 `SpriteAnimator` 都能用这个名字:
+
+```typescript
+import {
+ defineSystem, Res, Assets, SpriteAnimation,
+ createAnimClip, parseAnimClipData,
+} from 'esengine';
+
+const registerRun = defineSystem([Res(Assets), Res(SpriteAnimation)], async (assets, sprites) => {
+ const tex = await assets.loadTexture('textures/run-sheet.png');
+
+ // A 32×32 grid over the sheet; frames reference grid cells (row-major).
+ const data = createAnimClip('textures/run-sheet.png', 32, 32, tex.width, tex.height);
+ data.fps = 10;
+ for (let cell = 0; cell < 6; cell++) data.frames.push({ cell });
+
+ const handles = new Map([['textures/run-sheet.png', tex.handle]]);
+ sprites.registerClip(parseAnimClipData('run', data, handles));
+ // Any SpriteAnimator can now set clip = 'run'.
+});
+```
+
+| 辅助函数 | 说明 |
+|---|---|
+| `createAnimClip(texture, cellWidth, cellHeight, pageWidth, pageHeight)` | 一个全新的按网格切片的 `AnimClipAssetData`(fps `12`、`loop: true`、边距/间距 `0`、暂无帧)。 |
+| `parseAnimClipData(name, data, textureHandles)` | 把资产数据解析成运行时 `SpriteAnimClip`——每个格子帧得到纹理句柄与 UV 窗口。 |
+| `parseAnimClipAsset(json)` / `serializeAnimClip(data)` | 解析 / 写出 `.esanim` JSON 文档(两者可往返)。 |
+| `animClipCellRect(sheet, cell)` / `animClipCellUv(sheet, cell)` | 网格格子的像素矩形 / UV 窗口——即该帧 `Sprite` 显示的内容。 |
+
### 用状态机驱动剪辑——零代码
[FSM/BT 内置](/docs/zh-cn/guides/ai/)以数据驱动翻页动画。动作的可选**参数**
@@ -166,6 +199,38 @@ tween.cancelAll(entity); // stop everything on an entity
`TweenHandle` 有 `.then(next)`、`.bezier(...)`、`.pause()`、`.resume()` 和 `.cancel()`。
+### 组合句柄
+
+`tween.parallel` 返回 `TweenGroup`,`tween.sequence` 返回 `TweenSequence`——它们是
+覆盖全体成员的父级句柄。两者都有 `state`(一个 `TweenState`)、会扇出到每个成员的
+`pause()` / `resume()` / `cancel()`,以及 `onComplete(cb)`:
+
+```typescript
+const popX = tween.to(e, TweenTarget.ScaleX, 1, 1.3, 0.2);
+const popY = tween.to(e, TweenTarget.ScaleY, 1, 1.3, 0.2);
+tween.parallel([popX, popY]).onComplete(() => spawnSparkles());
+
+tween.sequence([
+ () => tween.to(e, TweenTarget.PositionY, 0, 60, 0.3),
+ () => tween.delay(0.2),
+ () => tween.to(e, TweenTarget.PositionY, 60, 0, 0.3),
+]).onComplete(() => landDust());
+```
+
+组和序列一定要**通过 `Tween` 资源创建**——资源会把它们登记进内部轮询器
+(`TweenCompositionManager`),`onComplete` 的触发和序列推进到下一个工厂都靠它。
+手写 `new TweenGroup(...)` 不会被任何人轮询。
+
+`tween.value(...)` 和 `tween.delay(...)` 返回 `ValueTweenHandle`——同一套控制面
+(`state`、`.pause()` / `.resume()` / `.cancel()`、`.bezier(...)`),外加
+`.then(next)`:可以串接另一个数值补间,*或*任何可暂停/恢复的东西(一个组、一个序列)。
+`TweenHandle.then` 同样接受 `ValueTweenHandle`,所以属性补间和数值补间可以在一条链里
+自由混用。
+
+优先用简写辅助(`tween.parallel` / `tween.sequence` / `tween.delay` / 句柄的
+`.then`);这些类就是那些调用返回的东西——只有当你要存下句柄、稍后暂停/取消/观察
+组合时,才需要点名 `TweenGroup` / `TweenSequence` / `ValueTweenHandle`。
+
## 动画状态机
角色动画用一个**动画控制器**:它持有状态、转移和由命名**参数**驱动的 1D 混合树。在编辑器
@@ -188,7 +253,7 @@ const drive = defineSystem([Query(Animator), Res(AnimatorController)], (q, anim)
| `Animator` 字段 | 类型 | 默认 | 说明 |
|---|---|---|---|
| `controller` | string | `''` | 已注册的控制器名。 |
-| `currentState` | string | `''` | 活动状态(从控制器的初始状态种入)。 |
+| `currentState` | string | `''` | 活动状态;嵌套状态机时是 `/` 分隔的路径(从控制器的初始状态种入)。 |
| `enabled` | boolean | `true` | 关掉即冻结状态机。 |
| `AnimatorController` 方法 | 说明 |
@@ -202,6 +267,119 @@ const drive = defineSystem([Query(Animator), Res(AnimatorController)], (q, anim)
控制器可以同时驱动精灵**和** [Spine](/docs/zh-cn/guides/spine/) 动画,所以一套状态机就能
管一整个角色。
+参数有三种类型(`AnimatorParamType`):`'float'`、`'bool'`、`'trigger'`。条件用
+`gt` / `lt` / `eq` / `neq` 比较数值(带 `value`),用 `true` / `false` 测试 bool,
+`trigger` 触发一次即被消费。没有单独的 int 类型——整数走 float 参数配合
+`eq` / `neq`。
+
+### 混合树
+
+状态可以携带一个 1D **blend** 来代替单个片段:由一个 float 参数在
+`AnimatorBlendThreshold` 档位之间做选择。因为精灵通道一次只播一个片段,这里的混合是
+按阈值的*选择*——`value` 不超过参数值的档位中取最大者(低于所有档位时播第一个)——
+而不是加权姿态混合。每个档位是 `{ value, clip, speed?, loop? }`;档位级的
+`speed` / `loop` 覆盖状态自己的。选择每帧重算,所以 `speed` 参数上升时
+idle→walk→run 无需任何转移:
+
+```typescript
+import { defineSystem, Res, AnimatorController, type AnimatorControllerDef } from 'esengine';
+
+const movement: AnimatorControllerDef = {
+ parameters: [{ name: 'speed', type: 'float', default: 0 }],
+ initialState: 'move',
+ states: [{
+ name: 'move',
+ blend: {
+ parameter: 'speed',
+ thresholds: [
+ { value: 0, clip: 'idle' },
+ { value: 0.5, clip: 'walk' },
+ { value: 4, clip: 'run', speed: 1.2 },
+ ],
+ },
+ transitions: [],
+ }],
+};
+
+const setup = defineSystem([Res(AnimatorController)], (anim) => {
+ anim.registerController('movement', movement);
+});
+```
+
+纯函数 `selectBlendClip(blend, value)` 返回某个值会选中的档位——方便做工具或测试。
+
+骨骼角色的状态可以改为携带 `spine` 运动(`AnimatorSpineMotion`,
+`{ animation, loop? }`):进入时控制器设置该 [Spine](/docs/zh-cn/guides/spine/)
+动画(`loop` 默认 `true`),轨道播放与混合交给 Spine 运行时——完全不碰
+`SpriteAnimator`。状态互斥:`clip`、`blend`、`spine`、`stateMachine` 四者取一。
+
+### 子状态机
+
+携带 `stateMachine`(`AnimatorSubMachine`)的状态是一个**容器**:它自己不播任何运动。
+进入时状态机下钻到子机的 `initialState`;容器自己的 `transitions` 是*退出边*,
+从其内部的每个叶子状态求值。子机可以声明自己的 `anyStateTransitions`,对它的所有
+子状态生效。`Animator.currentState` 保存完整的 `/` 分隔路径(`STATE_PATH_SEP`),
+例如 `locomotion/run`:
+
+```typescript
+import { defineSystem, Res, AnimatorController, type AnimatorControllerDef } from 'esengine';
+
+const player: AnimatorControllerDef = {
+ parameters: [
+ { name: 'speed', type: 'float', default: 0 },
+ { name: 'jump', type: 'trigger' },
+ ],
+ initialState: 'locomotion',
+ states: [
+ {
+ name: 'locomotion', // container: no motion of its own
+ stateMachine: {
+ initialState: 'idle',
+ states: [
+ { name: 'idle', clip: 'idle', transitions: [
+ { to: 'run', conditions: [{ param: 'speed', op: 'gt', value: 0.1 }] },
+ ] },
+ { name: 'run', clip: 'run', transitions: [
+ { to: 'idle', conditions: [{ param: 'speed', op: 'lt', value: 0.1 }] },
+ ] },
+ ],
+ },
+ // Exit edges — leave the whole machine from idle OR run.
+ transitions: [{ to: 'jump', conditions: [{ param: 'jump', op: 'trigger' }] }],
+ },
+ { name: 'jump', clip: 'jump', loop: false, transitions: [
+ { to: 'locomotion', conditions: [], hasExitTime: true }, // back in at idle
+ ] },
+ ],
+};
+
+const setup = defineSystem([Res(AnimatorController)], (anim) => {
+ anim.registerController('player', player);
+});
+```
+
+进入 `locomotion` 会落在 `locomotion/idle`;jump 触发器从任一叶子退出;一次性的 jump
+片段播完后,`hasExitTime` 从容器的初始状态重新进入。转移优先级从高到低:顶层
+any-state → 各层子机的 any-state(由外向内)→ 叶子自己的转移 → 容器退出边(由内向外)。
+
+路径机制以纯函数形式暴露(`AnimatorScope` 是顶层控制器和每个子机共享的形状):
+
+```typescript
+import { enterStatePath, leafStateOf, evaluateAnimatorPath } from 'esengine';
+
+enterStatePath(player, 'locomotion'); // ['locomotion', 'idle']
+leafStateOf(player, 'locomotion/run')?.clip; // 'run'
+evaluateAnimatorPath(player, 'locomotion/idle', { speed: 3 }, new Set());
+// → { nextPath: 'locomotion/run', consumedTriggers: [] }
+```
+
+| 辅助函数 | 说明 |
+|---|---|
+| `enterStatePath(scope, name)` | 从某状态下钻到具体叶子;返回路径分段。 |
+| `leafStateOf(def, path)` | 路径的承载运动的叶子状态,或 `null`。 |
+| `evaluateAnimatorPath(def, path, params, triggers, clipFinished?)` | 对路径做一步纯求值 → `{ nextPath, consumedTriggers }`。 |
+| `STATE_PATH_SEP` | 路径分隔符,`'/'`。 |
+
## 如何选择
<Aside type="tip">
diff --git a/docs/astro/src/content/docs/zh-cn/guides/assets.mdx b/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
index 8743afaf7..7ed2afbd5 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/assets.mdx
@@ -124,21 +124,42 @@ const { failed } = await assets.preload(
纹理预算默认 **64 MB**(`RuntimeConfig.textureCacheBudget`,也可在构建配置里用
`textureCacheBudget` 设置);解码音频有自己的 **32 MB** 镜像(`audioCacheBudget`,
-见[音频指南](/docs/zh-cn/guides/audio/))。用 `setTextureBudget` 按你的游戏调纹理预算大小,
-用 `getResourceStats` 观测驻留情况:
+见[音频指南](/docs/zh-cn/guides/audio/))。
+
+## 纹理内存与预算
+
+纹理是真正要紧的预算——它们主宰 GPU 内存。引擎启动时应用
+`RuntimeConfig.textureCacheBudget`;用 `setTextureBudget` 按你的游戏调它的大小(它是
+C++ 池之上唯一面向游戏的表面——没有一个会与之漂移的平行 TS 侧预算),用
+`getResourceStats` 观测驻留:
```typescript
-import { setTextureBudget, getResourceStats } from 'esengine';
+import { setTextureBudget, getResourceStats, trimTextureCache } from 'esengine';
setTextureBudget(256 * 1024 * 1024); // 256 MB texture budget
-const stats = getResourceStats();
+const stats = getResourceStats(); // 引擎初始化前为 null
// stats.textureBytes — 常驻纹理字节数(持有 + 可逐出)
-// stats.textureBudget — 当前预算
+// stats.textureBudget — 当前预算(0 = 逐出关闭)
// stats.textureEvictableCount — 等待复活或逐出的热缓存条目数
+// …还有 shaderCount / textureCount / vertexBufferCount / indexBufferCount
+// 与 cacheHits / cacheMisses
+
+const freed = trimTextureCache(); // 立即丢弃所有可逐出纹理
```
-把预算设为 `0` 会关闭热缓存——每个纹理在最后一个引用释放的瞬间就被销毁。
+这里的"GC"就是上文的 LRU:一旦 `textureBytes` 超出 `textureBudget`,C++ 池逐出最久未用的
+**无引用**纹理直到装下——持有中的纹理绝不会被动。`setTextureBudget(0)` 完全关闭热缓存
+(每个纹理在最后一个引用释放的瞬间销毁),`trimTextureCache()` 一次性释放所有可逐出条目并
+返回数量——引擎在系统内存警告时会调用它;在已知的内存尖峰之前也可以自己调。
+
+还有两个小帮手补全这个表面:`getTextureDimensions(handle)` 返回纹理的
+`{ width, height }`(首次查询后缓存在 TS 侧),`evictTextureDimensions(handle)` 丢弃那条
+缓存——资源系统在纹理真正释放时会这么做,所以只有绕过资源系统自己销毁重建纹理时才需要它。
+
+想逐帧观察这些数字(编辑器内和运行时),见[性能分析](/docs/zh-cn/guides/profiling/)。
+逐纹理的**采样/过滤**参数(像素风 nearest 还是平滑 linear)见
+[精灵指南](/docs/zh-cn/guides/sprites/)。
## 最佳实践
diff --git a/docs/astro/src/content/docs/zh-cn/guides/audio.mdx b/docs/astro/src/content/docs/zh-cn/guides/audio.mdx
index 1dddfa9a0..b45afbbc5 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/audio.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/audio.mdx
@@ -160,6 +160,79 @@ audio.setBusDucking('music', null); // 移除
`Bitrate` 控制打包时的 WAV → MP3 转码(在打包对话框勾选**压缩音频**)。
已压缩格式原样通过。MP3 有少量编码器延迟——需要无缝循环的素材请关闭 `Compress`。
+## 门面之下
+
+`Audio` 是一个门面,其后是 Web Audio 后端组装的三个导出类——`AudioMixer`、`AudioBus`、
+`AudioPool`。游戏里很少直接构造它们(微信后端上它们根本不存在,这正是总线 API 在那里
+降级为空操作的原因),但它们公开导出是为了两件实事:**内建四条之外的自定义总线**,以及
+**独立音频管线**——试听工具、自定义 `PlatformAudioBackend`、测试——建在你自己的
+`AudioContext` 上。
+
+自定义总线完全不需要类——门面就够:
+
+```typescript
+audio.ensureBus('ambience'); // create under master (idempotent)
+audio.ensureBus('footsteps', 'sfx'); // or under an existing bus
+audio.setBusVolume('ambience', 0.5);
+audio.playSFX('assets/wind.ogg', { bus: 'ambience' }); // or AudioSource.bus
+```
+
+`ensureBus(name, parent?)` 在总线缺失时创建它(挂在 `parent` 下,默认 `master`),
+无混音图的后端上返回 `false`;之后所有按名字的门面调用(`setBusVolume`、`muteBus`、
+`setBusEffects`、`setBusDucking`)都能触达它。
+
+### `AudioBus`
+
+一条混音 strip:`input → [效果插入…] → duck → gain(volume) → parent`。声源和子总线
+连到 `input`;`node` 是**输出**增益——音量/静音作用在这里,父总线(或做 VU 表的
+`AnalyserNode`)也从这里取信号。闪避级是独立的增益,所以旁链闪避永远不会与用户音量设置
+打架。用 `AudioBusConfig` 构造:
+
+| `AudioBusConfig` | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `name` | string | – | 总线名。 |
+| `volume` | number | `1` | 初始音量,钳制到 0..1。 |
+| `muted` | boolean | `false` | 以静音启动。 |
+| `parent` | string | `'master'` | 父总线名(由 `AudioMixer.createBus` 消费)。 |
+
+| 成员 | 说明 |
+|---|---|
+| `input` / `node` | 入口 `GainNode` / 输出 `GainNode`(analyser 从 `node` 取信号)。 |
+| `volume` | 0..1;变化在约 15 ms 内平滑,永不爆音。 |
+| `muted` | 把输出渐变到 0 再回来,不丢失 `volume`。 |
+| `effects` / `setEffects(defs)` | 读取 / 幂等替换 DSP 插入链(`BusEffectDef[]`)。 |
+| `duckTo(level, timeConstant)` | 把闪避级向 `level` 渐变(混音器的闪避驱动它)。 |
+| `connect(dest)` / `addChild(bus)` | 把输出接进父总线或裸 `AudioNode`。 |
+
+### `AudioMixer`
+
+拥有总线树。构造一个就建好接到 `context.destination` 的
+`master → { music, sfx, ui, voice }`,音量来自 `AudioMixerConfig`
+(`masterVolume` / `musicVolume` / `sfxVolume` / `uiVolume` / `voiceVolume`——
+music 默认 `0.8`,其余 `1`):
+
+```typescript
+import { AudioMixer } from 'esengine';
+
+const mixer = new AudioMixer(new AudioContext(), { musicVolume: 0.6 });
+const ambience = mixer.createBus({ name: 'ambience' }); // under master
+```
+
+| 方法 | 说明 |
+|---|---|
+| `master` / `music` / `sfx` / `ui` / `voice` | 内建总线,作为只读字段。 |
+| `getBus(name)` / `busNames()` | 查找总线 / 列出所有名字(创建顺序,`master` 在先)。 |
+| `createBus(config)` | 创建总线并接到 `config.parent` 下(默认 `master`)。 |
+| `setDucking(target, rule \| null)` / `getDucking(target)` | 安装或清除旁链 `BusDuckRule`(`trigger`、`amount`、`attack`、`release`、`threshold`)。 |
+| `updateDucking()` | 每帧:测量各触发总线的 RMS,渐变其目标的闪避级(引擎的混音器由音频系统调用)。 |
+
+### `AudioPool`
+
+一次性播放背后的声部池:预建的 `gain → panner` 节点对(`PooledAudioNode`),每次播放
+`acquire()`、声音结束时 `release()`,超过初始 16 个时按需增长;`activeCount` 与
+`capacity` 报告用量。当你在自己的 `AudioContext` 上做自定义播放、想避免每次播放的节点
+开销时可以用它。
+
## 空间音频
设 `AudioSource.spatial = true`,并给监听实体(通常是相机或玩家)加一个启用的 `AudioListener`。
@@ -192,6 +265,25 @@ const setupSpatial = defineSystem([Commands()], (cmds) => {
`AudioListener` 只有一个字段 `enabled`(默认 `true`)——场景里保持恰好一个启用的监听器。
+Estella 的空间管线是诚实的 2D:每帧,音频系统取声源和监听器的世界位置,算出距离,用
+`volume × 衰减` 加上**沿 x 轴的立体声声像**(`(sourceX − listenerX) / maxDistance`,
+钳制到 ±1)驱动正在播放的句柄。没有 HRTF、多普勒或遮挡。空间声源在没有启用监听器时播放,
+会警告一次并从世界原点量距离。
+
+曲线数学以纯函数导出,供工具和测试使用——`calculateAttenuation(distance, config)`
+配 `SpatialAudioConfig`(`model`、`refDistance`、`maxDistance`、`rolloff`——系统用
+`AudioSource.minDistance`/`maxDistance`/`rolloff` 填充它),以及
+`calculatePanning(sourceX, sourceY, listenerX, listenerY, maxDistance)`:
+
+```typescript
+import { calculateAttenuation, calculatePanning, AttenuationModel } from 'esengine';
+
+const gain = calculateAttenuation(250, {
+ model: AttenuationModel.Inverse, refDistance: 100, maxDistance: 1000, rolloff: 1,
+}); // 0.4 — refDistance / distance
+const pan = calculatePanning(600, 0, 0, 0, 1000); // 0.6 — to the right
+```
+
## 最佳实践
- 对在关键时刻要播放的片段**预加载**(`preload` / `preloadAll`),第一次播放就不会因解码而静音。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/build-export.mdx b/docs/astro/src/content/docs/zh-cn/guides/build-export.mdx
index 15128a6bc..de424f721 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/build-export.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/build-export.mdx
@@ -75,6 +75,29 @@ node build-tools/cli.js build -t playable
侧模块(`physics-wechat`、`spine-wechat`,压缩纹理用 `basis-wechat`)——见
[微信小游戏](/docs/zh-cn/guides/wechat/)。
+## 侧模块
+
+可选的引擎特性以独立的 WebAssembly **侧模块**发布——每个模块是一对 emscripten
+产物:`<file>.js` 胶水加 `<file>.wasm`——按需加载,让基础引擎保持小体积:
+
+| 模块 | 产物 | 何时加载 |
+|---|---|---|
+| 物理(Box2D) | `physics.js` / `physics.wasm` | 项目声明了物理,或场景使用了物理组件。 |
+| Spine | `spine38` / `spine41` / `spine42` 的 `.js`/`.wasm` | 场景使用了对应格式版本的 Spine 骨骼。 |
+| Basis 转码器 | `basis.js` / `basis.wasm` | 构建里发布了 KTX2 压缩纹理。 |
+| 视频解码器 | `videodec.js` / `videodec.wasm` | wasm 视频路径解码片段时。 |
+
+- **Web / 桌面** —— 产物作为零散文件放在 `esengine.wasm` 旁;运行时经 fetch
+ 侧模块 host 从 `wasmBaseUrl`(引擎自身加载自的目录)拉取。
+- **Playable** —— 不允许任何外部请求,导出器把模块以 base64 内联进单个 HTML
+ 文件;启动代码(`initPlayableRuntime`)拿到的是内嵌侧模块 host 而非 URL。
+- **微信** —— 侧模块打包为微信预编译的模块工厂(这也是每个特性都需要上文
+ `*-wechat` 运行时构建的原因)。
+
+编辑器自己的播放模式也经由同一个发行运行时启动(`initPlayRealmRuntime`),从
+编辑器 origin 拉取侧模块——所以"玩到的即发布的"同样覆盖这些模块。运行时 API 见
+[应用设置与生命周期](/docs/zh-cn/core-concepts/app-lifecycle/#侧模块)。
+
## 构建配置与 source map
- **Development** —— 不压缩的构建;配上 source map 得到可调试的输出。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/camera.mdx b/docs/astro/src/content/docs/zh-cn/guides/camera.mdx
index 49b2f0cc1..469a4dd2a 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/camera.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/camera.mdx
@@ -73,6 +73,28 @@ const zoomIn = defineSystem([Res(Tween)], (tween) => {
`Perspective` 只用于伪 3D 的分层场景;2D 游戏保持 `Orthographic`,尺寸才不随深度变化。
+## 设计分辨率适配
+
+发布的游戏里,主相机通常**不会**按原始 `orthoSize` 渲染。引擎每帧解析一个*适配源*,当其
+生效时,把项目的设计分辨率(默认 1920×1080)letterbox 进实际屏幕宽高比——可见半高由
+`designResolution.y / 2` 加一个缩放模式算出,让世界单位在任何设备上都是设计像素。适配源
+按此顺序:
+
+1. **`ScreenScaling`** 资源(项目设置 → 显示 → 相机适配),当其 `scaleMode` 是真实模式
+ (`≥ 0`)时;
+2. 否则,场景的 **`Canvas`** 组件(若存在);
+3. 否则无——相机按原始 `orthoSize` 渲染。
+
+<Aside type="caution">
+ 适配源生效期间,相机自己写的 `orthoSize` **不会被使用**——可见区域来自设计分辨率与
+ 缩放模式。通过 `orthoSize` 缩放(含上面的 tween)只在场景无 `Canvas` 且项目适配关闭时
+ 生效。
+</Aside>
+
+默认 `orthoSize` 为 `540`,恰是 `designResolution.y / 2`,所以有无适配的视图在设计宽高比
+下一致。缩放模式、letterbox 实例与 `ScreenScaling` 字段详见
+[屏幕与设计分辨率](/docs/zh-cn/core-concepts/screen/)。
+
## 跟随目标
给相机加一个 `FollowTarget` 并指向一个实体。跟随是帧率无关的阻尼移动,带一个死区,所以相机
@@ -101,6 +123,9 @@ const follow = defineSystem([Query(Camera), Commands()], (cameras, cmds) => {
| `deadzone` | number | `0` | 目标可漫游而相机不动的半径(世界单位)。 |
| `damping` | number | `0.25` | 平滑时间常数(秒,越大越慢;`0` = 立即吸附)。 |
+数据形状导出为 `FollowTargetData` 类型。跟随系统直接写相机的 `Transform`(所以 director
+混合的是已跟随的视图),且**只在 play 模式运行**——编辑器的导航视图永远不会被它拖走。
+
## 屏幕 ↔ 世界坐标
读 `CameraView` 资源在两个空间之间转换——用于把实体放到光标下,或检测什么可见。无活动相机
@@ -135,6 +160,17 @@ import { shakeCamera } from 'esengine';
shakeCamera(app, { amplitude: 12, rotation: 0, frequency: 22, duration: 0.4 });
```
+`shakeCamera` 与 `setViewTarget` 的第一个参数既可以是 `App`(宿主代码),也可以是
+`CameraDirector` 资源状态——在系统里直接传 `Res(CameraDirector)` 给你的值:
+
+```typescript
+import { defineSystem, Res, Input, CameraDirector, shakeCamera } from 'esengine';
+
+const shakeOnHit = defineSystem([Res(Input), Res(CameraDirector)], (input, director) => {
+ if (input.isKeyPressed('Space')) shakeCamera(director, { amplitude: 16 });
+});
+```
+
| 选项 | 默认 | 说明 |
|---|---|---|
| `amplitude` | `12` | 峰值位置偏移(世界单位)。 |
@@ -159,6 +195,70 @@ setViewTarget(app, cutsceneCamera, { time: 1.5, curve: BlendCurve.EaseInOut });
`BlendCurve` 取值为 `Linear`、`EaseIn`、`EaseOut`、`EaseInOut`。`time <= 0`(或没有先前视图)
即硬切。位置、缩放、旋转会插值;离散字段(投影、视口)在中点翻转。
+## 相机 director
+
+`setViewTarget` 与 `shakeCamera` 是**相机 director** 的 API——一个 per-app 资源
+(`CameraDirector`),每帧从全屏相机候选中解析出*一个*主视点:已提交的视图目标(或活动/
+最高优先级相机),过渡进行中则向新目标混合,震屏只叠加在渲染视图之上。其状态
+(`CameraDirectorState`)可读;把它当**只读**,用 `setViewTarget` / `shakeCamera` 去改:
+
+| 字段 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `target` | number | `-1` | 已提交的视图目标实体;`-1` = 回退到 `isActive` / 最高 `priority` 的选择。 |
+| `blending` | boolean | `false` | 视图目标混合正在进行。 |
+| `duration` / `curve` | number | `0` / `EaseInOut` | 当前混合的时长(秒)与缓动。 |
+| `currentMain` | `CameraPOV \| null` | `null` | 最后解析出的主 POV,**未加震屏**——也是屏幕↔世界转换所用的视图。 |
+| `shakes` | `ActiveShake[]` | `[]` | 活动的瞬时震屏(由 `shakeCamera` 压入,衰减完即丢弃)。 |
+
+其余字段(`hasPending`、`pendingTarget`、`pendingTime`、`pendingCurve`、`from`、
+`startTime`、`shakeSeq`)是 `setViewTarget` 写入的 director 内部请求/混合簿记。
+
+```typescript
+import { defineSystem, Res, CameraDirector } from 'esengine';
+
+const watchDirector = defineSystem([Res(CameraDirector)], (director) => {
+ if (director.blending) { /* e.g. suppress player input during the hand-off */ }
+ const pov = director.currentMain; // CameraPOV | null — the view being rendered
+ if (pov) { /* pov.x, pov.y, pov.orthoSize, ... */ }
+});
+```
+
+### `CameraPOV`
+
+`CameraPOV` 是相机*被作者的视图参数*的一个纯快照——director 混合的单位,也是
+`currentMain` 存的形状:
+
+| 字段 | 类型 | 说明 |
+|---|---|---|
+| `entity` | number | 来源相机实体,`-1` 表示合成 POV(编辑器视图)。 |
+| `isActive` | boolean | 权威的"这就是主相机"标志。 |
+| `x` / `y` / `z` | number | 相机位置(世界单位)。 |
+| `rotation` | number | Z 旋转,弧度。 |
+| `projection` | number | 一个 `ProjectionType` 值。 |
+| `orthoSize` | number | 作者写的正交半高(世界单位)。 |
+| `fov` | number | 视场角,度(透视)。 |
+| `near` / `far` | number | 裁剪距离。 |
+| `viewport` | `{x, y, z, w}` | 屏幕矩形,0–1(`z`/`w` 是宽/高)。 |
+| `clearFlags` | number | 一个 `ClearFlags` 值。 |
+| `priority` | number | 活动相机间的优先级。 |
+| `pixelPerfect` | boolean | 像素网格吸附标志。 |
+
+混合期间,连续字段(位置、按最短角路径的 `rotation`、`orthoSize`、`fov`、`near`/`far`)
+插值;离散字段(`projection`、`pixelPerfect`)在中点翻转,`viewport` / `clearFlags` /
+`priority` 取目标值。
+
+## 匹配画布宽高比
+
+`updateCameraAspectRatio(world, aspect)` 把 `aspectRatio` 写到世界里**每个** `Camera`
+组件上。各发布运行时启动时用真实画布的 `width / height` 调用它,让作者字段与实际表面保持
+同步(渲染本身每帧从活动视口推导宽高比):
+
+```typescript
+import { updateCameraAspectRatio } from 'esengine';
+
+updateCameraAspectRatio(app.world, canvas.width / canvas.height);
+```
+
## 多相机与分屏
有多个 `Camera` 实体时,`isActive` + `priority` 决定谁是活动的。用 `viewport` 给每个相机一个
@@ -179,6 +279,8 @@ setViewTarget(app, cutsceneCamera, { time: 1.5, curve: BlendCurve.EaseInOut });
## 参见
+- [屏幕与设计分辨率](/docs/zh-cn/core-concepts/screen/) —— 设计分辨率适配、缩放模式、
+ `ScreenScaling` 与 `pixelPerfect` 的深入讲解。
- [动画](/docs/zh-cn/guides/animation/) —— 用 tween 缩放 `orthoSize`。
- [输入](/docs/zh-cn/guides/input/) —— 用鼠标配 `screenToWorld` 做拾取。
- [UI](/docs/zh-cn/guides/ui/) —— UI 在屏幕空间渲染,与相机无关。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/drawing.mdx b/docs/astro/src/content/docs/zh-cn/guides/drawing.mdx
index 63c466941..a40974d19 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/drawing.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/drawing.mdx
@@ -1,6 +1,6 @@
---
title: 自定义绘制
-description: 超出组件的绘制——用 Draw 画即时模式图元、用 Graphics 画矢量路径、用 Mesh2D 画自定义三角网格,以及离屏渲染纹理。
+description: 超出组件的绘制——用 Draw 画即时模式图元、用 Graphics 画矢量路径、用 Mesh2D 与 Geometry API 画自定义三角网格,以及离屏渲染纹理。
---
import { Aside } from '@astrojs/starlight/components';
@@ -9,6 +9,17 @@ import { Aside } from '@astrojs/starlight/components';
表达不了你要的东西——调试覆盖层、程序化形状、自定义几何——引擎把绘制层直接暴露
给你。
+## 该用哪个 API
+
+| API | 模型 | 适用场景 |
+|---|---|---|
+| `Draw` | **即时模式**,全局——命令自动合批、每帧清空。 | 调试覆盖层、gizmo、任何每帧从头重画的东西。 |
+| `Graphics` | **保留式**路径记录器——构建一次,`flush()` 时经 `Draw` 回放。 | 带路径/贝塞尔/圆弧的矢量形状,不想每帧重新细分。 |
+| `ShapeRenderer` / `Mesh2D` | **组件**——带排序层、材质、编辑器 gizmo 的实体。 | 属于场景的形状/网格(见[精灵](/docs/zh-cn/guides/sprites/))。 |
+
+经验法则:视觉属于*场景*(参与排序、保存、可检视)就做成组件;属于*某一帧*
+(调试、类 HUD 覆盖、程序化效果)就在回调里画。
+
## 绘制回调
注册一个回调,它每帧在渲染通道内执行,相机的 view-projection 已经就位——无需任何
@@ -43,6 +54,7 @@ registerDrawCallback('debug-overlay', (elapsed) => {
| `circle(center, radius, color, filled?, segments?)` / `circleOutline(…)` | 一个圆(默认 `32` 段)。 |
| `texture(pos, size, textureHandle, tint?)` | 一个贴图四边形。 |
| `textureRotated(pos, size, rotation, textureHandle, tint?)` | 同上,带旋转(弧度)。 |
+| `drawMesh(geometry, shader, transform)` / `drawMeshWithMaterial(geometry, material, transform?)` | 按句柄绘制自定义网格(见下面的 `Geometry` API)。 |
| `setLayer(layer)` / `setDepth(depth)` | 后续命令的排序。 |
| `setBlendMode(mode)` / `setDepthTest(on)` | 后续命令的混合 / 深度状态。 |
| `getDrawCallCount()` / `getPrimitiveCount()` | 本帧统计。 |
@@ -93,12 +105,90 @@ cmds.spawn()
`Meshes2D` 资源——`setGeometry(entity, geometry)` 重新上传(索引在引擎侧校验),
另有 `getGeometry` / `clearGeometry`。只改 `geometry` 字段本身不会被变更检测。
+## 自定义几何:`Geometry` API
+
+`Mesh2D` 是*组件*路径,`Geometry` 则是*即时*路径:它上传一个索引顶点缓冲,交回
+一个**句柄**由你自己绘制——配上[材质](/docs/zh-cn/guides/material/)用
+`Draw.drawMeshWithMaterial(geometry, material, transform?)`(或配原始着色器用
+`Draw.drawMesh(geometry, shader, transform)`)。
+
+```typescript
+import { Geometry, Draw, Material, registerDrawCallback } from 'esengine';
+
+const quad = Geometry.createQuad(120, 120); // 1 单位 ≙ 1 设计像素
+const mat = Material.create({ shader }); // 一个 compileShader 材质
+
+registerDrawCallback('custom-mesh', () => {
+ Draw.drawMeshWithMaterial(quad, mat); // 单位矩阵变换
+});
+```
+
+### `GeometryOptions`
+
+| 字段 | 默认 | 说明 |
+|---|---|---|
+| `vertices` | — | 交错的顶点数据,一个 `Float32Array`(每次上传上限 64K 个 float)。 |
+| `layout` | — | `VertexAttributeDescriptor[]`——按缓冲顺序、每个属性一个 `{ name, type }`。 |
+| `indices` | — | `Uint16Array` 或 `Uint32Array` 三角形列表(每次上传上限 16K 个索引)。 |
+| `dynamic` | `false` | 为 `updateVertices` 的频繁更新分配。 |
+
+`DataType` 命名每个属性的形状:`Float`、`Float2`、`Float3`、`Float4`、`Int`、
+`Int2`、`Int3`、`Int4`。
+
+### 方法与辅助函数
+
+| 方法 | 作用 |
+|---|---|
+| `create(options)` | 上传网格;返回 `GeometryHandle`(失败或数据超限时抛错)。 |
+| `updateVertices(handle, vertices, offset?)` | 重写 `dynamic` 几何的顶点数据(offset 单位 float)。 |
+| `release(handle)` / `isValid(handle)` | 释放 / 探测句柄。 |
+| `createQuad(width?, height?)` | 居中四边形(默认 1×1),布局为 `a_position` + `a_texCoord`。 |
+| `createCircle(radius?, segments?)` | 三角扇圆形(默认 1、32),同一布局。 |
+| `createPolygon(points)` | 由 `{x, y}` 点扇形三角化的多边形,UV 取自包围盒。 |
+
+辅助网格都用双属性 `Float2` 位置 + `Float2` UV 布局,可直接配只写片元的
+`.esshader` 材质。
+
## 离屏目标:`RenderTexture`
-进阶用法——小地图、头像、镜面——`RenderTexture.create({ width, height })` 分配
-一个离屏目标;把绘制命令包在 `RenderTexture.begin(rt, viewProjection)` / `end()`
-之间即渲染进去,用完 `release(rt)`。这是低层接口(view-projection 矩阵由你提供)
-——细节见 TypeScript API 参考。
+小地图、头像、镜面——以及[位图缓存](/docs/zh-cn/guides/sprites/)的底层——
+`RenderTexture` 分配一个离屏渲染目标。把绘制命令包在 `begin`/`end` 之间即渲染
+进去;得到的 `textureId` 是普通纹理句柄,哪里都能用(`Sprite.texture`、
+`Draw.texture`、材质纹理参数):
+
+```typescript
+import { RenderTexture, Draw } from 'esengine';
+
+const rt = RenderTexture.create({ width: 256, height: 256, filter: 'linear' });
+
+RenderTexture.begin(rt, viewProjection); // 你提供的正交 view-projection
+Draw.circle({ x: 0, y: 0 }, 80, { r: 1, g: 0.5, b: 0, a: 1 });
+RenderTexture.end();
+
+sprite.texture = rt.textureId;
+```
+
+### `RenderTextureOptions`
+
+| 字段 | 默认 | 说明 |
+|---|---|---|
+| `width` / `height` | — | 目标像素尺寸(必填)。 |
+| `depth` | `true` | 附加深度缓冲——纯 2D 合成可关掉省内存。 |
+| `filter` | `'nearest'` | 结果被绘制时的采样过滤:`'nearest'` 或 `'linear'`。 |
+
+### 方法
+
+| 方法 | 作用 |
+|---|---|
+| `create(options)` | 分配目标;返回带 `textureId`、`width`、`height` 的句柄。 |
+| `begin(rt, viewProjection)` | 把后续绘制重定向进目标(矩阵由你提供)。 |
+| `end()` | 结束离屏渲染,回到屏幕。 |
+| `resize(rt, width, height)` | 释放并重建——返回**新**句柄(`textureId` 会变)。 |
+| `getDepthTexture(rt)` | 以可采样纹理句柄取深度附件。 |
+| `release(rt)` | 释放目标及其纹理。 |
+
+这是低层接口:它不会替你渲染场景——只是把你在 `begin`/`end` 之间画的东西,
+在你构建的 view-projection 矩阵下重定向到目标。
## 参见
diff --git a/docs/astro/src/content/docs/zh-cn/guides/input.mdx b/docs/astro/src/content/docs/zh-cn/guides/input.mdx
index 9dd888357..8e0dc11fc 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/input.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/input.mdx
@@ -119,6 +119,38 @@ if (Controls.pressed('Jump')) { /* 本帧边沿 */ }
| `Keys2D(up, down, left, right)` | axis2d | 四个键 → 2D 方向。 |
| `Stick('left' \| 'right', pad?)` | axis2d | 一根手柄摇杆(上 = +y,与 `Keys2D` 一致)。 |
+### 数据模型
+
+这些构造函数只是普通可序列化数据之上的糖——`Binding` 是一个带标签的联合类型,
+一个动作则是 `type` 加它的绑定列表:
+
+```typescript
+import { type Binding, type ActionDef } from 'esengine';
+
+const jump: ActionDef = {
+ type: 'button', // 'button' | 'axis' | 'axis2d'
+ bindings: [
+ { kind: 'key', code: 'Space' }, // Key('Space')
+ { kind: 'gpButton', button: 0 }, // GpButton(GamepadButton.South)
+ ],
+};
+```
+
+| `Binding` kind | 字段 | 构造函数 |
+|---|---|---|
+| `key` | `code` | `Key` |
+| `mouse` | `button` | `MouseButton` |
+| `gpButton` | `button`、`pad?` | `GpButton` |
+| `gpAxis` | `axis`、`pad?`、`scale?` | `GpAxis` |
+| `keys1d` | `neg`、`pos` | `Keys1D` |
+| `keys2d` | `up`、`down`、`left`、`right` | `Keys2D` |
+| `stick` | `stick: 'left' \| 'right'`、`pad?` | `Stick` |
+
+因为绑定就是数据,这一份模型同时也是**改键与持久化格式**:`toJSON()` / `loadJSON()`
+只往返绑定本身(每动作一个 `Binding[]`),而 `toAsset()` 序列化整张映射——连动作类型
+一起——成一个 `InputMapAsset`(`{ version, actions }`),即 `.inputmap` 文件的内容。
+`loadJSON` 会忽略映射里不存在的动作,所以已删除动作的陈旧存档数据永远不会复活它。
+
### 改键与持久化
绑定是普通的可序列化数据,所以按键设置界面写起来很小:
@@ -131,6 +163,10 @@ Controls.save('controls'); // 持久化到平台 Storage
Controls.load('controls'); // 重新应用已存的绑定(如有)
```
+`rebind` / `listenForBinding` 接受一个 `ListenOptions`,选择捕获监听哪些设备族:
+`keyboard` 和 `gamepad` 默认**开**,`mouse` 默认**关**——这样按下"改键"按钮的那次点击
+不会被捕获成绑定。轴类输入永远不会被捕获;改键只面向离散输入。
+
`getBindings` / `setBindings` 以编程方式查看和编辑绑定;`cancelListen()` 中止
挂起的捕获(以 `null` 解析)。
@@ -165,6 +201,60 @@ const gestureSystem = defineSystem([Res(Input), Res(Time)], (input, time) => {
点按 = 0.3 s 内、移动小于 10 px;滑动需 ≥ 50 px 且 ≥ 200 px/s;捏合报告双指
间距逐帧的缩放系数及中心点。
+## 输入路由(分层)
+
+原始平台事件在落进 `Input` 资源之前,会先经过 **`InputRouter`**——一条三层的
+责任链:
+
+1. **编辑器**——工具(gizmo、框选拖拽)最先认领。
+2. **UI**——组件和对话框认领落下来的部分。
+3. **游戏**——隐式的:就是 `Input` 资源本身。玩法只会看到没有被上游处理器
+ 消费的事件。
+
+处理器回调返回 `true` 即**消费**该事件——它既不更新 `Input`,也不再传给后面的层。
+返回 `false` / 什么都不返回则放行。因为消费是按事件粒度的(而不是一个全局的
+"编辑器激活"开关),工具可以只认领它真正关心的:框选拖拽在按住期间消费指针移动,
+但让滚轮穿透到相机;模态框消费 Escape,却不管方向键。
+
+引擎的 UI 插件已经占据了 UI 层——`isPointerOverUI()` 和防点击穿透正是靠它工作的。
+只有在做工具、或把引擎嵌进宿主应用时,你才需要自己写处理器:
+
+```typescript
+import { inputRouter, type InputHandler } from 'esengine';
+
+const modalHandler: InputHandler = {
+ onKeyDown(code, mods) {
+ if (code === 'Escape') { closeModal(); return true; } // consumed
+ },
+ onPointerDown(button, x, y, mods) {
+ return isInsideModal(x, y); // claim clicks on the modal, pass the rest
+ },
+};
+
+const release = inputRouter.setUIHandler(modalHandler);
+// when the modal closes:
+release();
+```
+
+`inputRouter` 是模块级单例;`setEditorHandler` / `setUIHandler` 每层安装一个
+处理器,并返回一个注销函数(注销只移除*你的*处理器,不会碰更新的那个)。
+`InputHandler` 的所有方法都是可选的:
+
+| `InputHandler` 方法 | 签名 |
+|---|---|
+| `onKeyDown` / `onKeyUp` | `(code, mods)` |
+| `onPointerMove` | `(x, y, mods)` |
+| `onPointerDown` | `(button, x, y, mods)` |
+| `onPointerUp` | `(button, mods)` |
+| `onWheel` | `(deltaX, deltaY, mods)` |
+| `onTouchStart` / `onTouchMove` | `(id, x, y)` |
+| `onTouchEnd` / `onTouchCancel` | `(id)` |
+
+`mods` 是一份 **`Modifiers`** 快照——`{ shift, ctrl, alt, meta }`——由路由器从
+按键事件跟踪(任何时候也可以读 `inputRouter.currentMods`)。在释放修饰键的那个
+key-up 边沿,处理器看到的它仍是按住的,与 DOM `event.shiftKey` 的语义一致。
+抛异常的处理器按未消费处理,坏掉的工具不会吞掉全部输入。
+
## 参考
| 分组 | 方法 |
diff --git a/docs/astro/src/content/docs/zh-cn/guides/material.mdx b/docs/astro/src/content/docs/zh-cn/guides/material.mdx
index efc6ffcbd..0bca1b73b 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/material.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/material.mdx
@@ -135,6 +135,117 @@ const v = Material.getUniform(tintMat, 'u_intensity');
| `setUniform(material, name, value)` | 运行时设置一个反射参数。 |
| `getUniform(material, name)` | 读取一个参数的当前值。 |
+### `MaterialOptions`
+
+`Material.create(options)` 接受完整的渲染状态,不只是着色器 + uniform:
+
+| 字段 | 默认 | 说明 |
+|---|---|---|
+| `shader` | — | `compileShader` / `createShader` 返回的着色器句柄(必填)。 |
+| `uniforms` | — | 按名字给出的初始参数值;纹理用 `Material.tex(textureId)`。 |
+| `blendMode` | `BlendMode.Normal` | 材质的合成方式(`Normal`、`Additive`、`Multiply` 等)。 |
+| `depthTest` | `false` | 对深度缓冲做测试。 |
+| `depthWrite` | `true` | 写入深度缓冲。 |
+| `cull` | `CullMode.None` | 三角形剔除模式。 |
+| `switches` | `{}` | 启用的 `#pragma switch` 名——该材质编译时选定的静态排列。 |
+
+每个状态字段都有运行时 setter——`setBlendMode`、`setDepthTest`、`setDepthWrite`、
+`setCull`——而 `Material.createInstance(source)` 构建一个廉价变体:从父材质继承
+一切,只存储你之后在它上面设置的差异。
+
+### `CullMode`
+
+| 值 | 含义 |
+|---|---|
+| `CullMode.None` | 双面都画(2D 默认)。 |
+| `CullMode.Back` | 剔除背面。 |
+| `CullMode.Front` | 剔除正面。 |
+
+### `ShaderSources`
+
+走原始 `createShader` 路径时,`ShaderSources` 提供现成的 ES 3.0 GLSL,使用批处理
+顶点布局(`vec3` position + `vec4` color + `vec2` texCoord,带 `u_projection` /
+`u_model` uniform)——顶点与片元配对使用:
+
+| 源 | Stage | 作用 |
+|---|---|---|
+| `ShaderSources.SPRITE_VERTEX` | 顶点 | 透传位置、颜色和 UV。 |
+| `ShaderSources.SPRITE_FRAGMENT` | 片元 | `texture(u_texture, uv) × v_color`。 |
+| `ShaderSources.COLOR_VERTEX` | 顶点 | 仅位置 + 颜色(无 UV)。 |
+| `ShaderSources.COLOR_FRAGMENT` | 片元 | 平铺顶点色。 |
+
+它们**不是** `.esshader` 模板——没有 `#pragma param` 反射;把它们当
+`Material.createShader(vertex, fragment)` 网格的起点。
+
+## 用代码构建材质图
+
+编辑器的材质图不是另一条管线——它是**生成 `.esshader` 的可视化前端**。
+`compileMaterialGraph(graph)` 从输出节点遍历节点 DAG,发出与手写等价的着色器源
+(GLSL 片元和它的 WGSL 孪生同时生成),所以图材质在两个后端都能跑,而它的
+常量/纹理节点会变成普通的反射 `#pragma param`。这意味着图可以完全用代码编写——
+图就是普通数据:
+
+```typescript
+import { compileMaterialGraph, Material, type MaterialGraph } from 'esengine';
+
+const graph: MaterialGraph = {
+ name: 'TintedSprite',
+ output: 'out', // 输出节点的 id
+ nodes: [
+ { id: 'tex', type: 'textureSample', params: { name: 'u_albedo', default: 'white' } },
+ { id: 'tint', type: 'constColor', params: { name: 'u_tint', value: [1, 0.6, 0.2, 1] } },
+ { id: 'mul', type: 'multiply', inputs: { a: 'tex', b: 'tint' } },
+ { id: 'out', type: 'output', inputs: { color: 'mul' } },
+ ],
+};
+
+const shader = Material.compileShader(compileMaterialGraph(graph));
+const mat = Material.create({ shader });
+Material.setUniform(mat, 'u_tint', [1, 0, 0, 1]); // 图参数就是普通参数
+```
+
+`compileMaterialGraph` 在出现环、缺节点/缺输入、或 `output` 根不是 output 节点时
+抛错。
+
+### 节点类型
+
+`GraphNodeType` 覆盖输入、参数和数学(`NODE_SPECS` 保存每种类型的端口和可编辑
+字面量——编辑器调色板读的就是这份 schema):
+
+| 节点 | 输出 | 说明 |
+|---|---|---|
+| `uv` / `screenUV` | `vec2` | 纹理 UV / 画布归一化屏幕 UV(0–1,y 朝上)。 |
+| `vertexColor` | `vec4` | 精灵的逐实例色调。 |
+| `time` | `float` | 引擎帧时钟,单位秒。 |
+| `constFloat` / `constColor` | `float` / `vec4` | 一个反射材质参数(`params: { name, value }`)。 |
+| `textureSample` | `vec4` | 在某 UV 采样一个纹理参数(`params: { name, default }`)。 |
+| `multiply` / `add` / `lerp` | 拓宽类型 / `vec4` | 算术;标量对向量广播。 |
+| `oneMinus` / `saturate` / `sin` | 同输入类型 | `1 − x` / 钳制 0–1 / 正弦。 |
+| `smoothstep` | 同输入类型 | `smoothstep(edge0, edge1, x)`——边界是节点字面量。 |
+| `noise` | `float` | 基于 UV 的程序化值噪声(`scale` 字面量)。 |
+| `panner` | `vec2` | `uv + time × speed`——滚动 UV(`speedX` / `speedY` 字面量)。 |
+
+### 编辑操作
+
+面向工具(或程序化生成图),SDK 导出一组纯函数操作——每个都返回**新**图,
+不改动输入:
+
+| 函数 | 作用 |
+|---|---|
+| `newMaterialGraph()` | 起始图:一个白色 `textureSample` 接到 `output`。 |
+| `addNode(g, type, x, y)` | 添加带合理默认参数的节点;返回 `{ graph, id }`。 |
+| `connect(g, fromId, toId, toSlot)` | 连一条边;若会成环或槽位未知,**原样返回** `g`。 |
+| `disconnect(g, toId, toSlot)` | 清除一个输入连接。 |
+| `moveNode(g, id, x, y)` | 仅画布布局——编译器忽略位置。 |
+| `removeNode(g, id)` | 移除节点及所有相连的边(`output` 节点不可移除)。 |
+
+## 自定义几何
+
+材质不局限于组件渲染器:**`Geometry`** API(`Geometry.create` 加
+`GeometryOptions` 顶点布局,还有 `createQuad` / `createCircle` / `createPolygon`
+辅助函数)构建句柄式网格,用 `Draw.drawMeshWithMaterial(geometry, material)`
+即时绘制——完整参考见[自定义绘制](/docs/zh-cn/guides/drawing/)。
+
## 最佳实践
- 启动时**只编译一次**着色器并复用句柄——绝不在每帧系统里编译。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/math.mdx b/docs/astro/src/content/docs/zh-cn/guides/math.mdx
index ceaf9301f..0bb397409 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/math.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/math.mdx
@@ -7,7 +7,9 @@ import { Aside } from '@astrojs/starlight/components';
SDK 附带了几个小的数学命名空间——`v2` / `v3`(向量)、`col`(颜色)、`scalar`(数值)
——它们操作的正是你组件里用的那套规范类型(`{x, y}` 向量、0..1 的 `{r, g, b, a}` 颜色)。
-每个辅助函数都是**纯函数**:返回新值,绝不修改入参。
+每个辅助函数都是**纯函数**:返回新值,绝不修改入参。至于这些数字*意味着*什么——世界
+单位、设计像素、物理米制以及 Y 轴向上的坐标系——见
+[变换、单位与坐标系](/docs/zh-cn/core-concepts/transforms/)。
## 向量
@@ -69,9 +71,46 @@ scalar.deg2rad(90); // degrees -> radians
还有:`clamp`、`inverseLerp`、`rad2deg`、`approximately`、`mod`、`sign`。
+## 旋转辅助
+
+`Transform.rotation` 是四元数;2D 下只会绕 Z 轴旋转,几个导出就覆盖了
+角度 ↔ 四元数的往返:
+
+```typescript
+import { quat, quaternionToAngle2D, facingFromQuat, normalizeAngle } from 'esengine';
+
+// Angle -> quaternion. NOTE: the factory takes w FIRST — quat(w, x, y, z).
+const a = Math.PI / 3;
+const rot = quat(Math.cos(a / 2), 0, 0, Math.sin(a / 2));
+
+// Quaternion -> angle (radians), from the z/w components.
+const facing = quaternionToAngle2D(rot.z, rot.w); // Math.PI / 3
+facingFromQuat(rot.z, rot.w); // same math, the AI/perception spelling
+
+// Wrap to (-π, π] — the shortest signed turn from facing toward a target angle.
+const delta = normalizeAngle(targetAngle - facing);
+```
+
+| 辅助函数 | 说明 |
+|---|---|
+| `quat(w?, x?, y?, z?)` | 四元数工厂;不传参数得到单位四元数 `{w: 1, x: 0, y: 0, z: 0}`。 |
+| `quaternionToAngle2D(rz, rw)` | 由四元数的 `z`/`w` 求 Z 角度(弧度,`2 * atan2(z, w)`)。 |
+| `facingFromQuat(z, w)` | 同样的数学,AI/感知模块的命名。 |
+| `normalizeAngle(a)` | 把任意角度归一到 `(-π, π]`,用于最短转向比较。 |
+
+如果需要的是方向*向量*而不是旋转,留在 `v2` 里就好:`fromAngle` / `angle` /
+`rotate`。完整的工作示例(炮塔朝向光标)见
+[变换、单位与坐标系](/docs/zh-cn/core-concepts/transforms/#2d-旋转)。
+
<Aside type="tip">
返回值用的是和组件一样的规范类型,可以直接落回去——例如
`transform.position = v2.add(transform.position, step)` 或
`sprite.color = col.withAlpha(sprite.color, a)`,无需转换。因为每次调用都会分配一个
新对象,在计较分配次数的热点内循环里请把它们提到循环外。
</Aside>
+
+## 另请参阅
+
+- [变换、单位与坐标系](/docs/zh-cn/core-concepts/transforms/)——这些数字的含义:
+ 世界单位 = 设计像素、物理米制、Y 轴向上,以及用四元数旋转实体。
+- [物理](/docs/zh-cn/guides/physics/)——这些辅助函数最终喂给的米制单位面。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/physics.mdx b/docs/astro/src/content/docs/zh-cn/guides/physics.mdx
index f04db7fb2..6bbe2293f 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/physics.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/physics.mdx
@@ -25,10 +25,34 @@ app.addPlugin(new PhysicsPlugin('physics.js', { gravity: { x: 0, y: -9.81 } }));
`CharacterController`)来自主 `esengine` barrel。
</Aside>
+## 单位
+
+Box2D 以**米**模拟;引擎其余部分以**世界像素**工作。二者的换算系数是当前的
+**每单位像素数**(PPU)——`Canvas.pixelsPerUnit`,默认每米 `100` 像素。物理 API 的
+每一部分都固定站在这条边界的某一侧:
+
+| 表面 | 单位 |
+|---|---|
+| 碰撞体组件尺寸——`halfExtents`、`radius`、`offset`…… | **米。** |
+| 面向求解器的方法——`applyForce` / `applyImpulse`、`setLinearVelocity` / `getLinearVelocity`、`setGravity`…… | **米**(m/s、m/s²)。 |
+| 空间查询——`raycast`、`shapeCast*`、`overlapCircle` / `overlapAABB`、`moveCharacter` | **世界像素**,按当前 PPU 缩放。 |
+| `CharacterController.velocity`、`MotorJoint.linearVelocity` | 世界像素/秒。 |
+
+`physics.getPixelsPerUnit()` 返回当前 PPU(每帧从 `Canvas` 推送),换算永远不用写死 `100`:
+
+```typescript
+const ppu = physics.getPixelsPerUnit(); // world pixels per meter
+const speedPx = physics.getLinearVelocity(e).x * ppu; // m/s → px/s
+physics.applyImpulse(e, { x: 0, y: jumpPx / ppu }); // px/s → m/s
+```
+
+混用两个空间——把像素传给 `applyForce`,或把米传给 `raycast`——是最常见的物理 bug。
+拿不准时记住:**组件与求解器 = 米;查询与角色控制器 = 像素。**
+
## 刚体与碰撞体
加一个 `RigidBody` 再加一个碰撞体形状。**碰撞体尺寸以米计,不是像素**——把像素尺寸除以你的
-每单位像素数(PPU)。从一个取 `Commands()` 的系统里生成:
+每单位像素数(见[单位](#单位))。从一个取 `Commands()` 的系统里生成:
```typescript
import {
@@ -36,7 +60,7 @@ import {
RigidBody, BodyType, CircleCollider,
} from 'esengine';
-const PPU = 100;
+const PPU = 100; // = Canvas.pixelsPerUnit; read the live value via physics.getPixelsPerUnit()
const spawnBall = defineSystem([Commands()], (cmds) => {
cmds.spawn()
@@ -106,7 +130,8 @@ const LAYER_GROUND = 0x0008;
## 移动刚体 —— 力与速度
-读 `Physics` 资源来驱动刚体。每个方法都取世界实体:
+读 `Physics` 资源——一个 `PhysicsAPI` 实例——来驱动刚体。这些方法直接和求解器对话,
+所以全部以**米**计(m/s、m/s²——见[单位](#单位))。每个方法都取世界实体:
```typescript
import { defineSystem, Query, Res, RigidBody } from 'esengine';
@@ -131,6 +156,14 @@ const move = defineSystem([Query(RigidBody), Res(Physics)], (q, physics) => {
| `getMass(e)` / `getInertia(e)` / `getCenterOfMass(e)` / `getMassData(e)` | 质量属性。 |
| `setAwake(e, awake)` / `isAwake(e)` | 睡眠刚体控制。 |
+`getMassData(e)` 把质量属性打包成一个 `MassData`:
+
+| `MassData` 字段 | 类型 | 说明 |
+|---|---|---|
+| `mass` | number | 刚体质量(由碰撞体 `density` × 面积得出)。 |
+| `inertia` | number | 绕质心的转动惯量。 |
+| `centerOfMass` | `Vec2` | 质心,在刚体的**局部坐标系**里,以像素计(× PPU)。 |
+
## 空间查询
查询取**像素空间**参数,并按当前 PPU 自动缩放。每个都接受一个可选的 `maskBits` 按层过滤:
@@ -154,6 +187,15 @@ const swept = physics.shapeCastCircle(/* … */); // sweep a shape
| `overlapAABB(min, max, maskBits?)` | `Entity[]` | 与盒重叠的碰撞体。 |
| `shapeCastCircle` / `shapeCastBox` / `shapeCastCapsule` | 命中 | 扫掠一个形状并得到它会撞到什么。 |
+各种 cast 都返回 `RaycastHit`(`ShapeCastHit` 是同一个形状):
+
+| `RaycastHit` 字段 | 类型 | 说明 |
+|---|---|---|
+| `entity` | `Entity` | 被命中碰撞体所属的实体。 |
+| `point` | `Vec2` | 命中点,世界像素。 |
+| `normal` | `Vec2` | 命中点处的表面法线(单位向量)。 |
+| `fraction` | number | 命中处占投射距离的比例,`0..1`——结果按它排序,最近优先。 |
+
## 碰撞与传感事件
`PhysicsEvents` 资源携带这一帧的接触。给碰撞体设 `isSensor: true` 即可得到 enter/exit 事件
@@ -213,7 +255,7 @@ physics.destroyJoint(bodyA);
```typescript
// 传送带:把箱子沿 +x 匀速驱动。
-world.spawn(MotorJoint, {
+world.insert(crate, MotorJoint, {
connectedEntity: anchor,
linearVelocity: { x: 200, y: 0 }, // 世界像素/秒
maxVelocityForce: 500, // 可用于达到该速度的力(牛顿)
@@ -302,12 +344,43 @@ const drive = defineSystem([Query(Mut(CharacterController))], (q) => {
供独立的 `moveAndSlide` 解析器(`esengine/physics`)使用;实际控制器用的原生 mover 自带迭代与
间隙处理,会忽略它们。斜坡/台阶的地面吸附(`snapLength`)是 mover 计划中的补充。</Aside>
+## 调试绘制
+
+物理插件会安装一个 **`PhysicsDebugDraw`** 资源——一个游戏内叠加层,通过
+[`Draw`](/docs/zh-cn/guides/drawing/) API 描出碰撞体轮廓、速度向量和接触点。
+它默认关闭;在任何系统里翻转 `enabled`,就能看见求解器眼中的世界:
+
+```typescript
+import { defineSystem, Res, Input } from 'esengine';
+import { PhysicsDebugDraw } from 'esengine/physics';
+
+const toggleDebug = defineSystem([Res(Input), Res(PhysicsDebugDraw)], (input, dbg) => {
+ if (input.isKeyPressed('F1')) dbg.enabled = !dbg.enabled;
+});
+```
+
+| `PhysicsDebugDrawConfig` 字段 | 默认 | 绘制内容 |
+|---|---|---|
+| `enabled` | `false` | 整个叠加层的总开关。 |
+| `showColliders` | `true` | 碰撞体轮廓,按刚体类型着色:蓝 = 静态,绿 = 动态,青 = 运动学;传感器为黄色。 |
+| `showVelocity` | `false` | 每个动态刚体沿线速度画一支红色箭头。 |
+| `showContacts` | `false` | 本帧新开始的每个接触点画一个红点。 |
+
+叠加层在每个刚体的实时变换处以**世界像素**绘制(按当前 PPU 缩放),你看到的正是查询
+认定的碰撞体位置。`setupPhysicsDebugDraw(app, Physics, PhysicsEvents)` 就是
+`PhysicsPlugin` 替你跑的接线——插入该资源并注册绘制回调;只有在绕开插件的自定义宿主里,
+才需要自己调它(或每帧调底层的 `drawPhysicsDebug(app, Physics, PhysicsEvents)`)。
+
+<Aside type="note">这是运行时的叠加层。**编辑器视口**在物理显示标记下有自己的碰撞体/关节
+gizmo(见[关节——在编辑器里](#在编辑器里));两者互相独立。</Aside>
+
## 最佳实践
- **固定时间步**:*每帧*施加持续力、读 `PhysicsEvents`,因为物理独立于帧 delta 做子步。
- 快速细小刚体(子弹、薄平台)用 **`bullet: true`** 防穿透。
- 角色用 **`fixedRotation: true`** 免得翻倒。
-- **碰撞体用米**(÷ PPU),但**查询和角色控制器用像素**——混用是最常见的 bug。
+- **碰撞体与求解器用米,查询和角色控制器用像素**——混用是最常见的 bug;用
+ `physics.getPixelsPerUnit()` 换算(见[单位](#单位))。
- **触发器用传感器**:`isSensor: true` 给出 enter/exit 事件而无物理推挤。
- **用层过滤**(`categoryBits` / `maskBits`),而不是在事件处理里判断实体类型。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/profiling.mdx b/docs/astro/src/content/docs/zh-cn/guides/profiling.mdx
new file mode 100644
index 000000000..bf7de1ba9
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/profiling.mdx
@@ -0,0 +1,356 @@
+---
+title: 性能剖析与诊断
+description: 帧统计与游戏内浮层、结构化日志、帧捕获、GL 调试、GPU 资源预算,以及子系统健康。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Estella 把诊断能力做成普通的 SDK 表面:系统可以读取的 **`Stats` 资源**、**游戏内
+浮层**、带可插拔输出的结构化**日志器**、记录每个 draw call(并能重放到其中任意一个)
+的**帧捕获**、**GL 错误检查**、GPU **资源驻留统计**,以及每个 App 一份的**子系统健康
+注册表**。本篇逐一讲清。
+
+## 帧统计 — `statsPlugin`
+
+添加 `statsPlugin` 后,引擎每帧把性能数据收集进 `Stats` 资源(在 `Last` 调度阶段,
+一切系统跑完之后):
+
+```typescript
+import { statsPlugin } from 'esengine';
+
+app.addPlugin(statsPlugin);
+```
+
+`statsPlugin` 是一个带默认配置的现成实例。需要选项时,自己构造 `StatsPlugin`:
+
+```typescript
+import { StatsPlugin } from 'esengine';
+
+app.addPlugin(new StatsPlugin({ overlay: true, position: 'top-right' }));
+```
+
+| `StatsPluginOptions` | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `overlay` | boolean | `true` | 显示 DOM 浮层(没有 `document` 的环境会自动跳过)。 |
+| `position` | `StatsPosition` | `'bottom-left'` | 浮层角落:`'top-left'` / `'top-right'` / `'bottom-left'` / `'bottom-right'`。 |
+| `container` | HTMLElement | `document.body` | 浮层面板挂载到的元素。 |
+
+该插件还会调用 `app.enableStats()`,开启逐系统、逐阶段的耗时采集(默认关闭,
+所以正式发布的游戏不为此付费)。
+
+### 在系统里读取 `Stats`
+
+`Stats` 是普通资源——用 `Res(Stats)` 注入:
+
+```typescript
+import { defineSystem, addSystem, Res, Stats } from 'esengine';
+
+const watchPerf = defineSystem([Res(Stats)], (stats) => {
+ if (stats.fps > 0 && stats.fps < 30) {
+ console.warn(`slow frame: ${stats.frameTimeMs.toFixed(1)}ms, ${stats.drawCalls} draw calls`);
+ }
+});
+addSystem(watchPerf);
+```
+
+`FrameStats` 字段(FPS 与帧时间是 60 帧滑动窗口的平均;渲染计数是当前帧的):
+
+| `FrameStats` 字段 | 类型 | 说明 |
+|---|---|---|
+| `fps` | number | 每秒帧数,按最近 60 帧平均。 |
+| `frameTimeMs` | number | 同一窗口内的平均帧时间(毫秒)。 |
+| `entityCount` | number | 世界中的存活实体数。 |
+| `systemTimings` | `Map<string, number>` | 本帧每个系统的 CPU 毫秒数,按系统名索引。 |
+| `phaseTimings` | `Map<string, number>` | 本帧每个调度阶段的 CPU 毫秒数。 |
+| `drawCalls` | number | 本帧发出的 GPU draw call 数。 |
+| `triangles` | number | 本帧提交的三角形数。 |
+| `sprites` | number | 本帧渲染的精灵数。 |
+| `text` | number | 本帧渲染的文本实体数。 |
+| `spine` | number | 本帧渲染的 Spine 骨骼数。 |
+| `meshes` | number | 本帧渲染的网格数。 |
+| `culled` | number | 本帧被剔除(未提交)的实体数。 |
+
+## 统计浮层
+
+`overlay: true`(默认)时,插件渲染一个固定位置的小等宽字体面板:FPS + 帧时间、
+draw call / 三角形 / 精灵 / 剔除数、实体数,以及按最差帧排名的**前 5 个系统**——
+每行显示 `平均 / 最大 ms`。面板最多每 500&nbsp;毫秒重绘一次,期间持续累积系统耗时,
+因此开销极小,而单帧尖峰仍会出现在 `max` 列里。
+
+也可以自己驱动 `StatsOverlay`——比如绑到调试热键上:
+
+```typescript
+import { StatsOverlay, defineSystem, addSystem, Res, Stats } from 'esengine';
+
+const overlay = new StatsOverlay(document.body, 'top-right');
+
+const feedOverlay = defineSystem([Res(Stats)], (stats) => {
+ overlay.update(stats);
+});
+addSystem(feedOverlay);
+
+// overlay.hide() / overlay.show() 切换显示,overlay.dispose() 移除。
+```
+
+<Aside type="note">
+ 浮层基于 DOM,因此在 Web 与桌面端存在,在无 DOM 的环境里没有;`statsPlugin`
+ 会自动跳过创建。`Stats` 资源本身在所有环境都可用。
+</Aside>
+
+## 渲染器计数 — `Renderer.getStats()`
+
+`FrameStats` 里的渲染计数来自 `Renderer.getStats()`,也可以直接调用(不需要
+stats 插件)——它返回一个 `RenderStats`,同样是那七个字段:`drawCalls`、
+`triangles`、`sprites`、`text`、`spine`、`meshes`、`culled`。
+
+```typescript
+import { Renderer } from 'esengine';
+
+const rs = Renderer.getStats();
+console.log(`${rs.drawCalls} draw calls, ${rs.triangles} triangles`);
+```
+
+## 自建工具
+
+插件背后有两个小工具类,均已导出供自定义工具使用:
+
+- **`StatsCollector`** — `fps` / `frameTimeMs` 背后的 60 帧滑动窗口。用
+ `pushFrame(deltaSeconds)` 喂入帧间隔,读 `getFps()` / `getFrameTimeMs()`;
+ `reset()` 清空窗口。
+- **`FrameHistory`** — `FrameSnapshot` 的环形缓冲(默认容量 300,60&nbsp;fps 下约
+ 5&nbsp;秒),用于绘制帧时间曲线。`push(frameTimeMs, phaseTimings, systemTimings?)`
+ 会深拷贝两个 Map,快照保持有效;`getLatest()` 返回最新快照,`getAll()` 返回从旧到
+ 新的整个窗口,`count` / `reset()` 顾名思义。
+
+| `FrameSnapshot` 字段 | 说明 |
+|---|---|
+| `frameTimeMs` | 该帧的总 CPU 时间。 |
+| `phaseTimings` | 逐阶段毫秒数(push 时拷贝)。 |
+| `systemTimings` | 逐系统毫秒数(push 时拷贝)。 |
+
+## 日志
+
+SDK 自身的诊断信息走结构化日志器而不是裸 `console.*`,你的游戏代码可以用同一条
+通道。每条消息有**级别**、自由字符串的**类别**(`'physics'`、`'net'`、你自己的
+`'gameplay'`……)、消息文本,以及可选的结构化 `data`:
+
+```typescript
+import { log, setLogLevel, LogLevel } from 'esengine';
+
+setLogLevel(LogLevel.Debug); // default is LogLevel.Info
+
+log.debug('gameplay', 'Wave spawned', { wave: 3, enemies: 12 });
+log.info('save', 'Game saved');
+log.warn('net', 'High latency', { rttMs: 240 });
+log.error('boot', 'Asset manifest failed', err); // Error keeps its stack
+```
+
+`LogLevel` 为 `Debug < Info < Warn < Error`;`setLogLevel` 设置最低级别——低于它
+的消息在到达任何 handler 之前就被丢弃。独立的 `debug` / `info` / `warn` / `error`
+函数同样已导出,转发到同一个默认日志器;需要 `Logger` 实例本身时用 `getLogger()`。
+
+默认装有一个控制台 handler:它格式化为 `[time] [LEVEL] [category] message`,按级别
+选择对应的 `console` 方法,并把 `Error` 数据作为独立参数传入,让浏览器原生渲染堆栈。
+
+### 自定义日志输出
+
+**`LogHandler`** 以结构化 `LogEntry` 的形式收到每条被接受的消息——这是游戏内
+控制台、文件写入器、崩溃报告面包屑的挂接点。handler 抛异常会被捕获并上报,
+绝不拖垮应用:
+
+```typescript
+import { getLogger, LogLevel, type LogEntry, type LogHandler } from 'esengine';
+
+class Breadcrumbs implements LogHandler {
+ entries: LogEntry[] = [];
+ handle(entry: LogEntry): void {
+ if (entry.level >= LogLevel.Warn) {
+ this.entries.push(entry);
+ if (this.entries.length > 100) this.entries.shift();
+ }
+ }
+}
+
+const crumbs = new Breadcrumbs();
+getLogger().addHandler(crumbs);
+// getLogger().removeHandler(crumbs) to detach,
+// getLogger().clearHandlers() to remove every handler (console one included).
+```
+
+| `LogEntry` 字段 | 类型 | 说明 |
+|---|---|---|
+| `timestamp` | number | 记录时刻的 `Date.now()`(epoch 毫秒)。 |
+| `level` | `LogLevel` | `Debug` / `Info` / `Warn` / `Error`。 |
+| `category` | string | 调用方传入的通道字符串。 |
+| `message` | string | 消息文本。 |
+| `data` | unknown | 可选负载(对象、`Error`……)。 |
+
+## 帧捕获 — 每个 draw call 都有解释
+
+当"这帧为什么是 40 个 draw call?"需要答案时,捕获一帧。先武装捕获,让一帧渲染
+完,然后读回**每个 draw call** 的记录——它画了什么、绑了哪个贴图/材质/着色器和
+什么状态,以及最关键的:**上一个批次为什么被打断**:
+
+```typescript
+import { Renderer, RenderType, FlushReason } from 'esengine';
+
+Renderer.captureNextFrame(); // arm: the NEXT rendered frame records
+
+// …one frame later:
+if (Renderer.hasCapturedData()) {
+ const capture = Renderer.getCapturedData(); // FrameCaptureData | null
+ for (const dc of capture!.drawCalls) {
+ console.log(
+ `#${dc.index} ${RenderType[dc.type]} tex=${dc.textureId} ` +
+ `tris=${dc.triangleCount} entities=${dc.entityCount} ` +
+ `flush=${FlushReason[dc.flushReason]}`
+ );
+ }
+ console.log(`${capture!.cameraCount} camera pass(es)`);
+}
+```
+
+`FrameCaptureData` 是 `{ drawCalls: DrawCallInfo[], cameraCount }`。每个
+`DrawCallInfo`:
+
+| `DrawCallInfo` 字段 | 说明 |
+|---|---|
+| `index` | 该 draw call 在帧内的序号(提交顺序)。 |
+| `cameraIndex` | 由哪个相机 pass 发出。 |
+| `stage` | 渲染阶段(`RenderStage`:Background / Opaque / Transparent / Overlay)。 |
+| `type` | 绘制的内容类型(`RenderType`,见下)。 |
+| `blendMode` | 生效的混合模式 id。 |
+| `textureId` / `materialId` / `shaderId` | 该调用绑定的 GPU 资源。 |
+| `vertexCount` / `triangleCount` | 提交的几何量。 |
+| `entityCount` / `entityOffset` / `entities` | 被批进该调用的实体 id。 |
+| `layer` | 批次的渲染层。 |
+| `flushReason` | 该批次为何结束(`FlushReason`,见下)。 |
+| `scissorX/Y/W/H`、`scissorEnabled` | 裁剪矩形状态(UI 遮罩)。 |
+| `stencilWrite` / `stencilTest` / `stencilRef` | 模板状态(遮罩写入/读取方)。 |
+| `textureSlotUsage` | 批次占用的纹理槽数。 |
+
+`RenderType` 说明一个调用画了什么:`Sprite`、`Spine`、`Mesh`、`ExternalMesh`、
+`Text`、`Particle`、`Shape`、`UIElement`。
+
+`FlushReason` 就是合批的故事——每个值都点名了迫使新开一个 draw call 的那次状态
+变化,也就是想合批更好该修什么:
+
+| `FlushReason` | 含义 |
+|---|---|
+| `BatchFull` | 顶点批次到达容量——"好"的 flush,说明内容多。 |
+| `TextureSlotsFull` | 纹理槽用尽——把更多贴图打进图集。 |
+| `ScissorChange` | 裁剪矩形变化(`UIMask` 边界)。 |
+| `StencilChange` | 模板状态变化(遮罩写入/测试边界)。 |
+| `MaterialChange` | 材质切换——按材质给实体分组。 |
+| `BlendModeChange` | 混合模式切换——加法/普通内容交错。 |
+| `StageEnd` | 渲染阶段边界。 |
+| `TypeChange` | 内容类型切换(如精灵 → 文本 → 精灵)。 |
+| `FrameEnd` | 该帧的最终 flush。 |
+
+### 重放到某个 draw call
+
+捕获可以**重放到任意 draw call**,看这一帧是怎么一步步画出来的——编辑器的帧检查
+器就是这么做的。`replayToDrawCall(i)` 把 draw call `0…i` 重渲染进一张快照;
+`getSnapshotImageData()` 在 GPU 回读落地后解析出像素(WebGL 上立即,WebGPU 上晚
+一个 tick):
+
+```typescript
+import { Renderer } from 'esengine';
+
+Renderer.replayToDrawCall(5); // draw calls 0..5 only
+const img = await Renderer.getSnapshotImageData(); // ImageData | null
+if (img) ctx2d.putImageData(img, 0, 0); // e.g. into a debug canvas
+```
+
+## GL 调试 — `GLDebug`
+
+`GLDebug` 开关 wasm 渲染器内部的 GL 错误检查——默认关闭,因为检查有开销:
+
+```typescript
+import { GLDebug } from 'esengine';
+
+GLDebug.enable(); // check GL errors at key points
+const errors = GLDebug.check('after-spawn'); // explicit check; returns error count
+GLDebug.diagnose(); // dump renderer diagnostics to the console
+GLDebug.disable();
+```
+
+`check(context)` 立即执行一次错误检查并返回发现的 GL 错误数,日志输出会带上你的
+`context` 字符串,便于二分定位错误出现在帧内的哪个位置。
+
+## GPU 资源预算与驻留
+
+已释放的贴图会驻留在一个按字节预算的温缓存里(完整模型见
+[资源指南](/docs/zh-cn/guides/assets/#生命周期与引用计数))。这里是它的诊断面:
+
+```typescript
+import { getResourceStats, setTextureBudget, trimTextureCache } from 'esengine';
+
+setTextureBudget(256 * 1024 * 1024); // resize the budget (0 = no warm cache)
+
+const stats = getResourceStats(); // ResourceStats | null before engine init
+if (stats && stats.textureBytes > stats.textureBudget * 0.9) {
+ const freed = trimTextureCache(); // drop every evictable texture now
+ console.log(`freed ${freed} cached textures`);
+}
+```
+
+| `ResourceStats` 字段 | 说明 |
+|---|---|
+| `shaderCount` | 存活的已编译着色器数。 |
+| `textureCount` | 存活的 GPU 贴图数。 |
+| `vertexBufferCount` / `indexBufferCount` | 存活的 GPU 缓冲数。 |
+| `cacheHits` / `cacheMisses` | 资源缓存命中/未命中计数。 |
+| `textureBytes` | 驻留贴图字节数(RGBA8 估算)——持有的 + 可逐出的。 |
+| `textureBudget` | 当前驻留字节预算(`0` = 关闭逐出缓存)。 |
+| `textureEvictableCount` | 引用数为 0、等待复活或逐出的缓存贴图数。 |
+
+`trimTextureCache()` 立即释放所有可逐出条目并返回释放的贴图数——引擎在收到 OS
+内存警告时会调用它;在已知的内存尖峰前你也可以主动调用。被持有(有引用)的贴图
+和预算本身不受影响。
+
+`evictTextureDimensions(handle)` 丢弃 SDK 侧缓存的某个贴图句柄的宽高,下一次
+`getTextureDimensions` 查询会重新从引擎读取——只有在同一句柄下替换贴图内容的
+工具代码才会用到。
+
+## 子系统健康
+
+每个 `App` 在 `app.subsystems` 上携带一个 `SubsystemRegistry`,跟踪各引擎子系统的
+生命周期阶段(`registered` → `initializing` → `ready`,`error` 为终态)和派生的
+活跃度(`stepping` / `idle` / `inactive`)——回答"物理到底在不在跑?":
+
+```typescript
+for (const s of app.subsystems.getStatuses()) {
+ console.log(`${s.displayName}: ${s.phase} (${s.activity})`, s.lastError ?? '');
+}
+```
+
+`recentEvents()` 返回最近的生命周期转换,`subscribe(fn)` 在阶段变化时通知。完整的
+生命周期模型见 [App 与生命周期](/docs/zh-cn/core-concepts/app-lifecycle/)。
+
+## 在编辑器里
+
+桌面编辑器的剖析 UI 建立在同一套表面上:**Profiler 面板**显示实时帧时间曲线以及
+逐阶段、逐系统的分解(点击某帧可检查它),视口里还有一个小的性能浮层用来一眼看
+FPS。对游戏内构建,上面的 `statsPlugin` 就是对应物。
+
+## 最佳实践
+
+- **发布时不带 `statsPlugin`**(或用调试开关门控)——耗时采集默认关闭是有原因的;
+ 剖析时再加。
+- **先归因再优化** — 读 `systemTimings` / `phaseTimings` 找到*哪个*系统慢再动代码;
+ 浮层的 `max` 列能抓住平均值掩盖的单帧尖峰。
+- **用帧捕获修 draw call** — `flushReason` 点名打断每个批次的那次状态变化
+ (`TextureSlotsFull` → 打图集;`MaterialChange` → 按材质分组)。
+- **用类别记日志,别用 `console.log`** — 结构化条目让 handler 能按通道和级别过滤,
+ `setLogLevel(LogLevel.Debug)` 不改代码就能打开详细输出。
+- **生产环境关闭 `GLDebug`** — 逐调用的 GL 错误检查很贵;只在追渲染 bug 时开。
+- **在内存受限的目标上盯住 `textureBytes` 与 `textureBudget` 的关系**,并在已知
+ 尖峰前 `trimTextureCache()`。
+
+## 另请参阅
+
+- [资源](/docs/zh-cn/guides/assets/) — 资源统计所观察的贴图温缓存与预算。
+- [App 与生命周期](/docs/zh-cn/core-concepts/app-lifecycle/) — 插件、调度与子系统注册表。
+- [系统](/docs/zh-cn/core-concepts/systems/) — 调度与系统名(`systemTimings` 的键)。
+- [编辑器](/docs/zh-cn/guides/editor/) — 桌面编辑器,含其 Profiler 面板。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/scene.mdx b/docs/astro/src/content/docs/zh-cn/guides/scene.mdx
index 7424e43c3..d2e259931 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/scene.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/scene.mdx
@@ -20,6 +20,46 @@ const goToLevel2 = defineSystem([Res(SceneManager)], async (scenes) => {
});
```
+## 场景过渡
+
+`switchTo` 与 `unload` 接受 `TransitionOptions`。用 `transition: 'fade'` 时,切换会经一个
+纯色遮罩分三阶段淡入淡出:遮罩在 `duration` 的前一半内渐变到不透明,**在旧场景卸载、新场景
+加载期间保持全黑**(加载慢只会延长停留,不会闪屏),再在后一半内渐变回来。被 await 的
+promise 只在淡入完成后 resolve——加载失败则 reject。过渡进行中再调 `switchTo` 会被忽略并
+打警告;`isTransitioning()` 可以查询。
+
+| 选项 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `transition` | `'none' \| 'fade'` | `'none'` | 硬切,或经 `color` 淡入淡出。 |
+| `duration` | number | `0.3` | 总淡出淡入时间(秒)——前一半出、后一半入(`RuntimeConfig.sceneTransitionDuration`)。 |
+| `color` | `Color` | 不透明黑 | 遮罩颜色(`RuntimeConfig.sceneTransitionColor`;构建配置里用十六进制字符串)。 |
+| `onStart` / `onComplete` | 回调 | – | 淡出开始时 / 淡入结束后触发。 |
+| `keepPersistent` | boolean | `true` | 让经 `SceneContext.setPersistent` 标记的实体在卸载中存活。 |
+
+`transitionTo` 是同一套机制上的一步到位便捷函数,用 `TransitionConfig` 配置
+(`type: 'fade'`、`duration`、可选 `color`)。第一个参数接受 `App`(引导代码、菜单胶水)
+或 SceneManager 资源状态——在系统里直接传 `Res(SceneManager)` 给你的值。菜单 → 关卡的流程:
+
+```typescript
+import { transitionTo, type TransitionConfig } from 'esengine';
+
+const fadeToBlack: TransitionConfig = {
+ type: 'fade',
+ duration: 0.5,
+ color: { r: 0, g: 0, b: 0, a: 1 },
+};
+
+async function onPlayClicked() {
+ await transitionTo(app, 'levels/level1', fadeToBlack); // menu → level
+}
+```
+
+<Aside type="note">
+ 以上这些都由 `sceneManagerPlugin` 提供,默认的 app 引导已经注册它:它插入 `SceneManager`
+ 和 `SceneStreaming` 资源、在启动时加载初始场景,并每帧推进过渡与流送。只有从零散插件手工
+ 组装 `App` 时才需要自己添加。
+</Aside>
+
## 叠加场景
把一个场景加载到当前场景**之上**——HUD、暂停菜单、流式区域——而不卸载下面的内容。
@@ -52,6 +92,25 @@ const setupStreaming = defineSystem([Res(SceneStreaming)], (streaming) => {
卸载:实体留在内存里、被禁用并隐藏,重进即恢复,代价是内存。单元场景就是普通的
项目场景,按名字引用(见下)。
+资源之下是 `SceneStreamingController`——对 `SceneManager` 原语
+(`loadAdditive` / `unload` / `sleep` / `wake`)的纯编排;它自己不拥有任何加载。距离量到
+**单元边缘**(中心距离减去 `radius`),所以大单元在中心还很远时就开始加载。加载与卸载是
+异步的,控制器保证其安全:某单元有加载/卸载在途时绝不重复下发;如果加载完成时焦点已经离开,
+该单元会被再次丢弃而不是泄漏驻留。没有注册任何单元时,`update()` 是空操作。
+
+| `SceneStreamingController` | 说明 |
+|---|---|
+| `configure({ loadRadius, unloadRadius, policy? })` | 设置半径(`unloadRadius` 向上钳制到不小于 `loadRadius`)与出界策略——`'unload'`(默认)或 `'sleep'`。 |
+| `register(cell)` / `unregister(scene)` / `clear()` | 管理单元集合(`{ scene, x, y, radius }`)。 |
+| `setFocus(x, y)` | 直接驱动焦点(每帧调用)。 |
+| `setFocusEntity(entity)` / `getFocusEntity()` | 改为跟随一个实体——流送系统每 tick 读它的 `Transform`(仅 play 模式)。 |
+| `getActive()` | 控制器当前认为在范围内的场景名。 |
+| `update()` | 按当前焦点调和驻留单元(`sceneManagerPlugin` 每帧调用)。 |
+
+阈值数学也单独导出为纯函数
+`computeStreaming(cells, focusX, focusY, loadRadius, unloadRadius, active)`——
+适合测试或自定义调度器。
+
## 构建里的场景
项目场景目录下的每个场景都会随导出发布,并注册为 `switchTo` 的目标。场景的**名字**是它
@@ -78,6 +137,84 @@ const setupStreaming = defineSystem([Res(SceneStreaming)], (streaming) => {
| `isPaused(name)` / `isSleeping(name)` | 上述两种挂起状态。 |
| `isTransitioning()` | `switchTo` 过渡期间为 `true`。 |
+## 序列化与迁移
+
+场景文件格式是公开表面:`SceneData` 是纯 JSON,编辑器和运行时读写它所用的原语都导出给
+游戏代码。你会在这些时刻用到它们:保存**活世界的快照**(比[存档 API](/docs/zh-cn/guides/save/)
+更完整的检查点)、加载玩家生成或下载的场景,或发布状态放不进普通字段的组件。
+
+`serializeScene(world, name?)` 遍历活世界,产出能经加载器往返的 `SceneData`——层级折叠进
+每个实体记录的 `parent`/`children` 字段,仅运行时的投影实体(瓦片碰撞体之类,由其系统重新
+派生)被排除。`loadSceneWithAssets(world, data, options?)` 先预加载所有被引用的资源再生成
+实体;同步的 `loadSceneData(world, data)` 不做资源解析直接生成。两者都返回序列化实体 id 到
+活实体的映射,之后可用 `findEntityByName(world, name)` 找实体:
+
+```typescript
+import { defineSystem, GetWorld, Res, Assets, serializeScene,
+ loadSceneWithAssets, findEntityByName, MissingAssetsError } from 'esengine';
+
+const checkpoint = defineSystem([GetWorld(), Res(Assets)], async (world, assets) => {
+ // Save: snapshot the live world as ordinary scene JSON.
+ const data = serializeScene(world, 'checkpoint');
+ localStorage.setItem('checkpoint', JSON.stringify(data));
+
+ // Load: preload assets, then spawn. Old saves are migrated automatically.
+ try {
+ await loadSceneWithAssets(world, JSON.parse(localStorage.getItem('checkpoint')!), {
+ assets,
+ abortOnMissingAssets: true, // throw instead of spawning with holes
+ onMissingAssets: (missing) => { // called once per load (list may be empty)
+ for (const m of missing) console.warn(`${m.ref}: ${m.reason}`);
+ },
+ });
+ } catch (e) {
+ if (e instanceof MissingAssetsError) { /* "content missing" UI — e.missing */ }
+ }
+
+ const player = findEntityByName(world, 'Player');
+});
+```
+
+`SceneLoadOptions`:
+
+| 选项 | 说明 |
+|---|---|
+| `assets` | `Assets` 资源;启用生成前的资源预加载(以及预制体实例展开)。 |
+| `assetBaseUrl` | 解析资源路径的基准 URL。 |
+| `onProgress` | `(loaded, total)` 预加载进度回调。 |
+| `onMissingAssets` | 用所有解析失败或加载失败的引用调用一次(`MissingAsset[]`——`ref`、可选 `type`、`reason: 'unresolved' \| 'load-failed'`)。列表为空也会触发。 |
+| `abortOnMissingAssets` | 默认 `false`——缺失资源拿到句柄 `0`,场景照常加载。`true` 时在预加载之后、任何实体生成之前抛出 `MissingAssetsError`。 |
+| `collectAssets` | 记账集合,加载把获取到的资源键加入其中,调用方(通常是场景管理器)卸载时据此释放。 |
+
+**版本化。** 场景文件带 `version`(当前 `SCENE_FORMAT_VERSION = '1.0'`)。
+`migrateSceneData(raw)` 把任何旧形态升级到当前格式:它从不改动输入(返回迁移后的深拷贝)、
+幂等、丢弃被引擎升级淘汰的组件类型,并**拒绝比引擎更新的数据**。每个加载器内部都会跑它——
+只有想检查 `migrated` / `fromVersion` 时才自己调用(比如提示重新保存升级后的文件):
+
+```typescript
+import { migrateSceneData } from 'esengine';
+
+const { data, migrated, fromVersion } = migrateSceneData(raw);
+if (migrated) console.log(`upgraded scene from format ${fromVersion}`);
+```
+
+**带外组件状态。** 完整状态放不进普通字段记录的组件——tilemap 图层的瓦片 chunk 存在 C++
+blob 里——注册一个 `SceneComponentCodec`,让通用(反)序列化器无需组件专有知识也能携带它:
+
+```typescript
+import { registerSceneComponentCodec } from 'esengine';
+
+registerSceneComponentCodec('MyVoxelChunk', {
+ exportData(entity, data) { data.chunks = myStore.serialize(entity); },
+ outOfBandFields: ['chunks'], // stripped before the component insert
+ importData(entity, outOfBand) { myStore.restore(entity, outOfBand.chunks); },
+});
+```
+
+保存时 `exportData` 把额外状态写进记录;加载时列出的 `outOfBandFields` 在组件插入前从记录
+中剥离,插入后交给 `importData`。注册是幂等的——由拥有它的插件在启动时完成(见
+`tilemapPlugin`)。
+
## 最佳实践
- **`await` 场景调用**——它们是异步的;未 await 的切换会与本帧其余逻辑竞态。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx b/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
index 7dfa7a542..f8e8fed35 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
@@ -187,7 +187,16 @@ const arm = defineSystem([Res(TimerRes)], (timers) => {
钩子签名——`entity`、`world`、`commands`,外加 `self`——也和[游戏 AI](/docs/zh-cn/guides/ai/) 层
的动作与行为树叶子是同一套编程模型,所以在 behavior 和 AI 动作之间搬逻辑很顺手。
-<Aside type="note">
- 热重载时,存活实体的 `start` 会再跑一次——契合 Estella 的快速重启语义,所以把 `start` 当作
- 幂等的初始化来写。
-</Aside>
+## 热重载
+
+编辑器播放期间保存代码时,只要可行就会触发**保状态热替换**:若组件形状未变、
+也没有系统被增、删或改名,存活的世界会被保留,只替换你的函数体。否则编辑器退回
+整体重载。这对你的代码的要求:
+
+- **组件与 behavior 的名字就是身份。**改名属于结构性变更——预期整体重载,该
+ 数据的状态归零。
+- 任何一种重载后,存活实体的 `start` 都会再跑一次——契合 Estella 的快速重启
+ 语义,所以把 `start` 当作幂等的初始化来写。
+
+其机制(探针上下文、模式指纹、`App.hotSwapSystems`)见
+[应用设置与生命周期](/docs/zh-cn/core-concepts/app-lifecycle/#热重载)。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx b/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
index 51c938619..960d789dc 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/sprites.mdx
@@ -1,6 +1,6 @@
---
title: 精灵与渲染
-description: 用 Sprite 组件绘制 2D 图像——纹理、着色与透明、尺寸与轴心、翻转、排序层与绘制顺序、视差——外加 ShapeRenderer 图元、精灵滤镜、拖尾与世界空间位图文字。
+description: 用 Sprite 组件绘制 2D 图像——纹理、着色与透明、尺寸与轴心、翻转、排序层与绘制顺序、视差——外加纹理过滤、点击检测、位图缓存、ShapeRenderer 图元、精灵滤镜、拖尾与世界空间位图文字。
---
import { Aside } from '@astrojs/starlight/components';
@@ -63,6 +63,21 @@ sprite.color = { r: 1, g: 1, b: 1, a: 0.5 }; // 50% 透明
1:1,或设成别的值来缩放。`Transform` 上的缩放会再乘上去。`pivot` 是精灵旋转/缩放所绕的归一化
轴心(0–1):`{0.5, 0.5}` 居中,`{0, 0}` 是左下角,`{0.5, 0}` 钉住底部中心(适合站在地面上的角色)。
+## 单位与坐标
+
+世界单位就是**设计像素**。把纹理拖进视口会生成一个尺寸等于纹理像素尺寸的精灵
+(`size = { tex.width, tex.height }`),而编辑器的相机按"一个世界单位 = 一个设计像素"
+创作(`orthoSize = designHeight / 2`)。因此 `Sprite.size` 的单位是设计像素,`pivot`
+是相对该尺寸的归一化比例。世界坐标 **Y 轴朝上**——屏幕向上是正 Y——所以
+`pivot: {0, 0}` 是**左下角**,不是左上角。
+
+<Aside type="note">
+ `Canvas.pixelsPerUnit`(默认 `100`)**不会**缩放精灵——它是**物理米尺度**:
+ 多少设计像素等于一个 Box2D 米(见[物理](/docs/zh-cn/guides/physics/))。精灵的
+ 显示尺寸只由 `size` × `Transform` 缩放决定,别无其他。完整的单位与坐标空间图景见
+ [变换](/docs/zh-cn/core-concepts/transforms/)。
+</Aside>
+
## 绘制顺序与排序层
当精灵重叠时,绘制顺序决定谁在上面。顺序由**排序层**(`sprite.layer`)决定——一个你在
@@ -96,6 +111,38 @@ sprite.layer = 2; // 例如 "Foreground" —— 画在上面
请用 [Animator](/docs/zh-cn/guides/animation/) 驱动这些,而非手动。)
- **滚动**:随时间改 `uvOffset` 来滚动纹理(水面、传送带),并设 `tileSize` 把它在大精灵上重复平铺。
+## 纹理过滤与环绕
+
+纹理的采样方式按**纹理句柄**设置,而非按精灵:
+
+| 枚举 | 取值 | 含义 |
+|---|---|---|
+| `TextureFilter` | `Nearest`、`Linear` | Nearest = 纹素边缘生硬(像素画);Linear = 平滑插值(默认)。 |
+| `TextureWrap` | `Repeat`、`ClampToEdge`、`MirroredRepeat` | 0–1 之外的 UV 采到什么——平铺重复,还是拉伸边缘像素。 |
+
+```typescript
+import { TextureFilter, TextureWrap, setTextureFilter, setTextureWrap, setTextureParams } from 'esengine';
+
+setTextureFilter(tex.handle, TextureFilter.Nearest); // 像素画保持锐利
+setTextureWrap(tex.handle, TextureWrap.Repeat); // 0–1 之外平铺
+
+// 上面两个便捷函数各自会把*另一组*参数重置为默认值
+// (ClampToEdge / Linear)。要同时设置过滤和环绕,用完整形式:
+setTextureParams(tex.handle, TextureFilter.Nearest, TextureFilter.Nearest,
+ TextureWrap.Repeat, TextureWrap.Repeat);
+```
+
+`setTextureParams(textureId, minFilter, magFilter, wrapS, wrapT)` 是完整接口——
+缩小/放大过滤分开,环绕逐轴设置。`tileSize` 平铺和 UV 滚动效果要无缝,靠的就是
+`Repeat`。
+
+<Aside type="tip">
+ 对像素画来说 `TextureFilter.Nearest` 只解决一半问题:它让**纹素**锐利,但相机
+ 停在小数位置时精灵仍会落在屏幕像素之间,移动时闪烁。把它和相机的
+ `pixelPerfect` 标志配合使用——它把(正交)相机吸附到像素网格——见
+ [相机](/docs/zh-cn/guides/camera/)。
+</Aside>
+
## 视差背景
`parallax` 缩放一个精灵相对相机的移动量:`1` 随世界移动,`0` 锁定到相机(固定背景板),中间的值
@@ -192,6 +239,92 @@ UI。把 `font` 指向一个 **BMFont** 资产(`.fnt` 文本或 `.bmfont` JSON),
屏幕空间的 UI 文字(布局、换行、SDF 锐度)请用 UI 的 `Text` 控件——见
[UI](/docs/zh-cn/guides/ui/)。
+## 精灵点击检测
+
+"这次点击落在这个精灵上了吗?"分两步:把屏幕点转到世界空间,再对精灵的矩形做测试。
+第一步由 `CameraView` 资源完成(见[相机](/docs/zh-cn/guides/camera/));第二步 SDK
+导出了感知轴心的点测试:
+
+| 函数 | 测试 |
+|---|---|
+| `pointInWorldRect(px, py, worldX, worldY, worldW, worldH, pivotX, pivotY)` | 由位置 + 轴心放置的轴对齐矩形(未旋转精灵的精确占位)。 |
+| `pointInOBB(…, rotationZ, rotationW)` | 同一矩形加**旋转**——传变换四元数的 `z`/`w`;未旋转时退化为矩形测试。 |
+| `pointInHitArea(px, py, area)` | 自定义 `HitAreaShape`——`rect`、`circle` 或 `polygon`。 |
+
+```typescript
+import { defineSystem, Query, Res, CameraView, Input, Transform, Sprite, pointInOBB } from 'esengine';
+
+const clickSprites = defineSystem(
+ [Query(Transform, Sprite), Res(CameraView), Res(Input)],
+ (q, view, input) => {
+ if (!input.isMouseButtonPressed(0)) return;
+ const p = view.screenToWorld(input.mouseX, input.mouseY);
+ if (!p) return;
+ for (const [entity, t, s] of q) {
+ const w = s.size.x * t.worldScale.x, h = s.size.y * t.worldScale.y;
+ if (pointInOBB(p.x, p.y, t.worldPosition.x, t.worldPosition.y,
+ w, h, s.pivot.x, s.pivot.y,
+ t.worldRotation.z, t.worldRotation.w)) {
+ console.log('hit', entity);
+ }
+ }
+ });
+```
+
+对可点击区域不是矩形的精灵——不规则角色、环形按钮——用精灵本地坐标描述一个
+`HitAreaShape`,再测试本地化后的点:
+
+```typescript
+import { pointInHitArea, type HitAreaShape } from 'esengine';
+
+const hull: HitAreaShape = { type: 'polygon', points: [0, 0, 64, 0, 64, 48, 32, 64, 0, 48] };
+// 未旋转的精灵,减去它的原点即可本地化:
+const hit = pointInHitArea(p.x - t.worldPosition.x, p.y - t.worldPosition.y, hull);
+```
+
+`screenToWorld` 也有独立导出(接收逆 view-projection 矩阵和视口矩形),供自己管理
+相机数学的代码使用——`CameraView` 资源就是同一个函数、替你填好了当前相机。至于
+交互式 **UI**,别手写这些:`Interactable` + `UIEvents` 会替你做拾取(见
+[UI](/docs/zh-cn/guides/ui/))。
+
+## 位图缓存(Cache as bitmap)
+
+**`CacheAsBitmap`** 支持把实体上昂贵的内容**渲染一次**进离屏纹理,之后只画这一个
+四边形——经典的 cache-as-bitmap 交换:用 GPU 内存(`width × height` RGBA)换每帧
+绘制开销。当内容每帧都画很贵(大量矢量路径、很多形状或文字)但**很少变化**时划算;
+内容每帧都变则毫无收益——你每次都得重渲缓存,*还*多付一次贴图开销。
+
+| 字段 | 默认 | 说明 |
+|---|---|---|
+| `enabled` | `true` | 该实体的缓存是否生效。 |
+| `dirty` | `true` | 设为 `true` 请求重新渲染缓存。 |
+| `width` / `height` | `256` | 缓存纹理的像素尺寸。 |
+
+这个组件是**记账的一半**——SDK 不内置自动遍历场景缓存子树的系统。刷新由你用导出的
+辅助函数驱动:逐实体缓存仓库(`getCacheForEntity`、`setCacheForEntity`、
+`removeCacheForEntity`、`clearAllCaches`)加 `CacheBitmap`——一个轻薄的渲染目标
+包装(`create`、`beginDraw`/`endDraw`、`resize`、`release`):
+
+```typescript
+import { CacheBitmap, getCacheForEntity, setCacheForEntity, Draw } from 'esengine';
+
+// 刷新(仅在 dirty 时):
+let cache = getCacheForEntity(entity);
+if (!cache) {
+ cache = CacheBitmap.create(512, 256);
+ setCacheForEntity(entity, cache);
+}
+CacheBitmap.beginDraw(cache, viewProjection); // 一个框住内容的正交矩阵
+// … 用 Draw / Graphics 把昂贵内容画一次 …
+CacheBitmap.endDraw();
+
+// 此后每帧:画一个贴图四边形,而不是整套重绘。
+Draw.texture(pos, { x: 512, y: 256 }, cache.textureId);
+```
+
+`cache.textureId` 是普通的纹理句柄——也可以直接当 `Sprite.texture` 用。底层就是一个
+不带深度缓冲的 [RenderTexture](/docs/zh-cn/guides/drawing/)。
+
## 在编辑器里
- **创建 → 精灵** 添加一个精灵实体,或从内容浏览器**把图拖**进视口,生成一个已带纹理的精灵。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/timeline.mdx b/docs/astro/src/content/docs/zh-cn/guides/timeline.mdx
index d90392b8d..033ea595f 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/timeline.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/timeline.mdx
@@ -80,13 +80,94 @@ const control = defineSystem([Query(TimelinePlayer), Res(Timeline)], (q, timelin
时间轴是一组每帧一起求值的轨道:
-| 轨道 | 驱动 |
+| 轨道 | `TrackType` | 驱动 |
+|---|---|---|
+| 属性 | `Property` | 组件字段关键帧——位置 / 旋转 / 缩放及任意数值点路径。 |
+| 精灵帧 | `AnimFrames` | 随时间切换精灵表帧。 |
+| 精灵剪辑 | `SpriteAnim` | 在某时刻启动一个命名 `anim-clip`。 |
+| 音频 | `Audio` | 在关键帧触发一次性声音。 |
+| 激活 | `Activation` | 按区间开关实体。 |
+| Spine | `Spine` | 把 Spine 动画作为片段播放。 |
+| 标记 | `Marker` | 命名时间标记。 |
+| 自定义事件 | `CustomEvent` | 带 payload 的命名事件,供你自己的系统消费。 |
+
+## 用代码构建时间轴
+
+`.estimeline` 文档就是普通数据——用 `TimelineAsset` 类型加上 `TrackType` /
+`InterpType` / `WrapMode` 常量,可以完全在代码里构建。用
+`registerTimelineAsset(path, asset)` 注册后,任何 `timeline` 指向同一路径的
+`TimelinePlayer` 都会像播放编辑器资产一样播放它:
+
+```typescript
+import {
+ defineSystem, Commands, registerTimelineAsset, TimelinePlayer,
+ TrackType, InterpType, WrapMode, type TimelineAsset,
+} from 'esengine';
+
+const slideIn: TimelineAsset = {
+ version: '1.1',
+ type: 'timeline',
+ duration: 2,
+ wrapMode: WrapMode.Once,
+ tracks: [{
+ type: TrackType.Property,
+ name: 'Slide in',
+ childPath: '', // '' = the player entity itself
+ component: 'Transform',
+ channels: [{
+ property: 'position.x',
+ keyframes: [
+ { time: 0, value: -200, inTangent: 0, outTangent: 0, interpolation: InterpType.EaseOut },
+ { time: 2, value: 0, inTangent: 0, outTangent: 0 },
+ ],
+ }],
+ }],
+};
+
+const attach = defineSystem([Commands()], (cmds) => {
+ registerTimelineAsset('code/slide-in', slideIn);
+ cmds.spawn().insert(TimelinePlayer, {
+ timeline: 'code/slide-in',
+ playing: true,
+ wrapMode: 'once',
+ });
+});
+```
+
+`Keyframe` 是 `{ time, value, inTangent, outTangent, interpolation? }`。以某
+关键帧*起始*的分段用该关键帧的 `interpolation`:`Hermite`(默认——切线驱动曲线)、
+`Linear`、`Step`、`EaseIn`、`EaseOut` 或 `EaseInOut`。属性轨道按 `childPath`
+解析目标实体(子实体名以 `/` 分隔;空 = 播放器实体本身),把通道的点路径字段写到
+命名组件上。
+
+### 循环模式
+
+播放采用**播放器组件**的 `wrapMode` 字符串;数值型 `WrapMode` 常量用在资产和纯求值
+API 里。映射与行为:
+
+| `WrapMode` | 播放器字符串 | 越过终点后的行为 |
+|---|---|---|
+| `WrapMode.Once`(`0`) | `'once'` | 停在 `duration`,停止,闩上 `finished`。 |
+| `WrapMode.Loop`(`1`) | `'loop'` | 回绕(`time % duration`)。 |
+| `WrapMode.PingPong`(`2`) | `'pingPong'` | 每周期先正放再倒放。 |
+
+`applyWrapMode(time, duration, mode)` 就是这个纯映射——对绝对时钟时间返回
+`{ time, stopped }`。
+
+### 采样与序列化
+
+求值器是纯 TypeScript,播放与编辑器 scrub 共用——你也可以自己调用:
+
+| 函数 | 说明 |
|---|---|
-| Transform | 位置 / 旋转 / 缩放关键帧(hermite / linear / step)。 |
-| 精灵帧 | 随时间切换精灵表帧。 |
-| 音频 | 在关键帧触发一次性声音。 |
-| 激活 | 开关实体。 |
-| Spine | 把 Spine 动画作为片段播放。 |
+| `sampleTimelineInWorld(asset, time, world, rootEntity, opts?)` | 在 `time` 求值所有属性轨道并把结果写进 world(即 scrub 操作)。 |
+| `sampleTimeline(asset, time, rootEntity, deps, opts?)` | 同上,但注入 `SampleDeps`(world / 组件查找 / 子实体解析)——用于测试和工具。 |
+| `evaluateChannel(channel, time)` | 单个属性通道在 `time` 的值;端点截断。 |
+| `serializeTimelineAsset(asset)` | 资产转为可 JSON 化对象(`.estimeline` 文档形状)。 |
+| `serializeTimelineToJson(asset, indent?)` | 美化打印的 `.estimeline` JSON 字符串(indent 默认 `2`)。 |
+
+采样只覆盖属性轨道;事件型轨道(音频、标记、自定义事件)在播放中按边沿检测触发,
+采样不会触发它们。
## 最佳实践
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-binding.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-binding.mdx
new file mode 100644
index 000000000..3a3dca862
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-binding.mdx
@@ -0,0 +1,203 @@
+---
+title: 数据绑定
+description: 把响应式信号写进组件字段——signal/derived/bind、bindWidgetValue 双向控件绑定,以及绑定、控制器与系统三者的取舍。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+数据绑定以**声明式**从游戏状态驱动 UI:*信号(signal)*持有一个值,*绑定*把它
+写进组件字段——立即生效,且此后每次变化都生效。它取代了命令式的"读组件、改
+字段、再插回去"循环,并且是**推(push)模型**:订阅者在 `set` 内同步运行,
+没有逐帧轮询。
+
+## 信号 —— `signal()`
+
+`signal(initial)` 创建一个可写的响应式值:
+
+```typescript
+import { signal } from 'esengine';
+
+const score = signal(0);
+
+score.get(); // → 0
+score.set(10); // notifies subscribers
+score.update((n) => n + 1); // set via the previous value
+const off = score.subscribe((n) => console.log('score is', n));
+off(); // unsubscribe
+```
+
+| `Signal<T>` 成员 | 契约 |
+|---|---|
+| `get()` | 当前值。 |
+| `set(value)` | 存储 + 通知——但**仅当值真的变了**(`Object.is`);写入未变的值零开销。 |
+| `update(fn)` | 即 `set(fn(previous))`。 |
+| `subscribe(fn)` | 每次变化时调用;返回退订函数。 |
+
+`ReadonlySignal<T>` 是只含 `get` + `subscribe` 的那一半——`derived` 返回它、
+`bind` 接受它,消费方因此无法写回一个只应读取的来源。
+
+## 派生值 —— `derived()`
+
+`derived(sources, compute)` 是由其他信号计算而来的只读信号;任一来源变化时它
+重算(且同样只在真的变化时通知):
+
+```typescript
+import { signal, derived } from 'esengine';
+
+const health = signal(75);
+const maxHealth = signal(100);
+const healthFrac = derived([health, maxHealth], () => health.get() / maxHealth.get());
+```
+
+<Aside type="caution">
+ `derived` 对来源的订阅存续到进程结束——请用于**应用生命周期**的派生
+ (分数文本、血量比例),不要为短命实体逐个铸造。
+</Aside>
+
+## 单向绑定 —— `bind()`
+
+`bind(world, entity, Component, field, source)` 用一个 `ReadonlySignal` 驱动
+一个组件字段:
+
+```typescript
+import { signal, derived, bind, Text } from 'esengine';
+
+const score = signal(0);
+bind(world, scoreLabel, Text, 'content',
+ derived([score], () => `Score: ${score.get()}`));
+
+score.set(1200); // the label now reads "Score: 1200"
+```
+
+按源码给出的契约:
+
+- 字段以信号的当前值**立即播种**,此后跟随每次变化。
+- 写入有**守卫**——实体已消失或丢失该组件时跳过——并经由 `world.insert`
+ 完成(一次完整的组件写入,与任何其他变更一致)。
+- 绑定在**实体销毁(despawn)时自动解除**;同时返回手动 dispose,可提前解绑。
+- 类型端到端对齐:`bind(world, e, Text, 'content', source)` 要求 `source` 是
+ `ReadonlySignal<string>`,因为 `Text.content` 是字符串。
+
+任何反射字段都同理——用 `ReadonlySignal<Color>` 驱动 `UIVisual.color`、
+`Text.color`,或 `UINode` 的某个尺寸,等等。
+
+## 双向控件绑定 —— `bindWidgetValue()`
+
+值控件(滑杆、开关、下拉框)需要双向流量:信号写入**向下**流进控件的值字段,
+用户输入**向上**从控件的 `change` 事件流回信号。`bindWidgetValue` 把两个方向
+一次接好:
+
+```typescript
+bindWidgetValue(world, events, entity, Component, field, signal, payloadKey?)
+```
+
+- **向下**:一条 `bind` 把信号写进字段;控件的行为系统观察组件,更新视觉并
+ 发出 `change`。
+- **向上**:控件的 `change` 事件把 payload 里的值写回信号。
+- **不成环**:信号就是断环器——`Signal.set` 与向下绑定对相等值都是 no-op,
+ 一次往返一跳即收敛。
+- 返回的 dispose 同时拆除两个方向(向下绑定在实体销毁时也会自动解除)。
+
+`payloadKey` 指名 `change` payload 里承载值的字段,默认与组件字段同名:
+
+| 控件 | 组件 / 字段 | `payloadKey` |
+|---|---|---|
+| 滑杆 | `UISlider.value` | `'value'`(默认) |
+| 开关 | `UIToggle.isOn` | `'isOn'`(默认) |
+| 下拉框 | `UIDropdown.selectedIndex` | `'index'`(需显式传入) |
+
+一行音量控件——滑杆与标签绑到同一个信号:
+
+```typescript
+import {
+ defineSystem, addStartupSystem, GetWorld, Res, UIEvents,
+ spawnUIEntity, createSlider, px,
+ signal, derived, bind, bindWidgetValue,
+ UISlider, Text,
+} from 'esengine';
+
+const buildVolumeRow = defineSystem([GetWorld(), Res(UIEvents)], (world, events) => {
+ const volume = signal(0.8);
+
+ // The slider: dragging it (or arrow keys while focused) writes `volume` up.
+ const slider = createSlider({
+ world, events,
+ node: { width: px(240), height: px(20) },
+ min: 0, max: 1, value: volume.get(),
+ });
+ bindWidgetValue(world, events, slider.entity, UISlider, 'value', volume);
+
+ // The label: follows the same signal down.
+ const label = spawnUIEntity({ world, text: { content: '' } });
+ bind(world, label, Text, 'content',
+ derived([volume], () => `${Math.round(volume.get() * 100)}%`));
+
+ // Game code sets the signal; the slider fill+handle AND the label follow.
+ volume.set(0.5);
+});
+
+addStartupSystem(buildVolumeRow);
+```
+
+因为向下这一边写的是*组件*,而控件的行为系统是视觉的唯一写者,所以每种写入方
+——指针、绑定、句柄上的 `setValue`、编辑器检视器——移动填充与手柄、触发
+`change` 的方式完全一致。
+
+## 绑定控制器页
+
+`bindControllerPage(world, entity, controller, source)` 用一个
+`ReadonlySignal<string>` 驱动 [UI 控制器](/docs/zh-cn/guides/ui-controllers/)
+的当前页——数据驱动页签栏的声明式路径。设置信号,页切换,所有 geared 元素
+随之重排:
+
+```typescript
+import { signal, bindControllerPage } from 'esengine';
+
+const activeTab = signal('home');
+bindControllerPage(world, root, 'tab', activeTab);
+activeTab.set('shop');
+```
+
+生命周期与 `bind` 相同:立即播种、实体销毁时自动解除、返回手动 dispose。未知
+的控制器/页被忽略而非抛错。
+
+## 绑定与列表
+
+[ListView](/docs/zh-cn/guides/ui-lists/) 本身*已经*是数据驱动的——它渲染自
+`DataSource`(例如 `ArrayDataSource`),带细粒度的插入/删除/更新通知,这是
+虚拟化所必需、而单个值信号表达不了的。所以:**集合放进 `DataSource`,标量 UI
+状态放进信号**,两者组合使用——条目模板的 `bind` 回调可以读信号,而一个信号
+(比如选中的 id)可以与拥有行数据的 data source 并肩存在。
+
+## 绑定 vs 控制器 vs 系统
+
+把游戏状态搬上屏幕的三条路——按状态的形状选:
+
+| 状态形状 | 用 | 原因 |
+|---|---|---|
+| 一个**值**——分数、血量、名字、滑杆位置 | `signal` + `bind` / `bindWidgetValue` | 变化时推送,无轮询;值控件可双向。 |
+| 有限集合中的一个**命名状态**——页签、开/关、按钮状态 | [控制器 + gear](/docs/zh-cn/guides/ui-controllers/) | 一次翻页带动多元素重排;可在编辑器创作;支持补间。用 `bindControllerPage` 从数据接入。 |
+| 一个**集合**——背包行、排行榜 | `DataSource` + [ListView](/docs/zh-cn/guides/ui-lists/) | 细粒度变更通知驱动虚拟化。 |
+| 由模拟派生的**逐帧**值——冷却扫过、跟随玩家的标记 | 普通[系统](/docs/zh-cn/guides/scripting/)写组件 | 值本来每帧都变;query 是天然的读者。 |
+
+经验法则:如果你正要写一个只在变量变化时把它拷进组件的系统,那就是一条
+`bind`。如果你正要在模式切换时手动给五个实体设颜色,那就是一个控制器。
+
+## 最佳实践
+
+- **一个事实一个信号。** 展示字符串用 `derived` 派生,别存格式化文本。
+- **让 despawn 收尾。** 系于实体的绑定会自我解除;只有需要在实体死*之前*解绑
+ 时才保留返回的 dispose。
+- **双向只在控件边缘。** 滑杆用 `bindWidgetValue`;其余一律单向读信号。
+- **别和相等断环较劲。** 信号用 `Object.is` 比较——对象值要 `set` 一个*新*
+ 对象;原地改旧对象不会通知任何人。
+- **游戏逻辑别放订阅者里。** 订阅者在 `set` 内同步运行;重活会卡住写入方。
+ 绑定管 UI,模拟归系统。
+
+## 参见
+
+- [UI](/docs/zh-cn/guides/ui/) —— 绑定所写入的组件模型。
+- [UI 控件](/docs/zh-cn/guides/ui-components/) —— 值控件(`createSlider`、`createToggle`、`createDropdown`)。
+- [UI 控制器](/docs/zh-cn/guides/ui-controllers/) —— 命名的页状态 + gear;`bindControllerPage` 把信号接进去。
+- [UI 列表](/docs/zh-cn/guides/ui-lists/) —— `DataSource` 驱动的虚拟化列表。
+- [主题](/docs/zh-cn/guides/ui-theme/) —— 设计令牌与实时换肤。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
index 079dd9bff..70cdb6970 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
@@ -1,19 +1,21 @@
---
title: UI 控件
-description: 内置控件工厂——Button、Toggle、Slider、Progress、Dropdown、Dialog、ListView——外加文本输入、拖放、键盘焦点、移动端安全区与主题。
+description: 内置控件工厂——Button、Toggle、Slider、Progress、Dropdown、Dialog 与文本输入——的选项、句柄与状态组件,外加编辑器预制体。
---
import { Aside } from '@astrojs/starlight/components';
控件工厂用 [UI](/docs/zh-cn/guides/ui/) 组件模型(`UINode` + `Interactable` +
-`$interaction` [控制器与属性绑定](/docs/zh-cn/guides/ui-controllers/))构建常见控件,免得你逐个手动接线。每个工厂接收一个选项对象,返回一个**句柄(handle)**——
+`$interaction` [控制器与属性绑定](/docs/zh-cn/guides/ui-controllers/))构建常见控件,
+免得你逐个手动接线。每个工厂接收一个选项对象,返回一个**句柄(handle)**——
总是带 `entity` 和 `dispose()`,外加读取和驱动它的命令式方法。
-交互式控件需要 world 和 UI 事件队列——`world` 来自 `GetWorld()`,`events` 来自 `Res(UIEvents)`,
-和 [UI 指南](/docs/zh-cn/guides/ui/)里一样。它们都接受 `parent?`、一个 `node?`
-([`UINode`](/docs/zh-cn/guides/ui/#uinode--the-layout-box) 布局)和视觉覆盖。交互式控件
-**默认键盘可达**:它们自带 `Focusable`,Tab 能到达、Enter/Space 能点击、方向键能驱动滑块——
-用 `focusable: false` 退出。
+交互式控件需要 world 和 UI 事件队列——`world` 来自 `GetWorld()`,`events` 来自
+`Res(UIEvents)`,和 [UI 指南](/docs/zh-cn/guides/ui/)里一样。它们都接受 `parent?`、
+一个 `node?`([`UINode`](/docs/zh-cn/guides/ui-layout/) 布局——**默认:填满父级**)
+和视觉覆盖;视觉默认值取自当前[主题](/docs/zh-cn/guides/ui-theme/)的角色,
+主题热切换时会重新解析。交互式控件**默认键盘可达**:它们自带 `Focusable`,
+Tab 能到达、Enter/Space 能点击、方向键能驱动滑块——用 `focusable: false` 退出。
<Aside type="tip">
这些是方便的起点,而非封闭集合——一个控件不过是挂了 UI 组件的实体树,所以你能用同样方式组合
@@ -48,23 +50,26 @@ const btn = createButton({
});
```
-| 选项 | 说明 |
-|---|---|
-| `text` | 标签——字符串或 `TextInit`。省略则无标签。 |
-| `states` | 状态名(`normal` / `hover` / `pressed` / `disabled` / `focused`)→ 颜色 / sprite / 缩放覆盖的映射。省略则用当前主题的 control 角色。 |
-| `background` | 背景视觉(默认:纯白)。 |
-| `fadeDuration` | 颜色 / 缩放状态切换的补间时长(默认 `0` = 瞬切;sprite 交换总是瞬切)。 |
-| `disabled` | 初始禁用。 |
-| `focusable` / `tabIndex` | 键盘可达性(默认 `true` / `0`)。 |
-| `onClick(entity)` | 点击回调。 |
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `node` | 填满父级 | 按钮的 `UINode` 布局。 |
+| `text` | 无 | 标签——字符串或 `TextInit`。省略则无标签。标签颜色/字号默认取主题的 `text` 角色与 label 字号。 |
+| `states` | 主题 control 角色 | 状态名(`normal` / `hover` / `pressed` / `disabled` / `focused`)→ 颜色 / 精灵 / 缩放覆盖的 map。允许自定义名(如 `'loading'`)。 |
+| `background` | 纯白 | 背景视觉(`UIVisualInit`)。 |
+| `fadeDuration` | `0`(瞬切) | 颜色/缩放状态切换的补间时长;精灵切换总是瞬切。 |
+| `disabled` | `false` | 以禁用态启动。 |
+| `focusable` / `tabIndex` | `true` / `0` | 键盘可达性与 Tab 顺序。 |
+| `onClick(entity)` | — | 点击回调(受启用态门控)。 |
**句柄:** `entity`、`setDisabled(disabled)`、`dispose()`。
-之后可用 `setButtonState(world, handle.entity, 'loading')` 切到自定义状态。
+主题默认状态也以 `themeButtonStates()` 导出——展开再覆盖,不必五个状态全写一遍。
+之后可用 `setButtonState(world, handle.entity, 'loading')` 切到自定义状态;
+指针驱动会放过任何非规范页,直到你切回去。
## Toggle 开关
-`createToggle(opts)` 用一个按钮加一个开/关勾选指示器组合而成。返回 `ToggleHandle`。
+`createToggle(opts)` 由一个按钮加一个开/关指示器组合而成。返回 `ToggleHandle`。
```typescript
import { createToggle } from 'esengine';
@@ -72,33 +77,37 @@ import { createToggle } from 'esengine';
const toggle = createToggle({
world, events, parent,
interactionStates: { normal: { color: /* … */ }, hover: { /* … */ }, pressed: { /* … */ } },
- check: { color: { r: 0.2, g: 0.8, b: 0.4, a: 1 } }, // "开"指示器
+ check: { color: { r: 0.2, g: 0.8, b: 0.4, a: 1 } }, // the "on" indicator
isOn: true,
onChange: (isOn, entity) => { /* … */ },
});
-toggle.setIsOn(false); // 程序化改变(触发 onChange)
+toggle.setIsOn(false); // programmatic change (fires onChange)
```
-| 选项 | 说明 |
-|---|---|
-| `interactionStates` | 框架视觉状态(类似按钮的 `states`;省略则用主题默认)。 |
-| `check` | 开状态指示器:`{ node?, color?, sprite? }`,开时显示(默认主题强调色)。 |
-| `isOn` | 初始状态。 |
-| `onChange(isOn, entity)` | 切换时触发。 |
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `node` / `background` | 填满父级 / 纯白 | 外框布局 + 背景,同 `createButton`。 |
+| `interactionStates` | 主题 control 角色 | 外框的视觉状态(同按钮的 `states`)。 |
+| `check` | 主题 `primary` 填充 | 开启态指示器:`{ node?, color?, sprite? }`,开时显示的子实体。默认填满外框——用 `check.node` 内缩。 |
+| `isOn` | `false` | 初始状态。 |
+| `disabled` | `false` | 以禁用态启动。 |
+| `focusable` / `tabIndex` | `true` / `0` | 键盘可达性。 |
+| `onChange(isOn, entity)` | — | 切换时触发。 |
**句柄:** `isOn()`、`setIsOn(value)`、`setDisabled(disabled)`、`entity`、`dispose()`。
<Aside type="note">
- 状态存在 **`UIToggle` 组件**里;行为系统在点击时翻转它,并且是勾选视觉的唯一写者——
- `setIsOn`、绑定、或编辑器 Inspector 改摆放的 prefab,都会同样地翻转指示器并触发 `change`。
+ 状态活在 **`UIToggle` 组件**里;行为系统在点击时翻转它,并且是勾选视觉的唯一写入者——
+ `setIsOn`、绑定、或编辑器里已摆放预制体的 inspector,翻转指示器和发 `change` 的方式
+ 完全一致。
</Aside>
## Slider 滑块
`createSlider(opts)` 构建轨道 + 填充 + 手柄。返回 `SliderHandle`。
-输入是内置的:在轨道上任意位置**拖拽**(按下即捕获,直到松开),或聚焦后用**方向键**
-(步长为 `step`,连续滑块为量程的 1%)、**Home**/**End**。
+输入内置:在轨道任意处**拖拽**(按下即捕获直到松开),或聚焦后用**方向键**
+(`step`,连续滑块为量程的 1%)、**Home**/**End**。
```typescript
import { createSlider } from 'esengine';
@@ -112,27 +121,30 @@ const slider = createSlider({
slider.setValue(75);
```
-| 选项 | 说明 |
-|---|---|
-| `min` / `max` / `value` | 范围与初始值。 |
-| `step` | 量化步长(`0` = 连续)。同时是键盘步进量。 |
-| `handleWidth` | 手柄宽度(像素,默认 `12`)。 |
-| `disabled` / `focusable` / `tabIndex` | 交互性与键盘可达性。 |
-| `trackVisual` / `fillVisual` / `handleVisual` | 各部件视觉。 |
-| `onChange(value, entity)` | 值改变时触发——无论来自输入、`setValue` 还是任何其他写者。 |
-
-**句柄:** `getValue()`、`setValue(v)`、`dispose()`,以及 `trackEntity` /
-`fillEntity` / `handleEntity`。
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `node` | 填满父级 | 轨道的 `UINode` 布局。 |
+| `min` / `max` | `0` / `1` | 量程。 |
+| `value` | `min` | 初始值(会收敛并按步长量化)。 |
+| `step` | `0`(连续) | 量化步长。同时是键盘步进量。 |
+| `handleWidth` | `12` | 手柄宽度(像素)。 |
+| `disabled` / `focusable` / `tabIndex` | `false` / `true` / `0` | 交互性 + 键盘可达性。 |
+| `trackVisual` / `fillVisual` / `handleVisual` | 主题 `track` / `primary` / `onPrimary` | 各部分视觉。 |
+| `onChange(value, entity)` | — | 值变化时触发——无论来自输入、`setValue` 还是任何其他写入者。 |
+
+**句柄:** `getValue()`、`setValue(v)`、`dispose()`,外加 `entity` /
+`trackEntity`(同一实体)/ `fillEntity` / `handleEntity`。
<Aside type="note">
- 状态存在轨道实体上的 **`UISlider` 组件**里;行为系统是视觉的唯一写者。任何写
- `UISlider.value` 的东西——指针、键盘、`setValue`、编辑器 Inspector 里改摆放的
- prefab——都会同样地移动填充与手柄并触发 `change`。
+ 状态活在轨道实体的 **`UISlider` 组件**上;行为系统是视觉的唯一写入者。任何写
+ `UISlider.value` 的东西——指针、键盘、`setValue`、编辑器里已摆放预制体的 inspector——
+ 移动填充和手柄、发 `change` 的方式完全一致。
</Aside>
## Progress 进度条
-`createProgress(opts)` 是一个非交互的填充条。返回 `ProgressHandle`。
+`createProgress(opts)` 是不可交互的填充条。返回 `ProgressHandle`。
+它不接 `events`——没有可交互的东西。
```typescript
import { createProgress } from 'esengine';
@@ -146,32 +158,34 @@ const bar = createProgress({
bar.setValue(0.6); // 0..1
-// 径向仪表(冷却 / 环形计量)——从 12 点钟方向顺时针扫过的扇形:
+// Radial gauge (cooldown / ring meter) — a clockwise wedge from 12 o'clock:
const ring = createProgress({ world, parent, radial: true, value: 0.75 });
```
-| 选项 | 说明 |
-|---|---|
-| `value` | 初始进度,`0..1`。 |
-| `direction` | 线性填充增长方向:`'right'`(默认)、`'left'`、`'up'`、`'down'`。 |
-| `radial` | 用径向仪表替代进度条——顺时针扫过整圆的扇形。忽略 `direction`。 |
-| `background` / `fill` | 轨道和填充视觉。 |
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `node` | 填满父级 | 轨道的 `UINode` 布局。 |
+| `value` | `0` | 初始进度,`0..1`(收敛)。 |
+| `direction` | `'right'` | 线性填充增长方向:`'right'`、`'left'`、`'up'`、`'down'`。 |
+| `radial` | `false` | 径向仪表而非条——从 12 点顺时针扫满一圈的扇形。忽略 `direction`。 |
+| `background` | 主题 `track` | 轨道视觉(`UIVisualInit`)。 |
+| `fill` | 主题 `primary` | 填充条:`{ color?, sprite? }`。 |
-**句柄:** `value()`、`setValue(v)`、`dispose()`,以及 `fillEntity`。
+**句柄:** `value()`、`setValue(v)`、`dispose()`,外加 `entity` / `fillEntity`。
<Aside type="note">
- **同一个填充原语。** 进度条就是一个处于 **`Filled`** 模式的
- [`UIVisual`](/docs/guides/ui/)——与滑块填充共用同一个原语,对应 Unity 的
- "血条 = Filled Image"。`setValue()` 写入 `fillAmount`,因此填充是渲染期裁剪、
- **不触发每帧布局**,贴图填充会沿轴**揭示**而非拉伸。`direction` 通过共享的
- `FILL_AXIS` 表解析为 `Filled` 的裁剪轴与锚定边,让进度条、滑块以及其他基于
- Filled 的控件填充行为完全一致。
+ **同一个填充原语。** 进度条就是一个 **`Filled`** 模式的
+ [`UIVisual`](/docs/zh-cn/guides/ui/)——滑块的填充也构建于同一原语,对应 Unity 的
+ "血条 = Filled Image"。`setValue()` 写 `fillAmount`,所以填充是渲染期裁剪,
+ **没有逐帧布局**,精灵填充沿轴*揭示*而不是拉伸。`direction` 经共享的 `FILL_AXIS`
+ 表解析为 `Filled` 的裁剪轴与锚边,因此进度条、滑块以及任何基于 Filled 的控件填充方式
+ 完全一致。
</Aside>
-## Dropdown 下拉
+## Dropdown 下拉框
-`createDropdown(opts)` 显示当前选择,并弹出一个选项行列表。它对选项类型是泛型的。返回
-`DropdownHandle<T>`。
+`createDropdown(opts)` 显示当前选中项,并打开一个选项行弹窗。对选项类型泛型。
+返回 `DropdownHandle<T>`。
```typescript
import { createDropdown } from 'esengine';
@@ -183,40 +197,42 @@ const dd = createDropdown({
onSelect: (index, option) => { /* … */ },
});
-// 对象需要一个标签映射:
+// Objects need a label mapper:
createDropdown({
world, events, parent,
- options: resolutions, // 例如 { w, h }[]
+ options: resolutions, // e.g. { w, h }[]
optionToLabel: (r) => `${r.w}×${r.h}`,
onSelect: (i, r) => applyResolution(r),
});
```
-| 选项 | 说明 |
-|---|---|
-| `options` | 可选值列表。 |
-| `selectedIndex` | 初始选择。 |
-| `optionToLabel(option, i)` | 把非字符串选项映射为显示文本。 |
-| `buttonStates` | 主按钮的颜色(选项行走主题角色)。 |
-| `optionHeight` | 行高(像素,默认 `32`)。 |
-| `disabled` / `focusable` / `tabIndex` | 交互性与键盘可达性。 |
-| `onSelect(index, option, entity)` | 选择时触发。 |
-
-**句柄:** `getSelected()`、`getSelectedIndex()`、`setSelectedIndex(i)`、`open()`、
-`close()`、`isOpen()`、`dispose()`。
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `node` | 填满父级 | 主按钮的 `UINode` 布局。 |
+| `options` | — | 可选值列表。必填。 |
+| `selectedIndex` | `0` | 初始选中。 |
+| `optionToLabel(option, i)` | `String(option)` | 把非字符串选项映射为显示文本。 |
+| `buttonStates` | 主题 control 角色 | 主按钮的 `{ normal?, hover?, pressed? }` 颜色(选项行用主题角色)。 |
+| `optionHeight` | `32` | 行高(像素)。 |
+| `disabled` / `focusable` / `tabIndex` | `false` / `true` / `0` | 交互性 + 键盘可达性。 |
+| `onSelect(index, option, entity)` | — | 选中时触发。 |
+
+**句柄:** `getSelected()`、`getSelectedIndex()`、`setSelectedIndex(i)`、
+`open()`、`close()`、`isOpen()`、`dispose()`,外加 `entity` / `labelEntity`
+(显示当前选中项的子 `Text`)。
<Aside type="note">
- 标签与选择存在 **`UIDropdown` 组件**里;行为系统拥有弹出层(点击开合,**点击其他任意位置
- 自动关闭**)、行选择、以及键盘:开合两态方向键都能换选(打开的弹出层高亮选中行),
- **Enter** 确认、**Escape** 取消——摆出来的 prefab 无需代码即完整可用。
- 弹出层每次打开都用新鲜的主题角色重建。
+ 标签 + 选中项活在 **`UIDropdown` 组件**里;行为系统拥有弹窗(点击开合,
+ **点其他任何地方都会关闭**)、行选中和键盘:方向键在开合两态都步进选中
+ (打开的弹窗高亮选中行),**Enter** 确认、**Escape** 取消——所以预制体摆放的下拉框
+ 无需代码即可完整工作。弹窗每次打开都用新的主题角色重建。
</Aside>
## Dialog 对话框
-`createDialog(opts)` 是一个模态:一个挡住点击的背景加一个居中面板,打开前隐藏。返回
-`DialogHandle`。**把你的内容作为 `panelEntity` 的子实体加进去**——关闭时会在背景根上
-设置 `display: none`,整棵子树(包括你的内容)一次性退出布局、渲染和输入。
+`createDialog(opts)` 是模态框:挡点击的背板 + 居中面板,打开前隐藏。返回 `DialogHandle`。
+**把你的内容挂为 `panelEntity` 的子级**——关闭时在背板根上写 `display: none`,
+整棵子树(含你的内容)一次写入就退出布局、渲染和输入。
```typescript
import { createDialog, spawnUIEntity } from 'esengine';
@@ -226,256 +242,151 @@ const dialog = createDialog({
panelNode: { width: px(420), height: px(260) },
});
-spawnUIEntity({ world, parent: dialog.panelEntity, text: { content: '确定吗?' } });
+spawnUIEntity({ world, parent: dialog.panelEntity, text: { content: 'Are you sure?' } });
dialog.open();
-// …之后
+// …later
dialog.close();
```
-| 选项 | 说明 |
-|---|---|
-| `backdropNode` / `backdropVisual` | 面板后方的全视口遮罩。 |
-| `panelNode` / `panelVisual` | 模态面板(默认:400×300,居中)。 |
-| `startHidden` | 初始关闭(默认 `true`)。 |
-| `closeOnEscape` / `closeOnBackdrop` | 两个标准关闭方式——Escape,以及点击遮罩(不含面板)。都默认 `true`。 |
-| `onOpenChange(open)` | 每次开/关都会触发,无论由谁发起。 |
-
-对话框打开期间还会**捕获 Tab 环**:只有打开对话框子树内的可聚焦控件参与轮换
-(遮罩本来就挡住了外部的指针聚焦)。
-
-**句柄:** `open()`、`close()`、`isOpen()`、`dispose()`,以及 `entity`(背景根)/ `panelEntity`。
-
-<Aside type="note">
- 关闭行为由背景根上的 **`UIDialog` 组件**数据驱动,打开状态就是根的
- `UINode.display`——因此从编辑器 prefab 实例化的对话框无需任何代码就能响应
- Escape / 遮罩点击。
-</Aside>
-
-## 列表与集合
-
-对于长的、可滚动的、**数据驱动**的列表——背包、排行榜、聊天记录——`createListView` 构建一个
-**虚拟化**列表(或网格):只有视口附近的条目会被挂载,所以一万行的列表也很轻。一次调用就组合了
-数据源、布局、条目回收、滚动和裁剪。
-
-```typescript
-import { createListView, uiPlugin, arrayDataSource, spawnUIEntity, px } from 'esengine';
-
-const list = createListView<Player>({
- world, host: uiPlugin, parent,
- viewportSize: { x: 320, y: 480 }, // 可见窗口,像素
- data: arrayDataSource(players), // 任意 DataSource<T>,或裸数组
- layout: { itemHeight: 56 }, // 列表
- item: {
- create: (world, parent) => spawnUIEntity({ world, parent, node: { height: px(56) } }),
- bind: (entity, player, index) => { /* 用 `player` 填这行的 Text / Sprite */ },
- },
-});
-```
-
-`host` 是驱动虚拟化并路由滚动输入的插件——传你 app 构建时用的 `uiPlugin`。
-`item.create` 建一个行实体;`item.bind` 用数据填它。`bind` 每当一行被复用到不同索引时都会跑,
-所以把它写成纯粹的"应用这份数据"函数。
-
-**布局**是列、行或网格:
-
-| `layout` | 结果 |
-|---|---|
-| `{ itemHeight }` | 竖直列表——固定行高,或传 **`(index) => number`** 实现[自适应行高](#自适应行高)。 |
-| `{ itemWidth, direction: 'row' }` | 水平列表。 |
-| `{ columns, itemSize }` | 网格(*TileView*)。 |
-
-**更新**列表 = 改它的数据源——`ArrayDataSource` 会通知视图,视图在下一帧重新同步:
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `backdropNode` / `backdropVisual` | 填满父级 / 主题 `backdrop` 幕布 | 面板背后的全视口幕布。它拦截指针命中但不可聚焦。 |
+| `panelNode` / `panelVisual` | 400×300 居中 / 主题 `surface` | 模态面板。面板吞掉点击,只有真正点在幕布上才触发关闭。 |
+| `startHidden` | `true` | 以关闭态启动。 |
+| `closeOnEscape` / `closeOnBackdrop` | `true` / `true` | 标准关闭方式——Escape,以及点击幕布(非面板)。 |
+| `onOpenChange(open)` | — | 每次开/关都触发,无论谁发起。 |
-```typescript
-list.data.append([newPlayer]); // 增
-list.data.remove(3); // 删索引 3
-list.data.update(0, updatedPlayer); // 改一个
-list.data.setItems(freshList); // 全替换
-```
+对话框打开期间还会**困住 Tab 环**:只有打开的对话框子树内的可聚焦项参与
+(幕布本就挡住了外部的指针聚焦)。
-**句柄:** `data`(改它来改列表)· `scrollToIndex(i)` · `refresh()` · `mountedCount()`
-(永远不随数据量增长——测试里好用)· `dispose()`,以及 `scroll` 和 `view` 作为通往底层
-`ScrollContainer` / `ListView` 的逃生舱。
+**句柄:** `open()`、`close()`、`isOpen()`、`dispose()`,外加 `entity`(背板根)/
+`panelEntity`。
<Aside type="note">
- 滚动开箱即用:视口上的鼠标滚轮、指针**拖拽 + 惯性甩动**(平台层把主触点并入指针流,
- 触摸滚动走同一条路径),以及每个可滚动轴的**自动淡出悬浮滚动条**(ScrollContainer 传
- `showScrollbar: false` 关闭)。可用 `dragScroll: false` 关闭,或用 `decelerationRate` 调惯性
- (甩动 1 秒后剩余的速度比例;默认 `0.135`,ScrollRect 标准值)。异构行:用「item 类型 → 模板」
- 的映射代替单个 `item`,并给数据源一个 `getItemType(i)`。
+ 关闭行为由背板根上的 **`UIDialog` 组件**数据驱动,而打开状态就是根的
+ `UINode.display`——所以从编辑器预制体实例化的对话框无需任何代码接线,
+ Escape / 点幕布即可关闭。
</Aside>
-### 自适应行高
-
-给 `itemHeight` 传一个**函数**,让每行按内容自适应高度——聊天记录里气泡随换行文本增高就是
-典型场景。列表会缓存测量结果,并在数据或视口变化时重排:
-
-```typescript
-import { measureText } from 'esengine';
-
-createListView<Message>({
- world, host: uiPlugin, parent,
- viewportSize: { x: 360, y: 480 },
- data: messages,
- layout: {
- itemHeight: (i) => measureText(messages.getItem(i).text, {
- fontSize: 14, maxWidth: 320,
- }).height + 16, // 换行文本高度 + 上下内边距
- spacing: 8,
- },
- item: { /* create / bind */ },
-});
-```
-
-`measureText(text, { fontSize, maxWidth?, bold?, italic?, letterSpacing?, lineHeight? })`
-返回 `{ width, lineCount, height }`,用的是**渲染器取字形 advance 的同一套 Canvas2D 度量**,
-所以测出的高度和实际渲染一致——不再有裁剪或溢出的行(无 DOM 的环境回退到平均字宽估算)。
-
-### 自由内容滚动
-
-滚动**任意内容**的面板(设置页、长表单)——不虚拟化、无数据源——用 `createScrollView`,
-把内容挂到它的 `content` 帧下:
-
-```typescript
-import { createScrollView, uiPlugin } from 'esengine';
-
-const panel = createScrollView({
- world, host: uiPlugin, parent,
- viewportSize: { x: 320, y: 480 },
- contentSize: { x: 320, y: 1200 },
-});
-// 在 panel.content 下构建内容 …
-panel.scrollTo({ x: 0, y: 300 });
-```
-
-滚轮、拖拽/触摸和惯性甩动与列表视图完全一致;内容变大后调 `setContentSize()`。
-
## 文本输入
-`createTextInput(opts)` 构建可编辑输入框——背景、光标、占位提示和 IME 管线都齐了——
-颜色走主题角色,换主题时会重新解析。返回 `TextInputHandle`(`getValue()` /
-`setValue(v)` / `entity` / `dispose()`)。
+`createTextInput(opts)` 构建可编辑输入框——背景、光标、占位符与 IME 管线齐备——
+颜色取主题角色,主题切换时重新解析。返回 `TextInputHandle`:
+`getValue()` / `setValue(v)` / `entity` / `dispose()`。
```typescript
import { createTextInput } from 'esengine';
const name = createTextInput({
world, events, parent,
- placeholder: '你的名字', maxLength: 20,
- onChange: (value) => { /* 内容被编辑 */ },
- onSubmit: (value) => save(value), // 回车
+ placeholder: 'Your name', maxLength: 20,
+ onChange: (value) => { /* value edited */ },
+ onSubmit: (value) => save(value), // Enter
});
```
-工厂是 `TextInput` **组件**之上的糖——想完全手动控制,把组件直接插到任意 UI 实体上:
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `node` | 220×32 | 输入框的 `UINode` 布局(唯一不默认填满父级的工厂)。 |
+| `value` / `placeholder` | `''` | 内容 / 为空时的提示。 |
+| `maxLength` | `0` | 字符上限(`0` = 不限)。 |
+| `multiline` | `false` | Enter 插入换行而不是提交。 |
+| `password` | `false` | 掩码显示字符。 |
+| `readOnly` | `false` | 可聚焦但不可编辑。 |
+| `fontSize` / `fontFamily` | 主题 label 字号 / `'Arial'` | 文本样式。 |
+| `color` / `backgroundColor` / `placeholderColor` | 主题 `text` / `control` / 淡化 `text` | 颜色覆盖——省略时用主题角色。 |
+| `padding` | `6` | 内部水平内边距(px)。 |
+| `renderMode` | `Auto` | 输入框文字的字形管线——`Auto`(未缩放时清晰位图,缩放后 SDF)、恒 `Bitmap`、或恒 `Sdf`。 |
+| `disabled` / `tabIndex` | `false` / `0` | 交互性 + Tab 顺序。文本框永远可聚焦——它就是干这个的。 |
+| `onChange(value, entity)` | — | 每次编辑触发。 |
+| `onSubmit(value, entity)` | — | Enter 触发(单行)。 |
+
+工厂是 `TextInput` **组件**之上的语法糖——直接把组件插到任意 UI 实体上可获得完全的
+手动控制(字段同上,外加实时的 `focused` / `cursorPos` 状态):
```typescript
import { spawnUIEntity, TextInput, px } from 'esengine';
const field = spawnUIEntity({ world, parent, node: { width: px(240), height: px(32) } });
-world.insert(field, TextInput, { placeholder: '你的名字', maxLength: 20 });
+world.insert(field, TextInput, { placeholder: 'Your name', maxLength: 20 });
-events.on(field, 'change', () => { /* 内容被编辑 */ });
-events.on(field, 'submit', () => save(world.get(field, TextInput).value)); // 回车
+events.on(field, 'change', () => { /* value edited */ });
+events.on(field, 'submit', () => save(world.get(field, TextInput).value)); // Enter
```
-| 字段 | 默认 | 说明 |
-|---|---|---|
-| `value` / `placeholder` | `''` | 内容 / 为空时显示的提示。 |
-| `maxLength` | `0` | 字符上限(`0` = 不限)。 |
-| `multiline` | `false` | 回车插入换行而不是提交。 |
-| `password` | `false` | 掩码显示。 |
-| `readOnly` | `false` | 可聚焦但不可编辑。 |
-| `fontSize` / `fontFamily` | `16` / `Arial` | 文字样式——`color`、`placeholderColor`、`backgroundColor` 和 `padding`(`6`)补全观感。 |
-| `renderMode` | `Auto` | 输入文本的字形管线——`Auto`(不缩放时用清晰位图、缩放后转 SDF)、始终 `Bitmap`、或始终 `Sdf`。 |
-
-点击(或 Tab 到)输入框即聚焦;**Escape** 失焦,单行输入框按**回车**触发
-`submit`。内容超出框宽时会**裁剪到框内并横向滚动**,让光标随输入始终可见。
+点击(或 Tab 到)输入框即聚焦;**Escape** 失焦,单行框 **Enter** 触发 `submit`。
+超出盒宽的内容**裁剪到盒内并横向滚动**,输入时光标始终可见。
<Aside type="note">
- 文本输入只在**播放模式**运行,且需要浏览器 DOM(它驱动一个隐藏的原生
- textarea 以支持 IME)——在编辑器编辑态下不生效。
+ 文本输入只在**播放模式**运行,且需要浏览器 DOM(它驱动一个隐藏的原生 textarea
+ 以支持 IME)——在编辑器的编辑视图中是惰性的。
</Aside>
-## 数据绑定
-
-控件的值就是普通组件字段,[signal](/docs/zh-cn/guides/ui/) 层可以直接绑——
-`bindWidgetValue` 让它**双向**:signal 驱动组件,控件的 `change` 事件回写 signal。
+## 列表与滚动
-```typescript
-import { signal, bindWidgetValue, UISlider, UIToggle } from 'esengine';
-
-const volume = signal(50);
-bindWidgetValue(world, events, slider.entity, UISlider, 'value', volume);
-const muted = signal(false);
-bindWidgetValue(world, events, toggle.entity, UIToggle, 'isOn', muted);
+虚拟化的数据驱动列表与网格(`createListView`)、自由滚动面板(`createScrollView`)、
+数据源、布局提供者、自动行高以及惯性滚动 / 滚动条机制,单独成章:
+**[列表与滚动](/docs/zh-cn/guides/ui-lists/)**。
-volume.set(80); // 滑块随之移动
-// 拖动滑块 ↦ volume.get() 跟随
-```
+## 数据绑定
-signal 的等值守卫会打断回环,一个来回一跳即收敛。
+控件值就是普通组件字段(`UISlider.value`、`UIToggle.isOn`……),信号层可直接绑定——
+`bindWidgetValue` 更把它做成双向。见 **[UI 数据绑定](/docs/zh-cn/guides/ui-binding/)**。
## 拖放
-给任何可交互的 UI 实体加 `Draggable`,指针拖动就能移动它——有 `UINode` 时移动
-其绝对 inset,否则移动 `Transform`:
-
-```typescript
-world.insert(entity, Draggable, { dragThreshold: 5, lockY: true });
-events.on(entity, 'drag_start', () => { /* 还有 'drag_move' 与 'drag_end' */ });
-```
-
-`lockX` / `lockY` 锁轴,`constraintMin` / `constraintMax` 钳制范围;自动插入的
-`DragState` 组件暴露实时拖动数据(`isDragging`、`deltaWorld`、`totalDeltaWorld`
-等)。没有内置的放置目标(drop target)概念——在你的 `drag_end` 处理器里自行
-判定落点。
+给任意可交互 UI 实体加 `Draggable`,指针拖拽即可移动它,附带
+`drag_start` / `drag_move` / `drag_end` 事件和实时的 `DragState` 组件。
+轴锁定与范围约束齐备。见 **[UI 交互](/docs/zh-cn/guides/ui-interaction/)**。
## 键盘焦点
-带 `Focusable` 组件的实体参与键盘焦点:**点击**聚焦,**Tab / Shift+Tab** 轮换
-(按 `tabIndex` 升序,跳过禁用控件,到头回绕),**Enter / Space** 激活聚焦的控件
-(合成一次 `click`;文本框保留这些键用于编辑),滑块响应**方向键**,**Escape**
-或点击空白处清除焦点。控件工厂自动添加 `Focusable`(用 `focusable: false` 退出);
-聚焦的控件显示它的 `focused` 交互页(默认主题 hover 色)。`FocusManager` 资源暴露
-`focusedEntity` 以及 `focus(entity)` / `blur()` 供编程控制,被聚焦的实体在 UI
-事件总线上收到 `focus` / `blur` 事件。
+带 `Focusable` 的实体参与键盘焦点:Tab / Shift+Tab 按 `tabIndex` 轮换,
+Enter/Space 激活,滑块接管方向键,聚焦的控件显示其 `focused` 交互页。
+控件工厂自动加 `Focusable`(`focusable: false` 退出);`FocusManager` 资源提供
+程序化控制。详见 **[UI 交互](/docs/zh-cn/guides/ui-interaction/)**。
## 安全区(移动端刘海)
-给一个全屏、绝对定位的 `UINode` 容器加 `SafeArea`,它的 inset 就会跟随平台
-安全区——刘海、圆角、微信胶囊——里面布局的子节点永远不会被硬件遮住。
-`applyTop` / `applyBottom` / `applyLeft` / `applyRight`(默认全 `true`)选择
-生效的边。
+给全屏、绝对定位的 `UINode` 容器加 `SafeArea`,其 inset 会跟随平台安全区——
+刘海、圆角、微信胶囊——并支持按边退出。见
+**[屏幕与分辨率](/docs/zh-cn/core-concepts/screen/)**。
## 主题
-控件颜色来自一套共享令牌:`getTheme()` / `setTheme(tokens)`,角色包括
-`surface`、`control`、`controlHover`、`primary`、`onPrimary`、`track`、
-`backdrop`(内置 `DARK_TOKENS` / `LIGHT_TOKENS`)。`setTheme` 影响之后构建的控件;
-**`switchTheme(world, tokens)`** 还会实时重刷屏幕上已有的一切——控件记录了每个颜色
-来自哪个主题*角色*(`ThemeStyle` 组件,也随 prefab 持久化),换主题时按角色重新
-解析色相并保留各自的 alpha。
-
-### 项目主题
-
-项目在**项目设置 → UI** 里一次性声明控件配色:先选基础主题(默认**深色**,内置
-**浅色**),再在**主题颜色**组里覆盖任意**颜色角色**——每个角色一个完整取色器,
-未设置的行显示继承的基础值,重置按钮清除覆盖。覆盖存进 `project.esproject` 的
-`features.ui.colors`(角色 → `#rrggbb[aa]` 十六进制),并按主题角色表校验。
-
-解析后的主题(基础 + 覆盖)**处处一致地生效**:改设置时编辑视口实时预览,Play
-使用它,每个导出目标——web、桌面、微信、playable——都在启动时先解析再给控件换肤。
-品牌色改 `primary`(以及 `primaryHover` / `primaryActive`)即可;`onPrimary`
-是画在它上面的内容色。
+控件颜色来自共享的 token 集,角色如 `surface`、`control`、`primary`、`track`;
+`switchTheme(world, tokens)` 实时重刷屏上一切,项目在 **Project Settings → UI**
+一次声明调色板。见 **[UI 主题](/docs/zh-cn/guides/ui-theme/)**。
## 编辑器预制体
-这些控件同时作为编辑器预制体提供,所以 **创建… → UI** 会把现成的 Button、Toggle、Slider、
-Dialog、TextInput 等放进场景,你再在 Details 里编辑。存在组件里的行为——滑块的拖拽/方向键、
-对话框的 Escape/遮罩关闭——摆出来的 prefab 无需代码即可用。
-
-从调色板拖放会**嵌套**:放手时会父接到指针下方的布局容器里(拖动过程中虚线描边预览
-将要嵌入的父级),拖到空画布则照旧落在根上。锚点选择器**按轴**编辑且保持控件原位——
-改横向锚点绝不打扰纵向布局,反之亦然。见 [编辑器](/docs/zh-cn/guides/editor/)。
+同一批控件也作为编辑器预制体提供,**Create… → UI** 即可把现成的 Button、Toggle、
+Slider、Dialog、TextInput 等丢进场景,再在 Details 里编辑。活在组件里的行为——
+滑块的拖拽/按键、对话框的 Escape/幕布关闭——在摆放的预制体上无需代码即可工作。
+
+从调色板拖放会**嵌套**:落点会认指针下的布局容器为父级(拖拽时虚线框预览将要成为的
+父级),空画布落点则照旧落在根上。锚点选择器**按轴**编辑并保持控件原位——
+改水平锚点绝不扰动垂直布局,反之亦然。见[编辑器](/docs/zh-cn/guides/editor/)。
+
+## 最佳实践
+
+- **优先状态组件而不是攥着句柄。** `UIToggle.isOn`、`UISlider.value`、
+ `UIDropdown.selectedIndex` 是唯一真相——写它们(或绑定它们),视觉自动跟上;
+ 句柄方法只是同一写入的带类型语法糖。
+- **让主题拥有颜色。** 省略 `states` / 视觉即可获得随主题热切换重新解析的角色色;
+ 只为刻意脱离主题的美术硬编码颜色。
+- **对话框内容放在 `panelEntity` 之下**,绝不放在旁边——这才让开/关成为整棵子树的
+ 单次 `display` 写入。
+- **运行时创建的句柄要 `dispose()`**——它销毁控件实体并解除事件订阅。
+- **保持键盘可达。** 只为装饰性或重复的控件传 `focusable: false`;
+ Tab 环就是你的无障碍故事。
+
+## 另请参阅
+
+- [UI](/docs/zh-cn/guides/ui/) —— 组件模型:`UINode`、`Text`、`UIVisual` 与交互。
+- [列表与滚动](/docs/zh-cn/guides/ui-lists/) —— `createListView`、`createScrollView` 与虚拟化。
+- [UI 控制器](/docs/zh-cn/guides/ui-controllers/) —— 共享"页"状态 + 声明式每页字段绑定。
+- [UI 数据绑定](/docs/zh-cn/guides/ui-binding/) —— 信号与控件双向绑定。
+- [UI 交互](/docs/zh-cn/guides/ui-interaction/) —— 焦点、拖放、指针事件。
+- [UI 主题](/docs/zh-cn/guides/ui-theme/) —— token、角色、主题热切换与项目主题。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-interaction.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-interaction.mdx
new file mode 100644
index 000000000..8d4b03b5a
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-interaction.mdx
@@ -0,0 +1,259 @@
+---
+title: UI 交互
+description: UI 交互完整参考——Interactable/UIInteraction 命中测试、UIEvents 冒泡总线、拖放、键盘焦点、手动拾取辅助函数,以及 UI 如何叠在游戏输入之上。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+指针输入每帧走同一条管线:命中测试找到光标下最顶层的 `Interactable` 节点,把
+逐帧状态写进 `UIInteraction`,并在 `UIEvents` 总线上发出冒泡事件。拖拽与键盘
+焦点系统叠在其上。这一切都随默认 `uiPlugin` 一起提供——无需安装——交互系统在
+**播放模式**下运行。
+
+## 命中测试:`Interactable` + `UIInteraction`
+
+给节点加 `Interactable` 使其可被命中:
+
+| `Interactable` 字段 | 默认 | 说明 |
+|---|---|---|
+| `enabled` | `true` | 总开关——禁用的节点被命中测试、事件和 Tab 环全部跳过。 |
+| `blockRaycast` | `true` | 节点遮挡其后方的节点(也会终止其上方的事件冒泡走链)。 |
+| `raycastTarget` | `true` | 节点自身可以成为命中结果。 |
+
+每帧命中测试把指针状态写进命中实体的 `UIInteraction`。它按需创建(**transient**
+——从不手工添加、从不持久化),且**对你的逻辑只读**:查询它,绝不改它。
+
+| `UIInteraction` 字段 | 说明 |
+|---|---|
+| `hovered` | 指针悬停在节点上。 |
+| `pressed` | 主键在节点上按住。 |
+| `justPressed` | 本帧变为按下(单帧沿)。 |
+| `justReleased` | 本帧在被按下的节点上释放(单帧沿——即一次点击)。 |
+
+```typescript
+import { defineSystem, Query, Interactable, UIInteraction } from 'esengine';
+
+const onTiles = defineSystem([Query(Interactable, UIInteraction)], (q) => {
+ for (const [entity, _gate, state] of q) {
+ if (state.justReleased) { /* this node was clicked */ }
+ }
+});
+```
+
+只要有任一 UI 节点被命中,`input.isPointerOverUI()` 即为 `true`——这是防止
+点按钮同时触发世界点击的标准防线。
+
+## `UIEvents` 总线
+
+`UIEvents` 资源是带 DOM 式冒泡的发布/订阅队列。控件与交互系统发出标准事件集;
+类型空间是**开放的**——你可以发出任意字符串(ListView 就发 `'item_selected'`)。
+
+| `UIEventType` 常量 | 字符串 | 触发时机 | 冒泡 |
+|---|---|---|---|
+| `Click` | `'click'` | 在同一节点上按下并释放。键盘 Enter/Space 也会发出(仅发到 target,不冒泡)。 | 是 |
+| `Press` / `Release` | `'press'` / `'release'` | 主键在节点上按下 / 抬起。 | 是 |
+| `HoverEnter` / `HoverExit` | `'hover_enter'` / `'hover_exit'` | 命中节点发生变化。 | 否 |
+| `Focus` / `Blur` | `'focus'` / `'blur'` | 键盘焦点移动(见[焦点](#焦点与键盘))。 | 否 |
+| `Change` | `'change'` | 控件值变化(toggle、slider、dropdown……)。 | 否 |
+| `Submit` | `'submit'` | 文本输入确认(Enter)。 | 否 |
+| `DragStart` / `DragMove` / `DragEnd` | `'drag_start'` / `'drag_move'` / `'drag_end'` | 拖拽系统(见[拖放](#拖放))。 | 否 |
+| `Scroll` / `Select` / `Deselect` | `'scroll'` / `'select'` / `'deselect'` | 滚动视图与列表选择。 | 否 |
+
+冒泡事件沿父链上行,途经每个**启用的** `Interactable` 祖先;带 `blockRaycast`
+的祖先终止走链,任何处理器都可调用 `stopPropagation()`。每个 `UIEvent` 携带:
+
+| `UIEvent` 字段 | 说明 |
+|---|---|
+| `type` | 事件字符串。 |
+| `target` | 事件起源的实体。 |
+| `currentTarget` | 当前处理它的实体(冒泡期间与 `target` 不同)。 |
+| `data` | 可选负载(如 dropdown `change` 的 `{ index }`)。 |
+| `stopPropagation()` / `propagationStopped` | 终止冒泡。 |
+| `preventDefault()` / `defaultPrevented` | 请求发出方跳过默认动作。 |
+
+按实体或全局订阅——`on` 返回退订函数,实体销毁时其处理器自动清理:
+
+```typescript
+import { defineSystem, addStartupSystem, Res, UIEvents } from 'esengine';
+
+const wireMenu = defineSystem([Res(UIEvents)], (events) => {
+ events.on(buttonEntity, 'click', (e) => { /* one widget */ });
+ events.on('click', (e) => console.log('clicked', e.target)); // any entity
+});
+addStartupSystem(wireMenu);
+```
+
+系统也可以不订阅、直接读本帧队列:`events.query('click')` 非破坏性地查看待处理
+事件(交互插件在每帧开头 drain 队列)。
+
+## `makeWidgetInteractable`——为自定义控件接线
+
+所有内置控件工厂共享同一套交互装配,并导出给你的控件用:
+
+```typescript
+import { makeWidgetInteractable } from 'esengine';
+
+makeWidgetInteractable(world, myWidgetRoot, { tabIndex: 2 });
+```
+
+它插入一个阻挡射线的 `Interactable`,并(默认)加一个 `Focusable`,让控件既可
+点击**又**可键盘到达(Tab 聚焦,Enter/Space 激活)。选项:`disabled`(以
+`Interactable.enabled = false` 起步)、`focusable`(默认 `true`)、`tabIndex`
+(默认 `0` = 文档顺序)。它刻意*不*插入 `UIInteraction`——那是 transient 状态。
+悬停/按下的**视觉**状态请把字段绑到内置交互控制器的页——见
+[UI 控制器](/docs/zh-cn/guides/ui-controllers/)。
+
+## 拖放
+
+给带 `Interactable` 的节点加 `Draggable`,拖拽系统包办其余:按下、移过阈值,
+实体就跟随指针——有 `UINode` 时推它的绝对 inset(位置在下一次布局后仍然保留),
+否则平移 `Transform`。
+
+| `Draggable` 字段 | 默认 | 说明 |
+|---|---|---|
+| `enabled` | `true` | 总开关。 |
+| `dragThreshold` | `5` | 拖拽启动前需移动的屏幕像素(保住点击手感)。 |
+| `lockX` / `lockY` | `false` | 冻结某轴(仅水平拖动的卡片)。 |
+| `constraintMin` / `constraintMax` | `null` | 世界空间夹取角点,`null` 为不限制。 |
+
+拖拽期间,transient 组件 `DragState` 携带实时几何(均为世界空间):
+
+| `DragState` 字段 | 说明 |
+|---|---|
+| `isDragging` | 已过阈值且仍按住。 |
+| `startWorldPos` | 按下时的实体位置。 |
+| `currentWorldPos` | 当前实体位置。 |
+| `deltaWorld` | 距上一帧的位移。 |
+| `totalDeltaWorld` | 距拖拽开始的位移。 |
+| `pointerStartWorld` | 按下时的指针位置。 |
+
+系统在总线上发出 `drag_start` / `drag_move` / `drag_end`。拖卡入槽就是这三个
+事件加一次落点检测:
+
+```typescript
+import {
+ defineSystem, addStartupSystem, GetWorld, Res, UIEvents,
+ spawnUIEntity, Draggable, DragState, UIPositionType, px,
+} from 'esengine';
+
+const buildCard = defineSystem([GetWorld(), Res(UIEvents)], (world, events) => {
+ const card = spawnUIEntity({
+ world,
+ node: { width: px(90), height: px(120), position: UIPositionType.Absolute },
+ visual: { color: { r: 0.85, g: 0.75, b: 0.4, a: 1 } },
+ });
+ world.insert(card, Draggable, { dragThreshold: 4 });
+
+ events.on(card, 'drag_end', () => {
+ const state = world.get(card, DragState);
+ // Drop test: snap into the slot if released over it, else return to hand.
+ if (overDropSlot(state.currentWorldPos)) { /* snap the card in */ }
+ });
+});
+addStartupSystem(buildCard);
+```
+
+<Aside type="note">
+ 指针下有多个 draggable 重叠时,系统选渲染层最高的那个,层相同再按层级深度
+ 取胜——你抓到的永远是最上面那张卡。
+</Aside>
+
+## 焦点与键盘
+
+键盘可达性**默认开启**:`focusPlugin` 内置于 `uiPlugin`,每个控件工厂都会加
+`Focusable`(经 `makeWidgetInteractable`)。`FocusManager` 资源追踪唯一的聚焦
+实体;`Focusable.isFocused` 按实体映射它,每次移动都发 `focus` / `blur` 事件。
+
+| 交互 | 行为 |
+|---|---|
+| 点击可聚焦控件 | 聚焦它。 |
+| 点击空白处 / 按 `Escape` | 清除焦点。 |
+| `Tab` / `Shift+Tab` | 循环焦点环——按 `tabIndex` 排序(相同者按发现顺序),跳过禁用的 `Interactable` 和树上被 `display: none` 隐藏的一切。 |
+| 焦点控件上按 `Enter` / `Space` | 发出 `click`——激活按钮、开关、下拉。文本输入保留这些键用于编辑。 |
+| 打开的 `UIDialog` | **焦点陷阱**:模态对话框打开期间,只有其内部的可聚焦项参与 Tab 环(遮罩已阻挡外部的指针聚焦)。 |
+| 聚焦的下拉框 | `ArrowDown` / `ArrowUp` 步进选择(弹层开或关都行,原生 `<select>` 惯例);`Enter` 确认,`Escape` 关闭打开的弹层。 |
+
+```typescript
+import { defineSystem, Res, FocusManager } from 'esengine';
+
+const focusDebug = defineSystem([Res(FocusManager)], (focus) => {
+ if (focus.focusedEntity !== null) { /* draw a focus ring, play a tick… */ }
+});
+```
+
+<Aside type="note">
+ 手柄导航未内置于焦点系统——焦点环由 `Tab` / `Enter` / `Space` / `Escape` 和
+ 方向键驱动。手柄菜单请用[输入映射](/docs/zh-cn/guides/input/)自行驱动选择,
+ 直接调用控件状态。
+</Aside>
+
+## 手动拾取
+
+游戏代码需要自己拾取时——自定义光标、任意 UI 上的 tooltip、编辑器工具——命中
+测试辅助函数已导出。它们与 C++ 内核对话,因此需要 wasm module 和 registry:
+
+```typescript
+import { uiPickWorld, UICameraInfo, Res, GetWorld, defineSystem } from 'esengine';
+
+const tooltip = defineSystem([GetWorld(), Res(UICameraInfo)], (world, camera) => {
+ if (!camera.valid) return;
+ const hit = uiPickWorld(
+ module, registry, // app.wasmModule / world.getCppRegistry()
+ camera.worldMouseX, camera.worldMouseY, // cursor already projected to world
+ );
+ if (hit !== null) { /* show tooltip for `hit` */ }
+});
+```
+
+| 辅助函数 | 返回 | 用途 |
+|---|---|---|
+| `uiHitTestWorld(module, registry, x, y, …)` | 最顶层**可交互**实体或 `null` | 运行时射线——与交互系统同一套规则。 |
+| `uiPickWorld(module, registry, x, y)` | 最顶层 UI 实体或 `null` | 编辑器式拾取,无视 `Interactable`。 |
+| `uiPickAllWorld(module, registry, x, y)` | 该点下全部 UI 实体,最具体的在前 | 穿透式菜单、调试叠层。 |
+| `screenToUiWorld(camera, glX, glY)` | `{ x, y }` 世界点 | 把 GL 朝向的屏幕点经 UI 相机投到世界。 |
+| `uiWorldToScreen(camera, x, y)` | `{ x, y }` 屏幕点 | 逆变换——把 DOM/屏幕特效对到 UI 节点上。 |
+
+常见情形其实用不到这些:`UICameraInfo.worldMouseX/Y` 就是已投影到世界空间的
+光标,`input.isPointerOverUI()` 回答"指针是否落在 UI 上"。
+
+## UI 输入与游戏输入
+
+平台原始事件先经过 `InputRouter` 才落到 `Input` 资源——一条三层的责任链:
+
+1. **编辑器** —— 视口工具(仅编辑器宿主)。
+2. **UI** —— 文本输入等必须占有原始事件的 UI 内部机制。
+3. **游戏** —— 隐式:上游未消费的一切进入你的系统轮询的 `Input` 资源。
+
+处理器(`InputHandler`)可实现 `onKeyDown`、`onKeyUp`、`onPointerMove`、
+`onPointerDown`、`onPointerUp`、`onWheel` 及触摸回调中的任意几个,每个都收到
+当前 `Modifiers`(`shift` / `ctrl` / `alt` / `meta`);返回 `true` 即**消费**
+该事件——它不会更新 `Input`,也不会到达后续层。用
+`inputRouter.setUIHandler(handler)` / `setEditorHandler(handler)` 注册;各返回
+一个注销函数,每层只持有一个处理器。
+
+游戏里通常不用碰路由:指针在 UI 上的仲裁已在轮询层解决——命中 UI 会置
+`input.pointerOverUI`,gameplay 用 `isPointerOverUI()` 防守即可。只有当某系统
+必须在 `Input` 资源看到之前占有*原始*事件时(吞掉 Escape 的模态、捕获全部按键
+的小游戏),才装路由处理器。
+
+## 最佳实践
+
+- **只读、绝不写 `UIInteraction`**——它是引擎持有的逐帧状态;逻辑从它或
+ `UIEvents` 驱动。
+- **控件走总线,网格走查询**——单个控件用 `events.on(entity, 'click', …)` 最
+ 清晰;整版同质格子用 `Query(Interactable, UIInteraction)` 更能扩展。
+- **用 `input.isPointerOverUI()` 防守世界点击**,别让 UI 点击漏进 gameplay。
+- **自定义控件用 `makeWidgetInteractable`**——一次调用同时获得命中测试与键盘
+ 可达,和内置控件一致。
+- **可点击的东西保持 `dragThreshold` 非零**,否则每次点击都可能变成 0 像素的
+ 拖拽。
+- **`tabIndex` 省着用**——文档顺序通常就是正确的 Tab 顺序;显式序号只留给
+ 跳转。
+
+## 另请参阅
+
+- [UI](/docs/zh-cn/guides/ui/) —— 组件模型总览。
+- [UI 组件](/docs/zh-cn/guides/ui-components/) —— 事件已接好线的控件工厂。
+- [UI 控制器](/docs/zh-cn/guides/ui-controllers/) —— 由交互控制器驱动的悬停/按下**视觉**状态。
+- [UI 数据绑定](/docs/zh-cn/guides/ui-binding/) —— 基于 `change` 事件的控件值双向绑定。
+- [输入](/docs/zh-cn/guides/input/) —— UI 层之下的 `Input` 资源、输入映射与手势。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-layout.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-layout.mdx
new file mode 100644
index 000000000..10fb3319e
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-layout.mdx
@@ -0,0 +1,311 @@
+---
+title: UI 布局
+description: UI 布局参考——设计像素单位、px/percent/auto 维度、UINode 与 FlexContainer 完整字段表、绝对定位与 auto 居中、锚点预设,以及布局配方。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+UI 几何是一套 CSS 盒模型,由 C++ 内核中的单趟 flexbox 引擎(Yoga)每帧针对相机的 UI
+框求解。本页是深入参考:单位、`Dimension` 类型、`UINode` 与 `FlexContainer` 的全部字段、
+绝对定位、锚点预设和配方。组件模型总览请从 [UI](/docs/zh-cn/guides/ui/) 开始。
+
+## 单位:设计像素
+
+UI 布局里的每个 `px` 都是**设计像素**——项目设计分辨率(Project Settings → Display)
+的单位,而非设备像素。场景相机把设计分辨率的适配烘焙进自己的视野范围,因此在 UI 布局框内
+**1 世界单位 = 1 设计像素**,一个 `px(320)` 的面板在任何设备上都是 320 设计像素宽;画布
+缩放模式决定这个设计框如何适配真实屏幕(letterbox、expand、match)。编辑器的自由缩放视图
+针对同一个固定设计框排布 UI,所以缩放视口永远不会让界面重排。见
+[屏幕与分辨率](/docs/zh-cn/core-concepts/screen/)和[相机](/docs/zh-cn/guides/camera/)。
+
+## 维度:`px`、`percent`、`auto`
+
+每个长度字段都是一个 `Dimension`——`{ value, unit }`——用三个助手构造:
+
+```typescript
+import { px, percent, auto, isAuto, DimensionUnit } from 'esengine';
+
+px(320) // 320 design pixels
+percent(50) // 50% of the parent's corresponding axis (0..100, not 0..1)
+auto() // content-/layout-driven; value is ignored
+isAuto(d) // true when d is the auto length
+```
+
+- **`px(n)`**——绝对设计像素(`DimensionUnit.Px`)。
+- **`percent(n)`**——**父项对应轴**的百分比:`width: percent(50)` 是父项宽度的一半,
+ `height: percent(50)` 是父项高度的一半。取值 0–100,与 CSS `%` 一致。
+- **`auto()`**——"让布局决定"。具体含义取决于字段:
+
+| 字段 | `auto()` 的含义 |
+|---|---|
+| `width` / `height` | 内容驱动(文本测量、子项)或被容器拉伸;**根**节点在 `auto` 轴上填满相机框。 |
+| `minWidth/Height`、`maxWidth/Height` | 无约束。 |
+| `flexBasis` | 使用 `width`/`height`,否则用内容尺寸。 |
+| `insetLeft/Top/Right/Bottom` | 该边不受约束(见[绝对定位](#绝对定位))。 |
+| `marginLeft/Top/Right/Bottom` | 外边距吸收剩余空间(CSS `margin: auto`);`Absolute` 节点上全 `auto` 的外边距 + 内偏移会使该轴居中。 |
+
+## `UINode`——盒子
+
+`UINode` 持有逐项布局字段(容器级字段在 `FlexContainer` 上)。以下默认值来自 SDK 源码的
+组件默认值。
+
+| 属性 | 类型 | 默认值 | 说明 |
+|---|---|---|---|
+| `position` | `UIPositionType` | `Relative` | `Relative` = 在 flex 流中;`Absolute` = 脱离流,由内偏移放置。 |
+| `display` | `UIDisplay` | `Flex` | `None` 把该节点**连同整棵子树**从布局、渲染和命中测试中移除——层级式显示/隐藏。对比 `UIVisual.enabled`:后者只隐藏本实体的视觉。 |
+| `width` / `height` | `Dimension` | `auto()` | 盒尺寸;`auto` = 内容/flex 驱动。 |
+| `minWidth` / `minHeight` | `Dimension` | `auto()` | 尺寸下限;`auto` = 无约束。 |
+| `maxWidth` / `maxHeight` | `Dimension` | `auto()` | 尺寸上限;`auto` = 无约束。 |
+| `flexGrow` | number | `0` | 吸收容器主轴剩余空间的份额(`0` = 不放大)。 |
+| `flexShrink` | number | `1` | 空间不足时的收缩因子(`0` = 永不收缩)。 |
+| `flexBasis` | `Dimension` | `auto()` | grow/shrink 之前的主轴基准尺寸;`auto` = 用 `width`/`height` 或内容。 |
+| `alignSelf` | `AlignSelf` | `Auto` | 逐项交叉轴覆盖(`Auto` / `Start` / `Center` / `End` / `Stretch`);`Auto` 继承容器的 `alignItems`。 |
+| `marginLeft/Top/Right/Bottom` | `Dimension` | `px(0)` | 外间距;`auto()` 吸收剩余空间(CSS auto margin)。 |
+| `insetLeft/Top/Right/Bottom` | `Dimension` | `auto()` | `position` 为 `Absolute` 时距父项各边的偏移(CSS `left/top/right/bottom`);`auto` = 该边不受约束。 |
+
+<Aside type="caution">
+ 布局趟每帧都会**写入**每个 UI 实体的 `Transform.position`(中心基准、pivot 0.5、
+ y 向上)。不要通过 `Transform` 手工摆放 UI 实体——用内偏移/外边距移动它们。
+ (补间通过逐轴覆盖标志与布局协调,所以用补间 API 动画化 UI 位置没问题。)
+</Aside>
+
+## `FlexContainer`——排布子项
+
+给节点加 `FlexContainer` 来排布其子项。心智模型就是 CSS flexbox——每个字段与一个
+CSS 属性一一对应:
+
+| 属性 | 类型 | 默认值 | CSS | 说明 |
+|---|---|---|---|---|
+| `direction` | `FlexDirection` | `Row` | `flex-direction` | `Row` / `Column` / `RowReverse` / `ColumnReverse`——主轴。 |
+| `wrap` | `FlexWrap` | `NoWrap` | `flex-wrap` | `NoWrap` / `Wrap`。 |
+| `justifyContent` | `JustifyContent` | `Start` | `justify-content` | 主轴分布:`Start` / `Center` / `End` / `SpaceBetween` / `SpaceAround` / `SpaceEvenly`。 |
+| `alignItems` | `AlignItems` | `Stretch` | `align-items` | 交叉轴对齐:`Start` / `Center` / `End` / `Stretch`。 |
+| `alignContent` | `AlignContent` | `Start` | `align-content` | 换行后各行的分布:`Start` / `Center` / `End` / `Stretch` / `SpaceBetween` / `SpaceAround`。 |
+| `gap` | `Vec2` | `{x: 0, y: 0}` | `column-gap` / `row-gap` | 子项间距,普通设计像素数(`x` = 列间距,`y` = 行间距)。 |
+| `padding` | `Padding` | `{0,0,0,0}` | `padding` | 内间距(`left/top/right/bottom`),普通设计像素数。 |
+
+<Aside type="note">
+ `gap` 和 `padding` 是普通数字(设计像素),不是 `Dimension`。
+</Aside>
+
+```typescript
+import { FlexContainer, FlexDirection, JustifyContent, AlignItems } from 'esengine';
+
+world.insert(panel, FlexContainer, {
+ direction: FlexDirection.Column,
+ justifyContent: JustifyContent.Center,
+ alignItems: AlignItems.Center,
+ gap: { x: 0, y: 12 },
+ padding: { left: 16, top: 16, right: 16, bottom: 16 },
+});
+```
+
+## 绝对定位
+
+`position: Absolute` 使节点脱离 flex 流;四个内偏移相对父项的盒子放置它,与 CSS
+`left/top/right/bottom` 完全一致:
+
+- **钉住一条边**——`insetTop: px(16), insetRight: px(16)` 把盒子放在距右上角 16px
+ 处;`auto` 的边不受约束,作者设置的 `width`/`height` 生效。
+- **两边都钉住 + `auto` 尺寸**——由内偏移决定尺寸:`insetLeft: px(0), insetRight:
+ px(0)` 配合 `width: auto()` 把盒子横向拉满父项。四个内偏移都为 `px(0)` = 填满
+ 父项(`spawnUIEntity` 的 `node: { fill: true }` 写的就是这个)。
+- **百分比内偏移**与其他 `Dimension` 一样,按父项对应轴解析。
+
+### 用 `auto` 居中
+
+`Absolute` 节点在某轴上**当该轴的两个内偏移*和*两个外边距全为 `auto` 时居中**——
+引擎把这种组合读作"把这个脱离流的节点在父盒中居中"。这是引擎在 Yoga 之上追加的
+逐节点规则(Yoga 的绝对定位居中依赖父项的 `justifyContent`,无法逐兄弟不同),也是
+无 pivot 的 CSS 盒唯一无法自行表达的锚点。每个轴独立解析,所以你可以水平居中的同时
+钉住顶边。
+
+<Aside type="caution">
+ `UINode` 的外边距**默认是 `px(0)`**而非 `auto`——所以一个全 `auto` 内偏移的新建
+ `Absolute` 节点*不会*居中,除非你把外边距也设为 `auto()`。`Center` 锚点预设替你
+ 写的正是这套组合(见下一节)。
+</Aside>
+
+```typescript
+import { spawnUIEntity, UIPositionType, px, auto } from 'esengine';
+
+// Dead-center 320×220 panel: insets AND margins all auto on both axes.
+const panel = spawnUIEntity({
+ world,
+ node: {
+ position: UIPositionType.Absolute,
+ width: px(320), height: px(220),
+ marginLeft: auto(), marginRight: auto(),
+ marginTop: auto(), marginBottom: auto(),
+ },
+ visual: { color: { r: 0.08, g: 0.10, b: 0.16, a: 0.95 } },
+});
+```
+
+## 代码里的锚点预设
+
+编辑器的锚点选择器——以及代码里的同一套 API——是一组**写入上述盒字段的快捷方式**。
+锚点*不是*存储的状态:`position`/内偏移/外边距字段始终是唯一权威源,因此预设与实际
+布局永远不会失同步。每个轴是四种模式之一:
+
+| `AnchorAxis` | 写入(逐轴) |
+|---|---|
+| `Start` | 近端内偏移 `px(0)`,远端内偏移 `auto`,外边距 `px(0)`——钉住左/上边。 |
+| `Center` | 两个内偏移**和**两个外边距全 `auto`——引擎居中(见上文)。 |
+| `End` | 远端内偏移 `px(0)`,近端内偏移 `auto`,外边距 `px(0)`——钉住右/下边。 |
+| `Stretch` | 两个内偏移 `px(0)`,外边距 `px(0)`,**尺寸 `auto`**——由内偏移决定尺寸。 |
+
+`anchorPresetFields({ h, v })` 把预设解析为要写入的字段。它总是设置
+`position: Absolute` 加四个内偏移和四个外边距;`width`/`height` **仅**在 `Stretch`
+轴上出现,因此非拉伸轴会保留你设置的尺寸。`ANCHOR_AXES` 按网格顺序列出四种模式
+(用于构建预设选择器 UI)。
+
+```typescript
+import {
+ UINode, AnchorAxis, anchorPresetFields, detectAnchor, detectAnchorAxes,
+} from 'esengine';
+
+// Anchor a badge to the top-right corner.
+const node = world.get(badge, UINode);
+Object.assign(node, anchorPresetFields({ h: AnchorAxis.End, v: AnchorAxis.Start }));
+node.insetRight = { ...node.insetRight, value: 16 }; // 16px in from the right
+node.insetTop = { ...node.insetTop, value: 16 };
+world.insert(badge, UINode, node);
+
+detectAnchor(node); // → { h: AnchorAxis.End, v: AnchorAxis.Start }
+detectAnchorAxes(node); // → per-axis; an axis is null when hand-tuned
+```
+
+`detectAnchor(node)` 把 `UINode` 归类回它匹配的预设——与 `anchorPresetFields`
+往返一致——对 `Relative` 节点或不构成干净预设的盒子返回 `null`。
+`detectAnchorAxes(node)` 逐轴独立归类(`h`/`v`,各为 `AnchorAxis | null`),因此一个
+轴被手工调过的盒子,另一个轴仍可读取——并可保留。
+
+## 布局时机与 `UILayoutGeneration`
+
+布局在 `PreUpdate` 运行(先于你的 `Update` 系统),并在 `PostUpdate` 中于滚动/列表
+变更之后重新求解,因此游戏逻辑系统看到的几何总是最新的。每次求解都会递增
+**`UILayoutGeneration`** 资源——一个单调计数器,你可以用它使任何基于计算后 UI 几何
+的缓存失效(内置指针命中测试正是这么用的):
+
+```typescript
+import { defineSystem, Res, UILayoutGeneration } from 'esengine';
+
+let seen = -1;
+const trackLayout = defineSystem([Res(UILayoutGeneration)], (gen) => {
+ if (gen.generation === seen) return; // layout unchanged since last frame
+ seen = gen.generation;
+ // Layout re-solved: re-read computed UI geometry, rebuild cached rects…
+});
+```
+
+## 配方
+
+### 全屏遮罩
+
+```typescript
+import { spawnUIEntity } from 'esengine';
+
+const scrim = spawnUIEntity({
+ world,
+ node: { fill: true }, // Absolute + all four insets px(0)
+ visual: { color: { r: 0, g: 0, b: 0, a: 0.6 } },
+});
+```
+
+### 居中一个面板
+
+两种等价工具:给**父项**一个居中的 `FlexContainer`(`justifyContent: Center,
+alignItems: Center`——[UI](/docs/zh-cn/guides/ui/) 快速上手的模式),或把面板本身设为
+`Absolute` 且内偏移**和**外边距全 `auto`([Center 锚点](#用-auto-居中)——不需要父容器)。
+
+### HUD 角标
+
+```typescript
+import { spawnUIEntity, UIPositionType, px } from 'esengine';
+
+const badge = spawnUIEntity({
+ world, parent: hudRoot,
+ node: {
+ position: UIPositionType.Absolute,
+ insetTop: px(16), insetRight: px(16), // other edges stay auto
+ width: px(48), height: px(48),
+ },
+ visual: { color: { r: 0.9, g: 0.2, b: 0.2, a: 1 } },
+});
+```
+
+### 响应式栏
+
+百分比宽度加像素上限——手机上流式,宽屏上封顶。`min`/`max` 不在 `spawnUIEntity`
+的 init 里,直接在组件上设置:
+
+```typescript
+import { spawnUIEntity, UINode, px, percent } from 'esengine';
+
+const column = spawnUIEntity({ world, parent: root, node: { width: percent(90) } });
+const n = world.get(column, UINode);
+n.maxWidth = px(480);
+world.insert(column, UINode, n);
+```
+
+### 拉伸子项 / 弹性占位
+
+`alignItems` 默认为 `Stretch`,所以 `Row` 的子项已经填满其高度。沿主轴用
+`flexGrow`——一个只放大的占位符把兄弟项推开:
+
+```typescript
+import { spawnUIEntity, FlexContainer, FlexDirection, px, percent } from 'esengine';
+
+const toolbar = spawnUIEntity({ world, node: { height: px(48), width: percent(100) } });
+world.insert(toolbar, FlexContainer, {
+ direction: FlexDirection.Row,
+ gap: { x: 8, y: 0 }, padding: { left: 8, top: 4, right: 8, bottom: 4 },
+});
+
+spawnUIEntity({ world, parent: toolbar, text: { content: 'Title' } });
+spawnUIEntity({ world, parent: toolbar, node: { flexGrow: 1 } }); // spacer
+spawnUIEntity({ world, parent: toolbar, text: { content: '99:59' } });
+```
+
+## 底层构建器
+
+`spawnUIEntity` 组合了三个纯构建器,你自己插入组件时也可以直接用——每个都把稀疏的
+init 补全为完整的组件字面量:
+
+- **`buildUINode(init)`**——完整的 `UINodeData`。`fill: true` 是控件的常见情形:
+ `Absolute` + 全部内偏移 `px(0)`。不带 `fill` 时默认是 `Relative` + `auto` 尺寸——
+ 注意 `spawnUIEntity` **不传** `node` init 时得到的就是这个相对 auto 盒,而不是
+ 填满父项的盒。
+- **`buildUIVisual(init)`**——完整的 `UIVisualData`(默认:纯白)。
+- **`buildText(init)`**——完整的 `TextData`,采用*控件风格*的默认值(14px、居中、
+ 不换行)——刻意区别于 `Text` 组件自身面向独立标签的默认值(24px、左/上、换行)。
+- **`setUIVisible(world, entity, visible)`**——切换 `UIVisual.enabled`(没有
+ `UIVisual` 时为 no-op)。要隐藏整棵子树,请改设 `UINode.display` 为
+ `UIDisplay.None`。
+
+```typescript
+import { UINode, UIVisual, buildUINode, buildUIVisual, px } from 'esengine';
+
+const e = world.spawn();
+world.insert(e, UINode, buildUINode({ width: px(200), height: px(40) }));
+world.insert(e, UIVisual, buildUIVisual({ color: { r: 0.2, g: 0.2, b: 0.25, a: 1 } }));
+```
+
+## 最佳实践
+
+- **Flex 优先**——用容器、`flexGrow` 和 `percent` 表达布局;`Absolute` 只留给
+ 悬浮层、角标和浮动面板。
+- **用预设做锚点**——`anchorPresetFields` 替你写出正确的内偏移/外边距组合
+ (尤其是 `Center` 的全 `auto` 规则),不用死记。
+- **绝不通过 `Transform` 摆放 UI**——布局趟每帧都会覆盖它;用内偏移和外边距移动盒子。
+- **给流式尺寸封顶**——`percent` 宽度配 `maxWidth: px(...)`,宽屏下才不失控。
+- **隐藏子树用 `display: None`**,隐藏单个视觉用 `UIVisual.enabled`。
+
+## 另请参阅
+
+- [UI](/docs/zh-cn/guides/ui/)——组件模型总览与快速上手。
+- [UI 文本](/docs/zh-cn/guides/ui-text/)——`Text` 如何在盒内测量与对齐。
+- [UI 交互](/docs/zh-cn/guides/ui-interaction/)——对排布好的盒子做命中测试。
+- [UI 组件](/docs/zh-cn/guides/ui-components/)——建立在这些原语上的控件(含移动端安全区)。
+- [相机](/docs/zh-cn/guides/camera/)——相机、画布缩放模式与 UI 框。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-lists.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-lists.mdx
new file mode 100644
index 000000000..21729144e
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-lists.mdx
@@ -0,0 +1,451 @@
+---
+title: 列表与滚动
+description: 用 createListView 构建虚拟化的数据驱动列表与网格——数据源、布局提供者、实体回收、自动行高——外加 createScrollView 自由滚动、惯性甩动与滚动条。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+在 Estella 里,长的可滚动内容由 [UI](/docs/zh-cn/guides/ui/) 组件模型之上的两个工厂构建:
+
+- **`createListView`** —— **虚拟化**的数据驱动列表或网格。任何时刻只挂载视口附近的条目,
+ 所以 10 000 行的背包、排行榜或聊天记录和 10 行的一样便宜。
+- **`createScrollView`** —— 承载**任意内容**的裁剪滚动面板(设置页、长表单)。
+ 无虚拟化、无数据源——把你的实体挂到它下面即可。
+
+两者组合的是同一套原语:一个 Scissor 模式的 [`UIMask`](#裁剪--uimask) 视口、一个由
+[`ScrollContainer`](#滚动模型) 平移的内容框,以及由 UI 插件路由的滚轮 / 拖拽 / 惯性甩动输入。
+
+## `createListView`
+
+一次调用组合出数据源、布局、条目回收、滚动与裁剪:
+
+```typescript
+import { createListView, uiPlugin, arrayDataSource, spawnUIEntity, px } from 'esengine';
+
+const list = createListView<Player>({
+ world, host: uiPlugin, parent,
+ viewportSize: { x: 320, y: 480 }, // the visible window, in pixels
+ data: arrayDataSource(players), // any DataSource<T>, or a raw array
+ layout: { itemHeight: 56 }, // a column list
+ item: {
+ create: (world, parent) => spawnUIEntity({ world, parent, node: { height: px(56) } }),
+ bind: (entity, player, index) => { /* fill the row's Text / Sprite from `player` */ },
+ },
+});
+```
+
+`host` 是驱动虚拟化 tick 并路由滚动输入的插件——传你的应用所构建的 `uiPlugin`
+(细粒度的 `uiBehaviorPlugin` 也满足该契约)。
+
+### 选项
+
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `world` / `host` | — | ECS world 与负责 tick 的插件(`uiPlugin`)。必填。 |
+| `parent` | 根 | 视口的父实体。 |
+| `viewportSize` | — | 可见窗口的像素尺寸。必填——滚动数学需要预先知道。 |
+| `node` | 尺寸取 `viewportSize` | 视口盒的额外 `UINode` 属性。 |
+| `background` | 透明 | 视口视觉。默认是不可见的**命中目标**——它必须存在,滚轮和拖拽才能落在列表上。 |
+| `data` | — | 一个 `DataSource<T>`,或裸数组(会被包成 `ArrayDataSource`——数组会被**拷贝**,之后请改数据源而不是你的原数组)。 |
+| `layout` | — | 布局语法糖(`itemHeight` / `itemWidth` / `columns`,见下)或完整的[布局提供者](#布局提供者)。 |
+| `item` | — | 一个[条目模板](#条目模板),或"条目类型 → 模板"的 map(异构行)。 |
+| `direction` | 由布局推导 | 滚动轴:`'vertical'` \| `'horizontal'` \| `'both'`。列/网格布局默认竖向,行布局默认横向。 |
+| `recycleBuffer` | `2` | 可见范围两侧各多保留挂载的索引数。网格按行思考:`columns * 2` 即多留两行。 |
+| `wheelSpeed` | `1` | 滚轮增量倍率。 |
+| `dragScroll` | `true` | 指针/触摸拖拽滚动,带惯性甩动。 |
+| `decelerationRate` | `0.135` | 甩动滑行 1 秒后剩余的速度比例。 |
+| `onItemBound` | — | 每次 bind 之后调用的 `(entity, data, index)`——用于逐条微调。 |
+
+**布局语法糖**(`ListLayoutSpec`)覆盖三种常见形态:
+
+| `layout` | 结果 |
+|---|---|
+| `{ itemHeight, spacing? }` | 竖向列表——固定行高,或传 **`(index) => number`** 函数做[自动行高](#自动行高)。 |
+| `{ itemWidth, direction: 'row', spacing? }` | 横向列表;条目撑满视口高度。 |
+| `{ columns, itemSize, spacing? }` | 网格(*TileView*);此处 `spacing` 是 `Vec2`。 |
+
+### 条目模板
+
+条目模板是一对 **create / bind**(`ListItemTemplate<T>`):
+
+```typescript
+item: {
+ // Build ONE row entity. Runs only when the pool has no free row to reuse.
+ create: (world, parent) => spawnUIEntity({ world, parent, text: { content: '' } }),
+ // Apply data to a row. Runs on every (re)bind — keep it a pure "apply this data".
+ bind: (entity, player, index) => setRowText(world, entity, player.name),
+}
+```
+
+- `create` 一次性搭好该行的实体子树——生成子实体、插组件、接交互都在这里。用
+ `spawnUIEntity`,让行自带 `UINode`。
+- `bind` 把数据填进行里。它在行**每次**被(重)用时运行——滚入视口时、数据更新时、
+ 以及每个滚动步进对所有已挂载行再跑一遍——所以必须**幂等且便宜**。
+
+**回收规则。** 行是池化实体,不是新生成的:
+
+- 复用的行仍保留**上一次 bind 写入的一切**——你设置过的每个字段都要重置
+ (文本、颜色、条件子节点的可见性)。只对*部分*条目设置的字段,`bind`
+ 也要为其余条目清掉。
+- 绝不要在 `bind` 里生成子实体或加组件——每次复用都会累积。结构属于 `create`。
+- 不要以行**实体**为键存外部状态——实体↔索引的映射随滚动变化。以数据为键
+ (或在 `bind` 里重新推导)。
+- 给写入加守卫:每个滚动步进 `bind` 会对所有已挂载行重跑,值没变就跳过组件写入
+ (提前返回的 `if (text.content === next) return;` 能让滚动零分配)。
+- 列表**拥有每行的盒子**:每次 bind 都会把该行的 `UINode` 设为 `Absolute`,
+ 并用布局矩形覆写 inset 和 `width`/`height`。行*内容*的尺寸用行内的子节点控制,
+ 不要写行节点本身。
+- 滚出屏幕的行会被隐藏(经 `setUIVisible`),不会销毁;它们被复用,或随列表一起销毁。
+
+**异构行**——传"条目类型 → 模板"的 map,并给数据源实现 `getItemType(index)`:
+
+```typescript
+item: {
+ header: { create: makeHeader, bind: bindHeader },
+ message: { create: makeMessage, bind: bindMessage },
+},
+```
+
+`getItemType` 返回的每个类型都必须有对应模板。当一次数据 reset 让某索引换了类型,
+旧行会被释放,换上正确模板的行再绑定。
+
+<Aside type="note">
+ **没有内置的选中模型**——行就是普通实体树。让行可点击(在 `create` 里放个
+ `createButton`,或 `Interactable` + `click` 处理器),把选中 id 存**在你的数据里**,
+ 由 `bind` 渲染选中态。活在数据里的状态天然经得起回收。
+</Aside>
+
+### 句柄
+
+`createListView` 返回 `ListViewHandle<T>`:
+
+| 成员 | 说明 |
+|---|---|
+| `entity` | 视口实体(裁剪窗口;把它摆进你的 UI 树)。 |
+| `content` | 行所挂载的滚动内容框。 |
+| `data` | `DataSource<T>`——改它就是改列表。 |
+| `refresh()` | 强制下一帧重新同步已挂载行(用于绕过数据源的带外改动)。 |
+| `scrollToIndex(i)` | 滚动到条目 `i` 位于视口左上角(收敛到合法范围)。 |
+| `mountedCount()` | 当前挂载的行实体数——不随数据增长;测试里很好用。 |
+| `scroll` / `view` | 底层 `ScrollContainer` / `ListView` 驱动器的逃生口。 |
+| `dispose()` | 注销、释放行、退订滚动/数据、销毁视口。 |
+
+## 数据源
+
+列表通过 `DataSource<T>` 接口读取条目:
+
+```typescript
+interface DataSource<T> {
+ getCount(): number;
+ getItem(index: number): T;
+ getItemType?(index: number): string; // default 'default'
+ getItemId?(index: number, item: T): string | number; // stable identity
+ subscribe?(listener: (change: DataSourceChange) => void): () => void;
+}
+```
+
+`subscribe` 让列表"活"起来:任何变更通知都会把视图标脏,下一帧重新同步——
+经数据源的改动永远不用你手动 `refresh()`。
+
+### `ArrayDataSource`
+
+内置的数组数据源(`arrayDataSource(items)` 是简写构造)。每个修改方法都在一次调用里
+更新数组**并**通知订阅者:
+
+| 方法 | 发出的变更 | 说明 |
+|---|---|---|
+| `setItems(items)` | `reset` | 替换全部条目。 |
+| `append(items)` | `insert` | 追加到末尾。 |
+| `insert(index, items)` | `insert` | 在 `index` 处插入(收敛到合法范围)。 |
+| `remove(index, count = 1)` | `remove` | 从 `index` 起移除 `count` 个。 |
+| `update(index, item)` | `update` | 替换一个条目。 |
+| `getCount()` / `getItem(i)` | — | 读取(`getItem` 越界会抛错)。 |
+| `subscribe(fn)` | — | 监听变更;返回退订函数。 |
+
+```typescript
+list.data.append([newPlayer]); // add
+list.data.remove(3); // remove index 3
+list.data.update(0, updatedPlayer); // replace one
+list.data.setItems(freshList); // replace all
+```
+
+<Aside type="caution">
+ 构造函数会**拷贝**你传入的数组。之后改你的原数组屏幕上什么也不会发生——请走上面的
+ 修改方法。若必须改数据源看不见的共享状态,调 `list.refresh()`(并且要知道:
+ 测量布局不会因此重新测量——见下文)。
+</Aside>
+
+### 自定义 `DataSource`
+
+数据不在数组里时——环形缓冲、查询结果、分页网络集合——直接实现接口:
+
+```typescript
+import type { DataSource, DataSourceChange } from 'esengine';
+
+class LogSource implements DataSource<string> {
+ private lines: string[] = [];
+ private listeners = new Set<(c: DataSourceChange) => void>();
+
+ getCount() { return this.lines.length; }
+ getItem(i: number) { return this.lines[i]; }
+ subscribe(fn: (c: DataSourceChange) => void) {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+
+ push(line: string) {
+ const at = this.lines.length;
+ this.lines.push(line);
+ for (const fn of this.listeners) fn({ type: 'insert', index: at, count: 1 });
+ }
+}
+```
+
+`getCount` + `getItem` 是必需的最小集;不实现 `subscribe` 列表也能工作,
+但每次改动后你得自己调 `refresh()`。
+
+## 布局提供者
+
+`layout` 选项接受完整的 `LayoutProvider`——语法糖背后的纯数学对象。提供者回答三个问题:
+内容总尺寸、条目 `i` 的矩形、给定视口矩形能看到哪个索引区间。内置三个实现:
+
+| 提供者 | 适用 | 选项 |
+|---|---|---|
+| `LinearLayoutProvider` | 定尺寸的行或列。 | `itemSize: Vec2`(必填)、`direction: 'row' \| 'column'`(默认 `'column'`)、`spacing`(默认 `0`)。 |
+| `GridLayoutProvider` | N 列定尺寸格子;竖向滚动。 | `columns`(必填,最小 1)、`itemSize: Vec2`(必填)、`spacing: Vec2`(默认 `{0, 0}`)。 |
+| `MeasuredLinearLayoutProvider` | 主轴尺寸逐条不同的行(聊天气泡、混排内容)。 | `crossSize`(必填)、`mainSizeOf: (index) => number`(必填)、`direction`(默认 `'column'`)、`spacing`(默认 `0`)。 |
+
+```typescript
+import { createListView, GridLayoutProvider, uiPlugin } from 'esengine';
+
+createListView<Item>({
+ world, host: uiPlugin, parent,
+ viewportSize: { x: 320, y: 480 },
+ data: items,
+ layout: new GridLayoutProvider({ columns: 4, itemSize: { x: 72, y: 72 }, spacing: { x: 8, y: 8 } }),
+ item: { create: makeCell, bind: bindCell },
+});
+```
+
+语法糖与它们一一对应:`{ itemHeight: 56 }` 构建以视口宽为交叉轴的
+`LinearLayoutProvider`;`{ itemHeight: (i) => … }` 构建
+`MeasuredLinearLayoutProvider`;`{ columns, itemSize }` 构建 `GridLayoutProvider`。
+
+**自动行高的机制。** `MeasuredLinearLayoutProvider` 对条目偏移做前缀和并缓存;
+条目定位与可见性查询都读缓存。缓存在条目数变化时、以及列表使其失效时重建——
+列表会在**每次数据源变更**和**视口改尺寸**时使其失效(依赖宽度的测量,如折行文本,
+需要重排)。一次重建会对每个条目各调一次 `mainSizeOf`,所以测量要便宜,或按条目做记忆化。
+
+### 自动行高
+
+给 `itemHeight` 传**函数**,让每行按内容定高——聊天记录里气泡随折行文本增高的完美场景:
+
+```typescript
+import { measureText } from 'esengine';
+
+createListView<Message>({
+ world, host: uiPlugin, parent,
+ viewportSize: { x: 360, y: 480 },
+ data: messages,
+ layout: {
+ itemHeight: (i) => measureText(messages.getItem(i).text, {
+ fontSize: 14, maxWidth: 320,
+ }).height + 16, // wrapped text height + vertical padding
+ spacing: 8,
+ },
+ item: { /* create / bind */ },
+});
+```
+
+`measureText(text, { fontSize, maxWidth?, fontFamily?, bold?, italic?, letterSpacing?, lineHeight? })`
+返回 `{ width, lineCount, height }`,度量来源与**字形图集绘制所用的同一份 Canvas2D 指标**,
+所以测出的高度与实际渲染一致——不再有被裁或溢出的行。`lineHeight` 默认
+`fontSize * 1.2`(`Text` 的默认比例);不传 `maxWidth` 即单行不折行。
+(无 DOM 的宿主回退到平均字宽估算。)
+
+## 虚拟化的工作方式
+
+每帧,host 插件对每个已注册的列表 tick 一次;除非有东西把列表标脏(滚动、数据变更、
+视口改尺寸),tick 是空操作。一次脏更新:
+
+1. 向布局提供者询问当前滚动偏移下的**可见索引区间**,
+2. 两侧各扩 `recycleBuffer` 个索引,
+3. 把落到区间外的已挂载行**释放**回实体池(隐藏,不销毁),
+4. 为进入区间的索引**获取**行——池里有空闲就复用,否则走模板的 `create`——
+ 并对区间内每一行 **bind**。
+
+结果:每帧工作量是 `O(mounted)`,且无论数据多大,`mounted ≈ visible +
+2 × recycleBuffer`。`mountedCount()` 暴露这个数——在测试里断言它不涨。
+数据变更同样有界:对滚动位置远离末尾的列表 `append`,一行都不用绑。
+
+**要:**
+
+- 让 `bind` 便宜、幂等、带变更守卫——它是滚动的热路径。
+- 所有数据变更走数据源(或调 `refresh()`)。
+- 用 `getItemType` + 模板 map,别写一个塞满 `if` 的模板。
+- 需要高级池控制(如预热行避免首次滚动尖峰)时,`ViewPool` 原语是公开的——
+ 用它组合你自己的 `ListView` 驱动。
+
+**不要:**
+
+- 别在 `bind` 里生成/插入,也别假设拿到的是新实体——见上文的回收规则。
+- 别跨帧按数据索引缓存实体引用。
+- 别从 `bind` 驱动逐行动画——bind 只写状态;动画用系统或 tween 去改行的组件。
+- 别给测量布局一个昂贵的 `mainSizeOf`——每次数据变更它会对**所有**条目运行。
+
+## 自由滚动 —— `createScrollView`
+
+任意内容的滚动面板——无虚拟化、无数据源——用 `createScrollView`,
+把内容挂到它的 `content` 框下:
+
+```typescript
+import { createScrollView, uiPlugin } from 'esengine';
+
+const panel = createScrollView({
+ world, host: uiPlugin, parent,
+ viewportSize: { x: 320, y: 480 },
+ contentSize: { x: 320, y: 1200 },
+});
+// build your content under panel.content …
+panel.scrollTo({ x: 0, y: 300 });
+```
+
+| 选项 | 默认 | 说明 |
+|---|---|---|
+| `world` / `host` | — | world 与路由输入的插件(`uiPlugin`)。必填。 |
+| `parent` | 根 | 视口的父实体。 |
+| `viewportSize` | — | 可见窗口的像素尺寸。必填。 |
+| `contentSize` | — | 可滚动内容框的像素尺寸。必填——尺寸显式给出,滚动数学需要预先知道。 |
+| `node` / `background` | 定尺寸盒 / 透明命中目标 | 同 `createListView`。 |
+| `direction` | `'vertical'` | 滚动轴:`'vertical'` \| `'horizontal'` \| `'both'`。 |
+| `wheelSpeed` | `1` | 滚轮增量倍率。 |
+| `dragScroll` | `true` | 拖拽/触摸滚动,带惯性甩动。 |
+| `decelerationRate` | `0.135` | 甩动衰减(1 秒后剩余比例)。 |
+| `onScroll` | — | 每次偏移变化触发 `(offset)`。 |
+
+**句柄**(`ScrollViewHandle`):`entity`(裁剪视口)· `content`(把内容挂这里)·
+`scrollTo(offset)` · `setContentSize(size)`——内容变大变小后调用,同时改框尺寸*和*
+滚动范围 · `scroll`(底层 `ScrollContainer`)· `dispose()`。
+
+## 滚动模型
+
+两个工厂驱动的都是 **`ScrollContainer`**——不含输入与 ECS 知识的纯滚动状态模型。
+它把偏移按轴收敛到 `[0, contentSize − viewportSize]`(`'vertical'` 容器把 `x` 钉在 0,
+反之亦然),任何变化都通知 `onScroll` 监听者。工厂订阅它并把内容框平移 `-offset`;
+UI 插件负责喂输入:
+
+- **滚轮** —— 悬停视口上的增量,乘以 `wheelSpeed`。
+- **拖拽 / 触摸** —— `dragScroll: true`(默认)时指针抓取拖动内容;平台层把主触点
+ 汇入指针流,所以触摸滚动走同一条路径。
+- **惯性甩动** —— 松手后按采样速度滑行、指数衰减:`decelerationRate` 是一秒后剩余的
+ 速度比例(默认 `0.135`,ScrollRect 标准——更小停得更快)。底层 `KineticScroll`
+ 模型同样公开,带静止速度下限(`4` px/s)与 EMA 采样率(`12`/s),供自定义组合使用。
+
+程序化滚动走句柄(`scrollToIndex`、`scrollTo`)或容器本身:
+`list.scroll.scrollBy({ x: 0, y: 120 })`。
+
+### 滚动条
+
+每个已挂接的滚动容器都会得到按可滚动轴的**自动淡出悬浮滚动条**:偏移移动时细长的
+thumb 出现,静止约 0.8 秒后淡出。thumb 长度跟随视口/内容比例,不占布局(脱离文档流)、
+不接输入(非交互),并以 `text` 主题角色标记,主题热切换时会重新上色。
+工厂始终开启滚动条;关闭(`showScrollbar: false`)是 `ScrollContainer`
+的构造选项,供手动组合使用。
+
+## 裁剪 —— `UIMask`
+
+两个工厂的视口实体都带 **Scissor** 模式的 `UIMask`:子节点只在视口的轴对齐矩形内渲染,
+这正是内容框滚出屏幕部分被隐藏的机制。Scissor 是一条渲染状态矩形——几乎免费,但只支持
+轴对齐;旋转下要正确裁剪用 **Stencil** 遮罩(`MaskMode.Stencil`)。你也可以用同样方式
+给任何 UI 节点加 `UIMask`:
+
+```typescript
+import { UIMask, MaskMode } from 'esengine';
+
+world.insert(panel, UIMask, { enabled: true, mode: MaskMode.Scissor });
+```
+
+## 完整示例:聊天记录
+
+把各部分拼起来——测量气泡行的虚拟化消息流,加一个向数据源追加的输入框
+(仓库里的 `examples/chat` 是完整的双侧气泡版本):
+
+```typescript
+import {
+ defineSystem, addStartupSystem, GetWorld, Res, UIEvents,
+ createListView, createTextInput, uiPlugin, ArrayDataSource,
+ spawnUIEntity, measureText, px, Text, UIPositionType,
+} from 'esengine';
+import type { World, Entity } from 'esengine';
+
+interface Message { from: 'me' | 'them'; text: string; }
+
+const W = 360, PAD = 8, FONT = 14;
+const messages = new ArrayDataSource<Message>([]);
+
+const rowHeight = (i: number) =>
+ measureText(messages.getItem(i).text, { fontSize: FONT, maxWidth: W - 2 * PAD }).height + 2 * PAD;
+
+function setRowText(world: World, row: Entity, content: string): void {
+ const t = world.get(row, Text);
+ if (t.content === content) return; // change-guard: bind is the hot path
+ t.content = content;
+ world.insert(row, Text, t);
+}
+
+const buildChat = defineSystem([GetWorld(), Res(UIEvents)], (world, events) => {
+ const list = createListView<Message>({
+ world, host: uiPlugin,
+ viewportSize: { x: W, y: 480 },
+ data: messages,
+ layout: { itemHeight: rowHeight, spacing: 6 },
+ item: {
+ create: (w, parent) => spawnUIEntity({
+ world: w, parent,
+ // The row box is owned by the list; the bubble look lives on the row itself.
+ visual: { color: { r: 0.15, g: 0.17, b: 0.22, a: 1 } },
+ text: { content: '', fontSize: FONT, wordWrap: true },
+ }),
+ bind: (row, msg) => setRowText(world, row, `${msg.from}: ${msg.text}`),
+ },
+ });
+
+ createTextInput({
+ world, events,
+ node: { position: UIPositionType.Absolute, insetLeft: px(0), insetBottom: px(0), width: px(W), height: px(32) },
+ placeholder: 'Type a message and press Enter…',
+ onSubmit: (text, entity) => {
+ if (!text.trim()) return;
+ messages.append([{ from: 'me', text }]); // notifies the list
+ list.scrollToIndex(messages.getCount() - 1); // keep the newest in view
+ },
+ });
+});
+
+addStartupSystem(buildChat);
+```
+
+`append` 会通知列表(标脏 → 下一帧重同步)**并**重新收敛滚动范围;`scrollToIndex`
+随后落在新的最后一行。因为布局是测量式的,追加同时使偏移缓存失效,新气泡的折行高度
+会在摆放之前完成测量。
+
+## 最佳实践
+
+- **数据形状的内容都虚拟化。** 只要内容是"N 个同类东西",即使 N 不大也用
+ `createListView`——一次调用拿到回收、滚动、裁剪与实时数据更新。
+ `createScrollView` 留给*异构*内容。
+- **数据源是唯一真相。** 选中、高亮、角标——建模进数据、在 `bind` 里渲染;
+ 绝不把列表状态存在行实体上。
+- **`bind` 里守卫写入。** 值没变就提前返回;每个滚动步进 `bind` 会跑遍所有挂载行。
+- **测量一次,处处复用。** 自动行高时,让 `itemHeight` 与行内文本布局共用同一个测量函数
+ (相同 `fontSize`、`maxWidth`),盒子与字形永远一致。
+- **创建的就要销毁。** `dispose()` 从插件注销、释放行、退订——泄漏的列表会一直 tick。
+
+## 另请参阅
+
+- [UI](/docs/zh-cn/guides/ui/) —— 这些工厂所依托的组件模型。
+- [UI 控件](/docs/zh-cn/guides/ui-components/) —— 其余控件工厂(Button、Dialog、文本输入……)。
+- [UI 布局](/docs/zh-cn/guides/ui-layout/) —— `UINode` 盒模型、flexbox 与尺寸。
+- [UI 数据绑定](/docs/zh-cn/guides/ui-binding/) —— 信号与控件双向绑定。
+- [UI 交互](/docs/zh-cn/guides/ui-interaction/) —— 指针事件、焦点、拖放。
+- [UI 主题](/docs/zh-cn/guides/ui-theme/) —— 滚动条与默认色所取用的 token 角色。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-text.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-text.mdx
new file mode 100644
index 000000000..e2dee3486
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-text.mdx
@@ -0,0 +1,230 @@
+---
+title: 文本
+description: Text 完整参考——Bitmap/SDF 双字形管线、全部 Text 属性、有无布局盒时的对齐语义、富文本标记、measureText、自定义字体与本地化。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+`Text` 组件从动态字形图集绘制字符串。给实体加一个 `UINode`,文本就在弹性盒
+(flexbox)盒内排版(换行、对齐、与同级 UI 一起排序);没有盒时则作为锚定在实体
+原点的自由世界空间标签渲染。代码里用 `spawnUIEntity({ text: … })` 生成,或在
+检查器里添加 `Text`。
+
+```typescript
+import { defineSystem, addStartupSystem, GetWorld, spawnUIEntity, TextAlign, px } from 'esengine';
+
+const buildHud = defineSystem([GetWorld()], (world) => {
+ spawnUIEntity({
+ world,
+ node: { width: px(240), height: px(40) },
+ text: { content: 'Score: 0', fontSize: 24, align: TextAlign.Left },
+ });
+});
+addStartupSystem(buildHud);
+```
+
+## 双字形管线
+
+每个字形只栅格化一次进共享图集,再以带纹理的四边形绘制。`renderMode` 按 Text
+逐个选择**如何**栅格化:
+
+- **`Bitmap`** —— 字形用 Canvas2D 在**实际屏幕像素尺寸**下栅格化:设备像素 ×
+ 画布设计分辨率适配都折算进栅格化,四边形 1:1 贴屏,享有原生抗锯齿和字体
+ hinting。任何窗口尺寸下都如 DOM 一样锐利——**静态** UI 的最锐选择。
+- **`Sdf`** —— 每个字形栅格化一次为带符号距离场(signed-distance field),着色器
+ 在边缘铺一条 **约 1px 的屏幕空间覆盖渐变**(msdfgen/TextMeshPro 技法)。在
+ **动态**缩放下——动画缩放、scale 补间、世界空间标签——边缘保持锐利,而位图
+ 会糊或闪。
+- **`Auto`**(默认)—— 实体自身世界缩放为 1 时(±2% 以内;画布适配已在位图路径
+ 中补偿)用位图,一旦实体缩放立即切 SDF。静态 UI 如 DOM 般锐利,动画文本缩放
+ 稳定,零配置。
+
+所以一个脉动的 "LEVEL UP!" 横幅什么都不用设——`Auto` 会在它缩放时切到 SDF:
+
+```typescript
+import {
+ defineSystem, Query, Mut, Res, Time, Transform, Text,
+} from 'esengine';
+
+// Tween the banner's scale; Auto routes the text to the SDF pipeline
+// while scale ≠ 1, so the glyph edges stay crisp mid-zoom.
+const pulseBanner = defineSystem([Query(Mut(Transform), Text), Res(Time)], (q, time) => {
+ for (const [, tr] of q) {
+ const s = 1 + 0.25 * Math.sin(time.elapsed * 4);
+ tr.scale.x = s;
+ tr.scale.y = s;
+ }
+});
+```
+
+文本*生来*就带缩放、或活在任意相机变焦的世界空间时,强制 `Sdf`;确定文本永不
+缩放、且想在微小的逐帧缩放噪声下也保住 hinting 时,强制 `Bitmap`。
+
+## `Text` 属性
+
+下表默认值为组件默认值(检查器所示)。
+
+| 属性 | 类型 | 默认 | 说明 |
+|---|---|---|---|
+| `content` | string | `''` | 要显示的字符串。`\n` 硬换行。 |
+| `i18nKey` | string | `''` | 本地化键。非空 ⇒ `content` 成为**派生值**:每帧从本地化目录解析([见下文](#本地化))。 |
+| `fontFamily` | string | `'Arial'` | 字体族,由平台 Canvas2D 解析(见[自定义字体](#自定义字体))。 |
+| `fontSize` | number | `24` | 尺寸,单位**设计像素**——与 `UINode` 的 `px()` 同一单位。设计分辨率适配与设备像素比在栅格化时补偿。 |
+| `color` | Color | `{1,1,1,1}` | 填充色(每通道 `0..1`)。 |
+| `align` | `TextAlign` | `Left` | 水平对齐:`Left` / `Center` / `Right`。 |
+| `verticalAlign` | `TextVerticalAlign` | `Top` | 垂直对齐:`Top` / `Middle` / `Bottom`。 |
+| `wordWrap` | boolean | `true` | 按盒宽换行(需要 `UINode` 盒)。 |
+| `overflow` | `TextOverflow` | `Visible` | `Visible` / `Clip` / `Ellipsis`。当前渲染器始终按 `Visible` 绘制;要裁剪溢出,给盒加 [`UIMask`](/docs/zh-cn/guides/ui/)。 |
+| `lineHeight` | number | `1.2` | 行距,为 **`fontSize` 的比率**(基线间距 = `lineHeight × fontSize`)。 |
+| `bold` / `italic` | boolean | `false` | 基础字体样式(富文本 `<b>`/`<i>` 在其上叠加)。 |
+| `strokeColor` | Color | `{0,0,0,1}` | 描边颜色。 |
+| `strokeWidth` | number | `0` | 描边宽度(px);`0` 关闭。以 8 方向扇形展开的换色字形副本绘制。 |
+| `shadowColor` | Color | `{0,0,0,1}` | 投影颜色。 |
+| `shadowOffsetX` / `shadowOffsetY` | number | `0` | 投影偏移(px)。仅当颜色有 alpha 且至少一个偏移非零时绘制。 |
+| `shadowBlur` | number | `0` | 保留字段——当前渲染器把投影画成硬边偏移副本,不应用模糊。 |
+| `richText` | boolean | `false` | 解析内联[富文本标记](#富文本)。 |
+| `renderMode` | `TextRenderMode` | `Auto` | 字形管线:`Auto` / `Bitmap` / `Sdf`(见上文)。 |
+| `enabled` | boolean | `true` | 渲染开关(编辑器的眼睛图标也用它)。 |
+
+<Aside type="note">
+ 代码组合路径有一套更适合控件的默认值,与组件不同:`spawnUIEntity({ text: … })` /
+ `buildText()` 默认 `fontSize: 14`、`align: Center`、`verticalAlign: Middle`、
+ `wordWrap: false`。要紧处请显式传字段。
+</Aside>
+
+## 对齐——有盒与无盒
+
+一条规则覆盖两种情况:**`align` / `verticalAlign` 把文本块定位在它的盒内,而
+"没有盒" 塌缩为实体原点处的零尺寸盒**——同样的字段用来*锚定*自由标签,而不是
+静默失效。
+
+- **有 `UINode` 盒**(实体带布局尺寸非零的 `UINode`):每行在盒宽内水平对齐——
+ 与 `wordWrap` 无关,后者只决定是否在该宽度*断行*——`verticalAlign` 分配块的
+ 垂直空余(`Middle` 平分,`Bottom` 推到底)。
+- **无盒**(没有 `UINode`,或 0×0):文本块锚定到实体原点。`align: Left` 让左缘
+ 落在原点,`Center` 以原点居中,`Right` 结束于原点;`verticalAlign` 同理锚定
+ 顶/中/底缘。世界空间标签——伤害数字、名牌——"以实体为中心"就是一个字段,
+ 不用算。
+
+## 富文本
+
+设 `richText: true`,在 `content` 里写内联标签。样式按栈嵌套;闭合标签弹出最内层
+样式。解析不出的内容按字面渲染(散落的 `<` 不会吃掉文本)。
+
+| 标记 | 效果 |
+|---|---|
+| `<b>…</b>` | 加粗片段。 |
+| `<i>…</i>` | 斜体片段。 |
+| `<color=#RRGGBB>…</color>` | 着色片段;`#RRGGBBAA` 带 alpha。 |
+| `<font size=32>…</font>` | 另一字号的片段(`size="32"` 也能解析);共享基线。 |
+| `<img src="…" width=24 height=24 />` | 内联图片片段——目前能解析,**尚未渲染**(见下)。 |
+
+```typescript
+import { defineSystem, addStartupSystem, GetWorld, spawnUIEntity, px } from 'esengine';
+
+const buildToast = defineSystem([GetWorld()], (world) => {
+ spawnUIEntity({
+ world,
+ node: { width: px(360), height: px(48) },
+ text: {
+ content: 'Found <color=#ffd75a><b>Iron Sword</b></color> <font size=12>(rare)</font>',
+ fontSize: 18,
+ richText: true,
+ },
+ });
+});
+addStartupSystem(buildToast);
+```
+
+解析器以 `parseRichText(input)` 导出,返回 `RichTextRun[]`——每段是
+`TextSegment`(`text`、`bold`、`italic`、`color`、`fontSize`)或
+`ImageSegment`——想用同一套标记驱动自定义管线时可用。
+
+<Aside type="caution">
+ `<img src="…" width=N height=N valign=baseline|middle|top|bottom offsetX=N
+ offsetY=N scale=N tint=#RRGGBB />` 会解析成 `ImageSegment`(标签必须自闭合且
+ 必须有 `src`),但内置文本渲染器目前**跳过图片片段**——文本内联精灵还画不
+ 出来。请改用 flexbox 把图片排在文本旁。
+</Aside>
+
+## 测量文本
+
+`measureText(text, opts)` 不生成实体就回答"这串字渲染出来多大?"——用于必须
+预先按内容定尺寸的布局,比如 ListView 为换行聊天气泡计算 `itemHeight(index)`。
+它通过与渲染器相同的 Canvas2D 来源和同一套换行算法测量,测得的换行与渲染一致。
+无 DOM 的主机(headless)退化为平均字宽估算。
+
+```typescript
+import { measureText, px, spawnUIEntity, defineSystem, addStartupSystem, GetWorld } from 'esengine';
+
+const buildBubble = defineSystem([GetWorld()], (world) => {
+ const message = 'You have been invited to join the guild "Night Watch".';
+ const m = measureText(message, { fontSize: 16, maxWidth: 260 });
+ spawnUIEntity({
+ world,
+ node: { width: px(280), height: px(m.height + 20) }, // pad the measured height
+ visual: { color: { r: 0.13, g: 0.15, b: 0.2, a: 1 } },
+ text: { content: message, fontSize: 16, wordWrap: true },
+ });
+});
+addStartupSystem(buildBubble);
+```
+
+| `MeasureTextOptions` | 默认 | 说明 |
+|---|---|---|
+| `fontSize` | ——(必填) | 尺寸(显示像素)。 |
+| `fontFamily` | `'Arial'` | 字体族。 |
+| `bold` / `italic` | `false` | 样式(影响字距)。 |
+| `letterSpacing` | `0` | 字形间额外像素。 |
+| `maxWidth` | —— | 换行宽度;`0`/省略 = 单行。 |
+| `lineHeight` | `fontSize × 1.2` | 行高(显示**像素**——注意不是组件里的比率)。 |
+
+| `TextMetrics` | 说明 |
+|---|---|
+| `width` | 最宽行的宽度(显示像素)。 |
+| `lineCount` | 换行加显式 `\n` 后的行数。 |
+| `height` | `lineCount × lineHeight`——给盒定高就用它。 |
+
+## 自定义字体
+
+`fontFamily` 在字形栅格化时由平台的 **Canvas2D** 解析——宿主页面能解析的任何
+字体族都可用:系统字体,或页面自己加载的 Web 字体(CSS `@font-face` 或
+`FontFace` API)。SDK 不会替 `Text` 组件抓取字体文件;请确保 Web 字体在文本
+首次渲染前已加载,否则其字形会用回退字体栅格化。
+
+另有**位图字体资产**(`.fnt` / `.bmfont`)走资产管线——`Assets.loadFont(ref)`
+解析 `.fnt`、加载其页纹理,返回 `FontResult`(`{ handle }`)。它们驱动
+**`BitmapText`** 组件:世界空间文本渲染器,其 `font` 字段引用加载的资产(在
+检查器里指定字体资产),另有 `text`、`color`、`fontSize`、`align`、`spacing`、
+`parallax`、`layer` 字段。预烘焙的分数/伤害字形美术用 `BitmapText`;UI 用
+`Text`。
+
+## 本地化
+
+不要手写 `content`,改设 `i18nKey`:存在 Localization 资源时(安装
+`localizationPlugin`),每帧有系统把键经目录解析并写入 `content`——因此
+`setLocale` 下一帧就重排所有绑定的标签。缺失的键解析为键本身(可见、可 grep);
+没有 Localization 资源时按原作 `content` 显示。见[本地化](/docs/zh-cn/guides/localization/)。
+
+## 最佳实践
+
+- **`renderMode` 留在 `Auto`**——只为生来带缩放的文本手选 `Sdf`,只为确定永不
+ 缩放、想钉住 hinting 的文本手选 `Bitmap`。
+- **给 UI 文本配 `UINode` 盒**,换行和对齐才有宽度可依;只有锚定到实体的世界
+ 空间标签才走无盒。
+- **`fontSize` 是设计像素**——与 `px()` 布局同一单位定字号,DPR 和设计分辨率
+ 适配交给引擎。
+- **先测量再定尺寸**——`measureText` 用的是渲染器自己的换行,按内容定尺寸的盒
+ (聊天行、tooltip)分毫不差。
+- **用 `i18nKey` 绑定标签**,不要把翻译串写进 `content`——切换语言即自动重排。
+- **强调用标记而非拆实体**:一个富文本 Text 胜过三个用 flexbox 粘起来的普通
+ Text。
+
+## 另请参阅
+
+- [UI](/docs/zh-cn/guides/ui/) —— 组件模型总览。
+- [UI 布局](/docs/zh-cn/guides/ui-layout/) —— 文本对齐与换行所依的 `UINode` 盒。
+- [UI 组件](/docs/zh-cn/guides/ui-components/) —— 可编辑文本的 `createTextInput`。
+- [UI 主题](/docs/zh-cn/guides/ui-theme/) —— 主题化的文本颜色角色与字号阶梯。
+- [UI 数据绑定](/docs/zh-cn/guides/ui-binding/) —— 用响应式 signal 驱动 `content`。
+- [本地化](/docs/zh-cn/guides/localization/) —— 目录、语言与 `i18nKey` 解析。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-theme.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-theme.mdx
new file mode 100644
index 000000000..28ec4ee4d
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-theme.mdx
@@ -0,0 +1,220 @@
+---
+title: 主题
+description: ThemeTokens 设计令牌模型——语义化颜色/文本角色、暗色/亮色调色板、switchTheme 实时换肤、项目级覆盖,以及如何让自定义控件正确接入主题。
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+控件层从不硬编码颜色。每个内建控件都从**设计令牌(design tokens)**解析默认值
+——一套*语义角色*调色板(`surface`、`control`、`primary`、`text`……)加一份字号
+标尺——于是外观在一处定义,同一份控件代码在暗色或亮色调色板下都能正确渲染,
+整套 UI 换一组令牌即可整体换肤。
+
+这由三层协作实现:
+
+1. **`ThemeTokens`** —— 令牌模型:颜色角色 + 字号标尺,以及内建的
+ `DARK_TOKENS` / `LIGHT_TOKENS` 两套令牌。
+2. **`ThemeStyle`** —— 一个组件,记录实体的颜色来自*哪个角色*,让已构建的控件
+ 能重新解析。
+3. **`switchTheme`** —— 实时切换:设置活动令牌*并且*重新着色世界里每个带
+ `ThemeStyle` 标记的实体。
+
+## 令牌模型 —— `ThemeTokens`
+
+```typescript
+interface ThemeTokens {
+ colors: ThemeColors; // semantic color roles
+ type: ThemeType; // font-size scale
+}
+```
+
+### 颜色角色(`ThemeColors`)
+
+全部角色按显示顺序列出(这也是运行时列表 `THEME_COLOR_ROLES`——主题编辑器或
+配置校验器迭代的那个数组):
+
+| 角色 | 用途 |
+|---|---|
+| `surface` | 对话框 / 面板背景。 |
+| `surfaceElevated` | 抬升表面——弹出层 / 下拉列表背景。 |
+| `control` | 交互控件的静止填充(按钮、选项)。 |
+| `controlHover` | 悬停时的控件填充。 |
+| `controlActive` | 按下时的控件填充。 |
+| `track` | 滑杆 / 进度条轨道。 |
+| `primary` | 强调色——滑杆填充、进度填充、选中项。 |
+| `primaryHover` | 悬停时的强调色。 |
+| `primaryActive` | 按下时的强调色。 |
+| `onPrimary` | 画在 `primary` *之上*的内容/手柄(例如滑杆拇指)。 |
+| `text` | `surface` / `control` 上的默认前景(标签文本 / 图标)。 |
+| `backdrop` | 对话框背后的模态遮罩。 |
+
+### 字号标尺(`ThemeType`)
+
+以 px 计的字号,亮暗两套主题共用:
+
+| 档位 | 默认值 | 用于 |
+|---|---|---|
+| `label` | `14` | 控件 / 标签文本(按钮、选项)。 |
+| `body` | `15` | 正文 / 默认文本。 |
+| `title` | `20` | 标题(对话框标题)。 |
+
+### 内建令牌集
+
+- **`DARK_TOKENS`** —— 内建默认值。
+- **`LIGHT_TOKENS`** —— 同一套角色,亮色表面配深色文字。
+
+用 `getTheme()`(或简写 `themeColors()` / `themeType()`)读取活动令牌集,用
+`setTheme(tokens)` 替换——但注意,单独的 `setTheme` 只影响*之后*构建的控件;
+要实时切换请用下文的 [`switchTheme`](#实时换肤--switchtheme)。
+
+## 控件如何消费令牌
+
+控件工厂在**构建时**解析令牌:`createButton` 读取 `themeColors().control` /
+`controlHover` / `controlActive` 作为状态页颜色,读 `themeColors().text` +
+`themeType().label` 作为标签样式;`createSlider` 用 `track` / `primary` /
+`onPrimary` 填轨道、填充与手柄;其余同理。解析出的值被烘焙进普通组件
+(`UIVisual`、`Text`、`$interaction` 颜色 gear)——不存在逐帧的主题查询。
+
+正因为值是烘焙的,每个工厂*还会*给它着色过的实体打上 **`ThemeStyle`** 组件,
+记录每个颜色来自哪个角色:
+
+| `ThemeStyle` 字段 | 记录驱动……的角色 |
+|---|---|
+| `visual` | ……该实体 `UIVisual.color` 的角色。 |
+| `text` | ……该实体 `Text.color` 的角色。 |
+| `states` | ……每个 `$interaction` 颜色 gear 页(页名 → 角色),例如按钮的 `{ normal: 'control', hover: 'controlHover', … }`。 |
+| `input` | ……`TextInput` 的 `background` / `text` / `placeholder` 颜色。 |
+
+`markThemed(world, entity, style)` 负责插入标记。角色标记是创作数据——会**随
+prefab 与场景持久化**,所以编辑器摆放的控件与代码构建的控件换肤行为完全一致。
+
+## 实时换肤 —— `switchTheme`
+
+`switchTheme(world, tokens)` 设置活动令牌**并**调用
+`applyThemeToWorld(world)`:遍历每个带 `ThemeStyle` 标记的实体,把它的角色绑定
+——`UIVisual.color`、`Text.color`、`TextInput` 各颜色,以及每个 `$interaction`
+颜色 gear 页——对照新调色板重新解析:
+
+```typescript
+import { switchTheme, getTheme, DARK_TOKENS, LIGHT_TOKENS } from 'esengine';
+
+// e.g. from a settings toggle:
+switchTheme(world, getTheme() === DARK_TOKENS ? LIGHT_TOKENS : DARK_TOKENS);
+```
+
+值得了解的语义:
+
+- **保留 alpha** —— 只有色相被重新着色。压暗的 `disabled` 状态保住它的透明度,
+ 你设置过的半透明也能在切换后幸存。
+- **prefab 里创作的颜色同样会重解析**:从 prefab 实例化的控件带着烘焙颜色*和*
+ `ThemeStyle` 标记,所以 `applyThemeToWorld` 对它的重新着色与现场构建的控件
+ 一模一样。
+- *没有* `ThemeStyle` 标记的实体不受影响——显式颜色永远是你的(见
+ [逐控件覆盖](#逐控件覆盖-vs-令牌))。
+
+## 项目级主题
+
+*基础*外观通常不用你调 `switchTheme`——由项目声明。编辑器的
+**项目设置 → UI** 会往项目清单(`project.esproject`)的 `features.ui` 下写两个
+字段:
+
+| 设置项 | 清单字段 | 含义 |
+|---|---|---|
+| 主题 | `features.ui.theme` | `'light'`,或缺省表示默认暗色。 |
+| 主题颜色 | `features.ui.colors` | 局部换肤:颜色角色 → `#rrggbb[aa]` 十六进制。只有已知角色(`THEME_COLOR_ROLES` 列表)且十六进制合法才会持久化;缺省的角色继承基础主题。 |
+
+两个共享函数把这些设置送达每个运行时:
+
+- **`parseThemeOverrides(colors)`** —— 把 JSON 十六进制映射转换为
+ `ThemeOverrides`(未知角色与畸形十六进制被丢弃)。
+- **`resolveThemeTokens(base, overrides?)`** —— 把基础主题名
+ (`'dark' | 'light'`)与局部覆盖合并成有效的 `ThemeTokens`,于是只覆盖
+ `primary` 的项目在继承其余角色的同时重染强调色。
+
+```typescript
+import { resolveThemeTokens, parseThemeOverrides, switchTheme } from 'esengine';
+
+const overrides = parseThemeOverrides({ primary: '#e5484d' });
+switchTheme(world, resolveThemeTokens('dark', overrides));
+```
+
+端到端的流程:**编辑器**在编辑视口里实时预览有效主题(它对编辑世界执行的正是
+`switchTheme(world, resolveThemeTokens(...))`——设置面板所见即所得,逐角色的
+取色器以继承的基础值为占位显示)。**导出**时,主题与颜色被烘焙进出货的游戏
+配置,每个运行时先启动场景、再应用
+`switchTheme(world, resolveThemeTokens(theme, overrides))`——prefab 烘焙的是
+暗色值,加载后的这次切换正是重解析所有 `ThemeStyle` 标记的那一步。
+
+<Aside type="note">
+ 暗色用*缺省*表达:清单里只持久化 `'light'` 与非空的颜色覆盖。没有
+ `features.ui` 块的项目按原样出货默认的 `DARK_TOKENS`。
+</Aside>
+
+## 逐控件覆盖 vs 令牌
+
+每个工厂都允许传入显式颜色——而这么做会让该字段**退出主题管理**。规则是一致
+的:走主题默认值的字段获得 `ThemeStyle` 标记并在换肤时重解析;调用方提供的颜色
+*没有*标记,永远归你。
+
+- `createButton({ states: {...} })` —— 自定义状态颜色不换肤;省略 `states` 则
+ 获得 `themeButtonStates()`(标准的 `control` 角色状态),会换肤。
+- `createButton({ text: { color } })` —— 显式标签颜色跳过 `text` 角色标记;
+ 省略 `color`,标签就跟随主题。
+- `createSlider({ trackVisual / fillVisual / handleVisual })` —— 逐部件同理。
+
+凡是应当跟随暗色/亮色的都优先用令牌;显式颜色留给真正固定的品牌色(红色的
+"录制"圆点在两套主题下都保持红色)。
+
+## 让自定义控件接入主题
+
+想让你自己的组合表现得像内建控件,就照工厂的做法来:构建时从
+`themeColors()` / `themeType()` 解析,然后用 `markThemed` 给每个实体标上你用过
+的角色。
+
+```typescript
+import type { World, Entity } from 'esengine';
+import { spawnUIEntity, markThemed, themeColors, themeType, px } from 'esengine';
+
+function createBadge(world: World, parent: Entity, label: string): Entity {
+ const c = themeColors();
+
+ const badge = spawnUIEntity({
+ world, parent,
+ node: { width: px(64), height: px(24) },
+ visual: { color: c.primary },
+ });
+ markThemed(world, badge, { visual: 'primary' });
+
+ const text = spawnUIEntity({
+ world, parent: badge,
+ text: { content: label, color: c.onPrimary, fontSize: themeType().label },
+ });
+ markThemed(world, text, { text: 'onPrimary' });
+
+ return badge;
+}
+```
+
+现在 `switchTheme` 会把这个徽标与其他一切一起重染。带 `$interaction` 颜色 gear
+的交互控件则改为标记页→角色映射:
+`markThemed(world, entity, { states: { normal: 'control', hover: 'controlHover', pressed: 'controlActive' } })`。
+
+## 最佳实践
+
+- **用角色,别用颜色。** 伸手拿 `themeColors().primary` 而非字面量——并用
+ `markThemed` 打标,让它在换肤后依然成立。
+- **在项目设置里声明基础主题**,别写在代码里——编辑器预览与所有导出目标就此
+ 达成一致。
+- **用覆盖重染品牌色**:在 `features.ui.colors` 里覆盖 `primary`(加
+ `primaryHover` / `primaryActive`)即可零代码地为所有控件换强调色。
+- **只有刻意的常量才退出主题。** 传显式颜色即是承诺该元素*不*跟随主题——确认
+ 这正是你的本意。
+- **切换用 `switchTheme`,不要裸 `setTheme`。** 裸 `setTheme` 只影响之后构建的
+ 控件;`switchTheme` 还会重新着色屏幕上已有的东西。
+
+## 参见
+
+- [UI](/docs/zh-cn/guides/ui/) —— 令牌所着色的组件模型。
+- [UI 控件](/docs/zh-cn/guides/ui-components/) —— 消费令牌的控件工厂。
+- [UI 控制器](/docs/zh-cn/guides/ui-controllers/) —— 主题状态色所依附的 `$interaction` gear。
+- [数据绑定](/docs/zh-cn/guides/ui-binding/) —— 把响应式值写进组件字段。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui.mdx
index bc9d93b09..3e5bcabfc 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/ui.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui.mdx
@@ -1,6 +1,6 @@
---
title: UI
-description: UI 完整参考——弹性盒组件模型(UINode/FlexContainer)、文本、视觉、控件与交互处理。
+description: UI 系统总览——弹性盒组件模型、暂停菜单快速上手、布局/视觉/交互/控件如何协作,以及各 UI 指南的导航地图。
---
import { Aside } from '@astrojs/starlight/components';
@@ -9,19 +9,21 @@ Estella 的 UI 是在 C++ 内核里求解的 CSS 式弹性盒(flexbox)系统。
在编辑器里或用代码——并在系统里处理交互。**没有 `RectTransform`**:`UINode` 就是真正的
flexbox,用 `px` / `percent` / `auto` 加 `Absolute` 内偏移(inset)来定尺寸。
+本页是总览:组件模型、快速上手,以及各 UI 详细指南的地图。每个领域的深入参考在各自的章节里。
+
## 组件
-| 组件 | 职责 |
-|---|---|
-| `UINode` | 布局盒;持有逐项的 flex 字段(尺寸、grow/shrink、margin、inset)。 |
-| `FlexContainer` | 用 flexbox 排布一个节点的子项(方向、对齐、gap、padding)。 |
-| `Text` | 经 SDF 字形图集渲染文本(内容、字体、颜色、对齐、描边、阴影、富文本)。 |
-| `UIVisual` | 填充——纯色、纹理、九宫格、平铺或填充。 |
-| `UIMask` | 裁剪它的子项。 |
-| `Interactable` | 标记节点可命中,从而能被悬停/点击。 |
-| `UIInteraction` | 引擎每帧写入的指针状态(对你的逻辑只读)。 |
+| 组件 | 职责 | 指南 |
+|---|---|---|
+| `UINode` | 布局盒;持有逐项的 flex 字段(尺寸、grow/shrink、margin、inset)。 | [UI 布局](/docs/zh-cn/guides/ui-layout/) |
+| `FlexContainer` | 用 flexbox 排布一个节点的子项(方向、justify、align、gap、padding)。 | [UI 布局](/docs/zh-cn/guides/ui-layout/) |
+| `Text` | 经动态字形图集渲染文本(内容、字体、颜色、对齐、描边、阴影、富文本)。 | [UI 文本](/docs/zh-cn/guides/ui-text/) |
+| `UIVisual` | 填充——纯色、纹理、九宫格、平铺或填充。 | 见下文 |
+| `UIMask` | 裁剪它的子项。 | 见下文 |
+| `Interactable` | 标记节点可命中,从而能被悬停/点击。 | [UI 交互](/docs/zh-cn/guides/ui-interaction/) |
+| `UIInteraction` | 引擎每帧写入的指针状态(对你的逻辑只读)。 | [UI 交互](/docs/zh-cn/guides/ui-interaction/) |
-## 用代码搭建 UI
+## 快速上手:暂停菜单
一个完整的暂停菜单——居中的列面板,带标题和一个按钮——用**启动系统**构建一次:
@@ -67,128 +69,84 @@ const buildPauseMenu = defineSystem([GetWorld(), Res(UIEvents)], (world, events)
addStartupSystem(buildPauseMenu);
```
-`spawnUIEntity({ world, parent?, node?, visual?, text? })` 返回实体;传 `parent` 即嵌套。
-尺寸用维度辅助 `px`、`percent`、`auto`。其它控件工厂用法相同:`createToggle`、`createSlider`、
-`createProgress`、`createDialog`、`createDropdown`。
-
-<Aside type="tip">
- 在编辑器里你可以可视化地搭同一棵树:添加 `UINode` 实体、嵌套它们,并在检视面板里加
- `FlexContainer` / `Text` / `UIVisual` / `Interactable`。
-</Aside>
-
-## `UINode` —— 布局盒
-
-逐项的尺寸与放置在这里(维度用 `px()` / `percent()` / `auto()` 构造)。
-
-| 属性 | 类型 | 默认 | 说明 |
-|---|---|---|---|
-| `position` | `UIPositionType` | `Relative` | `Relative`(在流中)或 `Absolute`(按 inset 放置)。 |
-| `width` / `height` | Dimension | `auto` | 盒尺寸;`auto` = 由内容/flex 决定。 |
-| `minWidth` / `minHeight` | Dimension | `auto` | 尺寸下界。 |
-| `maxWidth` / `maxHeight` | Dimension | `auto` | 尺寸上界。 |
-| `flexGrow` | number | `0` | 吸收多余空间的份额。 |
-| `flexShrink` | number | `1` | 空间紧张时的收缩因子。 |
-| `flexBasis` | Dimension | `auto` | grow/shrink 前的基准尺寸。 |
-| `alignSelf` | `AlignSelf` | `Auto` | 逐项的交叉轴对齐覆盖。 |
-| `marginLeft/Top/Right/Bottom` | Dimension | `0` | 外间距。 |
-| `insetLeft/Top/Right/Bottom` | Dimension | `auto` | `Absolute` 时的边偏移。 |
-
-## `FlexContainer` —— 布局
-
-给节点加一个 `FlexContainer` 来排布它的子项。枚举与 CSS 对应。
-
-| 属性 | 类型 | 默认 | 说明 |
-|---|---|---|---|
-| `direction` | `FlexDirection` | `Row` | `Row` / `Column` / `RowReverse` / `ColumnReverse`。 |
-| `wrap` | `FlexWrap` | `NoWrap` | `NoWrap` / `Wrap`。 |
-| `justifyContent` | `JustifyContent` | `Start` | 主轴分布(`Start`…`SpaceEvenly`)。 |
-| `alignItems` | `AlignItems` | `Stretch` | 交叉轴对齐(`Start` / `Center` / `End` / `Stretch`)。 |
-| `alignContent` | `AlignContent` | `Start` | 换行后各行的分布。 |
-| `gap` | Vec2 | `{0, 0}` | 子项间距(x = 列间距,y = 行间距)。 |
-| `padding` | Padding | `{0,0,0,0}` | 内间距(`left/top/right/bottom`)。 |
-
-## `Text`
-
-文本从动态字形图集渲染,有**两条管线**,由 `renderMode` 逐 Text 选择:
-
-- **`Bitmap`** —— 字形按**最终屏幕像素尺寸**(设备像素 × 画布设计分辨率适配)
- 光栅化,带 Canvas 原生抗锯齿与字体 hinting,1:1 贴屏——任何窗口尺寸下都像
- DOM 一样锐利。
-- **`Sdf`** —— 每个字形只光栅化一次为有向距离场(SDF),着色器在边缘铺一条
- **1px 屏幕空间覆盖率斜坡**(msdfgen / TextMeshPro 的标准做法),**动态**缩放
- 下保持清晰——变焦动画、缩放补间、世界空间标签。
-- **`Auto`**(默认)—— 实体自身未缩放时用 Bitmap(画布适配已在位图内补偿),
- 实体一旦缩放立即切 SDF。静态 UI 像 DOM 一样锐利,动态文本随缩放稳定,零配置。
-
-| 属性 | 类型 | 默认 | 说明 |
-|---|---|---|---|
-| `content` | string | `''` | 要显示的字符串。 |
-| `fontFamily` | string | `'Arial'` | 字体族。 |
-| `fontSize` | number | `24` | 字号(像素)。 |
-| `color` | Color | `{1,1,1,1}` | 文本颜色。 |
-| `align` | `TextAlign` | `Left` | 水平对齐。 |
-| `verticalAlign` | `TextVerticalAlign` | `Top` | 垂直对齐。 |
-| `wordWrap` | boolean | `true` | 在盒宽处换行。 |
-| `overflow` | `TextOverflow` | `Visible` | 溢出处理。 |
-| `lineHeight` | number | — | 行距倍率。 |
-| `bold` / `italic` | boolean | `false` | 字形样式。 |
-| `strokeColor` / `strokeWidth` | Color / number | — | 描边。 |
-| `shadowColor` / `shadowBlur` / `shadowOffsetX` / `shadowOffsetY` | — | 投影。 |
-| `richText` | boolean | `false` | 解析内联富文本标记。 |
-| `renderMode` | `TextRenderMode` | `Auto` | 字形管线:`Auto` / `Bitmap` / `Sdf`(见上)。 |
-| `enabled` | boolean | `true` | 渲染开关(编辑器的眼睛图标也走它)。 |
-
-## `UIVisual` —— 填充
-
-`UIVisual` 绘制节点的背景。`visualType` 选择模式:
-
-| `UIVisualType` | 使用 | 说明 |
+`spawnUIEntity({ world, parent?, node?, visual?, text? })` 返回实体;传 `parent` 来
+嵌套。尺寸用维度助手 `px`、`percent`、`auto`——单位都是**设计像素**(见
+[UI 布局](/docs/zh-cn/guides/ui-layout/#单位设计像素))。其余控件工厂用法相同:
+`createToggle`、`createSlider`、`createProgress`、`createDialog`、`createDropdown`——见
+[UI 组件](/docs/zh-cn/guides/ui-components/)。
+
+## 各部分如何协作
+
+每一层都建立在前一层之上:
+
+1. **布局**——`UINode` 盒子由 flexbox 引擎求解;`FlexContainer` 排布子项,
+ `Absolute` 内偏移放置悬浮层。→ [UI 布局](/docs/zh-cn/guides/ui-layout/)
+2. **视觉与文本**——`UIVisual` 填充盒子,`UIMask` 裁剪,`Text` 绘制锐利字形。
+ → [UI 文本](/docs/zh-cn/guides/ui-text/)
+3. **交互**——`Interactable` 让盒子可命中;引擎把指针状态写入 `UIInteraction`
+ 并发出冒泡的 `UIEvents`;拖放和键盘焦点建立在其上。
+ → [UI 交互](/docs/zh-cn/guides/ui-interaction/)
+4. **控件**——工厂(`createButton`、`createSlider`……)把前三层组合成现成的控件;
+ `createListView` 提供虚拟化列表。
+ → [UI 组件](/docs/zh-cn/guides/ui-components/)、[UI 列表](/docs/zh-cn/guides/ui-lists/)
+5. **控制器**——每个 UI 根一份命名"页面"状态加逐页字段绑定(标签页、按钮状态、
+ 显示/隐藏)——零代码。→ [UI 控制器](/docs/zh-cn/guides/ui-controllers/)
+6. **主题与绑定**——设计 token 给所有控件换肤(可实时切换),响应式 signal 让 UI
+ 与游戏状态保持同步。
+ → [UI 主题](/docs/zh-cn/guides/ui-theme/)、[UI 绑定](/docs/zh-cn/guides/ui-binding/)
+
+### `UIVisual` 与 `UIMask`
+
+`UIVisual` 绘制节点的背景;`visualType` 选择模式:
+
+| `UIVisualType` | 使用字段 | 说明 |
|---|---|---|
-| `None` | — | 不可见(仅布局/命中)。 |
-| `SolidColor` | `color` | 着色方块。 |
-| `Image` | `texture`、`uvOffset`、`uvScale` | 纹理方块 / 精灵区域。 |
-| `NineSlice` | `sliceBorder` | 角固定、可缩放的面板。 |
-| `Tiled` | `tileSize` | 纹理在盒内重复。 |
-| `Filled` | `fillAmount`、`fillMethod`、`fillOrigin` | 裁剪填充(血条/进度条)。 |
+| `None` | — | 不可见(仅参与布局/命中测试)。 |
+| `SolidColor` | `color` | 着色四边形。 |
+| `Image` | `texture`、`uvOffset`、`uvScale` | 贴图四边形 / 精灵区域。 |
+| `NineSlice` | `sliceBorder` | 角部固定、可缩放的面板。 |
+| `Tiled` | `tileSize` | 纹理在盒内平铺重复。 |
+| `Filled` | `fillAmount`、`fillMethod`、`fillOrigin` | 裁剪式填充(血条/进度条、冷却环)。 |
-## 处理交互
+`UIVisual.enabled` 只隐藏本实体的视觉;`UINode.display = None` 把该节点**连同整棵
+子树**从布局、渲染和命中测试中移除。给节点加 `UIMask` 可把子项裁剪到盒内。
-`createButton` 直接给你 `onClick`。对于自定义控件,命中系统会把每帧的指针状态写入任何带
-`Interactable` 的实体上的 `UIInteraction`。它是**只读**的——查询它,绝不修改:
+## 编辑器还是代码
-```typescript
-import { defineSystem, Query, Interactable, UIInteraction } from 'esengine';
+两者书写的是**同一套组件**——没有单独的编辑器格式:
-const onTiles = defineSystem([Query(Interactable, UIInteraction)], (q) => {
- for (const [entity, _gate, state] of q) {
- if (state.justReleased) { /* this node was clicked */ }
- }
-});
-```
+- **编辑器**——*Create… → UI* 放入控件预制件(Button、Toggle、Slider、Dialog……);
+ 拖拽嵌套,在 Details 里编辑每个字段,用逐轴锚点选择器摆放,并按项目的设计分辨率
+ 和设备预设预览。见[编辑器](/docs/zh-cn/guides/editor/)。
+- **代码**——`spawnUIEntity` + 控件工厂,如上例在启动系统里构建。编辑器能写的,
+ 代码都能写。
-| `UIInteraction` 字段 | 说明 |
-|---|---|
-| `hovered` | 指针在节点上方。 |
-| `pressed` | 指针在节点上按住。 |
-| `justPressed` | 本帧变为按下。 |
-| `justReleased` | 本帧释放(一次点击)。 |
+## 下一步去哪
-对于冒泡事件——`click`、`hover_enter`、`change`、`submit`、`drag` 沿父链向上——读
-`UIEvents` 资源(UI 事件总线)。
+| 你想…… | 打开 |
+|---|---|
+| 定尺寸摆盒子——`px`/`percent`/`auto`、flexbox、绝对内偏移、锚点 | [UI 布局](/docs/zh-cn/guides/ui-layout/) |
+| 绘制文本——字体、SDF/位图锐利度、换行、富文本 | [UI 文本](/docs/zh-cn/guides/ui-text/) |
+| 响应指针与键盘——点击、`UIEvents`、拖放、焦点 | [UI 交互](/docs/zh-cn/guides/ui-interaction/) |
+| 使用现成控件——按钮、开关、滑条、对话框、下拉、输入框 | [UI 组件](/docs/zh-cn/guides/ui-components/) |
+| 展示滚动数据——虚拟化列表与网格 | [UI 列表](/docs/zh-cn/guides/ui-lists/) |
+| 全局换肤——设计 token、项目主题、实时切换 | [UI 主题](/docs/zh-cn/guides/ui-theme/) |
+| 让 UI 与游戏状态同步——signal、`bind`、控件双向绑定 | [UI 绑定](/docs/zh-cn/guides/ui-binding/) |
+| 跨元素共享状态——标签页、单选组、页面驱动的视觉 | [UI 控制器](/docs/zh-cn/guides/ui-controllers/) |
## 最佳实践
-- **用 flex,别用绝对定位**——用 `FlexContainer` + `flexGrow` 布局;`Absolute` inset 留给
- 浮层和角标。
-- **用 `percent` / `auto` 定尺寸**做分辨率无关;只在确实要固定尺寸处用硬 `px`。
-- **逻辑由 `UIInteraction` 或 `UIEvents` 驱动**,绝不通过修改它们。
-- **复用控件工厂**(`createButton`、`createSlider`……)获得一致的状态视觉,别手接悬停/按下。
-- **九宫格面板**(`NineSlice`)让边框在任何尺寸都保持清晰。
+- **优先 flex 而非绝对定位**——用 `FlexContainer` + `flexGrow` 布局;`Absolute`
+ 内偏移只留给悬浮层和角标。
+- **用 `percent` / `auto` 定尺寸**以获得分辨率无关性;只有确实需要固定尺寸时才用
+ 硬编码 `px`。
+- **逻辑读 `UIInteraction` 或 `UIEvents` 驱动**,绝不去改写它们。
+- **复用控件工厂**以获得一致的状态视觉,而不是手工接线悬停/按下。
+- **九宫格面板**(`NineSlice`)在任意尺寸下保持边框锐利。
-## 参见
+## 另请参阅
-- [UI 控件](/docs/zh-cn/guides/ui-components/) —— 内建控件工厂。
-- [UI 控制器](/docs/zh-cn/guides/ui-controllers/) —— 共享的"页"状态 + 声明式的每页字段绑定(页签、按钮状态、显隐)。
-- [输入](/docs/zh-cn/guides/input/) —— UI 层之下的原始键鼠/触摸。
-- [本地化](/docs/zh-cn/guides/localization/) —— 把 `Text.content` 绑到翻译 key。
-- [动画](/docs/zh-cn/guides/animation/) —— 补间 UI 颜色/位置增加手感。
+- [输入](/docs/zh-cn/guides/input/)——UI 层之下的原始键盘/鼠标/触摸。
+- [本地化](/docs/zh-cn/guides/localization/)——把 `Text.content` 绑定到翻译键。
+- [动画](/docs/zh-cn/guides/animation/)——补间 UI 颜色/位置增加动感。
+- [编辑器](/docs/zh-cn/guides/editor/)——可视化编排、预制件、锚点选择器。