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.

feat(ai): a state hook and a BT leaf take declared parameters, like an event wire

yhhefe107b73fe6
diff --git a/desktop/src/ai/ParamControls.tsx b/desktop/src/ai/ParamControls.tsx
new file mode 100644
index 000000000..a2b73f79e
--- /dev/null
+++ b/desktop/src/ai/ParamControls.tsx
@@ -0,0 +1,162 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ParamControls.tsx
+ * @brief An action's declared parameters, rendered as real controls.
+ *
+ * One renderer for every surface that references an action by name — an event
+ * wire, an FSM state hook, a BT leaf. The declaration lives in the registry
+ * (sdk), the choices that depend on the scene come from `paramOptions`, and this
+ * decides which control each declared type gets. Keeping it in one place is the
+ * point: an action gains a parameter once and every authoring surface shows it.
+ *
+ * `entityId` is optional because not every surface HAS an entity: an `.esfsm`
+ * asset is authored outside any scene, so its `optionsSource` parameters have
+ * nothing to resolve against and fall back to free text — the same degradation
+ * as a source that yields no options yet.
+ */
+import { Select } from '@/components/Select';
+import { aiParamOptions } from '@/ai/paramOptions';
+import { actionParams, actionSeparator } from '@/ai/actionCatalog';
+import { prettyLabel } from '@/engine/schema';
+import type { EntityId } from '@/types';
+import { parseActionArg } from 'esengine';
+import type { AiParamDef, AiParamValue } from 'esengine';
+import type { ReactNode } from 'react';
+
+/**
+ * The values to show for an action reference, from whichever form it was
+ * authored in: named parameters if it has them, else the canonical string
+ * parsed through the action's own declaration (the projection the runtime uses).
+ */
+export function paramValuesOf(
+ action: string,
+ params: Readonly<Record<string, AiParamValue>> | undefined,
+ arg: string | undefined,
+): Record<string, AiParamValue> {
+ if (params && Object.keys(params).length) return { ...params };
+ return parseActionArg(arg, actionParams(action), actionSeparator(action));
+}
+
+/** One declared parameter, rendered by its declared type. */
+export function ParamControl({
+ def,
+ value,
+ entityId,
+ siblings,
+ onChange,
+}: {
+ def: AiParamDef;
+ value: AiParamValue | undefined;
+ /** The entity the action will run on, when the surface has one. */
+ entityId?: EntityId;
+ /** The reference's other parameter values, for one that narrows a sibling. */
+ siblings: Readonly<Record<string, AiParamValue>>;
+ onChange: (v: AiParamValue | undefined) => void;
+}) {
+ const label = def.label ?? prettyLabel(def.name);
+ const dynamic = def.optionsSource && entityId != null
+ ? aiParamOptions(def.optionsSource, { entityId, params: siblings })
+ : null;
+ const options = dynamic ?? (def.options ? def.options.map((o) => ({ value: o.value, label: o.label })) : null);
+ const text = value === undefined ? '' : String(value);
+
+ let control: ReactNode;
+ if (def.type === 'bool') {
+ control = (
+ <input type="checkbox" checked={value === true} aria-label={label} onChange={(e) => onChange(e.target.checked)} />
+ );
+ } else if (def.type === 'number') {
+ control = (
+ <input
+ className="evt-param-input"
+ type="number"
+ defaultValue={text}
+ key={text}
+ aria-label={label}
+ min={def.min}
+ max={def.max}
+ step={def.step}
+ onBlur={(e) => onChange(e.target.value === '' ? undefined : Number(e.target.value))}
+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
+ />
+ );
+ } else if (options && options.length) {
+ // The authored value survives even when it is no longer on offer (a renamed
+ // page), so opening the row never silently rewrites the data.
+ const opts = options.some((o) => o.value === text) || !text ? options : [...options, { value: text }];
+ control = (
+ <Select
+ value={text}
+ options={opts.map((o) => ({ value: o.value, label: o.label }))}
+ onChange={(v) => onChange(v)}
+ ariaLabel={label}
+ className="evt-param-sel"
+ />
+ );
+ } else {
+ control = (
+ <input
+ className="evt-param-input"
+ defaultValue={text}
+ key={text}
+ aria-label={label}
+ placeholder={def.tooltip}
+ spellCheck={false}
+ onBlur={(e) => onChange(e.target.value.trim() || undefined)}
+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
+ />
+ );
+ }
+
+ return (
+ <label className="evt-param" title={def.tooltip}>
+ <span className="evt-param-label">{label}</span>
+ {control}
+ </label>
+ );
+}
+
+/**
+ * Every declared parameter of `action`, as a block of controls. Renders nothing
+ * when the action declares none — the caller keeps its plain argument field for
+ * that case, since an undeclared action still takes a free string.
+ */
+export function ActionParams({
+ action,
+ params,
+ arg,
+ entityId,
+ onChange,
+}: {
+ action: string;
+ params: Readonly<Record<string, AiParamValue>> | undefined;
+ arg: string | undefined;
+ entityId?: EntityId;
+ /** Called with the whole next record, or undefined once it is empty. */
+ onChange: (next: Record<string, AiParamValue> | undefined) => void;
+}): ReactNode {
+ const defs = actionParams(action);
+ if (defs.length === 0) return null;
+ const values = paramValuesOf(action, params, arg);
+
+ return (
+ <div className="evt-params">
+ {defs.map((def) => (
+ <ParamControl
+ key={def.name}
+ def={def}
+ value={values[def.name]}
+ entityId={entityId}
+ siblings={values}
+ onChange={(v) => {
+ const next = { ...values };
+ if (v === undefined || v === '') delete next[def.name];
+ else next[def.name] = v;
+ onChange(Object.keys(next).length ? next : undefined);
+ }}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/desktop/src/events/EventBindingSection.tsx b/desktop/src/events/EventBindingSection.tsx
index ecf73591a..e6d9e48de 100644
--- a/desktop/src/events/EventBindingSection.tsx
+++ b/desktop/src/events/EventBindingSection.tsx
@@ -21,23 +21,21 @@
*/
import { useState } from 'react';
import { useSyncExternalStore } from 'react';
-import type { ReactNode } from 'react';
import { ChevronDown, ChevronRight, CornerDownRight, MousePointerClick, Plus, SlidersHorizontal, X } from 'lucide-react';
import { Select } from '@/components/Select';
import { SuggestInput } from '@/components/SuggestInput';
import { aiActionItems, aiConditionItems } from '@/components/aiSuggest';
-import { aiParamOptions } from '@/ai/paramOptions';
-import { actionParams, actionSeparator, subscribeActionCatalog, getActionCatalogRevision } from '@/ai/actionCatalog';
+import { ActionParams } from '@/ai/ParamControls';
+import { actionParams, subscribeActionCatalog, getActionCatalogRevision } from '@/ai/actionCatalog';
import { SceneStore } from '@/engine/SceneStore';
import { SceneCommands } from '@/engine/SceneCommands';
-import { prettyLabel } from '@/engine/schema';
import { readEventRows, resolveTargetName, sceneEntityNames } from '@/events/eventBindingModel';
import { useInspectorCollapse, isSectionCollapsed } from '@/store/inspectorCollapse';
import { t } from '@/i18n';
import type { EntityId } from '@/types';
-import { UIEventType, PhysicsEventType, parseActionArg } from 'esengine';
-import type { AiParamDef, AiParamValue, EventBindingRow } from 'esengine';
+import { UIEventType, PhysicsEventType } from 'esengine';
+import type { EventBindingRow } from 'esengine';
const SECTION_KEY = '__events';
/**
@@ -150,13 +148,7 @@ function EventRow({
const patch = (p: Partial<EventBindingRow>) => SceneCommands.updateEventBinding(entityId, index, p);
const enabled = row.enabled !== false;
- // What the chosen action takes. A row authored before the action declared its
- // parameters still shows them: the canonical string parses into the same
- // record the runtime would build (registry.ts owns that projection).
- const defs = actionParams(row.action);
- const values: Record<string, AiParamValue> = row.params && Object.keys(row.params).length
- ? { ...row.params }
- : parseActionArg(row.arg, defs, actionSeparator(row.action));
+ const hasParams = actionParams(row.action).length > 0;
// An authored value the built-in list doesn't know (a widget's own event, or
// an entity renamed since) still has to be selectable — append it rather than
@@ -223,7 +215,7 @@ function EventRow({
// The old input belongs to the old action — switching drops both forms.
onCommit={(v) => (v.trim() === row.action ? undefined : patch({ action: v.trim(), params: undefined, arg: undefined }))}
/>
- {defs.length === 0 && (
+ {!hasParams && (
<input
className="evt-arg"
defaultValue={row.arg ?? ''}
@@ -238,27 +230,15 @@ function EventRow({
)}
</div>
- {defs.length > 0 && (
- <div className="evt-params">
- {defs.map((def) => (
- <ParamControl
- key={def.name}
- def={def}
- value={values[def.name]}
- // Options come from the entity the action RUNS on, so a row that
- // targets a panel offers that panel's controllers, not the button's.
- optionsEntity={targetEntity ?? entityId}
- siblings={values}
- onChange={(v) => {
- const next = { ...values };
- if (v === undefined || v === '') delete next[def.name];
- else next[def.name] = v;
- patch({ params: Object.keys(next).length ? next : undefined, arg: undefined });
- }}
- />
- ))}
- </div>
- )}
+ {/* Options come from the entity the action RUNS on, so a row that targets
+ a panel offers that panel's controllers, not the button's. */}
+ <ActionParams
+ action={row.action}
+ params={row.params}
+ arg={row.arg}
+ entityId={targetEntity ?? entityId}
+ onChange={(next) => patch({ params: next, arg: undefined })}
+ />
{open && (
<div className="evt-row-more" data-row={index}>
@@ -283,82 +263,3 @@ function EventRow({
</div>
);
}
-
-/**
- * One declared parameter, rendered by its declared type. An `optionsSource` that
- * yields nothing (no controller on the target yet) degrades to a text box rather
- * than an empty dropdown — the row stays authorable while the scene is half-built.
- */
-function ParamControl({
- def,
- value,
- optionsEntity,
- siblings,
- onChange,
-}: {
- def: AiParamDef;
- value: AiParamValue | undefined;
- optionsEntity: EntityId;
- siblings: Readonly<Record<string, AiParamValue>>;
- onChange: (v: AiParamValue | undefined) => void;
-}) {
- const label = def.label ?? prettyLabel(def.name);
- const dynamic = def.optionsSource ? aiParamOptions(def.optionsSource, { entityId: optionsEntity, params: siblings }) : null;
- const options = dynamic ?? (def.options ? def.options.map((o) => ({ value: o.value, label: o.label })) : null);
- const text = value === undefined ? '' : String(value);
-
- let control: ReactNode;
- if (def.type === 'bool') {
- control = (
- <input type="checkbox" checked={value === true} aria-label={label} onChange={(e) => onChange(e.target.checked)} />
- );
- } else if (def.type === 'number') {
- control = (
- <input
- className="evt-param-input"
- type="number"
- defaultValue={text}
- key={text}
- aria-label={label}
- min={def.min}
- max={def.max}
- step={def.step}
- onBlur={(e) => onChange(e.target.value === '' ? undefined : Number(e.target.value))}
- onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
- />
- );
- } else if (options && options.length) {
- // The authored value survives even when it is no longer on offer (a renamed
- // page), so opening the row never silently rewrites the data.
- const opts = options.some((o) => o.value === text) || !text ? options : [...options, { value: text }];
- control = (
- <Select
- value={text}
- options={opts.map((o) => ({ value: o.value, label: o.label }))}
- onChange={(v) => onChange(v)}
- ariaLabel={label}
- className="evt-param-sel"
- />
- );
- } else {
- control = (
- <input
- className="evt-param-input"
- defaultValue={text}
- key={text}
- aria-label={label}
- placeholder={def.tooltip}
- spellCheck={false}
- onBlur={(e) => onChange(e.target.value.trim() || undefined)}
- onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur(); }}
- />
- );
- }
-
- return (
- <label className="evt-param" title={def.tooltip}>
- <span className="evt-param-label">{label}</span>
- {control}
- </label>
- );
-}
diff --git a/desktop/src/panels/BtTreeEditor.tsx b/desktop/src/panels/BtTreeEditor.tsx
index 6467b7d44..406ef3223 100644
--- a/desktop/src/panels/BtTreeEditor.tsx
+++ b/desktop/src/panels/BtTreeEditor.tsx
@@ -25,6 +25,8 @@ import { Select } from '@/components/Select';
import { SaveButton } from '@/components/SaveButton';
import { SuggestInput } from '@/components/SuggestInput';
import { aiActionItems, aiConditionItems } from '@/components/aiSuggest';
+import { ActionParams } from '@/ai/ParamControls';
+import { actionParams } from '@/ai/actionCatalog';
type BtCanvasNode = BtNode & CanvasNode;
@@ -187,16 +189,29 @@ export function BtTreeEditor() {
items={selNode.type === 'action' ? aiActionItems() : aiConditionItems()}
defaultValue={selNode.name ?? ''} key={`${selNode.id}-name`}
placeholder={selNode.type === 'action' ? t('ng.phActionName') : t('ng.phConditionName')}
- onCommit={v => patch(selNode.id, { name: v || undefined })} />
+ // The old input belongs to the old action — switching drops both forms.
+ onCommit={v => { if (v !== (selNode.name ?? '')) patch(selNode.id, { name: v || undefined, arg: undefined, params: undefined }); }} />
</label>
)}
- {selNode.type === 'action' && (
+ {/* A leaf whose action declares parameters gets the same controls an
+ event wire renders; anything else keeps the free-text argument. */}
+ {selNode.type === 'action' && actionParams(selNode.name ?? '').length === 0 && (
<label className="ng-field">{t('ng.actionArg')}
<input className="ng-input" defaultValue={selNode.arg ?? ''} key={`${selNode.id}-arg`}
placeholder={t('ng.phActionArg')} spellCheck={false}
onBlur={e => { const v = e.target.value.trim(); if (v !== (selNode.arg ?? '')) patch(selNode.id, { arg: v || undefined }); }} />
</label>
)}
+ {selNode.type === 'action' && actionParams(selNode.name ?? '').length > 0 && (
+ <label className="ng-field">{t('ng.actionArg')}
+ <ActionParams
+ action={selNode.name ?? ''}
+ params={selNode.params}
+ arg={selNode.arg}
+ onChange={next => patch(selNode.id, { params: next, arg: undefined })}
+ />
+ </label>
+ )}
{selNode.type === 'repeater' && (
<label className="ng-field">{t('bt.count')}
<input className="ng-input" type="number" min={0} defaultValue={selNode.count ?? 0} key={`${selNode.id}-count`}
diff --git a/desktop/src/panels/StateMachineEditor.tsx b/desktop/src/panels/StateMachineEditor.tsx
index 67bf4c651..4c626aa72 100644
--- a/desktop/src/panels/StateMachineEditor.tsx
+++ b/desktop/src/panels/StateMachineEditor.tsx
@@ -17,7 +17,7 @@ import { useMemo, useRef, useState, useSyncExternalStore } from 'react';
import { Plus, Trash2, Workflow } from 'lucide-react';
import {
fsmEdges, addState, removeState, moveState, renameState, setStateHook, setInitial,
- addTransition, removeTransition, updateTransition, actionRefName, actionRefArg,
+ addTransition, removeTransition, updateTransition, actionRefName, actionRefArg, actionRefParams,
type FsmDefinition, type FsmState, type FsmEdge, type CompareOp,
} from 'esengine';
import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';
@@ -28,6 +28,8 @@ import { Select } from '@/components/Select';
import { SaveButton } from '@/components/SaveButton';
import { SuggestInput } from '@/components/SuggestInput';
import { aiActionItems, aiConditionItems } from '@/components/aiSuggest';
+import { ActionParams } from '@/ai/ParamControls';
+import { actionParams } from '@/ai/actionCatalog';
type FsmCanvasNode = FsmState & CanvasNode;
@@ -191,16 +193,30 @@ function StateInspector({ def, state, onRename }: { def: FsmDefinition; state: F
{HOOKS.map((h) => {
const name = actionRefName(state[h]);
const arg = actionRefArg(state[h]) ?? '';
+ const params = actionRefParams(state[h]);
+ // An action that declares its parameters gets real controls here, the
+ // same ones an event wire renders — one declaration, every surface.
+ // Choices that depend on a scene entity have none to resolve against in
+ // an asset editor, so those degrade to free text (see ParamControls).
+ const declared = actionParams(name).length > 0;
return (
<label className="ng-field" key={h}>{h}
<SuggestInput items={actions} defaultValue={name} key={`${state.name}-${h}-${name}`}
placeholder={t('ng.phActionName')}
- onCommit={(v) => { if (v !== name) FsmGraphDocument.edit(`Set ${h}`, (d) => Object.assign(d, setStateHook(d, state.name, h, v, arg || undefined))); }} />
- {name && (
+ onCommit={(v) => { if (v !== name) FsmGraphDocument.edit(`Set ${h}`, (d) => Object.assign(d, setStateHook(d, state.name, h, v))); }} />
+ {name && !declared && (
<input className="ng-input" defaultValue={arg} key={`${state.name}-${h}-arg-${arg}`}
placeholder={t('ng.phActionArg')} spellCheck={false}
onBlur={(e) => { const v = e.target.value.trim(); if (v !== arg) FsmGraphDocument.edit(`Set ${h} argument`, (d) => Object.assign(d, setStateHook(d, state.name, h, name, v || undefined))); }} />
)}
+ {name && declared && (
+ <ActionParams
+ action={name}
+ params={params}
+ arg={arg || undefined}
+ onChange={(next) => FsmGraphDocument.edit(`Set ${h} parameters`, (d) => Object.assign(d, setStateHook(d, state.name, h, name, undefined, next)))}
+ />
+ )}
</label>
);
})}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 20b6422c3..c95ddf591 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1355 stable · 17 beta · 1 deprecated
+Symbols: 1356 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1073,6 +1073,7 @@ children: BtNode[] | undefined
count: number | undefined
id: string | undefined
name: string | undefined
+params: Record<string, AiParamValue> | undefined
policy: "all" | "one" | undefined
seconds: number | undefined
type: BtNodeType
@@ -2517,7 +2518,7 @@ Rectangle = 2
## EngineApi — type
```
-NativeEngineApi
+NativeEngineApi & Partial<NativeHeap>
```
## Entity — type
@@ -2893,7 +2894,7 @@ triangles: number
## FsmActionRef — type
```
-string | { name: string; arg?: string }
+string | { name: string; arg?: string; params?: Record<string, AiParamValue> }
```
## FsmDefinition — interface
@@ -3920,7 +3921,7 @@ BuiltinComponentDef<Mesh2DData>
clearGeometry: (entity: Entity) => void
getGeometry: (entity: Entity) => Mesh2DGeometry | undefined
setGeometry: (entity: Entity, geometry: Mesh2DGeometry) => void
-static new (module_: ESEngineModule, registry_: CppRegistry): Mesh2DAPI
+static new (module_: NonNullable<EngineApi>, registry_: CppRegistry): Mesh2DAPI
static prototype: Mesh2DAPI
```
@@ -4284,7 +4285,7 @@ setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): ParticleAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
static prototype: ParticleAPI
```
@@ -7235,7 +7236,7 @@ ResourceDef<TrailAPI>
```
clear: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): TrailAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): TrailAPI
static prototype: TrailAPI
```
@@ -8062,6 +8063,11 @@ TransformData
(ref: FsmActionRef | undefined): string
```
+## actionRefParams — function
+```
+(ref: FsmActionRef | undefined): Record<string, AiParamValue> | undefined
+```
+
## activeRemoteRoot — function
```
(config: AssetGroupsConfig | null | undefined): string | undefined
@@ -10014,7 +10020,7 @@ Plugin
## setStateHook — function
```
-(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string): FsmDefinition
+(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string, params?: Record<string, AiParamValue>): FsmDefinition
```
## setTextureBudget — function
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 972f081ea..735637170 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1374 stable · 22 beta · 1 deprecated
+Symbols: 1375 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -1073,6 +1073,7 @@ children: BtNode[] | undefined
count: number | undefined
id: string | undefined
name: string | undefined
+params: Record<string, AiParamValue> | undefined
policy: "all" | "one" | undefined
seconds: number | undefined
type: BtNodeType
@@ -2525,7 +2526,7 @@ Rectangle = 2
## EngineApi — type
```
-NativeEngineApi
+NativeEngineApi & Partial<NativeHeap>
```
## Entity — type
@@ -2901,7 +2902,7 @@ triangles: number
## FsmActionRef — type
```
-string | { name: string; arg?: string }
+string | { name: string; arg?: string; params?: Record<string, AiParamValue> }
```
## FsmDefinition — interface
@@ -3933,7 +3934,7 @@ BuiltinComponentDef<Mesh2DData>
clearGeometry: (entity: Entity) => void
getGeometry: (entity: Entity) => Mesh2DGeometry | undefined
setGeometry: (entity: Entity, geometry: Mesh2DGeometry) => void
-static new (module_: ESEngineModule, registry_: CppRegistry): Mesh2DAPI
+static new (module_: NonNullable<EngineApi>, registry_: CppRegistry): Mesh2DAPI
static prototype: Mesh2DAPI
```
@@ -4431,7 +4432,7 @@ setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): ParticleAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
static prototype: ParticleAPI
```
@@ -7392,7 +7393,7 @@ ResourceDef<TrailAPI>
```
clear: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): TrailAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): TrailAPI
static prototype: TrailAPI
```
@@ -8219,6 +8220,11 @@ TransformData
(ref: FsmActionRef | undefined): string
```
+## actionRefParams — function
+```
+(ref: FsmActionRef | undefined): Record<string, AiParamValue> | undefined
+```
+
## activeRemoteRoot — function
```
(config: AssetGroupsConfig | null | undefined): string | undefined
@@ -10221,7 +10227,7 @@ Plugin
## setStateHook — function
```
-(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string): FsmDefinition
+(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string, params?: Record<string, AiParamValue>): FsmDefinition
```
## setTextureBudget — function
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 82ef613c7..7740db983 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1354 stable · 19 beta · 1 deprecated
+Symbols: 1355 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1068,6 +1068,7 @@ children: BtNode[] | undefined
count: number | undefined
id: string | undefined
name: string | undefined
+params: Record<string, AiParamValue> | undefined
policy: "all" | "one" | undefined
seconds: number | undefined
type: BtNodeType
@@ -2512,7 +2513,7 @@ Rectangle = 2
## EngineApi — type
```
-NativeEngineApi
+NativeEngineApi & Partial<NativeHeap>
```
## Entity — type
@@ -2888,7 +2889,7 @@ triangles: number
## FsmActionRef — type
```
-string | { name: string; arg?: string }
+string | { name: string; arg?: string; params?: Record<string, AiParamValue> }
```
## FsmDefinition — interface
@@ -3915,7 +3916,7 @@ BuiltinComponentDef<Mesh2DData>
clearGeometry: (entity: Entity) => void
getGeometry: (entity: Entity) => Mesh2DGeometry | undefined
setGeometry: (entity: Entity, geometry: Mesh2DGeometry) => void
-static new (module_: ESEngineModule, registry_: CppRegistry): Mesh2DAPI
+static new (module_: NonNullable<EngineApi>, registry_: CppRegistry): Mesh2DAPI
static prototype: Mesh2DAPI
```
@@ -4279,7 +4280,7 @@ setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): ParticleAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
static prototype: ParticleAPI
```
@@ -7230,7 +7231,7 @@ ResourceDef<TrailAPI>
```
clear: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): TrailAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): TrailAPI
static prototype: TrailAPI
```
@@ -8057,6 +8058,11 @@ TransformData
(ref: FsmActionRef | undefined): string
```
+## actionRefParams — function
+```
+(ref: FsmActionRef | undefined): Record<string, AiParamValue> | undefined
+```
+
## activeRemoteRoot — function
```
(config: AssetGroupsConfig | null | undefined): string | undefined
@@ -10019,7 +10025,7 @@ Plugin
## setStateHook — function
```
-(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string): FsmDefinition
+(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string, params?: Record<string, AiParamValue>): FsmDefinition
```
## setTextureBudget — function
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 1b9351799..a3f3af132 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1375 stable · 17 beta · 1 deprecated
+Symbols: 1376 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1068,6 +1068,7 @@ children: BtNode[] | undefined
count: number | undefined
id: string | undefined
name: string | undefined
+params: Record<string, AiParamValue> | undefined
policy: "all" | "one" | undefined
seconds: number | undefined
type: BtNodeType
@@ -2512,7 +2513,7 @@ Rectangle = 2
## EngineApi — type
```
-NativeEngineApi
+NativeEngineApi & Partial<NativeHeap>
```
## Entity — type
@@ -2888,7 +2889,7 @@ triangles: number
## FsmActionRef — type
```
-string | { name: string; arg?: string }
+string | { name: string; arg?: string; params?: Record<string, AiParamValue> }
```
## FsmDefinition — interface
@@ -3915,7 +3916,7 @@ BuiltinComponentDef<Mesh2DData>
clearGeometry: (entity: Entity) => void
getGeometry: (entity: Entity) => Mesh2DGeometry | undefined
setGeometry: (entity: Entity, geometry: Mesh2DGeometry) => void
-static new (module_: ESEngineModule, registry_: CppRegistry): Mesh2DAPI
+static new (module_: NonNullable<EngineApi>, registry_: CppRegistry): Mesh2DAPI
static prototype: Mesh2DAPI
```
@@ -4494,7 +4495,7 @@ setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): ParticleAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
static prototype: ParticleAPI
```
@@ -7445,7 +7446,7 @@ ResourceDef<TrailAPI>
```
clear: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): TrailAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): TrailAPI
static prototype: TrailAPI
```
@@ -8272,6 +8273,11 @@ TransformData
(ref: FsmActionRef | undefined): string
```
+## actionRefParams — function
+```
+(ref: FsmActionRef | undefined): Record<string, AiParamValue> | undefined
+```
+
## activeRemoteRoot — function
```
(config: AssetGroupsConfig | null | undefined): string | undefined
@@ -10239,7 +10245,7 @@ Plugin
## setStateHook — function
```
-(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string): FsmDefinition
+(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string, params?: Record<string, AiParamValue>): FsmDefinition
```
## setTextureBudget — function
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index fc8702841..75781e19e 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1365 stable · 17 beta · 1 deprecated
+Symbols: 1366 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -1068,6 +1068,7 @@ children: BtNode[] | undefined
count: number | undefined
id: string | undefined
name: string | undefined
+params: Record<string, AiParamValue> | undefined
policy: "all" | "one" | undefined
seconds: number | undefined
type: BtNodeType
@@ -2512,7 +2513,7 @@ Rectangle = 2
## EngineApi — type
```
-NativeEngineApi
+NativeEngineApi & Partial<NativeHeap>
```
## Entity — type
@@ -2888,7 +2889,7 @@ triangles: number
## FsmActionRef — type
```
-string | { name: string; arg?: string }
+string | { name: string; arg?: string; params?: Record<string, AiParamValue> }
```
## FsmDefinition — interface
@@ -3922,7 +3923,7 @@ BuiltinComponentDef<Mesh2DData>
clearGeometry: (entity: Entity) => void
getGeometry: (entity: Entity) => Mesh2DGeometry | undefined
setGeometry: (entity: Entity, geometry: Mesh2DGeometry) => void
-static new (module_: ESEngineModule, registry_: CppRegistry): Mesh2DAPI
+static new (module_: NonNullable<EngineApi>, registry_: CppRegistry): Mesh2DAPI
static prototype: Mesh2DAPI
```
@@ -4286,7 +4287,7 @@ setColorLut: (entity: Entity, lut: Float32Array | null) => void
setSizeLut: (entity: Entity, lut: Float32Array | null) => void
stop: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): ParticleAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): ParticleAPI
static prototype: ParticleAPI
```
@@ -7237,7 +7238,7 @@ ResourceDef<TrailAPI>
```
clear: (entity: Entity) => void
update: (dt: number) => void
-static new (module: ESEngineModule, registry: CppRegistry): TrailAPI
+static new (module: NonNullable<EngineApi>, registry: CppRegistry): TrailAPI
static prototype: TrailAPI
```
@@ -8081,6 +8082,11 @@ TransformData
(ref: FsmActionRef | undefined): string
```
+## actionRefParams — function
+```
+(ref: FsmActionRef | undefined): Record<string, AiParamValue> | undefined
+```
+
## activeRemoteRoot — function
```
(config: AssetGroupsConfig | null | undefined): string | undefined
@@ -10038,7 +10044,7 @@ Plugin
## setStateHook — function
```
-(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string): FsmDefinition
+(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string, params?: Record<string, AiParamValue>): FsmDefinition
```
## setTextureBudget — function
diff --git a/sdk/src/ai/bt/BtRunner.ts b/sdk/src/ai/bt/BtRunner.ts
index 97a5082a8..b7a4e53d3 100644
--- a/sdk/src/ai/bt/BtRunner.ts
+++ b/sdk/src/ai/bt/BtRunner.ts
@@ -51,7 +51,7 @@ function tickNode<Ctx>(
case 'action': {
const name = node.name ?? '';
if (!registry.hasAction(name)) return Status.Failure;
- const r = invokeAction(registry, name, ctx, bb, { arg: node.arg });
+ const r = invokeAction(registry, name, ctx, bb, { arg: node.arg, params: node.params });
// A void-returning (one-shot FSM-style) action completes as Success.
return r === undefined ? Status.Success : r;
}
diff --git a/sdk/src/ai/bt/types.ts b/sdk/src/ai/bt/types.ts
index 9505630e1..1bf1c3ecb 100644
--- a/sdk/src/ai/bt/types.ts
+++ b/sdk/src/ai/bt/types.ts
@@ -9,6 +9,8 @@
* data embeds no code — matching `.esfsm` and the input maps.
*/
+import type { AiParamValue } from '../fsm/registry';
+
export type BtNodeType =
// composites (many children)
| 'sequence' | 'selector' | 'parallel'
@@ -25,6 +27,8 @@ export interface BtNode {
name?: string;
/** Optional string argument an `action` leaf passes to its registry fn. */
arg?: string;
+ /** The action's declared parameters by name — the other projection of `arg`. */
+ params?: Record<string, AiParamValue>;
/** Children: many for a composite, one for a decorator. */
children?: BtNode[];
/** `repeater`: iterations before Success; 0 = forever. */
diff --git a/sdk/src/ai/fsm/FsmRunner.ts b/sdk/src/ai/fsm/FsmRunner.ts
index e613056d7..ca92e3363 100644
--- a/sdk/src/ai/fsm/FsmRunner.ts
+++ b/sdk/src/ai/fsm/FsmRunner.ts
@@ -10,7 +10,7 @@
* `onUpdate` on ticks where no transition fires.
*/
-import { actionRefName, actionRefArg, type FsmActionRef, type FsmDefinition, type FsmState, type FsmTransition } from './types';
+import { actionRefName, actionRefArg, actionRefParams, type FsmActionRef, type FsmDefinition, type FsmState, type FsmTransition } from './types';
import { Blackboard, evalGuards } from './Blackboard';
import { invokeAction, type AiRegistry } from './registry';
@@ -95,5 +95,5 @@ function runAction<Ctx>(
): void {
const name = actionRefName(ref);
if (!name) return;
- invokeAction(registry, name, ctx, bb, { arg: actionRefArg(ref) });
+ invokeAction(registry, name, ctx, bb, { arg: actionRefArg(ref), params: actionRefParams(ref) });
}
diff --git a/sdk/src/ai/fsm/fsmGraph.ts b/sdk/src/ai/fsm/fsmGraph.ts
index 35bea0f49..f458a663c 100644
--- a/sdk/src/ai/fsm/fsmGraph.ts
+++ b/sdk/src/ai/fsm/fsmGraph.ts
@@ -11,7 +11,8 @@
* ignores), so there is no separate editor model to compile.
*/
-import type { FsmDefinition, FsmState, FsmTransition } from './types';
+import type { FsmActionRef, FsmDefinition, FsmState, FsmTransition } from './types';
+import type { AiParamValue } from './registry';
import {
type GraphSpec, type GraphEdge,
graphEdges, addGraphState, removeGraphState, moveGraphState, renameGraphState,
@@ -79,14 +80,24 @@ export function updateTransition(
return updateGraphTransition(spec, def, from, index, patch);
}
+/**
+ * Point a state hook at an action, with its input in either form: the canonical
+ * string (`arg`) or the action's declared parameters. A bare name stays a bare
+ * string in the data — the shorthand most hooks use — and clearing the name
+ * clears the hook.
+ */
export function setStateHook(
def: FsmDefinition,
name: string,
hook: 'onEnter' | 'onUpdate' | 'onExit',
action: string,
arg?: string,
+ params?: Record<string, AiParamValue>,
): FsmDefinition {
- const ref = action ? (arg ? { name: action, arg } : action) : undefined;
+ const hasParams = params !== undefined && Object.keys(params).length > 0;
+ const ref: FsmActionRef | undefined = action
+ ? (hasParams ? { name: action, params } : arg ? { name: action, arg } : action)
+ : undefined;
return {
...def,
states: def.states.map(s => (s.name === name ? { ...s, [hook]: ref } : s)),
diff --git a/sdk/src/ai/fsm/index.ts b/sdk/src/ai/fsm/index.ts
index e70b6f169..a4a69fff5 100644
--- a/sdk/src/ai/fsm/index.ts
+++ b/sdk/src/ai/fsm/index.ts
@@ -13,7 +13,7 @@ export type {
FsmDefinition,
FsmActionRef,
} from './types';
-export { actionRefName, actionRefArg } from './types';
+export { actionRefName, actionRefArg, actionRefParams } from './types';
export { Blackboard, evalGuard, evalGuards } from './Blackboard';
export {
AiRegistry,
diff --git a/sdk/src/ai/fsm/types.ts b/sdk/src/ai/fsm/types.ts
index aca2c6527..82fa8e0e3 100644
--- a/sdk/src/ai/fsm/types.ts
+++ b/sdk/src/ai/fsm/types.ts
@@ -11,6 +11,8 @@
* input maps stay code-free.
*/
+import type { AiParamValue } from './registry';
+
export type CompareOp = '==' | '!=' | '<' | '<=' | '>' | '>=' | 'truthy' | 'falsy';
/** A single blackboard comparison. `value` is unused for truthy/falsy. */
@@ -36,10 +38,12 @@ export interface FsmTransition {
}
/**
- * A hook/leaf action reference: a bare registry name, or a name plus a string
- * argument the action receives (e.g. `spriteAnim.play` with a clip ref).
+ * A hook/leaf action reference: a bare registry name, or a name plus its input.
+ * The input is either the canonical string (`spriteAnim.play` with a clip ref)
+ * or the action's declared parameters by name — the two are projections of each
+ * other, so a ref written either way runs the same (see registry.ts).
*/
-export type FsmActionRef = string | { name: string; arg?: string };
+export type FsmActionRef = string | { name: string; arg?: string; params?: Record<string, AiParamValue> };
/** Registry name of an action ref ('' for none). */
export function actionRefName(ref: FsmActionRef | undefined): string {
@@ -51,6 +55,11 @@ export function actionRefArg(ref: FsmActionRef | undefined): string | undefined
return typeof ref === 'object' && ref !== null ? ref.arg : undefined;
}
+/** Declared parameters of an action ref, if it was authored with them. */
+export function actionRefParams(ref: FsmActionRef | undefined): Record<string, AiParamValue> | undefined {
+ return typeof ref === 'object' && ref !== null ? ref.params : undefined;
+}
+
export interface FsmState {
name: string;
/** Named action run once when the state becomes active. */
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 160ed146e..ac0650c33 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -631,6 +631,7 @@ export {
setStateHook,
actionRefName,
actionRefArg,
+ actionRefParams,
type FsmActionRef,
setInitial,
addTransition,
diff --git a/sdk/tests/fsm-action-params.test.ts b/sdk/tests/fsm-action-params.test.ts
new file mode 100644
index 000000000..ca16780bd
--- /dev/null
+++ b/sdk/tests/fsm-action-params.test.ts
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fsm-action-params.test.ts
+ * @brief A state hook / BT leaf may carry declared parameters instead of the
+ * canonical string — the same reference shape an event wire uses, so a
+ * declaration written once serves all three authoring surfaces.
+ */
+import { beforeEach, describe, expect, it } from 'vitest';
+import { AiRegistry, type AiParams } from '../src/ai/fsm/registry';
+import { Blackboard } from '../src/ai/fsm/Blackboard';
+import { compileFsm, createFsmRunState, stepFsm } from '../src/ai/fsm/FsmRunner';
+import { setStateHook } from '../src/ai/fsm/fsmGraph';
+import { actionRefParams } from '../src/ai/fsm/types';
+import type { FsmDefinition } from '../src/ai/fsm/types';
+import { tickBt, createBtRunState } from '../src/ai/bt/BtRunner';
+import type { BtDefinition } from '../src/ai/bt/types';
+
+let seen: Array<{ arg?: string; params?: AiParams }>;
+let reg: AiRegistry<{ tag: string }>;
+const ctx = { tag: 'ctx' };
+
+beforeEach(() => {
+ seen = [];
+ reg = new AiRegistry<{ tag: string }>();
+ reg.registerAction('ui.setPage', {
+ params: [{ name: 'controller', type: 'enum' }, { name: 'page', type: 'enum' }],
+ run: (_c, _b, arg, params) => { seen.push({ arg, params }); },
+ });
+});
+
+const fsmWith = (hook: unknown): FsmDefinition =>
+ ({ initial: 'A', states: [{ name: 'A', onEnter: hook }] }) as FsmDefinition;
+
+describe('an FSM hook authored with parameters', () => {
+ it('reaches the action as parameters AND as the canonical string', () => {
+ const fsm = compileFsm(fsmWith({ name: 'ui.setPage', params: { controller: 'tabs', page: 'home' } }));
+ stepFsm(fsm, createFsmRunState(fsm), ctx, new Blackboard(), reg);
+
+ expect(seen[0]).toEqual({ arg: 'tabs:home', params: { controller: 'tabs', page: 'home' } });
+ });
+
+ it('a hook authored as a string still parses into parameters', () => {
+ const fsm = compileFsm(fsmWith({ name: 'ui.setPage', arg: 'tabs:home' }));
+ stepFsm(fsm, createFsmRunState(fsm), ctx, new Blackboard(), reg);
+
+ expect(seen[0]!.params).toEqual({ controller: 'tabs', page: 'home' });
+ });
+});
+
+describe('a BT action leaf authored with parameters', () => {
+ it('reaches the action the same way', () => {
+ const bt: BtDefinition = {
+ root: { type: 'action', id: 'a', name: 'ui.setPage', params: { controller: 'tabs', page: 'shop' } },
+ } as BtDefinition;
+
+ tickBt(bt, ctx, new Blackboard(), reg, createBtRunState(), 1 / 60);
+
+ expect(seen[0]).toEqual({ arg: 'tabs:shop', params: { controller: 'tabs', page: 'shop' } });
+ });
+});
+
+describe('setStateHook', () => {
+ const base: FsmDefinition = { initial: 'A', states: [{ name: 'A' }] } as FsmDefinition;
+
+ it('keeps a bare name a bare string — the shorthand most hooks use', () => {
+ const next = setStateHook(base, 'A', 'onEnter', 'timeline.play');
+ expect(next.states[0].onEnter).toBe('timeline.play');
+ });
+
+ it('stores parameters when given them, and drops the string form', () => {
+ const next = setStateHook(base, 'A', 'onEnter', 'ui.setPage', 'stale:value', { controller: 'tabs', page: 'home' });
+ expect(next.states[0].onEnter).toEqual({ name: 'ui.setPage', params: { controller: 'tabs', page: 'home' } });
+ expect(actionRefParams(next.states[0].onEnter)).toEqual({ controller: 'tabs', page: 'home' });
+ });
+
+ it('falls back to the string when the parameter record is empty', () => {
+ const next = setStateHook(base, 'A', 'onEnter', 'spriteAnim.play', 'run.esanim', {});
+ expect(next.states[0].onEnter).toEqual({ name: 'spriteAnim.play', arg: 'run.esanim' });
+ });
+
+ it('clearing the name clears the hook', () => {
+ const withHook = setStateHook(base, 'A', 'onEnter', 'ui.setPage', undefined, { controller: 'tabs' });
+ expect(setStateHook(withHook, 'A', 'onEnter', '').states[0].onEnter).toBeUndefined();
+ });
+});