A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
docs(resources): a resource may carry methods, and nothing said so
yhh0b1afe700883
diff --git a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdxindex 78c156942..a09f8c4ad 100644--- a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx+++ b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx@@ -144,6 +144,11 @@ export const scorePlugin: Plugin = {};```+That resource is plain data to keep the example about the plugin shape — but a+resource can equally be a class instance with methods, which is how every engine+subsystem publishes its API. See+[Plugins & Resources](/docs/core-concepts/plugins-resources/).+| 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. |diff --git a/docs/astro/src/content/docs/core-concepts/plugins-resources.mdx b/docs/astro/src/content/docs/core-concepts/plugins-resources.mdxindex 6f9ecdb9b..88c788c00 100644--- a/docs/astro/src/content/docs/core-concepts/plugins-resources.mdx+++ b/docs/astro/src/content/docs/core-concepts/plugins-resources.mdx@@ -3,6 +3,8 @@ title: Plugins & Resourcesdescription: How subsystems are composed and reached — the Res(XxxAPI) pattern.---+import { Aside } from '@astrojs/starlight/components';+An Estella game is an `App` composed of **plugins**. Each subsystem — physics,audio, tilemaps, particles, UI, and so on — is a plugin that registers itssystems and exposes a runtime API as a **resource**.@@ -56,15 +58,112 @@ resource whose contents are this frame's events, read the same frame:<br />-`Res(X)` gives read access; use `ResMut(X)` when the system **replaces or-mutates the resource's state** — same contract as `Mut` on components.+`Res(X)` hands the system the resource **itself**. `ResMut(X)` hands it a+**handle** wrapped around the resource — `.get()` to reach the value, `.set(v)`+to replace it, `.modify(fn)` to mutate it in place. Use `ResMut` when the system+replaces or mutates the resource's state — same contract as `Mut` on components.+The next section shows both shapes side by side.++## Defining your own resource++A resource is just a value the app owns, and it does **not** have to be plain+data. Every subsystem API in the table above is a class instance published as a+resource — `Res(Audio)` is an `AudioAPI`, `Res(SceneManager)` is a+`SceneManagerState` with `switchTo` / `load` / `unload` on it. Your own+resources can carry methods the same way.++`defineResource(defaultValue, name)` creates the definition — an identity, not+the value itself:++```typescript+import { defineResource } from 'esengine';++class ScoreState {+ value = 0;+ combo = 1;++ add(points: number): void {+ this.value += points * this.combo;+ }+}++export const Score = defineResource<ScoreState>(null!, 'Score');+```++The `null!` is a deliberate placeholder: the real instance is inserted when the+plugin builds, so each app gets its own. This is exactly how every engine+subsystem is wired — `SceneManager` is declared `defineResource<SceneManagerState>(null!, 'SceneManager')`+and its plugin does `app.insertResource(SceneManager, new SceneManagerState(app))`.++```typescript+import type { App, Plugin } from 'esengine';++export const scorePlugin: Plugin = {+ name: 'score',+ build(app: App) {+ app.insertResource(Score, new ScoreState());+ },+};+```++From there it is reached like any other resource:++```typescript+import { defineSystem, Res, ResMut } from 'esengine';++defineSystem([Res(Score)], (score) => {+ // score IS the ScoreState instance+ if (score.value > 1000) { /* … */ }+});++defineSystem([ResMut(Score)], (score) => {+ // score is the handle — unwrap it+ score.modify((s) => s.add(100));+});+```++Outside ECS code — host code, a `defineBehavior` hook — use+`app.getResource(Score)`, which returns that same live instance.++### What the default value costs you++A resource is materialised the first time it is read, by cloning the default you+passed to `defineResource`. That clone is **structural, not total**:++| Default value | What each app ends up with |+|---|---|+| Plain object / array | A deep clone — one independent copy per app. |+| Class instance | The *same* object, shared by every app that reads it. |+| Function-valued property | Shared by reference — methods always survive the clone. |++Class instances pass through by reference on purpose: cloning them into a bare+object would strip their prototype and with it every method. The practical+consequence is that `defineResource(new ScoreState(), 'Score')` gives **one+score shared by every app in the process** — and the editor runs two (edit mode+and play mode). Prefer the `null!` + `insertResource` form above whenever the+resource holds state.++<Aside type="caution">+ If you hang methods off a **plain object** default, write them as methods or+ `function`, never as arrow functions — an arrow function captures the module+ scope, so `this` is not the resource:++ ```typescript+ defineResource({ value: 0, add(n: number) { this.value += n; } }, 'Score'); // ✅+ defineResource({ value: 0, add: (n: number) => { this.value += n; } }, 'Score'); // ❌+ ```+</Aside>## Components vs. resources- **Components** are per-entity data. You attach them (in the editor or with- `Commands`) and iterate them with `Query`.+ `Commands`) and iterate them with `Query`. C++-backed components are decoded+ out of the wasm heap on every read, so what you get is a **copy** — change it+ and hand it back, or the write is lost (see+ [Scripting](/docs/scripting/overview/)).- **Resources** are per-app singletons — shared state and subsystem APIs — read- with `Res`.+ with `Res`. A resource is the **live object**, never a copy: calling a method+ or setting a field on it takes effect immediately.## Getting an entitydiff --git a/docs/astro/src/content/docs/core-concepts/systems.mdx b/docs/astro/src/content/docs/core-concepts/systems.mdxindex 93d6530d2..ce411c33e 100644--- a/docs/astro/src/content/docs/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/core-concepts/systems.mdx@@ -37,7 +37,9 @@ in order:- **`Mut(Component)`** — a component the system writes. Unwrapped components areread-only.- **`Res(Resource)`** / **`ResMut(Resource)`** — a shared resource, read-only or- writable (such as `Time` for frame timing).+ writable (such as `Time` for frame timing). `Res` gives you the resource+ itself; `ResMut` gives you a handle around it — `.get()` / `.set(v)` /+ `.modify(fn)`.- **`Commands()`** — deferred structural changes (spawn / despawn / add / remove),applied at the next flush.- **`EventReader(E)`** / **`EventWriter(E)`** — read or send a typed event stream.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.mdxindex 3cac6e274..da9367239 100644--- 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@@ -134,6 +134,10 @@ export const scorePlugin: Plugin = {};```+这里的资源是纯数据,为的是让例子聚焦在插件的形状上——但资源同样可以是一个带方法的类+实例,引擎的每个子系统都是这么发布自己 API 的。见+[插件与资源](/docs/zh-cn/core-concepts/plugins-resources/)。+| 成员 | 类型 | 含义 ||---|---|---|| `name` | `string?` | 可选但推荐:具名插件会自动注册进[子系统注册表](#子系统可观测性),且 `build()` 里添加的系统继承该名字用于存活性归因。 |diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/plugins-resources.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/plugins-resources.mdxindex ffb0fd4e8..c4c7d3a99 100644--- a/docs/astro/src/content/docs/zh-cn/core-concepts/plugins-resources.mdx+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/plugins-resources.mdx@@ -3,6 +3,8 @@ title: 插件与资源description: 子系统如何组合与取用 —— Res(XxxAPI) 范式。---+import { Aside } from '@astrojs/starlight/components';+一个 Estella 游戏就是由**插件**组合成的 `App`。每个子系统——物理、音频、瓦片地图、粒子、UI 等等——都是一个插件,它注册自己的系统,并把运行时 API 暴露为一个**资源**。@@ -51,14 +53,102 @@ defineSystem([Res(Audio)], (audio) => {<br />-`Res(X)` 是读取;当系统要**替换或改动资源的状态**时用 `ResMut(X)`——与组件上的-`Mut` 是同一契约。+`Res(X)` 交给系统的是**资源本身**。`ResMut(X)` 交给它的是包在资源外面的一个+**句柄**——`.get()` 取值、`.set(v)` 替换、`.modify(fn)` 原地改动。当系统要替换或+改动资源的状态时用 `ResMut`——与组件上的 `Mut` 是同一契约。下一节把两种形态并排+放在一起。++## 定义你自己的资源++资源只是 App 持有的一个值,它**不必**是纯数据。上表里每个子系统 API 都是一个发布成+资源的类实例——`Res(Audio)` 是一个 `AudioAPI`,`Res(SceneManager)` 是一个带+`switchTo` / `load` / `unload` 的 `SceneManagerState`。你自己的资源同样可以带方法。++`defineResource(默认值, 名字)` 创建的是定义——一个身份,不是值本身:++```typescript+import { defineResource } from 'esengine';++class ScoreState {+ value = 0;+ combo = 1;++ add(points: number): void {+ this.value += points * this.combo;+ }+}++export const Score = defineResource<ScoreState>(null!, 'Score');+```++`null!` 是刻意的占位:真正的实例在插件 build 时插入,于是每个 App 拿到自己的一份。+引擎的每个子系统都是这么接的——`SceneManager` 声明为+`defineResource<SceneManagerState>(null!, 'SceneManager')`,它的插件里再+`app.insertResource(SceneManager, new SceneManagerState(app))`。++```typescript+import type { App, Plugin } from 'esengine';++export const scorePlugin: Plugin = {+ name: 'score',+ build(app: App) {+ app.insertResource(Score, new ScoreState());+ },+};+```++之后它和别的资源一样取用:++```typescript+import { defineSystem, Res, ResMut } from 'esengine';++defineSystem([Res(Score)], (score) => {+ // score 就是那个 ScoreState 实例+ if (score.value > 1000) { /* … */ }+});++defineSystem([ResMut(Score)], (score) => {+ // score 是句柄——要先解包+ score.modify((s) => s.add(100));+});+```++在 ECS 之外——宿主代码、`defineBehavior` 的钩子里——用+`app.getResource(Score)`,拿到的是同一个活实例。++### 默认值的代价++资源在第一次被读取时才真正生成,方式是克隆你传给 `defineResource` 的默认值。这次+克隆是**结构性的,不是全量的**:++| 默认值 | 每个 App 最终拿到什么 |+|---|---|+| 普通对象 / 数组 | 一份深克隆——每个 App 各自独立的一份。 |+| 类实例 | *同一个*对象,读到它的每个 App 共用。 |+| 函数字段 | 按引用共享——方法永远不会在克隆中丢失。 |++类实例按引用透传是有意为之:把它克隆成一个裸对象会剥掉原型,连带剥掉所有方法。实际+后果是 `defineResource(new ScoreState(), 'Score')` 会让**进程里所有 App 共用同一份+分数**——而编辑器同时跑着两个(编辑态与 Play 态)。只要资源持有状态,就优先用上面+`null!` + `insertResource` 那种写法。++<Aside type="caution">+ 如果你把方法挂在**普通对象**默认值上,请写成方法简写或 `function`,不要用箭头+ 函数——箭头函数捕获的是模块作用域,`this` 并不指向资源:++ ```typescript+ defineResource({ value: 0, add(n: number) { this.value += n; } }, 'Score'); // ✅+ defineResource({ value: 0, add: (n: number) => { this.value += n; } }, 'Score'); // ❌+ ```+</Aside>## 组件 vs 资源- **组件**是逐实体的数据。你(在编辑器里或用 `Commands`)把它挂到实体上,用 `Query`- 遍历它。-- **资源**是逐 App 的单例——共享状态与子系统 API——用 `Res` 读取。+ 遍历它。C++ 支撑的组件每次读取都要从 wasm 堆里解码出来,所以你拿到的是一份**拷贝**+ ——改完要交回去,否则这次写入会丢(见[脚本](/docs/zh-cn/scripting/overview/))。+- **资源**是逐 App 的单例——共享状态与子系统 API——用 `Res` 读取。资源是那个**活对象**,+ 从来不是拷贝:在它上面调方法或改字段立刻生效。## 获取实体diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/systems.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/systems.mdxindex 474bcff3e..537305e29 100644--- a/docs/astro/src/content/docs/zh-cn/core-concepts/systems.mdx+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/systems.mdx@@ -34,6 +34,7 @@ addSystem(defineSystem(`[entity, ...组件]`。- **`Mut(Component)`** —— 系统会写入的组件。未包裹的组件是只读的。- **`Res(Resource)`** / **`ResMut(Resource)`** —— 一个共享资源,只读或可写(例如提供帧计时的 `Time`)。+ `Res` 给你资源本身;`ResMut` 给你包在它外面的句柄——`.get()` / `.set(v)` / `.modify(fn)`。- **`Commands()`** —— 延迟的结构性改动(生成 / 销毁 / 增删组件),在下次 flush 时应用。- **`EventReader(E)`** / **`EventWriter(E)`** —— 读取或发送一条类型化事件流。