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(editor): behavior-tree editor + generic node-graph canvas
esenginefee69880a79b
diff --git a/desktop/src/bt/BtDocument.ts b/desktop/src/bt/BtDocument.tsnew file mode 100644index 000000000..1bb5c29ab--- /dev/null+++ b/desktop/src/bt/BtDocument.ts@@ -0,0 +1,25 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file BtDocument.ts+ * @brief Reactive, undoable document for a `.esbt` — the behavior-tree editor's model.+ * Same AssetDocument contract as FsmGraphDocument; edits go through the pure+ * SDK btGraph ops via {@link edit}. A `.esbt` IS the runtime BtDefinition+ * (nodes carry editor-only id/x/y the interpreter ignores) — no compile step.+ */+import type { BtDefinition } from 'esengine';+import { AssetDocument } from '@/document/AssetDocument';++class BtDocumentImpl extends AssetDocument<BtDefinition> {+ open(def: BtDefinition, filePath: string | null): void {+ this.openAsset(def, filePath);+ }+ openJson(raw: unknown, filePath: string | null): void {+ this.open(raw as BtDefinition, filePath);+ }+ close(): void {+ this.closeAsset();+ }+}++export const BtDocument = new BtDocumentImpl();diff --git a/desktop/src/bt/openBehaviorTree.ts b/desktop/src/bt/openBehaviorTree.tsnew file mode 100644index 000000000..fb55ab06e--- /dev/null+++ b/desktop/src/bt/openBehaviorTree.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file openBehaviorTree.ts+ * @brief Open / create a `.esbt` (the visual behavior tree, AI3). A `.esbt` IS+ * the runtime BtDefinition, so there is no compile step — Save writes JSON.+ */+import { emptyBt, ensureBtIds, type BtDefinition } from 'esengine';+import { BtDocument } from './BtDocument';+import { ProjectStore } from '@/project/ProjectStore';+import { dockApi } from '@/layout/dockApi';+import { baseName } from '@/project/assetMeta';+import { Toasts } from '@/store/Toasts';++export async function openBehaviorTree(path: string): Promise<void> {+ try {+ const text = await window.estella.fs.read(path);+ // Hand-written trees may lack editor ids; assign before editing.+ BtDocument.openJson(ensureBtIds(JSON.parse(text) as BtDefinition), path);+ dockApi.openDocument('behaviortree', 'behaviortree', 'Behavior Tree');+ } catch (e) {+ Toasts.push(`无法打开行为树:${String(e)}`, 'error');+ }+}++export async function createBehaviorTree(dir: string): Promise<void> {+ const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';+ let rel = `${folder}NewBehaviorTree.esbt`;+ for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${folder}NewBehaviorTree-${n}.esbt`;++ const def = emptyBt();+ try {+ await window.estella.fs.write(rel, JSON.stringify(def, null, 2) + '\n');+ await window.estella.fs.write(+ rel + '.meta',+ JSON.stringify({ uuid: crypto.randomUUID(), version: '1.0', type: 'behaviortree', importer: { autoMigrate: true } }, null, 2) + '\n',+ );+ } catch (e) {+ Toasts.push(`创建行为树失败:${String(e)}`, 'error');+ return;+ }+ await ProjectStore.refreshAssets();+ Toasts.push(`已创建行为树:${baseName(rel)}`, 'info');+ await openBehaviorTree(rel);+}diff --git a/desktop/src/layout/DockLayout.tsx b/desktop/src/layout/DockLayout.tsxindex 72c91c779..98577cebf 100644--- a/desktop/src/layout/DockLayout.tsx+++ b/desktop/src/layout/DockLayout.tsx@@ -19,6 +19,7 @@ import { TilesetEditor } from '@/panels/TilesetEditor';import { TilemapPainter } from '@/panels/TilemapPainter';import { MaterialGraphEditor } from '@/panels/MaterialGraphEditor';import { StateMachineEditor } from '@/panels/StateMachineEditor';+import { BtTreeEditor } from '@/panels/BtTreeEditor';import { ProfilerPanel } from '@/panels/ProfilerPanel';import { Perf } from '@/components/Perf';import { dockApi } from '@/layout/dockApi';@@ -37,6 +38,7 @@ const components: Record<string, FC<IDockviewPanelProps>> = {tilemap: () => panel('tilemap', <TilemapPainter />),materialgraph: () => panel('materialgraph', <MaterialGraphEditor />),statemachine: () => panel('statemachine', <StateMachineEditor />),+ behaviortree: () => panel('behaviortree', <BtTreeEditor />),profiler: () => <ProfilerPanel />,// The "Game" view (isolated play realm) — added on Play, removed on Stop.game: () => panel('game', <GamePanel />),diff --git a/desktop/src/panels/BtTreeEditor.tsx b/desktop/src/panels/BtTreeEditor.tsxnew file mode 100644index 000000000..a83dccc8a--- /dev/null+++ b/desktop/src/panels/BtTreeEditor.tsx@@ -0,0 +1,209 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file BtTreeEditor.tsx+ * @brief The `.esbt` behavior-tree editor — nodes on the shared NodeGraphCanvas,+ * parent/child edges. All mutation goes through the pure, tested SDK+ * btGraph ops on a reactive BtDocument (one undo step each). A `.esbt` IS+ * the runtime BtDefinition, so Save just writes JSON — no compile step.+ *+ * Uses the generic <NodeGraphCanvas> (shared with StateMachineEditor):+ * drag-to-connect reparents a node under the drop target.+ */+import { useRef, useState, useSyncExternalStore, type CSSProperties } from 'react';+import { Trash2, Save } from 'lucide-react';+import {+ btNodes, btEdges, addBtChild, removeBtNode, moveBtNode, setBtNodeField, reparentBtNode,+ canHaveChildren, aiRegistry,+ type BtNode, type BtNodeType, type BtDefinition, type BtEdge,+} from 'esengine';+import { BtDocument } from '@/bt/BtDocument';+import { EditorHistory } from '@/engine/EditorHistory';+import { NodeGraphCanvas, type CanvasNode } from '@/panels/NodeGraphCanvas';++type BtCanvasNode = BtNode & CanvasNode;++const NODE_W = 132;+const NODE_H = 46;++const BT_TYPES: Array<{ type: BtNodeType; label: string; cat: 'composite' | 'decorator' | 'leaf' }> = [+ { type: 'sequence', label: 'Sequence', cat: 'composite' },+ { type: 'selector', label: 'Selector', cat: 'composite' },+ { type: 'parallel', label: 'Parallel', cat: 'composite' },+ { type: 'inverter', label: 'Inverter', cat: 'decorator' },+ { type: 'succeeder', label: 'Succeeder', cat: 'decorator' },+ { type: 'repeater', label: 'Repeater', cat: 'decorator' },+ { type: 'wait', label: 'Wait', cat: 'leaf' },+ { type: 'action', label: 'Action', cat: 'leaf' },+ { type: 'condition', label: 'Condition', cat: 'leaf' },+];+const specOf = (t: BtNodeType) => BT_TYPES.find(s => s.type === t)!;+const CAT_COLOR: Record<string, string> = { composite: '#7faf9c', decorator: '#8fa0c4', leaf: '#b0a080' };++function leafSummary(n: BtNode): string {+ switch (n.type) {+ case 'action':+ case 'condition': return n.name || '(unnamed)';+ case 'repeater': return `× ${(n.count ?? 0) || '∞'}`;+ case 'wait': return `${n.seconds ?? 0}s`;+ case 'parallel': return n.policy ?? 'all';+ default: return '';+ }+}++export function BtTreeEditor() {+ useSyncExternalStore(BtDocument.subscribe, BtDocument.getRevision);+ const def = BtDocument.asset;+ const filePath = BtDocument.filePath;+ const dirty = BtDocument.dirty;++ const [selected, setSelected] = useState<string | null>(null);+ const [addType, setAddType] = useState<BtNodeType>('action');+ const dragBefore = useRef<BtDefinition | null>(null);++ if (!def || !filePath) {+ return <div className="panel" style={S.empty}><p>Open a <code>.esbt</code> from the Content Browser to edit it.</p></div>;+ }++ const nodes = btNodes(def).filter((n): n is BtCanvasNode => !!n.id);+ const edges: BtEdge[] = btEdges(def);+ const selNode = selected ? nodes.find(n => n.id === selected) ?? null : null;++ const save = () => {+ void window.estella.fs.write(filePath, JSON.stringify(def, null, 2) + '\n').then(() => BtDocument.markSaved());+ };++ const addChild = (parentId: string, type: BtNodeType) => {+ BtDocument.edit('Add node', d => Object.assign(d, addBtChild(d, parentId, type, 200, 120)));+ };++ const patch = (id: string, p: Partial<BtNode>) =>+ BtDocument.edit('Edit node', d => Object.assign(d, setBtNodeField(d, id, p)));++ const toolbar = (+ <>+ <span style={S.title}>{filePath.split('/').pop()}{dirty && <span style={S.dot} title="Unsaved">●</span>}</span>+ <span style={{ flex: 1 }} />+ {selected && def.root.id !== selected && (+ <button type="button" style={S.btn} title="Delete node"+ onClick={() => { BtDocument.edit('Delete node', d => Object.assign(d, removeBtNode(d, selected))); setSelected(null); }}>+ <Trash2 size={13} strokeWidth={1.9} />+ </button>+ )}+ <button type="button" style={{ ...S.btn, ...S.primary }} disabled={!dirty} onClick={save}>+ <Save size={13} strokeWidth={1.9} /> Save+ </button>+ </>+ );++ return (+ <div style={S.root} data-bt-canvas>+ <div style={S.body}>+ <div style={{ flex: 1, minWidth: 0 }}>+ <NodeGraphCanvas<BtCanvasNode, BtEdge>+ nodes={nodes}+ edges={edges}+ selectedNode={selected}+ selectedEdge={null}+ nodeSize={() => ({ width: NODE_W, height: NODE_H })}+ onSelectNode={setSelected}+ onSelectEdge={() => { /* BT edges are structural; not independently selectable */ }}+ onMoveNodeStart={() => { dragBefore.current = def; }}+ onMoveNode={(id, x, y) => BtDocument.replaceAsset(moveBtNode(def, id, x, y), { dirty: true })}+ onMoveNodeEnd={() => {+ const after = BtDocument.asset;+ const before = dragBefore.current;+ if (after && before) EditorHistory.record('Move node', () => BtDocument.replaceAsset(after), () => BtDocument.replaceAsset(before));+ }}+ onConnect={(from, to) => BtDocument.edit('Reparent', d => Object.assign(d, reparentBtNode(d, to, from)))}+ onDeleteNode={id => { if (def.root.id !== id) { BtDocument.edit('Delete node', d => Object.assign(d, removeBtNode(d, id))); setSelected(null); } }}+ onDeleteEdge={() => { /* structural */ }}+ toolbar={toolbar}+ emptyHint="Drag from a node's handle to another to set parent → child."+ renderNode={(n, sel) => {+ const spec = specOf(n.type);+ return (+ <div style={{ ...S.node, borderColor: sel ? 'var(--accent, #6ea9ff)' : (def.root.id === n.id ? '#c98a93' : CAT_COLOR[spec.cat]) }}>+ <div style={S.nodeType}>{def.root.id === n.id ? '▶ ' : ''}{spec.label}</div>+ <div style={S.nodeSub}>{leafSummary(n)}</div>+ </div>+ );+ }}+ />+ </div>++ {selNode && (+ <div style={S.inspector}>+ <div style={S.inspTitle}>Node</div>+ <label style={S.field}>Type+ <select style={S.input} value={selNode.type} onChange={e => patch(selNode.id, { type: e.target.value as BtNodeType })}>+ {BT_TYPES.map(s => <option key={s.type} value={s.type}>{s.label}</option>)}+ </select>+ </label>++ {(selNode.type === 'action' || selNode.type === 'condition') && (+ <label style={S.field}>Name+ <input style={S.input} list="bt-names" defaultValue={selNode.name ?? ''} key={`${selNode.id}-name`}+ placeholder={selNode.type === 'action' ? 'action name' : 'condition name'}+ onBlur={e => patch(selNode.id, { name: e.target.value.trim() || undefined })} />+ </label>+ )}+ {selNode.type === 'repeater' && (+ <label style={S.field}>Count (0 = forever)+ <input style={S.input} type="number" min={0} defaultValue={selNode.count ?? 0} key={`${selNode.id}-count`}+ onBlur={e => patch(selNode.id, { count: Number(e.target.value) || 0 })} />+ </label>+ )}+ {selNode.type === 'wait' && (+ <label style={S.field}>Seconds+ <input style={S.input} type="number" min={0} step={0.1} defaultValue={selNode.seconds ?? 0} key={`${selNode.id}-sec`}+ onBlur={e => patch(selNode.id, { seconds: Number(e.target.value) || 0 })} />+ </label>+ )}+ {selNode.type === 'parallel' && (+ <label style={S.field}>Success policy+ <select style={S.input} value={selNode.policy ?? 'all'} onChange={e => patch(selNode.id, { policy: e.target.value as 'all' | 'one' })}>+ <option value="all">all children</option>+ <option value="one">any child</option>+ </select>+ </label>+ )}++ {canHaveChildren(selNode.type) && (+ <>+ <div style={S.inspSub}>Add child</div>+ <div style={{ display: 'flex', gap: 4 }}>+ <select style={{ ...S.input, flex: 1 }} value={addType} onChange={e => setAddType(e.target.value as BtNodeType)}>+ {BT_TYPES.map(s => <option key={s.type} value={s.type}>{s.label}</option>)}+ </select>+ <button type="button" style={S.btn} onClick={() => addChild(selNode.id, addType)}>+ Add</button>+ </div>+ </>+ )}+ <datalist id="bt-names">+ {[...aiRegistry.actionNames(), ...aiRegistry.conditionNames()].map(n => <option key={n} value={n} />)}+ </datalist>+ </div>+ )}+ </div>+ </div>+ );+}++const S: Record<string, CSSProperties> = {+ root: { display: 'flex', flexDirection: 'column', height: '100%' },+ empty: { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', opacity: 0.6, fontSize: 13 },+ body: { display: 'flex', flex: 1, minHeight: 0 },+ title: { fontSize: 12, opacity: 0.85 },+ dot: { color: '#e0a03a', marginLeft: 4 },+ btn: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 8px', fontSize: 12, borderRadius: 4, border: '1px solid var(--border, #333)', background: 'var(--panel, #222)', color: 'inherit', cursor: 'pointer' },+ primary: { background: 'var(--accent, #3a6ea5)', borderColor: 'transparent' },+ node: { boxSizing: 'border-box', width: '100%', height: '100%', borderRadius: 6, border: '1.5px solid #3a4048', background: 'var(--node, #232830)', boxShadow: '0 1px 3px rgba(0,0,0,0.4)', padding: 6, display: 'flex', flexDirection: 'column', justifyContent: 'center' },+ nodeType: { fontSize: 12, fontWeight: 600 },+ nodeSub: { fontSize: 10, opacity: 0.75, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },+ inspector: { width: 232, flexShrink: 0, borderLeft: '1px solid var(--border, #2a2f36)', padding: 10, overflow: 'auto', fontSize: 12 },+ inspTitle: { fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.5, opacity: 0.6, marginBottom: 8 },+ inspSub: { fontSize: 11, opacity: 0.6, margin: '10px 0 4px' },+ field: { display: 'flex', flexDirection: 'column', gap: 3, marginBottom: 8, fontSize: 11 },+ input: { padding: '3px 6px', fontSize: 12, borderRadius: 4, border: '1px solid var(--border, #333)', background: 'var(--input, #1a1d22)', color: 'inherit' },+};diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex 3fe6074bf..84b57b621 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -17,6 +17,7 @@ import { createTilemapFromTileset } from '@/tilemap/createTilemap';import { createMaterial, createMaterialInstance } from '@/material/openMaterial';import { createMaterialGraph } from '@/material/openMaterialGraph';import { createStateMachine } from '@/fsm/openStateMachine';+import { createBehaviorTree } from '@/bt/openBehaviorTree';import { createAnimationClip } from '@/timeline/openClip';import { fsRefresh } from '@/project/fsWatch';import type { DirEntry } from '@/project/format';@@ -560,6 +561,7 @@ export function ContentBrowser() {{ label: 'New Material', onClick: () => void createMaterial(cwd) },{ label: 'New Material Graph', onClick: () => void createMaterialGraph(cwd) },{ label: 'New State Machine', onClick: () => void createStateMachine(cwd) },+ { label: 'New Behavior Tree', onClick: () => void createBehaviorTree(cwd) },{ sep: true },{ label: 'Show in Explorer', onClick: () => void showInExplorer(cwd) },];diff --git a/desktop/src/panels/NodeGraphCanvas.tsx b/desktop/src/panels/NodeGraphCanvas.tsxnew file mode 100644index 000000000..0676bf9ff--- /dev/null+++ b/desktop/src/panels/NodeGraphCanvas.tsx@@ -0,0 +1,217 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file NodeGraphCanvas.tsx+ * @brief Generic node-graph canvas — draggable nodes wired by selectable bezier+ * edges, shared by the state-machine and behavior-tree editors.+ *+ * Owns only the interaction (pan-by-scroll, node drag, wire-to-connect, edge/node+ * selection, delete, bezier + self-loops). Everything domain-specific — node body,+ * edge label, sizes, connect policy — is injected via props, so FSM (arbitrary+ * guarded edges, cycles) and BT (parent/child tree edges) both drive it. Extracted+ * from the proven StateMachineEditor canvas.+ */+import { useEffect, useRef, useState, type ReactNode, type CSSProperties } from 'react';++export interface CanvasNode {+ id: string;+ x?: number;+ y?: number;+}++export interface CanvasEdge {+ id: string;+ from: string;+ to: string;+}++export interface NodeGraphCanvasProps<N extends CanvasNode, E extends CanvasEdge> {+ nodes: N[];+ edges: E[];+ selectedNode: string | null;+ selectedEdge: string | null;+ nodeSize: (n: N) => { width: number; height: number };+ /** Node body (header + content); the canvas frames it and adds the output handle. */+ renderNode: (n: N, selected: boolean) => ReactNode;+ /** Optional label drawn at an edge's midpoint (e.g. an FSM guard). */+ renderEdgeLabel?: (e: E) => ReactNode;+ /** Allow an edge from a node to itself (FSM self-transition). */+ allowSelfLoop?: boolean;+ onSelectNode: (id: string | null) => void;+ onSelectEdge: (id: string | null) => void;+ onMoveNode: (id: string, x: number, y: number) => void;+ onMoveNodeStart?: (id: string) => void;+ onMoveNodeEnd?: (id: string) => void;+ onConnect: (from: string, to: string) => void;+ onDeleteNode: (id: string) => void;+ onDeleteEdge: (id: string) => void;+ /** Toolbar row above the canvas. */+ toolbar?: ReactNode;+ /** Shown when there are no nodes. */+ emptyHint?: ReactNode;+}++const nx = (n: CanvasNode) => n.x ?? 0;+const ny = (n: CanvasNode) => n.y ?? 0;++function bezier(x1: number, y1: number, x2: number, y2: number): string {+ const dx = Math.max(40, Math.abs(x2 - x1) * 0.5);+ return `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2} ${y2}`;+}++export function NodeGraphCanvas<N extends CanvasNode, E extends CanvasEdge>(props: NodeGraphCanvasProps<N, E>) {+ const {+ nodes, edges, selectedNode, selectedEdge, nodeSize, renderNode, renderEdgeLabel,+ allowSelfLoop, onSelectNode, onSelectEdge, onMoveNode, onMoveNodeStart, onMoveNodeEnd,+ onConnect, onDeleteNode, onDeleteEdge, toolbar, emptyHint,+ } = props;++ const canvasRef = useRef<HTMLDivElement>(null);+ const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);+ const drag = useRef<{ id: string; offX: number; offY: number } | null>(null);+ const wire = useRef<{ from: string } | null>(null);++ const byId = new Map(nodes.map(n => [n.id, n]));+ const out = (n: N) => { const s = nodeSize(n); return { x: nx(n) + s.width, y: ny(n) + s.height / 2 }; };+ const inp = (n: N) => ({ x: nx(n), y: ny(n) + nodeSize(n).height / 2 });++ const toCanvas = (clientX: number, clientY: number) => {+ const el = canvasRef.current;+ if (!el) return { x: clientX, y: clientY };+ const r = el.getBoundingClientRect();+ return { x: clientX - r.left + el.scrollLeft, y: clientY - r.top + el.scrollTop };+ };++ const nodeAt = (x: number, y: number): N | null => {+ for (const n of nodes) {+ const s = nodeSize(n);+ if (x >= nx(n) && x <= nx(n) + s.width && y >= ny(n) && y <= ny(n) + s.height) return n;+ }+ return null;+ };++ useEffect(() => {+ const onMove = (e: PointerEvent) => {+ const p = toCanvas(e.clientX, e.clientY);+ if (drag.current) onMoveNode(drag.current.id, p.x - drag.current.offX, p.y - drag.current.offY);+ else if (wire.current) setCursor(p);+ };+ const onUp = (e: PointerEvent) => {+ if (drag.current) {+ onMoveNodeEnd?.(drag.current.id);+ drag.current = null;+ }+ if (wire.current) {+ const p = toCanvas(e.clientX, e.clientY);+ const target = nodeAt(p.x, p.y);+ const from = wire.current.from;+ if (target && (allowSelfLoop || target.id !== from)) onConnect(from, target.id);+ wire.current = null;+ setCursor(null);+ }+ };+ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ return () => {+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [nodes]);++ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key !== 'Delete' && e.key !== 'Backspace') return;+ const el = document.activeElement;+ if (el && (el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'TEXTAREA')) return;+ if (selectedNode) onDeleteNode(selectedNode);+ else if (selectedEdge) onDeleteEdge(selectedEdge);+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [selectedNode, selectedEdge, onDeleteNode, onDeleteEdge]);++ const selfLoopPath = (n: N): string => {+ const cx = nx(n) + nodeSize(n).width / 2;+ const y = ny(n);+ return `M ${cx - 16} ${y} C ${cx - 30} ${y - 40}, ${cx + 30} ${y - 40}, ${cx + 16} ${y}`;+ };++ return (+ <div className="panel" style={S.root}>+ {toolbar && <div style={S.bar}>{toolbar}</div>}+ <div style={S.canvas} ref={canvasRef} onPointerDown={() => { onSelectNode(null); onSelectEdge(null); }}>+ {nodes.length === 0 && emptyHint && <div style={S.empty}>{emptyHint}</div>}+ <svg style={S.svg}>+ {edges.map(e => {+ const from = byId.get(e.from);+ const to = byId.get(e.to);+ if (!from || !to) return null;+ const self = e.from === e.to;+ const a = out(from);+ const b = self ? { x: nx(to) + nodeSize(to).width / 2, y: ny(to) } : inp(to);+ const d = self ? selfLoopPath(from) : bezier(a.x, a.y, b.x, b.y);+ const sel = selectedEdge === e.id;+ return (+ <g key={e.id}>+ <path d={d} stroke="transparent" strokeWidth={12} fill="none" style={{ cursor: 'pointer' }}+ onPointerDown={ev => { ev.stopPropagation(); onSelectEdge(e.id); onSelectNode(null); }} />+ <path d={d} stroke={sel ? 'var(--accent, #6ea9ff)' : '#7d8794'} strokeWidth={sel ? 2.5 : 1.6} fill="none" />+ </g>+ );+ })}+ {wire.current && cursor && (() => {+ const from = byId.get(wire.current.from);+ if (!from) return null;+ const a = out(from);+ return <path d={bezier(a.x, a.y, cursor.x, cursor.y)} stroke="#6ea9ff" strokeWidth={1.6} strokeDasharray="4 3" fill="none" />;+ })()}+ </svg>++ {renderEdgeLabel && edges.map(e => {+ const from = byId.get(e.from);+ const to = byId.get(e.to);+ if (!from || !to) return null;+ const self = e.from === e.to;+ const mx = self ? nx(from) + nodeSize(from).width / 2 : (out(from).x + inp(to).x) / 2;+ const my = self ? ny(from) - 22 : (out(from).y + inp(to).y) / 2;+ return (+ <div key={`lbl-${e.id}`} style={{ ...S.edgeLabel, left: mx - 40, top: my - 9, borderColor: selectedEdge === e.id ? 'var(--accent, #6ea9ff)' : 'transparent' }}+ onPointerDown={ev => { ev.stopPropagation(); onSelectEdge(e.id); onSelectNode(null); }}>+ {renderEdgeLabel(e)}+ </div>+ );+ })}++ {nodes.map(n => {+ const s = nodeSize(n);+ return (+ <div key={n.id} style={{ ...S.node, left: nx(n), top: ny(n), width: s.width, height: s.height }}+ onPointerDown={e => {+ e.stopPropagation();+ onSelectNode(n.id); onSelectEdge(null);+ const p = toCanvas(e.clientX, e.clientY);+ drag.current = { id: n.id, offX: p.x - nx(n), offY: p.y - ny(n) };+ onMoveNodeStart?.(n.id);+ }}>+ {renderNode(n, selectedNode === n.id)}+ <span style={{ ...S.handle, top: s.height / 2 - 6 }} title="Drag to another node to connect"+ onPointerDown={e => { e.stopPropagation(); wire.current = { from: n.id }; setCursor(toCanvas(e.clientX, e.clientY)); }} />+ </div>+ );+ })}+ </div>+ </div>+ );+}++const S: Record<string, CSSProperties> = {+ root: { display: 'flex', flexDirection: 'column', height: '100%' },+ bar: { display: 'flex', alignItems: 'center', gap: 6, padding: '6px 8px', borderBottom: '1px solid var(--border, #2a2f36)' },+ canvas: { position: 'relative', flex: 1, overflow: 'auto', background: 'var(--canvas, #191c20)', backgroundImage: 'radial-gradient(var(--grid, #262b31) 1px, transparent 1px)', backgroundSize: '20px 20px' },+ empty: { position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: 0.5, fontSize: 13, pointerEvents: 'none' },+ svg: { position: 'absolute', top: 0, left: 0, width: 4000, height: 4000, overflow: 'visible' },+ node: { position: 'absolute', boxSizing: 'border-box', cursor: 'grab', userSelect: 'none' },+ handle: { position: 'absolute', right: -6, width: 11, height: 11, borderRadius: '50%', background: '#6ea9ff', border: '2px solid var(--canvas, #191c20)', cursor: 'crosshair' },+ edgeLabel: { position: 'absolute', width: 80, textAlign: 'center', fontSize: 10, padding: '1px 3px', borderRadius: 3, background: 'var(--canvas, #191c20)', border: '1px solid transparent', color: '#aeb6c0', cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },+};diff --git a/desktop/src/panels/StateMachineEditor.tsx b/desktop/src/panels/StateMachineEditor.tsxindex ad32e6185..b2b2d681c 100644--- a/desktop/src/panels/StateMachineEditor.tsx+++ b/desktop/src/panels/StateMachineEditor.tsx@@ -2,53 +2,35 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/*** @file StateMachineEditor.tsx- * @brief The `.esfsm` transition-graph editor — states as draggable nodes, transitions- * as selectable bezier edges. All mutation goes through the pure, tested SDK- * fsmGraph ops on the reactive FsmGraphDocument (one undo step each). A `.esfsm`- * IS the runtime FsmDefinition (states carry x/y layout the interpreter ignores),- * so Save just writes the JSON — no compile step.+ * @brief The `.esfsm` transition-graph editor — states as nodes, transitions as+ * guarded edges, on the shared <NodeGraphCanvas>. All mutation goes through+ * the pure, tested SDK fsmGraph ops on the reactive FsmGraphDocument (one+ * undo step each). A `.esfsm` IS the runtime FsmDefinition (states carry+ * x/y layout the interpreter ignores), so Save just writes JSON.*- * Interaction mirrors MaterialGraphEditor (toCanvas / drag ref / wire ref / window- * move-up effects / bezier); specialized for FSM: first-class selectable edges with- * guard labels, self-loops, and cycles allowed. A generic <NodeGraphCanvas> is- * deferred until the behavior-tree editor gives a second real consumer (AI3).+ * FSM specifics: self-loops (allowSelfLoop), guard labels on edges+ * (renderEdgeLabel), and a right-side inspector for state hooks /+ * transition trigger·condition·guard. The canvas interaction is the+ * generic component shared with the behavior-tree editor.*/-import { useEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react';+import { useRef, useState, useSyncExternalStore, type CSSProperties } from 'react';import { Plus, Trash2, Save } from 'lucide-react';import {- fsmEdges,- addState,- removeState,- moveState,- renameState,- setStateHook,- setInitial,- addTransition,- removeTransition,- updateTransition,- aiRegistry,- type FsmDefinition,- type FsmState,- type CompareOp,+ fsmEdges, addState, removeState, moveState, renameState, setStateHook, setInitial,+ addTransition, removeTransition, updateTransition, aiRegistry,+ type FsmDefinition, type FsmState, type FsmEdge, type CompareOp,} from 'esengine';import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';import { EditorHistory } from '@/engine/EditorHistory';+import { NodeGraphCanvas, type CanvasNode } from '@/panels/NodeGraphCanvas';++type FsmCanvasNode = FsmState & CanvasNode;const NODE_W = 156;const NODE_H = 60;const HOOKS: Array<'onEnter' | 'onUpdate' | 'onExit'> = ['onEnter', 'onUpdate', 'onExit'];const OPS: CompareOp[] = ['==', '!=', '<', '<=', '>', '>=', 'truthy', 'falsy'];-const stateX = (s: FsmState) => s.x ?? 0;-const stateY = (s: FsmState) => s.y ?? 0;-const outAnchor = (s: FsmState) => ({ x: stateX(s) + NODE_W, y: stateY(s) + NODE_H / 2 });-const inAnchor = (s: FsmState) => ({ x: stateX(s), y: stateY(s) + NODE_H / 2 });--function bezier(x1: number, y1: number, x2: number, y2: number): string {- const dx = Math.max(40, Math.abs(x2 - x1) * 0.5);- return `M ${x1} ${y1} C ${x1 + dx} ${y1}, ${x2 - dx} ${y2}, ${x2} ${y2}`;-}-/** A short human summary of a transition's enabling condition, for the edge label. */function edgeSummary(t: { trigger?: string; condition?: string; guard?: unknown }): string {const parts: string[] = [];@@ -70,178 +52,82 @@ export function StateMachineEditor() {const filePath = FsmGraphDocument.filePath;const dirty = FsmGraphDocument.dirty;- const canvasRef = useRef<HTMLDivElement>(null);const [selState, setSelState] = useState<string | null>(null);const [selEdge, setSelEdge] = useState<string | null>(null);- const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);- const drag = useRef<{ name: string; offX: number; offY: number; before: FsmDefinition } | null>(null);- const wire = useRef<{ from: string } | null>(null);-- const toCanvas = (clientX: number, clientY: number) => {- const el = canvasRef.current;- if (!el) return { x: clientX, y: clientY };- const r = el.getBoundingClientRect();- return { x: clientX - r.left + el.scrollLeft, y: clientY - r.top + el.scrollTop };- };-- useEffect(() => {- const onMove = (e: PointerEvent) => {- const p = toCanvas(e.clientX, e.clientY);- if (drag.current && def) {- FsmGraphDocument.replaceAsset(moveState(def, drag.current.name, p.x - drag.current.offX, p.y - drag.current.offY), { dirty: true });- } else if (wire.current) {- setCursor(p);- }- };- const onUp = (e: PointerEvent) => {- if (drag.current && def) {- const after = def;- const before = drag.current.before;- EditorHistory.record('Move state', () => FsmGraphDocument.replaceAsset(after), () => FsmGraphDocument.replaceAsset(before));- drag.current = null;- }- if (wire.current && def) {- const p = toCanvas(e.clientX, e.clientY);- const target = stateAt(def, p.x, p.y);- const from = wire.current.from;- if (target) FsmGraphDocument.edit('Add transition', (d) => Object.assign(d, addTransition(d, from, target)));- wire.current = null;- setCursor(null);- }- };- window.addEventListener('pointermove', onMove);- window.addEventListener('pointerup', onUp);- return () => {- window.removeEventListener('pointermove', onMove);- window.removeEventListener('pointerup', onUp);- };- }, [def]);-- useEffect(() => {- const onKey = (e: KeyboardEvent) => {- if (e.key !== 'Delete' && e.key !== 'Backspace') return;- if (!def) return;- const el = document.activeElement;- if (el && (el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'TEXTAREA')) return;- if (selState) {- FsmGraphDocument.edit('Delete state', (d) => Object.assign(d, removeState(d, selState)));- setSelState(null);- } else if (selEdge) {- const parsed = parseEdgeId(selEdge);- if (parsed) FsmGraphDocument.edit('Delete transition', (d) => Object.assign(d, removeTransition(d, parsed.from, parsed.index)));- setSelEdge(null);- }- };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, [selState, selEdge, def]);+ const dragBefore = useRef<FsmDefinition | null>(null);if (!def || !filePath) {- return (- <div className="panel" style={S.empty}>- <p>Open a <code>.esfsm</code> from the Content Browser to edit it.</p>- </div>- );+ return <div className="panel" style={S.empty}><p>Open a <code>.esfsm</code> from the Content Browser to edit it.</p></div>;}+ const nodes: FsmCanvasNode[] = def.states.map(s => ({ ...s, id: s.name }));+ const edges: FsmEdge[] = fsmEdges(def);+ const byName = new Map(def.states.map(s => [s.name, s]));+const addStateAt = () => {- const el = canvasRef.current;- const x = (el?.scrollLeft ?? 0) + 60;- const y = (el?.scrollTop ?? 0) + 60;const name = uniqueName(def, 'State');- FsmGraphDocument.edit('Add state', (d) => Object.assign(d, addState(d, name, x, y)));+ FsmGraphDocument.edit('Add state', d => Object.assign(d, addState(d, name, 200, 120)));setSelState(name);setSelEdge(null);};-+ const deleteSelected = () => {+ if (selState) { FsmGraphDocument.edit('Delete state', d => Object.assign(d, removeState(d, selState))); setSelState(null); }+ else if (selEdge) { const p = parseEdgeId(selEdge); if (p) FsmGraphDocument.edit('Delete transition', d => Object.assign(d, removeTransition(d, p.from, p.index))); setSelEdge(null); }+ };const save = () => {void window.estella.fs.write(filePath, JSON.stringify(def, null, 2) + '\n').then(() => FsmGraphDocument.markSaved());};- const byName = new Map(def.states.map((s) => [s.name, s]));- const edges = fsmEdges(def);+ const toolbar = (+ <>+ <button type="button" style={S.btn} onClick={addStateAt} title="Add state"><Plus size={13} strokeWidth={2} /> State</button>+ {(selState || selEdge) && <button type="button" style={S.btn} title="Delete selected" onClick={deleteSelected}><Trash2 size={13} strokeWidth={1.9} /></button>}+ <span style={S.title}>{filePath.split('/').pop()}{dirty && <span style={S.dot} title="Unsaved">●</span>}</span>+ <span style={{ flex: 1 }} />+ <button type="button" style={{ ...S.btn, ...S.primary }} disabled={!dirty} onClick={save}><Save size={13} strokeWidth={1.9} /> Save</button>+ </>+ );return (- <div className="panel" style={S.root}>- <div style={S.bar}>- <button type="button" style={S.btn} onClick={addStateAt} title="Add state"><Plus size={13} strokeWidth={2} /> State</button>- {(selState || selEdge) && (- <button type="button" style={S.btn} title="Delete selected" onClick={() => {- if (selState) { FsmGraphDocument.edit('Delete state', (d) => Object.assign(d, removeState(d, selState))); setSelState(null); }- else if (selEdge) { const p = parseEdgeId(selEdge); if (p) FsmGraphDocument.edit('Delete transition', (d) => Object.assign(d, removeTransition(d, p.from, p.index))); setSelEdge(null); }- }}><Trash2 size={13} strokeWidth={1.9} /></button>- )}- <span style={S.title}>{filePath.split('/').pop()}{dirty && <span style={S.dot} title="Unsaved">●</span>}</span>- <span style={{ flex: 1 }} />- <button type="button" style={{ ...S.btn, ...S.primary }} disabled={!dirty} onClick={save}><Save size={13} strokeWidth={1.9} /> Save</button>- </div>-+ <div style={S.root}><div style={S.body}>- <div style={S.canvas} ref={canvasRef} onPointerDown={() => { setSelState(null); setSelEdge(null); }}>- <svg style={S.svg}>- {edges.map((e) => {- const from = byName.get(e.from);- const to = byName.get(e.to);- if (!from || !to) return null;- const a = outAnchor(from);- const b = e.from === e.to ? { x: stateX(to) + NODE_W / 2, y: stateY(to) } : inAnchor(to);- const d = e.from === e.to ? selfLoop(from) : bezier(a.x, a.y, b.x, b.y);- const sel = selEdge === e.id;+ <div style={{ flex: 1, minWidth: 0 }}>+ <NodeGraphCanvas<FsmCanvasNode, FsmEdge>+ nodes={nodes}+ edges={edges}+ selectedNode={selState}+ selectedEdge={selEdge}+ nodeSize={() => ({ width: NODE_W, height: NODE_H })}+ allowSelfLoop+ onSelectNode={setSelState}+ onSelectEdge={setSelEdge}+ onMoveNodeStart={() => { dragBefore.current = def; }}+ onMoveNode={(id, x, y) => FsmGraphDocument.replaceAsset(moveState(def, id, x, y), { dirty: true })}+ onMoveNodeEnd={() => {+ const after = FsmGraphDocument.asset;+ const before = dragBefore.current;+ if (after && before) EditorHistory.record('Move state', () => FsmGraphDocument.replaceAsset(after), () => FsmGraphDocument.replaceAsset(before));+ }}+ onConnect={(from, to) => FsmGraphDocument.edit('Add transition', d => Object.assign(d, addTransition(d, from, to)))}+ onDeleteNode={id => { FsmGraphDocument.edit('Delete state', d => Object.assign(d, removeState(d, id))); setSelState(null); }}+ onDeleteEdge={id => { const p = parseEdgeId(id); if (p) FsmGraphDocument.edit('Delete transition', d => Object.assign(d, removeTransition(d, p.from, p.index))); setSelEdge(null); }}+ toolbar={toolbar}+ emptyHint="Add a state, then drag from its handle to another to add a transition."+ renderEdgeLabel={e => <>{edgeSummary(e.transition)}</>}+ renderNode={(n, sel) => {+ const isInitial = def.initial === n.name;+ const setHooks = HOOKS.filter(h => n[h]).map(h => `${h[2].toUpperCase()}:${n[h]}`).join(' ');return (- <g key={e.id}>- {/* Fat transparent hit path so the thin edge is easy to click. */}- <path d={d} stroke="transparent" strokeWidth={12} fill="none" style={{ cursor: 'pointer' }}- onPointerDown={(ev) => { ev.stopPropagation(); setSelEdge(e.id); setSelState(null); }} />- <path d={d} stroke={sel ? 'var(--accent, #6ea9ff)' : '#7d8794'} strokeWidth={sel ? 2.5 : 1.6} fill="none" markerEnd="" />- </g>- );- })}- {wire.current && cursor && (() => {- const from = byName.get(wire.current.from);- if (!from) return null;- const a = outAnchor(from);- return <path d={bezier(a.x, a.y, cursor.x, cursor.y)} stroke="#6ea9ff" strokeWidth={1.6} strokeDasharray="4 3" fill="none" />;- })()}- </svg>-- {/* Edge guard labels, positioned at the edge midpoint. */}- {edges.map((e) => {- const from = byName.get(e.from);- const to = byName.get(e.to);- if (!from || !to) return null;- const mx = e.from === e.to ? stateX(from) + NODE_W / 2 : (outAnchor(from).x + inAnchor(to).x) / 2;- const my = e.from === e.to ? stateY(from) - 22 : (outAnchor(from).y + inAnchor(to).y) / 2;- return (- <div key={`lbl-${e.id}`} style={{ ...S.edgeLabel, left: mx - 40, top: my - 9, borderColor: selEdge === e.id ? 'var(--accent, #6ea9ff)' : 'transparent' }}- onPointerDown={(ev) => { ev.stopPropagation(); setSelEdge(e.id); setSelState(null); }}>- {edgeSummary(e.transition)}- </div>- );- })}-- {def.states.map((s) => {- const isInitial = def.initial === s.name;- const sel = selState === s.name;- const setHooks = HOOKS.filter((h) => s[h]).map((h) => `${h[2].toUpperCase()}:${s[h]}`).join(' ');- return (- <div key={s.name} style={{ ...S.node, left: stateX(s), top: stateY(s), width: NODE_W, height: NODE_H, borderColor: sel ? 'var(--accent, #6ea9ff)' : isInitial ? '#7faf9c' : '#3a4048' }}- onPointerDown={(e) => {- e.stopPropagation();- setSelState(s.name); setSelEdge(null);- const p = toCanvas(e.clientX, e.clientY);- drag.current = { name: s.name, offX: p.x - stateX(s), offY: p.y - stateY(s), before: def };- }}>- <div style={S.nodeHead}>- {isInitial && <span title="Initial state" style={S.initialBadge}>▶</span>}- <span style={S.nodeName}>{s.name}</span>+ <div style={{ ...S.nodeBox, borderColor: sel ? 'var(--accent, #6ea9ff)' : isInitial ? '#7faf9c' : '#3a4048' }}>+ <div style={S.nodeHead}>+ {isInitial && <span title="Initial state" style={S.initialBadge}>▶</span>}+ <span style={S.nodeName}>{n.name}</span>+ </div>+ <div style={S.nodeHooks}>{setHooks || <span style={{ opacity: 0.4 }}>no actions</span>}</div></div>- <div style={S.nodeHooks}>{setHooks || <span style={{ opacity: 0.4 }}>no actions</span>}</div>- {/* Output handle — drag to another state to add a transition. */}- <span style={S.outHandle} title="Drag to a state to add a transition"- onPointerDown={(e) => { e.stopPropagation(); wire.current = { from: s.name }; setCursor(toCanvas(e.clientX, e.clientY)); }} />- </div>- );- })}+ );+ }}+ /></div>{(selState || selEdge) && (@@ -332,20 +218,6 @@ function TransitionInspector({ def, edgeId }: { def: FsmDefinition; edgeId: stri// -- helpers -----------------------------------------------------------------function stateAt(def: FsmDefinition, x: number, y: number): string | null {- for (const s of def.states) {- const sx = stateX(s), sy = stateY(s);- if (x >= sx && x <= sx + NODE_W && y >= sy && y <= sy + NODE_H) return s.name;- }- return null;-}--function selfLoop(s: FsmState): string {- const x = stateX(s) + NODE_W / 2;- const y = stateY(s);- return `M ${x - 16} ${y} C ${x - 30} ${y - 40}, ${x + 30} ${y - 40}, ${x + 16} ${y}`;-}-function parseEdgeId(id: string): { from: string; index: number } | null {const m = /^(.*)->.*#(\d+)$/.exec(id);return m ? { from: m[1], index: Number(m[2]) } : null;@@ -367,26 +239,19 @@ function coerce(v: string): number | string | boolean {return t;}-// -- inline styles (self-contained; no shared CSS dependency) -----------------const S: Record<string, CSSProperties> = {root: { display: 'flex', flexDirection: 'column', height: '100%' },empty: { display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', opacity: 0.6, fontSize: 13 },- bar: { display: 'flex', alignItems: 'center', gap: 6, padding: '6px 8px', borderBottom: '1px solid var(--border, #2a2f36)' },+ body: { display: 'flex', flex: 1, minHeight: 0 },btn: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '3px 8px', fontSize: 12, borderRadius: 4, border: '1px solid var(--border, #333)', background: 'var(--panel, #222)', color: 'inherit', cursor: 'pointer' },primary: { background: 'var(--accent, #3a6ea5)', borderColor: 'transparent' },title: { fontSize: 12, opacity: 0.85, marginLeft: 4 },dot: { color: '#e0a03a', marginLeft: 4 },- body: { display: 'flex', flex: 1, minHeight: 0 },- canvas: { position: 'relative', flex: 1, overflow: 'auto', background: 'var(--canvas, #191c20)', backgroundImage: 'radial-gradient(var(--grid, #262b31) 1px, transparent 1px)', backgroundSize: '20px 20px' },- svg: { position: 'absolute', top: 0, left: 0, width: 4000, height: 4000, overflow: 'visible' },- node: { position: 'absolute', boxSizing: 'border-box', borderRadius: 6, border: '1.5px solid #3a4048', background: 'var(--node, #232830)', boxShadow: '0 1px 3px rgba(0,0,0,0.4)', cursor: 'grab', userSelect: 'none', padding: 6 },+ nodeBox: { boxSizing: 'border-box', width: '100%', height: '100%', borderRadius: 6, border: '1.5px solid #3a4048', background: 'var(--node, #232830)', boxShadow: '0 1px 3px rgba(0,0,0,0.4)', padding: 6 },nodeHead: { display: 'flex', alignItems: 'center', gap: 5, fontSize: 12.5, fontWeight: 600 },initialBadge: { color: '#7faf9c', fontSize: 10 },nodeName: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },nodeHooks: { marginTop: 5, fontSize: 10.5, opacity: 0.75, lineHeight: 1.4, overflow: 'hidden' },- outHandle: { position: 'absolute', right: -6, top: NODE_H / 2 - 6, width: 11, height: 11, borderRadius: '50%', background: '#6ea9ff', border: '2px solid var(--canvas, #191c20)', cursor: 'crosshair' },- edgeLabel: { position: 'absolute', width: 80, textAlign: 'center', fontSize: 10, padding: '1px 3px', borderRadius: 3, background: 'var(--canvas, #191c20)', border: '1px solid transparent', color: '#aeb6c0', pointerEvents: 'auto', cursor: 'pointer', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' },inspector: { width: 232, flexShrink: 0, borderLeft: '1px solid var(--border, #2a2f36)', padding: 10, overflow: 'auto', fontSize: 12 },inspTitle: { fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.5, opacity: 0.6, marginBottom: 8 },inspSub: { fontSize: 11, opacity: 0.6, margin: '10px 0 4px' },diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.tsindex ded7699ba..fc4c6fa33 100644--- a/desktop/src/project/assetOpen.ts+++ b/desktop/src/project/assetOpen.ts@@ -16,6 +16,7 @@ import { openTileset } from '@/tileset/openTileset';import { openMaterial } from '@/material/openMaterial';import { openMaterialGraph } from '@/material/openMaterialGraph';import { openStateMachine } from '@/fsm/openStateMachine';+import { openBehaviorTree } from '@/bt/openBehaviorTree';/** Open action per asset type; types absent here aren't double-click-openable. */export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string) => void>> = {@@ -29,4 +30,5 @@ export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string)material: (path) => void openMaterial(path),materialgraph: (path) => void openMaterialGraph(path),statemachine: (path) => void openStateMachine(path),+ behaviortree: (path) => void openBehaviorTree(path),};diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex be6729fa5..f0aa1bdde 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -13,7 +13,7 @@*/import {Folder, Film, Image, FileImage, PersonStanding, Music,- Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch,+ Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree,type LucideIcon,} from 'lucide-react';import type { AssetType } from '@/types';@@ -49,6 +49,7 @@ export const ASSET_TYPES: Record<AssetType, AssetTypeDef> = {tilemap: { extensions: ['estilemap'], badge: 'TMP', icon: Grid3x3, tint: '#7fa6c4' },inputmap: { extensions: ['inputmap'], badge: 'INP', icon: Gamepad2, tint: '#a0b88f' },statemachine: { extensions: ['esfsm'], badge: 'FSM', icon: GitBranch, tint: '#8fb0a0' },+ behaviortree: { extensions: ['esbt'], badge: 'BT', icon: ListTree, tint: '#8fa0c4' },file: { badge: '', icon: File, tint: 'var(--text-dim)' },};diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 2812d43a7..e9bf35ab2 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -148,6 +148,7 @@ export type AssetType =| 'tilemap'| 'inputmap'| 'statemachine'+ | 'behaviortree'| 'file';export interface AssetItem {diff --git a/sdk/src/ai/bt/btGraph.ts b/sdk/src/ai/bt/btGraph.tsnew file mode 100644index 000000000..fa2d51dd8--- /dev/null+++ b/sdk/src/ai/bt/btGraph.ts@@ -0,0 +1,168 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file btGraph.ts+ * @brief Immutable tree operations on a BtDefinition — the editor's model.+ *+ * Pure functions returning new definitions (never mutating), so the tree editor+ * drives them through AssetDocument.edit for free undo, mirroring fsmGraph. Nodes+ * carry an editor-only `id` (the interpreter ignores it); a `.esbt` IS the runtime+ * definition, so there is no compile step. Composite/decorator/leaf capacities are+ * enforced so the graph can only form a valid tree.+ */++import type { BtDefinition, BtNode, BtNodeType } from './types';++export interface BtEdge {+ /** Stable id `from->to`. */+ id: string;+ from: string;+ to: string;+}++const COMPOSITES = new Set<BtNodeType>(['sequence', 'selector', 'parallel']);+const DECORATORS = new Set<BtNodeType>(['inverter', 'succeeder', 'repeater']);++/** Max children a node type accepts: composites unbounded, decorators one, leaves none. */+export function maxChildren(type: BtNodeType): number {+ if (COMPOSITES.has(type)) return Infinity;+ if (DECORATORS.has(type)) return 1;+ return 0; // action, condition, wait+}++export function canHaveChildren(type: BtNodeType): boolean {+ return maxChildren(type) > 0;+}++function clone(def: BtDefinition): BtDefinition {+ return JSON.parse(JSON.stringify(def)) as BtDefinition;+}++function walk(node: BtNode, fn: (n: BtNode) => void): void {+ fn(node);+ for (const c of node.children ?? []) walk(c, fn);+}++function find(node: BtNode, id: string): BtNode | null {+ if (node.id === id) return node;+ for (const c of node.children ?? []) {+ const r = find(c, id);+ if (r) return r;+ }+ return null;+}++function findParent(node: BtNode, id: string): BtNode | null {+ for (const c of node.children ?? []) {+ if (c.id === id) return node;+ const r = findParent(c, id);+ if (r) return r;+ }+ return null;+}++function freshId(def: BtDefinition): string {+ const used = new Set<string>();+ walk(def.root, n => { if (n.id) used.add(n.id); });+ let i = 0;+ let id: string;+ do { id = `n${i++}`; } while (used.has(id));+ return id;+}++/** Assign ids to any node missing one (e.g. a hand-written `.esbt`). Mutates + returns the def. */+export function ensureBtIds(def: BtDefinition): BtDefinition {+ const used = new Set<string>();+ walk(def.root, n => { if (n.id) used.add(n.id); });+ let i = 0;+ const nextId = () => {+ let id: string;+ do { id = `n${i++}`; } while (used.has(id));+ used.add(id);+ return id;+ };+ walk(def.root, n => { if (!n.id) n.id = nextId(); });+ return def;+}++/** A blank tree: a Selector root. */+export function emptyBt(): BtDefinition {+ return { root: { type: 'selector', id: 'n0', x: 60, y: 80, children: [] } };+}++/** All nodes flattened (for the canvas). */+export function btNodes(def: BtDefinition): BtNode[] {+ const out: BtNode[] = [];+ walk(def.root, n => out.push(n));+ return out;+}++/** Parent -> child edges. */+export function btEdges(def: BtDefinition): BtEdge[] {+ const edges: BtEdge[] = [];+ walk(def.root, n => {+ for (const c of n.children ?? []) {+ if (n.id && c.id) edges.push({ id: `${n.id}->${c.id}`, from: n.id, to: c.id });+ }+ });+ return edges;+}++export function addBtChild(def: BtDefinition, parentId: string, type: BtNodeType, x = 0, y = 0): BtDefinition {+ const next = clone(def);+ const parent = find(next.root, parentId);+ if (!parent || (parent.children?.length ?? 0) >= maxChildren(parent.type)) return def;+ const child: BtNode = { type, id: freshId(next), x, y };+ (parent.children ??= []).push(child);+ return next;+}++export function removeBtNode(def: BtDefinition, id: string): BtDefinition {+ if (def.root.id === id) return def; // the root can't be removed+ const next = clone(def);+ const parent = findParent(next.root, id);+ if (!parent?.children) return def;+ parent.children = parent.children.filter(c => c.id !== id);+ return next;+}++export function moveBtNode(def: BtDefinition, id: string, x: number, y: number): BtDefinition {+ const next = clone(def);+ const n = find(next.root, id);+ if (!n) return def;+ n.x = x;+ n.y = y;+ return next;+}++/** Patch a node's fields (type/name/count/policy/seconds). Changing type clamps children to the new capacity. */+export function setBtNodeField(def: BtDefinition, id: string, patch: Partial<BtNode>): BtDefinition {+ const next = clone(def);+ const n = find(next.root, id);+ if (!n) return def;+ Object.assign(n, patch);+ if (patch.type) {+ const max = maxChildren(patch.type);+ if (max === 0) delete n.children;+ else if (n.children && n.children.length > max) n.children = n.children.slice(0, max);+ }+ return next;+}++/**+ * Reparent a subtree under a new parent (canvas drag-to-connect). No-ops on a+ * cycle (new parent is a descendant), a full parent, or the root itself.+ */+export function reparentBtNode(def: BtDefinition, id: string, newParentId: string): BtDefinition {+ if (id === newParentId || def.root.id === id) return def;+ const next = clone(def);+ const node = find(next.root, id);+ const newParent = find(next.root, newParentId);+ if (!node || !newParent) return def;+ if (find(node, newParentId)) return def; // would create a cycle+ if ((newParent.children?.length ?? 0) >= maxChildren(newParent.type)) return def;+ const oldParent = findParent(next.root, id);+ if (oldParent?.children) oldParent.children = oldParent.children.filter(c => c.id !== id);+ (newParent.children ??= []).push(node);+ return next;+}diff --git a/sdk/src/ai/bt/index.ts b/sdk/src/ai/bt/index.tsindex 46854d680..4341f3e00 100644--- a/sdk/src/ai/bt/index.ts+++ b/sdk/src/ai/bt/index.ts@@ -7,3 +7,17 @@export type { BtNodeType, BtNode, BtDefinition } from './types';export { tickBt, createBtRunState, type BtRunState } from './BtRunner';+export {+ emptyBt,+ ensureBtIds,+ btNodes,+ btEdges,+ maxChildren,+ canHaveChildren,+ addBtChild,+ removeBtNode,+ moveBtNode,+ setBtNodeField,+ reparentBtNode,+ type BtEdge,+} from './btGraph';diff --git a/sdk/src/ai/bt/types.ts b/sdk/src/ai/bt/types.tsindex 98a499d8d..1aff0fb1a 100644--- a/sdk/src/ai/bt/types.ts+++ b/sdk/src/ai/bt/types.ts@@ -19,6 +19,8 @@ export type BtNodeType =export interface BtNode {type: BtNodeType;+ /** Editor-only stable id for selection/addressing; ignored by the interpreter. */+ id?: string;/** Registry name for a leaf (`action`/`condition`). */name?: string;/** Children: many for a composite, one for a decorator. */diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 8de907640..9de5d860d 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -485,6 +485,18 @@ export {BehaviorTrees,AiBt,agentBtBlackboard,+ emptyBt,+ ensureBtIds,+ btNodes,+ btEdges,+ maxChildren,+ canHaveChildren,+ addBtChild,+ removeBtNode,+ moveBtNode,+ setBtNodeField,+ reparentBtNode,+ type BtEdge,type BtNodeType,type BtNode,type BtDefinition,diff --git a/sdk/tests/bt-graph.test.ts b/sdk/tests/bt-graph.test.tsnew file mode 100644index 000000000..757216158--- /dev/null+++ b/sdk/tests/bt-graph.test.ts@@ -0,0 +1,108 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import {+ emptyBt, ensureBtIds, btNodes, btEdges, maxChildren, canHaveChildren,+ addBtChild, removeBtNode, moveBtNode, setBtNodeField, reparentBtNode,+} from '../src/ai/bt/btGraph';+import type { BtDefinition } from '../src/ai/bt/types';++describe('btGraph', () => {+ it('reports child capacity per node type', () => {+ expect(maxChildren('selector')).toBe(Infinity);+ expect(maxChildren('inverter')).toBe(1);+ expect(maxChildren('action')).toBe(0);+ expect(canHaveChildren('sequence')).toBe(true);+ expect(canHaveChildren('wait')).toBe(false);+ });++ it('assigns ids to a hand-written tree', () => {+ const def: BtDefinition = { root: { type: 'sequence', children: [{ type: 'action', name: 'go' }] } };+ ensureBtIds(def);+ const ids = btNodes(def).map(n => n.id);+ expect(ids.every(Boolean)).toBe(true);+ expect(new Set(ids).size).toBe(2); // unique+ });++ it('adds children up to capacity, not mutating the input', () => {+ const a = emptyBt();+ const b = addBtChild(a, 'n0', 'action', 100, 40);+ expect(a.root.children).toHaveLength(0); // input untouched+ expect(b.root.children).toHaveLength(1);+ // A decorator accepts one child, then no more.+ let d = addBtChild(emptyBt(), 'n0', 'inverter');+ const invId = d.root.children![0].id!;+ d = addBtChild(d, invId, 'action');+ expect(find(d, invId)?.children).toHaveLength(1);+ const blocked = addBtChild(d, invId, 'condition');+ expect(blocked).toBe(d); // full decorator → no-op (same ref)+ });++ it('removes a subtree but never the root', () => {+ let def = emptyBt();+ def = addBtChild(def, 'n0', 'sequence');+ const seqId = def.root.children![0].id!;+ def = addBtChild(def, seqId, 'action');+ def = removeBtNode(def, seqId);+ expect(def.root.children).toHaveLength(0);+ expect(removeBtNode(def, 'n0')).toBe(def); // root remove → no-op+ });++ it('moves a node', () => {+ const def = moveBtNode(emptyBt(), 'n0', 250, 120);+ expect(def.root).toMatchObject({ x: 250, y: 120 });+ });++ it('patches fields and clamps children when the type loses capacity', () => {+ let def = emptyBt(); // selector root+ def = addBtChild(def, 'n0', 'action');+ def = addBtChild(def, 'n0', 'action');+ expect(def.root.children).toHaveLength(2);+ // selector -> inverter (max 1) truncates to one child+ def = setBtNodeField(def, 'n0', { type: 'inverter' });+ expect(def.root.children).toHaveLength(1);+ // -> action (leaf) drops children entirely+ def = setBtNodeField(def, 'n0', { type: 'action', name: 'x' });+ expect(def.root.children).toBeUndefined();+ expect(def.root.name).toBe('x');+ });++ it('reparentBtNodes a subtree, rejecting cycles and full parents', () => {+ let def = emptyBt();+ def = addBtChild(def, 'n0', 'sequence'); // n0 -> seq+ const seqId = def.root.children![0].id!;+ def = addBtChild(def, 'n0', 'inverter'); // n0 -> inv+ const invId = def.root.children![1].id!;++ // Move seq under inv.+ def = reparentBtNode(def, seqId, invId);+ expect(btEdges(def).map(e => e.id).sort()).toEqual([`${invId}->${seqId}`, `n0->${invId}`].sort());++ // Cycle: making n0 a child of its descendant seq is rejected.+ expect(reparentBtNode(def, 'n0', seqId)).toBe(def);+ // inv is full (already has seq) → another reparentBtNode into it is a no-op.+ def = addBtChild(def, seqId, 'action');+ const actId = find(def, seqId)!.children![0].id!;+ expect(reparentBtNode(def, actId, invId)).toBe(def);+ });++ it('flattens edges as parent->child', () => {+ let def = emptyBt();+ def = addBtChild(def, 'n0', 'action');+ def = addBtChild(def, 'n0', 'condition');+ const edges = btEdges(def);+ expect(edges).toHaveLength(2);+ expect(edges.every(e => e.from === 'n0')).toBe(true);+ });+});++// Local helper mirroring btGraph's private find, for assertions.+function find(def: BtDefinition, id: string): import('../src/ai/bt/types').BtNode | null {+ const stack = [def.root];+ while (stack.length) {+ const n = stack.pop()!;+ if (n.id === id) return n;+ for (const c of n.children ?? []) stack.push(c);+ }+ return null;+}