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.

refactor(sdk): shared stateGraph core behind fsmGraph and animatorGraph

esenginee131bb32061b
diff --git a/examples/enemy-ai/assets/scenes/main.esscene.meta b/examples/enemy-ai/assets/scenes/main.esscene.meta
new file mode 100644
index 000000000..04734672c
--- /dev/null
+++ b/examples/enemy-ai/assets/scenes/main.esscene.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "3914f3e6-ab5b-4597-b6b3-37f6ae355c3d",
+ "version": "2.0",
+ "type": "scene",
+ "importer": {
+ "autoMigrate": true
+ }
+}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 5c263c91a..55dcf0018 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -306,13 +306,9 @@ currentState: string
enabled: boolean
```
-## AnimatorEdge — interface
+## AnimatorEdge — type
```
-from: string
-id: string
-index: number
-to: string
-transition: AnimatorTransition
+GraphEdge<AnimatorTransition>
```
## AnimatorEvalResult — interface
@@ -2728,13 +2724,9 @@ initial: string
states: FsmState[]
```
-## FsmEdge — interface
+## FsmEdge — type
```
-from: string
-id: string
-index: number
-to: string
-transition: FsmTransition
+GraphEdge<FsmTransition>
```
## FsmPlugin — class
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index bf6f015b0..73d530b56 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -301,13 +301,9 @@ currentState: string
enabled: boolean
```
-## AnimatorEdge — interface
+## AnimatorEdge — type
```
-from: string
-id: string
-index: number
-to: string
-transition: AnimatorTransition
+GraphEdge<AnimatorTransition>
```
## AnimatorEvalResult — interface
@@ -2723,13 +2719,9 @@ initial: string
states: FsmState[]
```
-## FsmEdge — interface
+## FsmEdge — type
```
-from: string
-id: string
-index: number
-to: string
-transition: FsmTransition
+GraphEdge<FsmTransition>
```
## FsmPlugin — class
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 416693810..ff83ad860 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -301,13 +301,9 @@ currentState: string
enabled: boolean
```
-## AnimatorEdge — interface
+## AnimatorEdge — type
```
-from: string
-id: string
-index: number
-to: string
-transition: AnimatorTransition
+GraphEdge<AnimatorTransition>
```
## AnimatorEvalResult — interface
@@ -2723,13 +2719,9 @@ initial: string
states: FsmState[]
```
-## FsmEdge — interface
+## FsmEdge — type
```
-from: string
-id: string
-index: number
-to: string
-transition: FsmTransition
+GraphEdge<FsmTransition>
```
## FsmPlugin — class
diff --git a/sdk/src/ai/fsm/fsmGraph.ts b/sdk/src/ai/fsm/fsmGraph.ts
index ccb30c3cc..35bea0f49 100644
--- a/sdk/src/ai/fsm/fsmGraph.ts
+++ b/sdk/src/ai/fsm/fsmGraph.ts
@@ -4,35 +4,37 @@
* @file fsmGraph.ts
* @brief Immutable graph operations on an FsmDefinition — the editor's model.
*
- * Pure functions returning new definitions (never mutating), so the transition-
- * graph editor drives them through AssetDocument.edit for free undo, mirroring
- * how the material editor calls the SDK's materialGraph ops. Since a `.esfsm`
- * IS the runtime definition (states carry optional x/y layout the interpreter
- * ignores), there is no separate editor model to compile.
+ * The structural graph algorithms live in the shared `stateGraph` core; this
+ * module binds them to the `.esfsm` shape (`initial`, optional transition lists,
+ * bare `{to}` transitions) and adds the FSM-only state-hook op. A `.esfsm` IS
+ * the runtime definition (states carry optional x/y layout the interpreter
+ * ignores), so there is no separate editor model to compile.
*/
import type { FsmDefinition, FsmState, FsmTransition } from './types';
+import {
+ type GraphSpec, type GraphEdge,
+ graphEdges, addGraphState, removeGraphState, moveGraphState, renameGraphState,
+ setGraphInitial, addGraphTransition, removeGraphTransition, updateGraphTransition,
+} from '../../stateGraph';
/** A flattened transition edge, for the graph canvas. */
-export interface FsmEdge {
- /** Stable id `from->to#index`. */
- id: string;
- from: string;
- to: string;
- /** Index of this transition within `from`'s transition list. */
- index: number;
- transition: FsmTransition;
-}
+export type FsmEdge = GraphEdge<FsmTransition>;
+
+const spec: GraphSpec<FsmDefinition, FsmState, FsmTransition> = {
+ states: def => def.states,
+ withStates: (def, states) => ({ ...def, states }),
+ initial: def => def.initial,
+ withInitial: (def, initial) => ({ ...def, initial }),
+ transitions: state => state.transitions ?? [],
+ withTransitions: (state, transitions) => ({ ...state, transitions }),
+ makeState: (name, x, y) => ({ name, x, y }),
+ makeTransition: to => ({ to }),
+};
/** Flatten every state's outgoing transitions into addressable edges. */
export function fsmEdges(def: FsmDefinition): FsmEdge[] {
- const edges: FsmEdge[] = [];
- for (const s of def.states) {
- (s.transitions ?? []).forEach((transition, index) => {
- edges.push({ id: `${s.name}->${transition.to}#${index}`, from: s.name, to: transition.to, index, transition });
- });
- }
- return edges;
+ return graphEdges(spec, def);
}
/** A blank machine with one initial state. */
@@ -41,78 +43,31 @@ export function emptyFsm(): FsmDefinition {
}
export function addState(def: FsmDefinition, name: string, x = 0, y = 0): FsmDefinition {
- if (def.states.some(s => s.name === name)) return def;
- const state: FsmState = { name, x, y };
- return {
- ...def,
- states: [...def.states, state],
- // The first state added to an empty machine becomes the initial one.
- initial: def.states.length === 0 ? name : def.initial,
- };
+ return addGraphState(spec, def, name, x, y);
}
export function removeState(def: FsmDefinition, name: string): FsmDefinition {
- const states = def.states
- .filter(s => s.name !== name)
- .map(s => (s.transitions?.some(t => t.to === name)
- ? { ...s, transitions: s.transitions.filter(t => t.to !== name) }
- : s));
- const initial = def.initial === name ? (states[0]?.name ?? '') : def.initial;
- return { ...def, states, initial };
+ return removeGraphState(spec, def, name);
}
export function moveState(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition {
- return { ...def, states: def.states.map(s => (s.name === name ? { ...s, x, y } : s)) };
+ return moveGraphState(spec, def, name, x, y);
}
-/** Rename a state, rewiring `initial` and every transition that targets it. */
export function renameState(def: FsmDefinition, oldName: string, newName: string): FsmDefinition {
- if (oldName === newName || !newName) return def;
- if (def.states.some(s => s.name === newName)) return def;
- const states = def.states.map(s => {
- let ns = s.name === oldName ? { ...s, name: newName } : s;
- if (ns.transitions?.some(t => t.to === oldName)) {
- ns = { ...ns, transitions: ns.transitions.map(t => (t.to === oldName ? { ...t, to: newName } : t)) };
- }
- return ns;
- });
- return { ...def, states, initial: def.initial === oldName ? newName : def.initial };
-}
-
-export function setStateHook(
- def: FsmDefinition,
- name: string,
- hook: 'onEnter' | 'onUpdate' | 'onExit',
- action: string,
- arg?: string,
-): FsmDefinition {
- const ref = action ? (arg ? { name: action, arg } : action) : undefined;
- return {
- ...def,
- states: def.states.map(s => (s.name === name ? { ...s, [hook]: ref } : s)),
- };
+ return renameGraphState(spec, def, oldName, newName);
}
export function setInitial(def: FsmDefinition, name: string): FsmDefinition {
- return def.states.some(s => s.name === name) ? { ...def, initial: name } : def;
+ return setGraphInitial(spec, def, name);
}
export function addTransition(def: FsmDefinition, from: string, to: string): FsmDefinition {
- return {
- ...def,
- states: def.states.map(s => (s.name === from
- ? { ...s, transitions: [...(s.transitions ?? []), { to }] }
- : s)),
- };
+ return addGraphTransition(spec, def, from, to);
}
export function removeTransition(def: FsmDefinition, from: string, index: number): FsmDefinition {
- return {
- ...def,
- states: def.states.map(s => (s.name === from && s.transitions
- ? { ...s, transitions: s.transitions.filter((_, i) => i !== index) }
- : s)),
- };
+ return removeGraphTransition(spec, def, from, index);
}
export function updateTransition(
@@ -121,10 +76,19 @@ export function updateTransition(
index: number,
patch: Partial<FsmTransition>,
): FsmDefinition {
+ return updateGraphTransition(spec, def, from, index, patch);
+}
+
+export function setStateHook(
+ def: FsmDefinition,
+ name: string,
+ hook: 'onEnter' | 'onUpdate' | 'onExit',
+ action: string,
+ arg?: string,
+): FsmDefinition {
+ const ref = action ? (arg ? { name: action, arg } : action) : undefined;
return {
...def,
- states: def.states.map(s => (s.name === from && s.transitions
- ? { ...s, transitions: s.transitions.map((t, i) => (i === index ? { ...t, ...patch } : t)) }
- : s)),
+ states: def.states.map(s => (s.name === name ? { ...s, [hook]: ref } : s)),
};
}
diff --git a/sdk/src/animation/animatorGraph.ts b/sdk/src/animation/animatorGraph.ts
index 6816e0b4e..01d96524f 100644
--- a/sdk/src/animation/animatorGraph.ts
+++ b/sdk/src/animation/animatorGraph.ts
@@ -2,148 +2,133 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file animatorGraph.ts
- * @brief Immutable graph operations on an AnimatorControllerDef — the animation
- * controller editor's model.
+ * @brief Immutable graph operations on an AnimatorControllerDef — the
+ * animation controller editor's model.
*
- * Pure functions returning new definitions (never mutating), so the state-graph
- * editor drives them through AssetDocument.edit for free undo, mirroring
- * fsmGraph.ts. An `.esanimator` payload IS the runtime AnimatorControllerDef
- * (states carry optional x/y layout the interpreter ignores), so there is no
- * separate editor model to compile.
+ * The structural graph algorithms live in the shared `stateGraph` core; this
+ * module binds them to the `.esanimator` shape (`initialState`, required
+ * transition lists, `{to, conditions}` transitions) and adds the animator-only
+ * ops (motion/props on a state, condition editing, parameters, and the
+ * any-state transition rewiring on rename). An `.esanimator` payload IS the
+ * runtime AnimatorControllerDef, so there is no separate editor model.
*/
import type {
- AnimatorControllerDef,
- AnimatorState,
- AnimatorTransition,
- AnimatorCondition,
- AnimatorParam,
- AnimatorParamType,
+ AnimatorControllerDef,
+ AnimatorState,
+ AnimatorTransition,
+ AnimatorCondition,
+ AnimatorParam,
+ AnimatorParamType,
} from './Animator';
+import {
+ type GraphSpec, type GraphEdge,
+ graphEdges, addGraphState, removeGraphState, moveGraphState, renameGraphState,
+ setGraphInitial, addGraphTransition, removeGraphTransition, updateGraphTransition,
+} from '../stateGraph';
/** A flattened transition edge, for the graph canvas. */
-export interface AnimatorEdge {
- /** Stable id `from->to#index`. */
- id: string;
- from: string;
- to: string;
- index: number;
- transition: AnimatorTransition;
-}
+export type AnimatorEdge = GraphEdge<AnimatorTransition>;
+
+const spec: GraphSpec<AnimatorControllerDef, AnimatorState, AnimatorTransition> = {
+ states: def => def.states,
+ withStates: (def, states) => ({ ...def, states }),
+ initial: def => def.initialState,
+ withInitial: (def, initialState) => ({ ...def, initialState }),
+ transitions: state => state.transitions,
+ withTransitions: (state, transitions) => ({ ...state, transitions }),
+ makeState: (name, x, y) => ({ name, x, y, transitions: [] }),
+ makeTransition: to => ({ to, conditions: [] }),
+};
/** Flatten every state's outgoing transitions into addressable edges. */
export function animatorEdges(def: AnimatorControllerDef): AnimatorEdge[] {
- const edges: AnimatorEdge[] = [];
- for (const s of def.states) {
- s.transitions.forEach((transition, index) => {
- edges.push({ id: `${s.name}->${transition.to}#${index}`, from: s.name, to: transition.to, index, transition });
- });
- }
- return edges;
+ return graphEdges(spec, def);
}
/** A blank controller with one initial state and no parameters. */
export function emptyAnimatorController(): AnimatorControllerDef {
- return { parameters: [], states: [{ name: 'Idle', x: 80, y: 80, transitions: [] }], initialState: 'Idle' };
+ return { parameters: [], states: [{ name: 'Idle', x: 80, y: 80, transitions: [] }], initialState: 'Idle' };
}
export function addState(def: AnimatorControllerDef, name: string, x = 0, y = 0): AnimatorControllerDef {
- if (def.states.some((s) => s.name === name)) return def;
- const state: AnimatorState = { name, x, y, transitions: [] };
- return {
- ...def,
- states: [...def.states, state],
- // The first state added to an empty machine becomes the initial one.
- initialState: def.states.length === 0 ? name : def.initialState,
- };
+ return addGraphState(spec, def, name, x, y);
}
export function removeState(def: AnimatorControllerDef, name: string): AnimatorControllerDef {
- const states = def.states
- .filter((s) => s.name !== name)
- .map((s) => (s.transitions.some((t) => t.to === name) ? { ...s, transitions: s.transitions.filter((t) => t.to !== name) } : s));
- const initialState = def.initialState === name ? (states[0]?.name ?? '') : def.initialState;
- return { ...def, states, initialState };
+ return removeGraphState(spec, def, name);
}
export function moveState(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef {
- return { ...def, states: def.states.map((s) => (s.name === name ? { ...s, x, y } : s)) };
+ return moveGraphState(spec, def, name, x, y);
}
-/** Rename a state, rewiring `initialState` and every transition that targets it. */
+/**
+ * Rename a state. On top of the shared rewiring (initial + per-state transition
+ * targets) an animator also has any-state transitions to repoint.
+ */
export function renameState(def: AnimatorControllerDef, oldName: string, newName: string): AnimatorControllerDef {
- if (oldName === newName || !newName) return def;
- if (def.states.some((s) => s.name === newName)) return def;
- const rewire = (ts: AnimatorTransition[]) => ts.map((t) => (t.to === oldName ? { ...t, to: newName } : t));
- const states = def.states.map((s) => {
- const ns = s.name === oldName ? { ...s, name: newName } : s;
- return ns.transitions.some((t) => t.to === oldName) ? { ...ns, transitions: rewire(ns.transitions) } : ns;
- });
- return {
- ...def,
- states,
- initialState: def.initialState === oldName ? newName : def.initialState,
- ...(def.anyStateTransitions ? { anyStateTransitions: rewire(def.anyStateTransitions) } : {}),
- };
+ const next = renameGraphState(spec, def, oldName, newName);
+ if (next === def || !def.anyStateTransitions) return next;
+ return {
+ ...next,
+ anyStateTransitions: def.anyStateTransitions.map(t => (t.to === oldName ? { ...t, to: newName } : t)),
+ };
}
export function setInitial(def: AnimatorControllerDef, name: string): AnimatorControllerDef {
- return def.states.some((s) => s.name === name) ? { ...def, initialState: name } : def;
+ return setGraphInitial(spec, def, name);
}
/** Set the state's motion to a single sprite clip (clears blend/spine/nested). */
export function setStateClip(def: AnimatorControllerDef, name: string, clip: string): AnimatorControllerDef {
- return {
- ...def,
- states: def.states.map((s) =>
- s.name === name
- ? { name: s.name, x: s.x, y: s.y, transitions: s.transitions, speed: s.speed, loop: s.loop, ...(clip ? { clip } : {}) }
- : s,
- ),
- };
+ return {
+ ...def,
+ states: def.states.map((s) =>
+ s.name === name
+ ? { name: s.name, x: s.x, y: s.y, transitions: s.transitions, speed: s.speed, loop: s.loop, ...(clip ? { clip } : {}) }
+ : s,
+ ),
+ };
}
export function setStateProps(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean }): AnimatorControllerDef {
- return { ...def, states: def.states.map((s) => (s.name === name ? { ...s, ...patch } : s)) };
+ return { ...def, states: def.states.map((s) => (s.name === name ? { ...s, ...patch } : s)) };
}
export function addTransition(def: AnimatorControllerDef, from: string, to: string): AnimatorControllerDef {
- return {
- ...def,
- states: def.states.map((s) => (s.name === from ? { ...s, transitions: [...s.transitions, { to, conditions: [] }] } : s)),
- };
+ return addGraphTransition(spec, def, from, to);
}
export function removeTransition(def: AnimatorControllerDef, from: string, index: number): AnimatorControllerDef {
- return {
- ...def,
- states: def.states.map((s) => (s.name === from ? { ...s, transitions: s.transitions.filter((_, i) => i !== index) } : s)),
- };
+ return removeGraphTransition(spec, def, from, index);
}
-export function updateTransition(def: AnimatorControllerDef, from: string, index: number, patch: Partial<AnimatorTransition>): AnimatorControllerDef {
- return {
- ...def,
- states: def.states.map((s) => (s.name === from ? { ...s, transitions: s.transitions.map((t, i) => (i === index ? { ...t, ...patch } : t)) } : s)),
- };
+export function updateTransition(
+ def: AnimatorControllerDef,
+ from: string,
+ index: number,
+ patch: Partial<AnimatorTransition>,
+): AnimatorControllerDef {
+ return updateGraphTransition(spec, def, from, index, patch);
}
/** Replace the whole condition list on a transition. */
export function setConditions(def: AnimatorControllerDef, from: string, index: number, conditions: AnimatorCondition[]): AnimatorControllerDef {
- return updateTransition(def, from, index, { conditions });
+ return updateTransition(def, from, index, { conditions });
}
// — Parameters —
export function addParam(def: AnimatorControllerDef, name: string, type: AnimatorParamType): AnimatorControllerDef {
- if (!name || def.parameters.some((p) => p.name === name)) return def;
- return { ...def, parameters: [...def.parameters, { name, type }] };
+ if (!name || def.parameters.some((p) => p.name === name)) return def;
+ return { ...def, parameters: [...def.parameters, { name, type }] };
}
export function removeParam(def: AnimatorControllerDef, name: string): AnimatorControllerDef {
- return { ...def, parameters: def.parameters.filter((p) => p.name !== name) };
+ return { ...def, parameters: def.parameters.filter((p) => p.name !== name) };
}
export function updateParam(def: AnimatorControllerDef, name: string, patch: Partial<AnimatorParam>): AnimatorControllerDef {
- return { ...def, parameters: def.parameters.map((p) => (p.name === name ? { ...p, ...patch } : p)) };
+ return { ...def, parameters: def.parameters.map((p) => (p.name === name ? { ...p, ...patch } : p)) };
}
diff --git a/sdk/src/stateGraph.ts b/sdk/src/stateGraph.ts
new file mode 100644
index 000000000..3db030e6c
--- /dev/null
+++ b/sdk/src/stateGraph.ts
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file stateGraph.ts
+ * @brief Generic immutable ops over a named-state transition graph — the one
+ * core behind fsmGraph.ts and animatorGraph.ts.
+ *
+ * Both an `.esfsm` and an `.esanimator` are the same shape: a set of named
+ * states (each with optional x/y editor layout and outgoing transitions) plus
+ * one initial state. Only the field spelling (`initial` vs `initialState`),
+ * whether the transition list is optional, and the transition payload differ —
+ * and those are supplied per format through a {@link GraphSpec}, so the graph
+ * algorithms (add/remove/move/rename state, set-initial, add/remove/update
+ * transition, edge flattening) live here once instead of being copied.
+ *
+ * Every op returns a new definition (never mutating) so the editors drive them
+ * through AssetDocument.edit for free undo.
+ */
+
+export interface GraphState {
+ name: string;
+ /** Editor-only canvas position; the interpreter ignores it. */
+ x?: number;
+ y?: number;
+}
+
+export interface GraphTransition {
+ to: string;
+}
+
+/** A flattened transition edge, for the graph canvas. */
+export interface GraphEdge<T extends GraphTransition> {
+ /** Stable id `from->to#index`. */
+ id: string;
+ from: string;
+ to: string;
+ /** Index of this transition within `from`'s transition list. */
+ index: number;
+ transition: T;
+}
+
+/** Per-format adapter: how to read and rebuild a graph's states, initial, and transitions. */
+export interface GraphSpec<TDef, TState extends GraphState, TTransition extends GraphTransition> {
+ states(def: TDef): TState[];
+ withStates(def: TDef, states: TState[]): TDef;
+ initial(def: TDef): string;
+ withInitial(def: TDef, name: string): TDef;
+ /** Read a state's outgoing transitions (normalizing an optional list to `[]`). */
+ transitions(state: TState): TTransition[];
+ withTransitions(state: TState, transitions: TTransition[]): TState;
+ makeState(name: string, x: number, y: number): TState;
+ makeTransition(to: string): TTransition;
+}
+
+export function graphEdges<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+): GraphEdge<T>[] {
+ const edges: GraphEdge<T>[] = [];
+ for (const s of spec.states(def)) {
+ spec.transitions(s).forEach((transition, index) => {
+ edges.push({ id: `${s.name}->${transition.to}#${index}`, from: s.name, to: transition.to, index, transition });
+ });
+ }
+ return edges;
+}
+
+export function addGraphState<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+ name: string,
+ x = 0,
+ y = 0,
+): D {
+ const states = spec.states(def);
+ if (states.some(s => s.name === name)) return def;
+ const next = spec.withStates(def, [...states, spec.makeState(name, x, y)]);
+ // The first state added to an empty graph becomes the initial one.
+ return states.length === 0 ? spec.withInitial(next, name) : next;
+}
+
+export function removeGraphState<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+ name: string,
+): D {
+ const kept = spec.states(def)
+ .filter(s => s.name !== name)
+ .map(s => (spec.transitions(s).some(t => t.to === name)
+ ? spec.withTransitions(s, spec.transitions(s).filter(t => t.to !== name))
+ : s));
+ const next = spec.withStates(def, kept);
+ return spec.initial(def) === name ? spec.withInitial(next, kept[0]?.name ?? '') : next;
+}
+
+export function moveGraphState<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+ name: string,
+ x: number,
+ y: number,
+): D {
+ return spec.withStates(def, spec.states(def).map(s => (s.name === name ? { ...s, x, y } : s)));
+}
+
+/** Rename a state, rewiring `initial` and every state transition that targets it. */
+export function renameGraphState<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+ oldName: string,
+ newName: string,
+): D {
+ if (oldName === newName || !newName) return def;
+ const states = spec.states(def);
+ if (states.some(s => s.name === newName)) return def;
+ const renamed = states.map(s => {
+ const ns = s.name === oldName ? { ...s, name: newName } : s;
+ return spec.transitions(ns).some(t => t.to === oldName)
+ ? spec.withTransitions(ns, spec.transitions(ns).map(t => (t.to === oldName ? { ...t, to: newName } : t)))
+ : ns;
+ });
+ const next = spec.withStates(def, renamed);
+ return spec.initial(def) === oldName ? spec.withInitial(next, newName) : next;
+}
+
+export function setGraphInitial<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+ name: string,
+): D {
+ return spec.states(def).some(s => s.name === name) ? spec.withInitial(def, name) : def;
+}
+
+export function addGraphTransition<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+ from: string,
+ to: string,
+): D {
+ return spec.withStates(def, spec.states(def).map(s => (s.name === from
+ ? spec.withTransitions(s, [...spec.transitions(s), spec.makeTransition(to)])
+ : s)));
+}
+
+export function removeGraphTransition<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+ from: string,
+ index: number,
+): D {
+ return spec.withStates(def, spec.states(def).map(s => (s.name === from
+ ? spec.withTransitions(s, spec.transitions(s).filter((_, i) => i !== index))
+ : s)));
+}
+
+export function updateGraphTransition<D, S extends GraphState, T extends GraphTransition>(
+ spec: GraphSpec<D, S, T>,
+ def: D,
+ from: string,
+ index: number,
+ patch: Partial<T>,
+): D {
+ return spec.withStates(def, spec.states(def).map(s => (s.name === from
+ ? spec.withTransitions(s, spec.transitions(s).map((t, i) => (i === index ? { ...t, ...patch } : t)))
+ : s)));
+}
diff --git a/sdk/tests/animator-graph.test.ts b/sdk/tests/animator-graph.test.ts
new file mode 100644
index 000000000..fc8883ad2
--- /dev/null
+++ b/sdk/tests/animator-graph.test.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+// Locks the .esanimator graph ops after they were refactored onto the shared
+// `stateGraph` core — the structural algorithms are shared with fsmGraph, but
+// the animator keeps required transition lists, `{to, conditions}` payloads,
+// parameters, and any-state transition rewiring on rename.
+import { describe, it, expect } from 'vitest';
+import {
+ emptyAnimatorController, animatorEdges,
+ addState, removeState, moveState, renameState, setInitial,
+ addTransition, removeTransition, updateTransition, setConditions,
+ addParam, removeParam, updateParam,
+} from '../src/animation/animatorGraph';
+import type { AnimatorControllerDef } from '../src/animation/Animator';
+
+describe('animatorGraph', () => {
+ it('creates a blank controller with one initial state and no params', () => {
+ const def = emptyAnimatorController();
+ expect(def.initialState).toBe('Idle');
+ expect(def.states).toEqual([{ name: 'Idle', x: 80, y: 80, transitions: [] }]);
+ expect(def.parameters).toEqual([]);
+ });
+
+ it('adds states immutably; first state of an empty graph becomes initial', () => {
+ const empty: AnimatorControllerDef = { parameters: [], states: [], initialState: '' };
+ const one = addState(empty, 'Run', 10, 20);
+ expect(one).not.toBe(empty);
+ expect(one.initialState).toBe('Run');
+ expect(one.states[0]).toEqual({ name: 'Run', x: 10, y: 20, transitions: [] });
+ // duplicate is ignored
+ expect(addState(one, 'Run')).toBe(one);
+ });
+
+ it('removes a state and prunes transitions that target it, reassigning initial', () => {
+ let def = emptyAnimatorController();
+ def = addState(def, 'Run');
+ def = addTransition(def, 'Run', 'Idle');
+ def = removeState(def, 'Idle');
+ expect(def.states.map(s => s.name)).toEqual(['Run']);
+ expect(def.states[0].transitions).toEqual([]);
+ expect(def.initialState).toBe('Run');
+ });
+
+ it('creates transitions with an empty condition list and updates them', () => {
+ let def = emptyAnimatorController();
+ def = addState(def, 'Run');
+ def = addTransition(def, 'Idle', 'Run');
+ expect(def.states[0].transitions).toEqual([{ to: 'Run', conditions: [] }]);
+ def = setConditions(def, 'Idle', 0, [{ param: 'Speed', op: 'gt', value: 0.1 }]);
+ expect(def.states[0].transitions[0].conditions).toHaveLength(1);
+ def = updateTransition(def, 'Idle', 0, { hasExitTime: true });
+ expect(def.states[0].transitions[0].hasExitTime).toBe(true);
+ def = removeTransition(def, 'Idle', 0);
+ expect(def.states[0].transitions).toEqual([]);
+ });
+
+ it('renames a state, rewiring initial, state transitions AND any-state transitions', () => {
+ let def = emptyAnimatorController();
+ def = addState(def, 'Run');
+ def = addTransition(def, 'Run', 'Idle');
+ def = { ...def, anyStateTransitions: [{ to: 'Idle', conditions: [] }] };
+ def = renameState(def, 'Idle', 'Base');
+ expect(def.initialState).toBe('Base');
+ expect(def.states.find(s => s.name === 'Run')!.transitions[0].to).toBe('Base');
+ expect(def.anyStateTransitions![0].to).toBe('Base');
+ });
+
+ it('moves a state and sets initial only to an existing state', () => {
+ let def = addState(emptyAnimatorController(), 'Run', 0, 0);
+ def = moveState(def, 'Run', 40, 50);
+ expect(def.states.find(s => s.name === 'Run')).toMatchObject({ x: 40, y: 50 });
+ expect(setInitial(def, 'Nope')).toBe(def);
+ expect(setInitial(def, 'Run').initialState).toBe('Run');
+ });
+
+ it('manages parameters', () => {
+ let def = emptyAnimatorController();
+ def = addParam(def, 'Speed', 'float');
+ expect(def.parameters).toEqual([{ name: 'Speed', type: 'float' }]);
+ expect(addParam(def, 'Speed', 'int')).toBe(def); // duplicate ignored
+ def = updateParam(def, 'Speed', { type: 'int' });
+ expect(def.parameters[0].type).toBe('int');
+ def = removeParam(def, 'Speed');
+ expect(def.parameters).toEqual([]);
+ });
+
+ it('flattens transitions into addressable edges', () => {
+ let def = emptyAnimatorController();
+ def = addState(def, 'Run');
+ def = addTransition(def, 'Idle', 'Run');
+ const edges = animatorEdges(def);
+ expect(edges).toHaveLength(1);
+ expect(edges[0]).toMatchObject({ id: 'Idle->Run#0', from: 'Idle', to: 'Run', index: 0 });
+ });
+});