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(ecs): the gameplay systems tell the schedule what they touch
esenginec1c2768eeb30
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ebd95e61b..c858c1b2c 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -170,6 +170,7 @@ params: Readonly<Record<string, AiParamValue>> | undefinedparams: readonly AiParamDef[] | undefinedrun: AiAction<Ctx>separator: string | undefined+touches: AiTouchesSource | undefined```## AiBt — const @experimental@@ -225,8 +226,10 @@ Readonly<Record<string, AiParamValue>>## AiRegistry — class @experimental```actionNames: () => string[]+actionTouches: (name: string, input?: AiActionInput) => AiTouches | undefinedclear: () => voidconditionNames: () => string[]+conditionTouches: (name: string) => AiTouches | undefinedgetAction: (name: string) => AiAction<Ctx> | undefinedgetActionParams: (name: string) => readonly AiParamDef[]getActionSeparator: (name: string) => string@@ -234,7 +237,7 @@ getCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => booleanregisterAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => void-registerCondition: (name: string, fn: AiCondition<Ctx>) => void+registerCondition: (name: string, fn: AiCondition<Ctx> | AiConditionSpec<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```@@ -1117,6 +1120,7 @@ metadata: ComponentMetadata | undefinedschedule: Schedule | undefinedstart: ((ctx: BehaviorContext<S>) => void) | undefinedstate: S | undefined+touches: SystemTouches | undefinedupdate: ((ctx: BehaviorContext<S>, dt: number) => void) | undefined```@@ -7025,7 +7029,7 @@ query: QueryCost | undefined@internal _params: readonly SystemParam[]@internal _runAfter: readonly string[] | undefined@internal _runBefore: readonly string[] | undefined-@internal _touches: SystemTouches | undefined+@internal _touches: SystemTouches | (() => SystemTouches) | undefined```## SystemOptions — interface @public@@ -7033,7 +7037,7 @@ query: QueryCost | undefinedname: string | undefinedrunAfter: string[] | undefinedrunBefore: string[] | undefined-touches: SystemTouches | undefined+touches: SystemTouches | (() => SystemTouches) | undefined```## SystemParam — type @public@@ -7081,6 +7085,7 @@ systems: SystemDef[]## SystemTouches — interface @public```+opaque: boolean | undefinedreads: readonly string[] | undefinedwrites: readonly string[] | undefined```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex f92f3ec63..d760b8a38 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -170,6 +170,7 @@ params: Readonly<Record<string, AiParamValue>> | undefinedparams: readonly AiParamDef[] | undefinedrun: AiAction<Ctx>separator: string | undefined+touches: AiTouchesSource | undefined```## AiBt — const @experimental@@ -225,8 +226,10 @@ Readonly<Record<string, AiParamValue>>## AiRegistry — class @experimental```actionNames: () => string[]+actionTouches: (name: string, input?: AiActionInput) => AiTouches | undefinedclear: () => voidconditionNames: () => string[]+conditionTouches: (name: string) => AiTouches | undefinedgetAction: (name: string) => AiAction<Ctx> | undefinedgetActionParams: (name: string) => readonly AiParamDef[]getActionSeparator: (name: string) => string@@ -234,7 +237,7 @@ getCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => booleanregisterAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => void-registerCondition: (name: string, fn: AiCondition<Ctx>) => void+registerCondition: (name: string, fn: AiCondition<Ctx> | AiConditionSpec<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```@@ -1117,6 +1120,7 @@ metadata: ComponentMetadata | undefinedschedule: Schedule | undefinedstart: ((ctx: BehaviorContext<S>) => void) | undefinedstate: S | undefined+touches: SystemTouches | undefinedupdate: ((ctx: BehaviorContext<S>, dt: number) => void) | undefined```@@ -7218,7 +7222,7 @@ query: QueryCost | undefined@internal _params: readonly SystemParam[]@internal _runAfter: readonly string[] | undefined@internal _runBefore: readonly string[] | undefined-@internal _touches: SystemTouches | undefined+@internal _touches: SystemTouches | (() => SystemTouches) | undefined```## SystemOptions — interface @public@@ -7226,7 +7230,7 @@ query: QueryCost | undefinedname: string | undefinedrunAfter: string[] | undefinedrunBefore: string[] | undefined-touches: SystemTouches | undefined+touches: SystemTouches | (() => SystemTouches) | undefined```## SystemParam — type @public@@ -7274,6 +7278,7 @@ systems: SystemDef[]## SystemTouches — interface @public```+opaque: boolean | undefinedreads: readonly string[] | undefinedwrites: readonly string[] | undefined```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 7bfe8b9ed..6a423fb93 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -165,6 +165,7 @@ params: Readonly<Record<string, AiParamValue>> | undefinedparams: readonly AiParamDef[] | undefinedrun: AiAction<Ctx>separator: string | undefined+touches: AiTouchesSource | undefined```## AiBt — const @experimental@@ -220,8 +221,10 @@ Readonly<Record<string, AiParamValue>>## AiRegistry — class @experimental```actionNames: () => string[]+actionTouches: (name: string, input?: AiActionInput) => AiTouches | undefinedclear: () => voidconditionNames: () => string[]+conditionTouches: (name: string) => AiTouches | undefinedgetAction: (name: string) => AiAction<Ctx> | undefinedgetActionParams: (name: string) => readonly AiParamDef[]getActionSeparator: (name: string) => string@@ -229,7 +232,7 @@ getCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => booleanregisterAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => void-registerCondition: (name: string, fn: AiCondition<Ctx>) => void+registerCondition: (name: string, fn: AiCondition<Ctx> | AiConditionSpec<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```@@ -1112,6 +1115,7 @@ metadata: ComponentMetadata | undefinedschedule: Schedule | undefinedstart: ((ctx: BehaviorContext<S>) => void) | undefinedstate: S | undefined+touches: SystemTouches | undefinedupdate: ((ctx: BehaviorContext<S>, dt: number) => void) | undefined```@@ -7020,7 +7024,7 @@ query: QueryCost | undefined@internal _params: readonly SystemParam[]@internal _runAfter: readonly string[] | undefined@internal _runBefore: readonly string[] | undefined-@internal _touches: SystemTouches | undefined+@internal _touches: SystemTouches | (() => SystemTouches) | undefined```## SystemOptions — interface @public@@ -7028,7 +7032,7 @@ query: QueryCost | undefinedname: string | undefinedrunAfter: string[] | undefinedrunBefore: string[] | undefined-touches: SystemTouches | undefined+touches: SystemTouches | (() => SystemTouches) | undefined```## SystemParam — type @public@@ -7076,6 +7080,7 @@ systems: SystemDef[]## SystemTouches — interface @public```+opaque: boolean | undefinedreads: readonly string[] | undefinedwrites: readonly string[] | undefined```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 3e7182749..93acf379b 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -165,6 +165,7 @@ params: Readonly<Record<string, AiParamValue>> | undefinedparams: readonly AiParamDef[] | undefinedrun: AiAction<Ctx>separator: string | undefined+touches: AiTouchesSource | undefined```## AiBt — const @experimental@@ -220,8 +221,10 @@ Readonly<Record<string, AiParamValue>>## AiRegistry — class @experimental```actionNames: () => string[]+actionTouches: (name: string, input?: AiActionInput) => AiTouches | undefinedclear: () => voidconditionNames: () => string[]+conditionTouches: (name: string) => AiTouches | undefinedgetAction: (name: string) => AiAction<Ctx> | undefinedgetActionParams: (name: string) => readonly AiParamDef[]getActionSeparator: (name: string) => string@@ -229,7 +232,7 @@ getCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => booleanregisterAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => void-registerCondition: (name: string, fn: AiCondition<Ctx>) => void+registerCondition: (name: string, fn: AiCondition<Ctx> | AiConditionSpec<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```@@ -1112,6 +1115,7 @@ metadata: ComponentMetadata | undefinedschedule: Schedule | undefinedstart: ((ctx: BehaviorContext<S>) => void) | undefinedstate: S | undefined+touches: SystemTouches | undefinedupdate: ((ctx: BehaviorContext<S>, dt: number) => void) | undefined```@@ -7265,7 +7269,7 @@ query: QueryCost | undefined@internal _params: readonly SystemParam[]@internal _runAfter: readonly string[] | undefined@internal _runBefore: readonly string[] | undefined-@internal _touches: SystemTouches | undefined+@internal _touches: SystemTouches | (() => SystemTouches) | undefined```## SystemOptions — interface @public@@ -7273,7 +7277,7 @@ query: QueryCost | undefinedname: string | undefinedrunAfter: string[] | undefinedrunBefore: string[] | undefined-touches: SystemTouches | undefined+touches: SystemTouches | (() => SystemTouches) | undefined```## SystemParam — type @public@@ -7321,6 +7325,7 @@ systems: SystemDef[]## SystemTouches — interface @public```+opaque: boolean | undefinedreads: readonly string[] | undefinedwrites: readonly string[] | undefined```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 668faf492..1774d1139 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -165,6 +165,7 @@ params: Readonly<Record<string, AiParamValue>> | undefinedparams: readonly AiParamDef[] | undefinedrun: AiAction<Ctx>separator: string | undefined+touches: AiTouchesSource | undefined```## AiBt — const @experimental@@ -220,8 +221,10 @@ Readonly<Record<string, AiParamValue>>## AiRegistry — class @experimental```actionNames: () => string[]+actionTouches: (name: string, input?: AiActionInput) => AiTouches | undefinedclear: () => voidconditionNames: () => string[]+conditionTouches: (name: string) => AiTouches | undefinedgetAction: (name: string) => AiAction<Ctx> | undefinedgetActionParams: (name: string) => readonly AiParamDef[]getActionSeparator: (name: string) => string@@ -229,7 +232,7 @@ getCondition: (name: string) => AiCondition<Ctx> | undefinedhasAction: (name: string) => booleanhasCondition: (name: string) => booleanregisterAction: (name: string, fn: AiAction<Ctx> | AiActionSpec<Ctx>) => void-registerCondition: (name: string, fn: AiCondition<Ctx>) => void+registerCondition: (name: string, fn: AiCondition<Ctx> | AiConditionSpec<Ctx>) => voidstatic new <Ctx = unknown>(): AiRegistry<Ctx>static prototype: AiRegistry<any>```@@ -1112,6 +1115,7 @@ metadata: ComponentMetadata | undefinedschedule: Schedule | undefinedstart: ((ctx: BehaviorContext<S>) => void) | undefinedstate: S | undefined+touches: SystemTouches | undefinedupdate: ((ctx: BehaviorContext<S>, dt: number) => void) | undefined```@@ -7027,7 +7031,7 @@ query: QueryCost | undefined@internal _params: readonly SystemParam[]@internal _runAfter: readonly string[] | undefined@internal _runBefore: readonly string[] | undefined-@internal _touches: SystemTouches | undefined+@internal _touches: SystemTouches | (() => SystemTouches) | undefined```## SystemOptions — interface @public@@ -7035,7 +7039,7 @@ query: QueryCost | undefinedname: string | undefinedrunAfter: string[] | undefinedrunBefore: string[] | undefined-touches: SystemTouches | undefined+touches: SystemTouches | (() => SystemTouches) | undefined```## SystemParam — type @public@@ -7083,6 +7087,7 @@ systems: SystemDef[]## SystemTouches — interface @public```+opaque: boolean | undefinedreads: readonly string[] | undefinedwrites: readonly string[] | undefined```diff --git a/sdk/src/ai/bt/BehaviorTreeAgent.ts b/sdk/src/ai/bt/BehaviorTreeAgent.tsindex 5332b5aac..15c265927 100644--- a/sdk/src/ai/bt/BehaviorTreeAgent.ts+++ b/sdk/src/ai/bt/BehaviorTreeAgent.ts@@ -51,6 +51,12 @@ export function getBt(key: string): BtDefinition | undefined {return btStore.get(key);}+/** Every registered tree. What the schedule reads to learn what the BT system+ * reaches for — that answer lives in the loaded trees, not in the system. */+export function allBts(): Iterable<BtDefinition> {+ return btStore.values();+}+/** Drop all registered trees (tests / hot-reload). */export function clearBtStore(): void {btStore.clear();diff --git a/sdk/src/ai/bt/BtPlugin.ts b/sdk/src/ai/bt/BtPlugin.tsindex c3e078ef3..86499a342 100644--- a/sdk/src/ai/bt/BtPlugin.ts+++ b/sdk/src/ai/bt/BtPlugin.ts@@ -14,7 +14,7 @@import type { App, Plugin } from '../../app/app';import type { Entity } from '../../types';import type { World } from '../../ecs/world';-import { defineSystem, Schedule, GetWorld } from '../../ecs/system';+import { defineSystem, Schedule, GetWorld, type SystemTouches } from '../../ecs/system';import { Res, Time, type TimeData } from '../../ecs/resource';import { defineResource } from '../../ecs/resource';import { Commands, type CommandsInstance } from '../../ecs/commands';@@ -25,7 +25,9 @@ import { resolveAssetKey } from '../../asset/resolveAssetKey';import { Blackboard } from '../fsm/Blackboard';import { aiRegistry, type AiContext } from '../fsm/AiContext';import { tickBt, createBtRunState, type BtRunState } from './BtRunner';-import { BehaviorTreeAgent, getBt } from './BehaviorTreeAgent';+import { BehaviorTreeAgent, getBt, allBts } from './BehaviorTreeAgent';+import type { BtNode } from './types';+import { TouchesBuilder, touchesOfLeaves, type LeafRef } from '../worldView';import { ensureBuiltinAiRegistrations } from '../builtins';interface BtAgentState {@@ -122,6 +124,22 @@ export class BehaviorTrees {}}+/** Every leaf in a tree, root first. Orphans are not walked — the interpreter+ * ticks only `root`, so an unwired subtree reaches nothing. */+export function* btLeaves(node: BtNode): Iterable<LeafRef> {+ if (node.name && (node.type === 'action' || node.type === 'condition')) {+ yield { kind: node.type, name: node.name, input: { arg: node.arg, params: node.params } };+ }+ for (const child of node.children ?? []) yield* btLeaves(child);+}++/** What the BT system reaches for: the union over every loaded tree. */+export function btTouches(): SystemTouches {+ const builder = new TouchesBuilder().writing(BehaviorTreeAgent._name);+ for (const tree of allBts()) touchesOfLeaves(aiRegistry, btLeaves(tree.root), builder);+ return builder.build();+}+export const AiBt = defineResource<BehaviorTrees>(null!, 'AiBt');export class BtPlugin implements Plugin {@@ -138,14 +156,14 @@ export class BtPlugin implements Plugin {app.addSystemToSchedule(Schedule.Update,- // system-access: steps a project's behaviour tree, whose nodes read and- // write whatever that project's tree names.defineSystem([Res(Time), Commands(), GetWorld()],(time: TimeData, commands: CommandsInstance, world) => {stepBehaviorTrees(world as AiWorldView, commands, time.delta, states, resolveKey);},- { name: 'BehaviorTreeSystem' },+ // See fsmTouches: the reach is the union over the loaded trees,+ // which is why it is asked for rather than stated.+ { name: 'BehaviorTreeSystem', touches: btTouches },),{ runIf: playModeOnly },);diff --git a/sdk/src/ai/builtins.ts b/sdk/src/ai/builtins.tsindex 8897ffe06..57e170145 100644--- a/sdk/src/ai/builtins.ts+++ b/sdk/src/ai/builtins.ts@@ -14,11 +14,14 @@*/import { aiRegistry, type AiContext } from './fsm/AiContext';-import type { AiAction, AiCondition, AiParamValue } from './fsm/registry';+import type { AiAction, AiActionInput, AiCondition, AiParamValue, AiTouches } from './fsm/registry';import { TimelinePlayer } from '../timeline/TimelinePlugin';import { SpriteAnimator } from '../animation/SpriteAnimator';import { setEntityProperty } from '../ecs/propertyPath';+const TIMELINE: AiTouches = { reads: [TimelinePlayer._name], writes: [TimelinePlayer._name] };+const SPRITE_ANIM: AiTouches = { reads: [SpriteAnimator._name], writes: [SpriteAnimator._name] };+/*** Register the engine's built-in actions/conditions. Idempotent (and safe after* an `aiRegistry.clear()`): each name registers only if absent.@@ -32,7 +35,7 @@ export function ensureBuiltinAiRegistrations(): void {// TimelinePlayer flag contract (see TimelineDrive.applyPlayerFlags).player.playing = true;ctx.set(TimelinePlayer, player);- });+ }, TIMELINE);action('timeline.pause', ctx => {if (!ctx.has(TimelinePlayer)) return;@@ -40,7 +43,7 @@ export function ensureBuiltinAiRegistrations(): void {if (!player.playing) return;player.playing = false;ctx.set(TimelinePlayer, player);- });+ }, TIMELINE);// Latched only when a Once clip completes — false before and while playing,// so `onEnter: timeline.play` + a `timeline.finished` transition is a@@ -51,7 +54,7 @@ export function ensureBuiltinAiRegistrations(): void {if (!ctx.has(TimelinePlayer)) return false;const player = ctx.get(TimelinePlayer);return player.finished && !player.playing;- });+ }, { reads: [TimelinePlayer._name] });// `arg` is the clip to play (a `.esanim` ref/path); without it the action// resumes/replays the animator's current clip. Same-clip play while already@@ -71,7 +74,7 @@ export function ensureBuiltinAiRegistrations(): void {// the SpriteAnimator flag contract (mirrors TimelinePlayer's).sp.playing = true;ctx.set(SpriteAnimator, sp);- });+ }, SPRITE_ANIM);// Unconditional rewind + play (re-trigger a one-shot mid-flight), with the// same optional clip arg.@@ -84,7 +87,7 @@ export function ensureBuiltinAiRegistrations(): void {sp.finished = false;sp.playing = true;ctx.set(SpriteAnimator, sp);- });+ }, SPRITE_ANIM);action('spriteAnim.stop', ctx => {if (!ctx.has(SpriteAnimator)) return;@@ -92,7 +95,7 @@ export function ensureBuiltinAiRegistrations(): void {if (!sp.playing) return;sp.playing = false;ctx.set(SpriteAnimator, sp);- });+ }, SPRITE_ANIM);// Latched only when a one-shot clip completes (same shape as// timeline.finished): false before and while playing, so@@ -102,7 +105,7 @@ export function ensureBuiltinAiRegistrations(): void {if (!ctx.has(SpriteAnimator)) return false;const sp = ctx.get(SpriteAnimator);return sp.finished && !sp.playing;- });+ }, { reads: [SpriteAnimator._name] });// The general-purpose write, through the engine's reflection writer — the// same addressing a UIGear binding and a Timeline track use ("Component" +@@ -124,10 +127,26 @@ export function ensureBuiltinAiRegistrations(): void {if (!path || raw === undefined) return;setEntityProperty(ctx.world, ctx.entity, path, parseValue(raw));},+ // The component it writes is the first segment of the authored path,+ // so the reach is unknowable when this registers and plain in the+ // graph. A reference with no readable path admits it instead.+ touches: input => {+ const path = pathOf(input);+ const component = path.split('.')[0];+ return component ? { writes: [component] } : { opaque: true };+ },});}}+/** `property.set`'s target path, from whichever form the reference carries: the+ * named parameter, or the canonical `path=value` string. */+function pathOf(input: AiActionInput): string {+ const named = input.params?.path;+ if (typeof named === 'string') return named.trim();+ return (input.arg ?? '').split('=')[0].trim();+}+/** A parameter's JSON reading when it has one; otherwise the value itself. */function parseValue(raw: AiParamValue): unknown {if (typeof raw !== 'string') return raw;@@ -138,10 +157,10 @@ function parseValue(raw: AiParamValue): unknown {}}-function action(name: string, fn: AiAction<AiContext>): void {- if (!aiRegistry.hasAction(name)) aiRegistry.registerAction(name, fn);+function action(name: string, fn: AiAction<AiContext>, touches?: AiTouches): void {+ if (!aiRegistry.hasAction(name)) aiRegistry.registerAction(name, { run: fn, touches });}-function condition(name: string, fn: AiCondition<AiContext>): void {- if (!aiRegistry.hasCondition(name)) aiRegistry.registerCondition(name, fn);+function condition(name: string, fn: AiCondition<AiContext>, touches?: AiTouches): void {+ if (!aiRegistry.hasCondition(name)) aiRegistry.registerCondition(name, { check: fn, touches });}diff --git a/sdk/src/ai/fsm/FsmPlugin.ts b/sdk/src/ai/fsm/FsmPlugin.tsindex 77bcf5fb9..ee5c997c5 100644--- a/sdk/src/ai/fsm/FsmPlugin.ts+++ b/sdk/src/ai/fsm/FsmPlugin.ts@@ -14,7 +14,7 @@import type { App, Plugin } from '../../app/app';import type { Entity } from '../../types';import type { World } from '../../ecs/world';-import { defineSystem, Schedule, GetWorld } from '../../ecs/system';+import { defineSystem, Schedule, GetWorld, type SystemTouches } from '../../ecs/system';import { Res, Time, type TimeData } from '../../ecs/resource';import { defineResource } from '../../ecs/resource';import { Commands, type CommandsInstance } from '../../ecs/commands';@@ -23,9 +23,11 @@ import type { AnyComponentDef, ComponentData } from '../../ecs/component';import { Assets } from '../../asset/AssetPlugin';import { resolveAssetKey } from '../../asset/resolveAssetKey';import { Blackboard } from './Blackboard';-import { createFsmRunState, stepFsm, type FsmRunState } from './FsmRunner';+import { createFsmRunState, stepFsm, type CompiledFsm, type FsmRunState } from './FsmRunner';import { aiRegistry, type AiContext } from './AiContext';-import { StateMachineAgent, getFsm } from './StateMachineAgent';+import { StateMachineAgent, getFsm, allFsms } from './StateMachineAgent';+import { actionRefName, actionRefArg, actionRefParams } from './types';+import { TouchesBuilder, touchesOfLeaves, type LeafRef } from '../worldView';import { ensureBuiltinAiRegistrations } from '../builtins';/** Per-entity FSM runtime: blackboard persists; run rebuilds when the FSM key changes. */@@ -110,6 +112,32 @@ export function stepStateMachines(}}+/** Every leaf a compiled FSM names: the three state hooks and the transition+ * conditions. Blackboard guards reach no component, so they are not leaves. */+export function* fsmLeaves(fsm: CompiledFsm): Iterable<LeafRef> {+ for (const state of fsm.states.values()) {+ for (const hook of [state.onEnter, state.onUpdate, state.onExit]) {+ const name = actionRefName(hook);+ if (!name) continue;+ yield {+ kind: 'action',+ name,+ input: { arg: actionRefArg(hook), params: actionRefParams(hook) },+ };+ }+ for (const t of state.transitions ?? []) {+ if (t.condition) yield { kind: 'condition', name: t.condition };+ }+ }+}++/** What the FSM system reaches for: the union over every loaded graph. */+export function fsmTouches(): SystemTouches {+ const builder = new TouchesBuilder().writing(StateMachineAgent._name);+ for (const fsm of allFsms()) touchesOfLeaves(aiRegistry, fsmLeaves(fsm), builder);+ return builder.build();+}+/** Resource for game code to reach an agent's blackboard / current state. */export class StateMachines {constructor(private states: Map<Entity, AgentState>) {}@@ -145,14 +173,15 @@ export class FsmPlugin implements Plugin {app.addSystemToSchedule(Schedule.Update,- // system-access: steps a project's state machine, whose states read and- // write whatever that project's graph names.defineSystem([Res(Time), Commands(), GetWorld()],(time: TimeData, commands: CommandsInstance, world) => {stepStateMachines(world as FsmWorldView, commands, time.delta, states, resolveKey);},- { name: 'StateMachineSystem' },+ // Asked per analysis, not once: a graph loaded later changes the+ // answer, and no graph at all means this system touches only the+ // agent component.+ { name: 'StateMachineSystem', touches: fsmTouches },),{ runIf: playModeOnly },);diff --git a/sdk/src/ai/fsm/StateMachineAgent.ts b/sdk/src/ai/fsm/StateMachineAgent.tsindex ebc3f7a69..2922ec99a 100644--- a/sdk/src/ai/fsm/StateMachineAgent.ts+++ b/sdk/src/ai/fsm/StateMachineAgent.ts@@ -55,6 +55,12 @@ export function getFsm(key: string): CompiledFsm | undefined {return fsmStore.get(key);}+/** Every registered FSM. What the schedule reads to learn what the FSM system+ * reaches for — that answer lives in the loaded graphs, not in the system. */+export function allFsms(): Iterable<CompiledFsm> {+ return fsmStore.values();+}+/** Drop all registered FSMs (tests / hot-reload). */export function clearFsmStore(): void {fsmStore.clear();diff --git a/sdk/src/ai/fsm/registry.ts b/sdk/src/ai/fsm/registry.tsindex 33c086f3c..7939d3f90 100644--- a/sdk/src/ai/fsm/registry.ts+++ b/sdk/src/ai/fsm/registry.ts@@ -67,11 +67,32 @@ export interface AiParamDef {step?: number;}+/**+ * What a leaf reaches for on the world, by component name.+ *+ * The system running a graph is only as knowable as its leaves. `opaque` is a+ * leaf admitting it cannot say — different from one that never declared.+ */+export interface AiTouches {+ reads?: readonly string[];+ writes?: readonly string[];+ opaque?: boolean;+}++/**+ * A leaf's reach, either fixed or derived from the input the authored data+ * carries — `property.set` writes the component its `path` names, which is+ * unknowable at registration and plain in the data.+ */+export type AiTouchesSource = AiTouches | ((input: AiActionInput) => AiTouches);+/** An action registered with metadata rather than as a bare function. */export interface AiActionSpec<Ctx> {run: AiAction<Ctx>;/** Declared parameters, in canonical string order. */params?: readonly AiParamDef[];+ /** What it reaches for. Undeclared means unknown, not nothing. */+ touches?: AiTouchesSource;/*** Separator joining the parameters in the canonical string form. Default* `':'` — the convention authored data already uses (`"tabs:settings"`).@@ -85,11 +106,24 @@ interface ActionEntry<Ctx> {fn: AiAction<Ctx>;params: readonly AiParamDef[];separator: string;+ touches?: AiTouchesSource;+}++/** A condition registered with metadata rather than as a bare predicate. */+export interface AiConditionSpec<Ctx> {+ check: AiCondition<Ctx>;+ /** What it reads. Undeclared means unknown, not nothing. */+ touches?: AiTouches;+}++interface ConditionEntry<Ctx> {+ fn: AiCondition<Ctx>;+ touches?: AiTouches;}export class AiRegistry<Ctx = unknown> {private actions = new Map<string, ActionEntry<Ctx>>();- private conditions = new Map<string, AiCondition<Ctx>>();+ private conditions = new Map<string, ConditionEntry<Ctx>>();/*** Register `name`, either as a bare function (input is the raw `arg` string,@@ -113,17 +147,34 @@ export class AiRegistry<Ctx = unknown> {: parseActionArg(arg, params, separator);return run(ctx, bb, arg ?? formatActionArg(named, params, separator), named);};- this.actions.set(name, { fn: wrapped, params, separator });+ this.actions.set(name, { fn: wrapped, params, separator, touches: spec.touches });}- registerCondition(name: string, fn: AiCondition<Ctx>): void {- this.conditions.set(name, fn);+ registerCondition(name: string, fn: AiCondition<Ctx> | AiConditionSpec<Ctx>): void {+ const spec = typeof fn === 'function' ? { check: fn } : fn;+ this.conditions.set(name, { fn: spec.check, touches: spec.touches });}getAction(name: string): AiAction<Ctx> | undefined {return this.actions.get(name)?.fn;}+ /**+ * What running `name` reaches for, given the input an authored reference+ * carries. `undefined` for an unregistered name or one that never declared —+ * the caller has to decide what an unknown leaf means, and treating it as+ * "touches nothing" would be the one wrong answer.+ */+ actionTouches(name: string, input: AiActionInput = {}): AiTouches | undefined {+ const declared = this.actions.get(name)?.touches;+ if (!declared) return undefined;+ return typeof declared === 'function' ? declared(input) : declared;+ }++ conditionTouches(name: string): AiTouches | undefined {+ return this.conditions.get(name)?.touches;+ }+/** The declared parameters of `name` (empty when it takes a bare string). */getActionParams(name: string): readonly AiParamDef[] {return this.actions.get(name)?.params ?? [];@@ -135,7 +186,7 @@ export class AiRegistry<Ctx = unknown> {}getCondition(name: string): AiCondition<Ctx> | undefined {- return this.conditions.get(name);+ return this.conditions.get(name)?.fn;}hasAction(name: string): boolean {diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.tsindex 16da723d2..065237523 100644--- a/sdk/src/ai/nav/NavPlugin.ts+++ b/sdk/src/ai/nav/NavPlugin.ts@@ -116,14 +116,19 @@ export class NavPlugin implements Plugin {app.addSystemToSchedule(Schedule.Update,- // system-access: moves agents whose components are registered by the- // project, through the same World view the editor steps.defineSystem([Res(Nav), Res(Time), GetWorld()],(nav: Navigation, time: TimeData, world) => {stepNavigation(world as NavWorldView, nav, time.delta, runtimes);},- { name: 'NavAgentSystem' },+ {+ name: 'NavAgentSystem',+ touches: { writes: [NavAgent._name, Transform._name] },+ // Both move an entity; for one carrying both, the path is the+ // intent and the drift is not, so the follow lands last. The+ // order registration already produced — declared, not changed.+ runAfter: ['VelocitySystem'],+ },),{ runIf: playModeOnly },);diff --git a/sdk/src/ai/perception/PerceptionPlugin.ts b/sdk/src/ai/perception/PerceptionPlugin.tsindex 33440e4d1..c35fa965a 100644--- a/sdk/src/ai/perception/PerceptionPlugin.ts+++ b/sdk/src/ai/perception/PerceptionPlugin.ts@@ -97,14 +97,21 @@ export class PerceptionPlugin implements Plugin {build(app: App): void {app.addSystemToSchedule(Schedule.PreUpdate,- // system-access: senses whatever a project's perception graph names.defineSystem([GetWorld()],world => {const physics = app.hasResource(Physics) ? app.getResource<PhysicsAPI>(Physics) : null;stepPerception(world as PerceptionWorldView, physics ? makeLosCheck(physics) : undefined);},- { name: 'PerceptionSystem' },+ {+ name: 'PerceptionSystem',+ // The World is for the cross-entity sweep (every target against+ // every perceiver), not for reach beyond these four.+ touches: {+ reads: [Perceiver._name, PerceptionTarget._name, Transform._name],+ writes: [Perception._name],+ },+ },),{ runIf: playModeOnly },);diff --git a/sdk/src/ai/worldView.ts b/sdk/src/ai/worldView.tsnew file mode 100644index 000000000..2adbf3c76--- /dev/null+++ b/sdk/src/ai/worldView.ts@@ -0,0 +1,83 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file worldView.ts+ * @brief What the systems that run AUTHORED graphs actually touch.+ *+ * An FSM system's reach is not a property of the system — it is the union of the+ * leaves the loaded graphs name. That is unknowable when the system is defined+ * and perfectly knowable once the data is there, which is why the schedule reads+ * these through a function rather than a literal.+ *+ * One unknown leaf makes the whole claim opaque, and that is the point: a union+ * that quietly drops the leaf it could not read would be a claim the scheduler+ * trusts and the frame disproves.+ */++import type { AiRegistry, AiTouches, AiActionInput } from './fsm/registry';+import type { SystemTouches } from '../ecs/system';++/** Accumulates leaf claims into one system-level claim. */+export class TouchesBuilder {+ private readonly reads = new Set<string>();+ private readonly writes = new Set<string>();+ private unknown = false;++ /** A leaf that declared. `undefined` is a leaf that did not — see `opaque`. */+ add(touches: AiTouches | undefined): this {+ if (!touches) {+ this.unknown = true;+ return this;+ }+ for (const name of touches.reads ?? []) this.reads.add(name);+ for (const name of touches.writes ?? []) this.writes.add(name);+ if (touches.opaque) this.unknown = true;+ return this;+ }++ /** Access the system has regardless of the data — the agent component itself. */+ reading(...names: string[]): this {+ for (const name of names) this.reads.add(name);+ return this;+ }++ writing(...names: string[]): this {+ for (const name of names) this.writes.add(name);+ return this;+ }++ build(): SystemTouches {+ return {+ reads: [...this.reads].sort(),+ writes: [...this.writes].sort(),+ ...(this.unknown ? { opaque: true } : {}),+ };+ }+}++/** An authored leaf reference: the registry name plus whatever input it carries. */+export interface LeafRef {+ kind: 'action' | 'condition';+ name: string;+ input?: AiActionInput;+}++/** Fold every leaf of every loaded graph into one claim. */+export function touchesOfLeaves<Ctx>(+ registry: AiRegistry<Ctx>,+ leaves: Iterable<LeafRef>,+ builder = new TouchesBuilder(),+): TouchesBuilder {+ for (const leaf of leaves) {+ // A name nothing registered runs as a no-op, so it reaches for nothing —+ // counting it as unknown would make every graph with a typo opaque.+ if (leaf.kind === 'action') {+ if (!registry.hasAction(leaf.name)) continue;+ builder.add(registry.actionTouches(leaf.name, leaf.input));+ } else {+ if (!registry.hasCondition(leaf.name)) continue;+ builder.add(registry.conditionTouches(leaf.name));+ }+ }+ return builder;+}diff --git a/sdk/src/app/access.ts b/sdk/src/app/access.tsindex 0fa5b027d..48b145f87 100644--- a/sdk/src/app/access.ts+++ b/sdk/src/app/access.ts@@ -45,7 +45,8 @@ const isMut = (arg: QueryArg): boolean => (arg as MutWrapper)._type === 'mut';/** A resource's declared name — what `defineResource` stamped on it. */const resourceName = (r: unknown): string => (r as { _name?: string })?._name ?? String(r);-/** Read a system's declared access. Cheap and pure — the caller may cache it. */+/** Read a system's declared access. Cheap, and re-read rather than cached: a+ * system may answer for the data currently loaded (see `touches`). */export function accessOf(system: SystemDef): SystemAccess {const readsComponents = new Set<string>();const writesComponents = new Set<string>();@@ -90,11 +91,14 @@ export function accessOf(system: SystemDef): SystemAccess {// A system that says what it reaches for through the World is no longer// opaque: its claim IS the declaration, and it is named by component name// because the reason to use the hatch is usually a type registered later.- const touches = system._touches;+ // A function is asked now rather than at definition: a system running+ // authored data answers from what is loaded.+ const declared = system._touches;+ const touches = typeof declared === 'function' ? declared() : declared;if (touches) {for (const name of touches.reads ?? []) readsComponents.add(name);for (const name of touches.writes ?? []) writesComponents.add(name);- if (opaque) opaque = false;+ opaque = touches.opaque === true;}return { readsComponents, writesComponents, readsResources, writesResources, opaque };diff --git a/sdk/src/behavior.ts b/sdk/src/behavior.tsindex ebb510abd..1b35be2b4 100644--- a/sdk/src/behavior.ts+++ b/sdk/src/behavior.ts@@ -18,7 +18,7 @@ import {type ComponentDef,type ComponentMetadata,} from './ecs/component';-import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from './ecs/system';+import { Schedule, defineSystem, addSystemToSchedule, GetWorld, type SystemTouches } from './ecs/system';import { Query, Mut } from './ecs/query';import { Res, Time, type TimeData } from './ecs/resource';import { Commands, type CommandsInstance } from './ecs/commands';@@ -66,6 +66,12 @@ export interface BehaviorDef<S extends object> {schedule?: Schedule;/** Field-presentation metadata for `state` (ranges, enums, …), forwarded to the component. */metadata?: ComponentMetadata;+ /**+ * The components this behaviour reaches for through `ctx.get`/`ctx.set`, by+ * name — its own state component is already declared. Undeclared, the+ * schedule assumes anything, and this conflicts with every other system.+ */+ touches?: SystemTouches;/** Run once, the frame the behavior's component first appears on an entity. */start?(ctx: BehaviorContext<S>): void;/** Run every frame for each entity carrying the behavior. `dt` == `ctx.time.delta`. */@@ -133,8 +139,6 @@ export function defineBehavior<S extends object>(name: string, def: BehaviorDef<const { start, update, destroy } = def;- // system-access: runs a behaviour a project wrote, which may read or write- // any component it names.const system = defineSystem([Query(Mut(Comp)), Res(Time), Res(Input), Commands(), GetWorld()],(q, time, input, commands, world) => {@@ -169,7 +173,13 @@ export function defineBehavior<S extends object>(name: string, def: BehaviorDef<}}},- { name: `Behavior:${name}` },+ {+ name: `Behavior:${name}`,+ // Undeclared is opaque ON PURPOSE, and said rather than left out: the+ // body is a project's code, and the schedule must not assume that+ // silence means it touches nothing.+ touches: def.touches ?? { opaque: true },+ },);addSystemToSchedule(schedule, system);diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.tsindex ba2210bbf..2c8724c3f 100644--- a/sdk/src/ecs/system.ts+++ b/sdk/src/ecs/system.ts@@ -156,7 +156,7 @@ export interface SystemDef {/** @internal */readonly _runAfter?: readonly string[];/** @internal */- readonly _touches?: SystemTouches;+ readonly _touches?: SystemTouches | (() => SystemTouches);}let templateCounter_ = 0;@@ -175,8 +175,14 @@ export interface SystemOptions {runBefore?: string[];/** This system runs after each of these names (a system or a set). */runAfter?: string[];- /** What the system reaches for through {@link GetWorld}. See {@link SystemTouches}. */- touches?: SystemTouches;+ /**+ * What the system reaches for through {@link GetWorld}. See {@link SystemTouches}.+ *+ * A function is re-read every time the access is, which is what lets a system+ * running authored data (an FSM, a behaviour tree) answer from the data+ * actually loaded rather than from everything it could ever be handed.+ */+ touches?: SystemTouches | (() => SystemTouches);}/**@@ -190,6 +196,13 @@ export interface SystemOptions {export interface SystemTouches {reads?: readonly string[];writes?: readonly string[];+ /**+ * Some of the reach genuinely cannot be named — a system running data a+ * project authored, where one of the leaves does not say what it writes.+ * Declared rather than left out: an omitted `touches` and a known-incomplete+ * one are both "assume everything", but only this one says so on purpose.+ */+ opaque?: boolean;}/**diff --git a/sdk/src/physics/CharacterController.ts b/sdk/src/physics/CharacterController.tsindex 7f31228d3..8fa386f1b 100644--- a/sdk/src/physics/CharacterController.ts+++ b/sdk/src/physics/CharacterController.ts@@ -309,8 +309,6 @@ export function registerCharacterControllerSystem(app: App): void {warnedNonFiniteMove = false;app.addSystemToSchedule(Schedule.FixedUpdate,- // system-access: reads and writes the Transform of whatever a character is- // standing on, which the solver decides per contact.defineSystem([Query(Mut(CharacterController)), Res(Time), Res(Physics), GetWorld()],(@@ -372,7 +370,17 @@ export function registerCharacterControllerSystem(app: App): void {cc.realVelocity.y = r.dy * invDt;}},- { name: 'CharacterControllerSystem', runBefore: ['PhysicsStepSystem'] },+ {+ name: 'CharacterControllerSystem',+ runBefore: ['PhysicsStepSystem'],+ // The World is how it reaches the collider (whichever of the three+ // a character has) and the pose it resolves; the solver's contacts+ // are physics-side state, not components.+ touches: {+ reads: [BoxCollider._name, CircleCollider._name, CapsuleCollider._name],+ writes: [Transform._name],+ },+ },),{ runIf: playModeOnly },);diff --git a/sdk/src/stats.ts b/sdk/src/stats.tsindex 3010f3465..e5767d425 100644--- a/sdk/src/stats.ts+++ b/sdk/src/stats.ts@@ -179,7 +179,6 @@ export class StatsPlugin implements Plugin {const collector = this.collector_;const overlay = this.overlay_;- // system-access: counts what the world holds, whatever that is.const statsCollectSystem = defineSystem([Res(Time), GetWorld()],(time, world) => {@@ -213,7 +212,10 @@ export class StatsPlugin implements Plugin {overlay?.update(stats);},- { name: STATS_COLLECT_SYSTEM_NAME }+ // It holds the World to count entities, which is not component access+ // at all: an empty claim is the honest one, and it keeps the overlay+ // out of every other system's conflict set.+ { name: STATS_COLLECT_SYSTEM_NAME, touches: {} });app.addSystemToSchedule(Schedule.Last, statsCollectSystem);diff --git a/sdk/tests/ai-world-view.test.ts b/sdk/tests/ai-world-view.test.tsnew file mode 100644index 000000000..c3e265113--- /dev/null+++ b/sdk/tests/ai-world-view.test.ts@@ -0,0 +1,137 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What the systems that run AUTHORED graphs tell the schedule.+ *+ * Their reach is a property of the loaded data, not of the system, so the+ * claims here are about a graph: which leaves it names, what those leaves+ * declared, and what one undeclared leaf does to the whole answer.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { aiRegistry } from '../src/ai/fsm/AiContext';+import { registerFsm, clearFsmStore, StateMachineAgent } from '../src/ai/fsm/StateMachineAgent';+import { registerBt, clearBtStore, BehaviorTreeAgent } from '../src/ai/bt/BehaviorTreeAgent';+import { fsmTouches } from '../src/ai/fsm/FsmPlugin';+import { btTouches } from '../src/ai/bt/BtPlugin';+import { ensureBuiltinAiRegistrations } from '../src/ai/builtins';+import { TouchesBuilder } from '../src/ai/worldView';++const noop = (): void => { };++beforeEach(() => {+ clearFsmStore();+ clearBtStore();+ aiRegistry.clear();+ ensureBuiltinAiRegistrations();+});++describe('an FSM system, asked what it touches', () => {+ it('names only its own component when no graph is loaded', () => {+ expect(fsmTouches()).toEqual({ reads: [], writes: [StateMachineAgent._name] });+ });++ it('answers from the graph that is loaded, not from the registry', () => {+ // `spriteAnim.*` is registered either way; what puts SpriteAnimator in+ // the answer is a graph that names it.+ expect(fsmTouches().writes).not.toContain('SpriteAnimator');+ registerFsm('run', {+ initial: 'idle',+ states: [{ name: 'idle', onEnter: 'spriteAnim.play' }],+ });+ expect(fsmTouches().writes).toContain('SpriteAnimator');+ });++ it('includes what a transition condition reads', () => {+ registerFsm('cutscene', {+ initial: 'playing',+ states: [+ { name: 'playing', transitions: [{ to: 'done', condition: 'timeline.finished' }] },+ { name: 'done' },+ ],+ });+ expect(fsmTouches().reads).toContain('TimelinePlayer');+ });++ it('reads the component out of a property.set path', () => {+ registerFsm('fade', {+ initial: 'hit',+ states: [{+ name: 'hit',+ onEnter: { name: 'property.set', params: { path: 'UIVisual.color.a', value: '0.5' } },+ }],+ });+ expect(fsmTouches().writes).toContain('UIVisual');+ expect(fsmTouches().opaque).toBeUndefined();+ });++ it('reads it out of the canonical string form too', () => {+ registerFsm('fade', {+ initial: 'hit',+ states: [{ name: 'hit', onEnter: { name: 'property.set', arg: 'Sprite.color.r=1' } }],+ });+ expect(fsmTouches().writes).toContain('Sprite');+ });++ // The whole point of declaring: a union that quietly dropped the leaf it+ // could not read would be a claim the scheduler trusts and the frame breaks.+ it('goes opaque when one leaf never declared', () => {+ aiRegistry.registerAction('game.mystery', noop);+ registerFsm('mixed', {+ initial: 'a',+ states: [{ name: 'a', onEnter: 'spriteAnim.play', onUpdate: 'game.mystery' }],+ });+ const touches = fsmTouches();+ expect(touches.opaque).toBe(true);+ // Still says what it DOES know — a bad claim is not a reason to say nothing.+ expect(touches.writes).toContain('SpriteAnimator');+ });++ it('takes a declaring registration at its word', () => {+ aiRegistry.registerAction('game.hurt', { run: noop, touches: { writes: ['Health'] } });+ registerFsm('fight', { initial: 'a', states: [{ name: 'a', onEnter: 'game.hurt' }] });+ expect(fsmTouches()).toMatchObject({ writes: ['Health', StateMachineAgent._name] });+ });++ // A name nothing registered is a no-op at run time, so counting it as+ // unknown would make one typo hide the reach of an entire project.+ it('ignores a leaf no registration answers to', () => {+ registerFsm('typo', { initial: 'a', states: [{ name: 'a', onEnter: 'spriteAnim.paly' }] });+ expect(fsmTouches().opaque).toBeUndefined();+ });+});++describe('a behaviour-tree system, asked what it touches', () => {+ it('walks the whole tree, not just the root', () => {+ registerBt('patrol', {+ root: {+ type: 'sequence',+ children: [+ { type: 'condition', name: 'timeline.finished' },+ { type: 'action', name: 'spriteAnim.stop' },+ ],+ },+ });+ const touches = btTouches();+ expect(touches.reads).toContain('TimelinePlayer');+ expect(touches.writes).toContain('SpriteAnimator');+ expect(touches.writes).toContain(BehaviorTreeAgent._name);+ });++ // Orphans are authored-but-unwired subtrees; the interpreter ticks only+ // `root`, so counting them would claim reach the frame never has.+ it('leaves an unwired subtree out of the claim', () => {+ registerBt('wip', {+ root: { type: 'action', name: 'spriteAnim.stop' },+ orphans: [{ type: 'action', name: 'timeline.play' }],+ });+ expect(btTouches().writes).not.toContain('TimelinePlayer');+ });+});++describe('the builder that folds leaf claims', () => {+ it('is not opaque until something says it cannot say', () => {+ expect(new TouchesBuilder().reading('A').build()).toEqual({ reads: ['A'], writes: [] });+ expect(new TouchesBuilder().add(undefined).build().opaque).toBe(true);+ expect(new TouchesBuilder().add({ opaque: true }).build().opaque).toBe(true);+ });+});diff --git a/sdk/tests/schedule-declared.test.ts b/sdk/tests/schedule-declared.test.tsnew file mode 100644index 000000000..daded3360--- /dev/null+++ b/sdk/tests/schedule-declared.test.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The engine's OWN schedules, judged by what its systems declare.+ *+ * schedule-ambiguity.test.ts proves the analysis works on systems written+ * for it. This asks the question of the real stack, which is where it was+ * useless until recently: every gameplay system took the World and said+ * nothing, so all nine pairs it reported were "the World itself" — a+ * finding with no action attached, hiding the one real collision.+ *+ * Now the answer is a list short enough to be a rule: nothing in the+ * engine's own schedules may touch the same data with nobody having+ * decided the order.+ */+import { describe, it, expect, beforeAll } from 'vitest';+import { App } from '../src/app/app';+import { Schedule } from '../src/ecs/system';+import { simulationBasePlugins } from '../src/app/pluginSets';+import { setPlatform } from '../src/platform/base';+import { webAdapter } from '../src/platform/web';++const SCHEDULES = Object.entries(Schedule).filter(([, v]) => typeof v === 'number') as [string, Schedule][];++const build = (): App => {+ const app = App.new();+ for (const plugin of simulationBasePlugins()) app.addPlugin(plugin);+ return app;+};++beforeAll(() => {+ setPlatform(webAdapter);+});++describe('the engine stack', () => {+ it.each(SCHEDULES)('leaves nothing unordered in %s', (_name, schedule) => {+ const found = build().scheduleAmbiguities(schedule);+ expect(found.map((f) => `${f.a} <-> ${f.b} over ${f.over.join(', ')}`)).toEqual([]);+ });++ // The escape hatch is still there and still costs everything: a system that+ // takes the World without declaring conflicts with every other system, so a+ // regression shows up as a schedule that cannot be batched at all.+ it('has no system that conflicts with everything', () => {+ const app = build();+ for (const [, schedule] of SCHEDULES) {+ const systems = app.scheduleBatches(schedule).flat();+ if (systems.length < 2) continue;+ const found = app.scheduleAmbiguities(schedule);+ expect(found.filter((f) => f.over.includes('the World itself'))).toEqual([]);+ }+ });++ // What the declarations bought, in the one number that shows it: before+ // them, Update's four systems needed four batches — nothing could ever run+ // beside anything.+ it('can batch Update rather than running it entirely one at a time', () => {+ const app = build();+ const batches = app.scheduleBatches(Schedule.Update);+ expect(batches.flat().length).toBeGreaterThan(batches.length);+ });+});