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
feat(app): Plugin.activeWhen — a plugin whose components no entity has costs nothing per frame
yhh483bfe65224b
diff --git a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdxindex 194125266..0c568d7b7 100644--- a/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx+++ b/docs/astro/src/content/docs/core-concepts/app-lifecycle.mdx@@ -162,6 +162,7 @@ subsystem publishes its API. See| `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`. |+| `activeWhen` | `ComponentDef[]?` | The components the plugin's work is about. While no entity has any of them, the systems registered in its `build()` are skipped, so a game that never places water pays nothing for the water plugin each frame. They still run for one frame after the last one goes, so the plugin can release what it held. Absent: always run. The engine's water, terrain and planet plugins declare it. || `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. |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 8882eccd4..abd0eb839 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@@ -146,6 +146,7 @@ export const scorePlugin: Plugin = {| `dependencies` | `PluginDependency[]?` | 前置条件,每项是插件**名**(`string`)或**资源定义**。缺失时 `addPlugin` 抛错;`addPlugins` 还会用名字边为整批排序。 || `before` / `after` | `string[]?` | 相对其他插件名的软排序提示,在 `addPlugins` 批量安装时生效。 || `build(app)` | 必需 | 注册系统、资源与事件。`addPlugin` 时立即执行。 |+| `activeWhen` | `ComponentDef[]?` | 插件工作所针对的组件。当没有任何实体拥有其中之一时,它在 `build()` 里注册的系统会被跳过——从不放水体的游戏,每帧不为水体插件付出任何开销。最后一个组件消失后仍会再运行一帧,让插件释放持有的资源。不写则始终运行。引擎的 water、terrain、planet 插件已声明。 || `finish(app)` | 可选 | 在**所有**插件 build 完、应用首次 tick/run 时执行一次——用于需要完整集合的接线。 || `cleanup(app?)` | 可选 | `app.quit()` 时按安装逆序执行。 |diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex b4d65f01b..8994acc9e 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -45,7 +45,7 @@ import { SceneManager } from '../scene/sceneManager';import { sceneManagerPlugin } from '../scene/scenePlugin';import { getDefaultContext } from '../ecs/context';import { setLinearColorSpace } from '../ecs/env';-import { seedEngineComponents } from '../ecs/component';+import { seedEngineComponents, type AnyComponentDef } from '../ecs/component';import { cameraPlugin } from '../camera/CameraPlugin';import { ScreenScaling, SCREEN_FIT_OFF, type ScreenScalingData } from '../camera/ScreenScaling';import { RenderResolution } from '../camera/presentPlan';@@ -85,6 +85,13 @@ export interface Plugin {/** Cost domain the profiler files this plugin's systems under. Defaults to* `name`; declare it where the two differ, as `camera` producing `render`. */profileDomain?: string;+ /**+ * The components this plugin's work is about: while no entity has any of them,+ * its systems are not run — a game that never places water pays nothing for the+ * water plugin each frame. They keep running for one frame after the last one+ * goes, so a plugin can release what it held. Absent: always run.+ */+ activeWhen?: readonly AnyComponentDef[];build(app: App): void;finish?(app: App): void;/** Releases acquired resources on quit or a failed build; must tolerate a@@ -112,8 +119,19 @@ interface InflightSystem {done: Promise<void>;}+/** One plugin's {@link Plugin.activeWhen}, decided once a frame for all its systems. */+interface ActivityGate {+ readonly components: readonly AnyComponentDef[];+ frame: number;+ open: boolean;+ /** Whether any of them existed when last decided: the frame after the last goes still runs. */+ present: boolean;+}+interface SystemEntry {startupInvoked?: boolean;+ /** Skipped while the owning plugin's components are absent (see Plugin.activeWhen). */+ gate?: ActivityGate;system: SystemDef;runBefore?: string[];runAfter?: string[];@@ -209,6 +227,7 @@ export class App {private buildingPlugin_: string | null = null;/** The cost domain of that plugin, which is its name unless it declared one. */private buildingDomain_: string | null = null;+ private buildingGate_: ActivityGate | null = null;/** Registration undo actions for the current build; nested builds own theirs. */private buildRollback_: Array<() => void> | null = null;private addingBundleSystems_ = false;@@ -319,12 +338,15 @@ export class App {}const prevBuilding = this.buildingPlugin_;const prevDomain = this.buildingDomain_;+ const prevGate = this.buildingGate_;const prevRollback = this.buildRollback_;const rollback: Array<() => void> = [];const buildEpoch = this.quitEpoch_;this.buildRollback_ = rollback;this.buildingPlugin_ = plugin.name ?? null;this.buildingDomain_ = plugin.profileDomain ?? plugin.name ?? null;+ this.buildingGate_ = plugin.activeWhen?.length+ ? { components: plugin.activeWhen, frame: -1, open: true, present: true } : null;try {plugin.build(this);// Sync plugin: live once build() returns → promote. An async plugin@@ -343,6 +365,7 @@ export class App {} finally {this.buildingPlugin_ = prevBuilding;this.buildingDomain_ = prevDomain;+ this.buildingGate_ = prevGate;this.buildRollback_ = prevRollback;}return this;@@ -393,6 +416,22 @@ export class App {* read properties of undefined (reading 'push')" thrown from inside a* minified bundle, naming neither the system nor the value.*/+ /** Whether a plugin's systems run this frame: some entity has one of its components, or had last frame. */+ private gateOpen_(gate: ActivityGate): boolean {+ const frame = this.hasResource(Time) ? this.getResource(Time).frameCount : 0;+ if (gate.frame === frame) return gate.open;+ const world = this.world;+ let present = false;+ for (const c of gate.components) {+ // A cached query: unchanged structure answers without walking anything.+ if (world.queryEntities([c]).length > 0) { present = true; break; }+ }+ gate.open = present || gate.present;+ gate.present = present;+ gate.frame = frame;+ return gate.open;+ }+private registeringDomain_(): string {if (this.buildingDomain_) return this.buildingDomain_;return this.addingBundleSystems_ ? DOMAIN_SCRIPTS : DOMAIN_UNATTRIBUTED;@@ -432,6 +471,7 @@ export class App {subsystem: this.buildingPlugin_ ?? undefined,fromBundle: this.addingBundleSystems_ || undefined,domain: options?.profileDomain ?? this.registeringDomain_(),+ ...(this.buildingGate_ ? { gate: this.buildingGate_ } : {}),});this.sortedSystemsCache_.delete(schedule);this.dependencyCache_.delete(schedule);@@ -1851,6 +1891,7 @@ export class App {if (this.frame_paused_ || this.isExecutionHeld() || executionEpoch !== this.executionEpoch_) break;if (schedule === Schedule.Startup && entry.startupInvoked) continue;if (entry.runIf && !entry.runIf()) { if (schedule === Schedule.Startup) entry.startupInvoked = true; continue; }+ if (entry.gate && schedule !== Schedule.Startup && !this.gateOpen_(entry.gate)) continue;// Where the declarations are spent rather than reported: a system// starts beside an unfinished one only when it neither depends on itdiff --git a/sdk/src/terrain/planetPlugin.ts b/sdk/src/terrain/planetPlugin.tsindex 2af07590b..623e60ef1 100644--- a/sdk/src/terrain/planetPlugin.ts+++ b/sdk/src/terrain/planetPlugin.ts@@ -176,6 +176,8 @@ export class Planets {export class PlanetPlugin implements Plugin {name = 'planet';+ /** No planet, no work; the frame after the last one goes still lets it go. */+ readonly activeWhen = [Planet];private stock_ = 0;private planets_: Planets | null = null;diff --git a/sdk/src/terrain/terrainPlugin.ts b/sdk/src/terrain/terrainPlugin.tsindex b8650f439..f22b26269 100644--- a/sdk/src/terrain/terrainPlugin.ts+++ b/sdk/src/terrain/terrainPlugin.ts@@ -559,6 +559,8 @@ async function windowOf(provider: TerrainProvider, data: TerrainData, cx: numberexport class TerrainPlugin implements Plugin {name = 'terrain';+ /** No terrain, no work; the frame after the last one goes still runs its sweep. */+ readonly activeWhen = [Terrain];/** The stock materials a terrain with none of its own is an instance of: without layers, and with. */private stock_ = 0;diff --git a/sdk/src/water/waterPlugin.ts b/sdk/src/water/waterPlugin.tsindex 89e1f1684..2cde1f384 100644--- a/sdk/src/water/waterPlugin.ts+++ b/sdk/src/water/waterPlugin.ts@@ -379,6 +379,8 @@ interface Surface {export class WaterPlugin implements Plugin {name = 'water';+ /** Nothing to bake, carve or draw without a body or a zone; the frame after the last one goes still runs, and lets go. */+ readonly activeWhen = [WaterBody, WaterZone];/** The stock material the surface is an instance of when the zone names none, made once from the Water shader. */private stock_ = 0;diff --git a/sdk/tests/plugin-active-when.test.ts b/sdk/tests/plugin-active-when.test.tsnew file mode 100644index 000000000..af0c8336e--- /dev/null+++ b/sdk/tests/plugin-active-when.test.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * A plugin's systems run only while some entity has one of the components its work+ * is about (Plugin.activeWhen), and for one frame after the last one goes, so it can+ * let go of what it held. A game without water pays nothing for the water plugin.+ */+import { describe, it, expect } from 'vitest';+import { App, type Plugin } from '../src/app/app';+import { defineSystem, Schedule } from '../src/ecs/system';+import { defineComponent } from '../src/ecs/component';++describe('Plugin.activeWhen', () => {+ it('skips the plugin while its components are absent, and runs one frame past the last', async () => {+ const Pond = defineComponent('ActiveWhenPond', { depth: 1 });+ let runs = 0;+ const plugin: Plugin = {+ name: 'pond',+ activeWhen: [Pond],+ build(app) { app.addSystemToSchedule(Schedule.Update, defineSystem([], () => { runs++; }, { name: 'PondSystem' })); },+ };+ const app = App.new();+ app.addPlugin(plugin);+ await app.tick(1 / 60); // the first frame is the one-past of "present" until decided otherwise+ runs = 0;+ await app.tick(1 / 60);+ await app.tick(1 / 60);+ expect(runs).toBe(0);++ const e = app.world.spawn();+ app.world.insert(e, Pond, { depth: 2 });+ await app.tick(1 / 60);+ await app.tick(1 / 60);+ expect(runs).toBe(2);++ app.world.despawn(e);+ await app.tick(1 / 60); // the frame after: still runs, to release+ expect(runs).toBe(3);+ await app.tick(1 / 60);+ await app.tick(1 / 60);+ expect(runs).toBe(3);+ });++ it('leaves a plugin without activeWhen running every frame', async () => {+ let runs = 0;+ const app = App.new();+ app.addPlugin({ name: 'always', build(a) { a.addSystemToSchedule(Schedule.Update, defineSystem([], () => { runs++; }, { name: 'Always' })); } });+ await app.tick(1 / 60);+ await app.tick(1 / 60);+ expect(runs).toBe(2);+ });+});