refactor(editor): 提取行为树编辑器为独立包并重构编辑器架构 (#216)
* refactor(editor): 提取行为树编辑器为独立包并重构编辑器架构 * feat(editor): 添加插件市场功能 * feat(editor): 重构插件市场以支持版本管理和ZIP打包 * feat(editor): 重构插件发布流程并修复React渲染警告 * fix(plugin): 修复插件发布和市场的路径不一致问题 * feat: 重构插件发布流程并添加插件删除功能 * fix(editor): 完善插件删除功能并修复多个关键问题 * fix(auth): 修复自动登录与手动登录的竞态条件问题 * feat(editor): 重构插件管理流程 * feat(editor): 支持 ZIP 文件直接发布插件 - 新增 PluginSourceParser 解析插件源 - 重构发布流程支持文件夹和 ZIP 两种方式 - 优化发布向导 UI * feat(editor): 插件市场支持多版本安装 - 插件解压到项目 plugins 目录 - 新增 Tauri 后端安装/卸载命令 - 支持选择任意版本安装 - 修复打包逻辑,保留完整 dist 目录结构 * feat(editor): 个人中心支持多版本管理 - 合并同一插件的不同版本 - 添加版本历史展开/折叠功能 - 禁止有待审核 PR 时更新插件 * fix(editor): 修复 InspectorRegistry 服务注册 - InspectorRegistry 实现 IService 接口 - 注册到 Core.services 供插件使用 * feat(behavior-tree-editor): 完善插件注册和文件操作 - 添加文件创建模板和操作处理器 - 实现右键菜单创建行为树功能 - 修复文件读取权限问题(使用 Tauri 命令) - 添加 BehaviorTreeEditorPanel 组件 - 修复 rollup 配置支持动态导入 * feat(plugin): 完善插件构建和发布流程 * fix(behavior-tree-editor): 完整恢复编辑器并修复 Toast 集成 * fix(behavior-tree-editor): 修复节点选中、连线跟随和文件加载问题并优化性能 * fix(behavior-tree-editor): 修复端口连接失败问题并优化连线样式 * refactor(behavior-tree-editor): 移除调试面板功能简化代码结构 * refactor(behavior-tree-editor): 清理冗余代码合并重复逻辑 * feat(behavior-tree-editor): 完善编辑器核心功能增强扩展性 * fix(lint): 修复ESLint错误确保CI通过 * refactor(behavior-tree-editor): 优化编辑器工具栏和编译器功能 * refactor(behavior-tree-editor): 清理技术债务,优化代码质量 * fix(editor-app): 修复字符串替换安全问题
This commit is contained in:
614
packages/behavior-tree-editor/src/utils/BehaviorTreeExecutor.ts
Normal file
614
packages/behavior-tree-editor/src/utils/BehaviorTreeExecutor.ts
Normal file
@@ -0,0 +1,614 @@
|
||||
import { World, Entity, Scene, createLogger, Time, Core } from '@esengine/ecs-framework';
|
||||
import {
|
||||
BehaviorTreeData,
|
||||
BehaviorNodeData,
|
||||
BehaviorTreeRuntimeComponent,
|
||||
BehaviorTreeAssetManager,
|
||||
BehaviorTreeExecutionSystem,
|
||||
TaskStatus,
|
||||
NodeType
|
||||
} from '@esengine/behavior-tree';
|
||||
import type { BehaviorTreeNode } from '../stores';
|
||||
import { useExecutionStatsStore } from '../stores/ExecutionStatsStore';
|
||||
import type { Breakpoint } from '../types/Breakpoint';
|
||||
|
||||
const logger = createLogger('BehaviorTreeExecutor');
|
||||
|
||||
export interface ExecutionStatus {
|
||||
nodeId: string;
|
||||
status: 'running' | 'success' | 'failure' | 'idle';
|
||||
message?: string;
|
||||
executionOrder?: number;
|
||||
}
|
||||
|
||||
export interface ExecutionLog {
|
||||
timestamp: number;
|
||||
message: string;
|
||||
level: 'info' | 'success' | 'error' | 'warning';
|
||||
nodeId?: string;
|
||||
}
|
||||
|
||||
export type ExecutionCallback = (
|
||||
statuses: ExecutionStatus[],
|
||||
logs: ExecutionLog[],
|
||||
blackboardVariables?: Record<string, any>
|
||||
) => void;
|
||||
|
||||
export type BreakpointCallback = (nodeId: string, nodeName: string) => void;
|
||||
|
||||
/**
|
||||
* 行为树执行器
|
||||
*
|
||||
* 使用新的Runtime架构执行行为树
|
||||
*/
|
||||
export class BehaviorTreeExecutor {
|
||||
private world: World;
|
||||
private scene: Scene;
|
||||
private entity: Entity | null = null;
|
||||
private runtime: BehaviorTreeRuntimeComponent | null = null;
|
||||
private treeData: BehaviorTreeData | null = null;
|
||||
private callback: ExecutionCallback | null = null;
|
||||
private onBreakpointHit: BreakpointCallback | null = null;
|
||||
private isRunning = false;
|
||||
private isPaused = false;
|
||||
private executionLogs: ExecutionLog[] = [];
|
||||
private lastStatuses: Map<string, 'running' | 'success' | 'failure' | 'idle'> = new Map();
|
||||
private persistentStatuses: Map<string, 'running' | 'success' | 'failure' | 'idle'> = new Map();
|
||||
private executionOrders: Map<string, number> = new Map();
|
||||
private tickCount = 0;
|
||||
private nodeIdMap: Map<string, string> = new Map();
|
||||
private blackboardKeys: string[] = [];
|
||||
private rootNodeId: string = '';
|
||||
private breakpoints: Map<string, Breakpoint> = new Map();
|
||||
|
||||
private assetManager: BehaviorTreeAssetManager;
|
||||
private executionSystem: BehaviorTreeExecutionSystem;
|
||||
|
||||
constructor() {
|
||||
this.world = new World({ name: 'BehaviorTreeWorld' });
|
||||
this.scene = this.world.createScene('BehaviorTreeScene');
|
||||
|
||||
// 尝试获取已存在的 assetManager,如果不存在则创建新的
|
||||
try {
|
||||
this.assetManager = Core.services.resolve(BehaviorTreeAssetManager);
|
||||
} catch {
|
||||
this.assetManager = new BehaviorTreeAssetManager();
|
||||
Core.services.registerInstance(BehaviorTreeAssetManager, this.assetManager);
|
||||
}
|
||||
|
||||
this.executionSystem = new BehaviorTreeExecutionSystem();
|
||||
this.scene.addSystem(this.executionSystem);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从编辑器节点构建行为树数据
|
||||
*/
|
||||
buildTree(
|
||||
nodes: BehaviorTreeNode[],
|
||||
rootNodeId: string,
|
||||
blackboard: Record<string, any>,
|
||||
connections: Array<{ from: string; to: string; fromProperty?: string; toProperty?: string; connectionType: 'node' | 'property' }>,
|
||||
callback: ExecutionCallback
|
||||
): void {
|
||||
this.cleanup();
|
||||
this.callback = callback;
|
||||
|
||||
this.treeData = this.convertToTreeData(nodes, rootNodeId, blackboard, connections);
|
||||
this.rootNodeId = this.treeData.rootNodeId;
|
||||
|
||||
this.assetManager.loadAsset(this.treeData);
|
||||
|
||||
this.entity = this.scene.createEntity('BehaviorTreeEntity');
|
||||
this.runtime = new BehaviorTreeRuntimeComponent();
|
||||
|
||||
// 在添加组件之前设置资产ID和autoStart
|
||||
this.runtime.treeAssetId = this.treeData.id;
|
||||
this.runtime.autoStart = false;
|
||||
|
||||
this.entity.addComponent(this.runtime);
|
||||
|
||||
if (this.treeData.blackboardVariables) {
|
||||
this.blackboardKeys = Array.from(this.treeData.blackboardVariables.keys());
|
||||
for (const [key, value] of this.treeData.blackboardVariables.entries()) {
|
||||
this.runtime.setBlackboardValue(key, value);
|
||||
}
|
||||
} else {
|
||||
this.blackboardKeys = [];
|
||||
}
|
||||
|
||||
this.addLog('行为树构建完成', 'info');
|
||||
}
|
||||
|
||||
/**
|
||||
* 将编辑器节点转换为BehaviorTreeData
|
||||
*/
|
||||
private convertToTreeData(
|
||||
nodes: BehaviorTreeNode[],
|
||||
rootNodeId: string,
|
||||
blackboard: Record<string, any>,
|
||||
connections: Array<{ from: string; to: string; fromProperty?: string; toProperty?: string; connectionType: 'node' | 'property' }>
|
||||
): BehaviorTreeData {
|
||||
const rootNode = nodes.find((n) => n.id === rootNodeId);
|
||||
if (!rootNode) {
|
||||
throw new Error('未找到根节点');
|
||||
}
|
||||
|
||||
// 如果根节点是编辑器特有的"根节点",跳过它,使用其子节点
|
||||
let actualRootId = rootNodeId;
|
||||
let skipRootNode = false;
|
||||
|
||||
if (rootNode.template.displayName === '根节点') {
|
||||
skipRootNode = true;
|
||||
|
||||
if (rootNode.children.length === 0) {
|
||||
// 树为空时,记录警告但不抛出错误
|
||||
this.addLog('行为树为空!请在编辑器中添加节点并连接到根节点', 'warning');
|
||||
// 返回一个空的有效树数据,避免崩溃
|
||||
return {
|
||||
id: `tree_${Date.now()}`,
|
||||
name: 'EmptyTree',
|
||||
rootNodeId: rootNodeId,
|
||||
nodes: new Map(),
|
||||
blackboardVariables: new Map()
|
||||
};
|
||||
}
|
||||
|
||||
if (rootNode.children.length === 1) {
|
||||
actualRootId = rootNode.children[0]!;
|
||||
} else {
|
||||
// 如果有多个子节点,记录警告
|
||||
this.addLog('根节点有多个子节点,请使用组合节点(如序列、选择)作为第一个子节点', 'warning');
|
||||
// 使用第一个子节点作为根节点
|
||||
actualRootId = rootNode.children[0]!;
|
||||
}
|
||||
}
|
||||
|
||||
const treeData: BehaviorTreeData = {
|
||||
id: `tree_${Date.now()}`,
|
||||
name: 'EditorTree',
|
||||
rootNodeId: actualRootId,
|
||||
nodes: new Map(),
|
||||
blackboardVariables: new Map()
|
||||
};
|
||||
|
||||
this.nodeIdMap.clear();
|
||||
|
||||
for (const node of nodes) {
|
||||
// 跳过编辑器的虚拟根节点
|
||||
if (skipRootNode && node.id === rootNodeId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
this.nodeIdMap.set(node.id, node.id);
|
||||
|
||||
const nodeData: BehaviorNodeData = {
|
||||
id: node.id,
|
||||
name: node.template.displayName,
|
||||
nodeType: this.convertNodeType(node.template.type),
|
||||
implementationType: node.template.className || this.getImplementationType(node.template.displayName),
|
||||
config: { ...node.data },
|
||||
children: Array.from(node.children)
|
||||
};
|
||||
|
||||
treeData.nodes.set(node.id, nodeData);
|
||||
}
|
||||
|
||||
// 处理属性连接,转换为 bindings
|
||||
for (const conn of connections) {
|
||||
if (conn.connectionType === 'property' && conn.toProperty) {
|
||||
const targetNodeData = treeData.nodes.get(conn.to);
|
||||
const sourceNode = nodes.find((n) => n.id === conn.from);
|
||||
|
||||
if (targetNodeData && sourceNode) {
|
||||
// 检查源节点是否是黑板变量节点
|
||||
if (sourceNode.data.nodeType === 'blackboard-variable') {
|
||||
// 从黑板变量节点获取实际的变量名
|
||||
const variableName = sourceNode.data.variableName as string;
|
||||
|
||||
if (variableName) {
|
||||
// 初始化 bindings 如果不存在
|
||||
if (!targetNodeData.bindings) {
|
||||
targetNodeData.bindings = {};
|
||||
}
|
||||
|
||||
// 添加绑定:属性名 -> 黑板变量名
|
||||
targetNodeData.bindings[conn.toProperty] = variableName;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(blackboard)) {
|
||||
treeData.blackboardVariables!.set(key, value);
|
||||
}
|
||||
|
||||
return treeData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换节点类型
|
||||
*/
|
||||
private convertNodeType(type: string): NodeType {
|
||||
if (type === NodeType.Composite) return NodeType.Composite;
|
||||
if (type === NodeType.Decorator) return NodeType.Decorator;
|
||||
if (type === NodeType.Action) return NodeType.Action;
|
||||
if (type === NodeType.Condition) return NodeType.Condition;
|
||||
return NodeType.Action;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据显示名称获取实现类型
|
||||
*/
|
||||
private getImplementationType(displayName: string): string {
|
||||
const typeMap: Record<string, string> = {
|
||||
'序列': 'Sequence',
|
||||
'选择': 'Selector',
|
||||
'并行': 'Parallel',
|
||||
'并行选择': 'ParallelSelector',
|
||||
'随机序列': 'RandomSequence',
|
||||
'随机选择': 'RandomSelector',
|
||||
'反转': 'Inverter',
|
||||
'重复': 'Repeater',
|
||||
'直到成功': 'UntilSuccess',
|
||||
'直到失败': 'UntilFail',
|
||||
'总是成功': 'AlwaysSucceed',
|
||||
'总是失败': 'AlwaysFail',
|
||||
'条件装饰器': 'Conditional',
|
||||
'冷却': 'Cooldown',
|
||||
'超时': 'Timeout',
|
||||
'等待': 'Wait',
|
||||
'日志': 'Log',
|
||||
'设置变量': 'SetBlackboardValue',
|
||||
'修改变量': 'ModifyBlackboardValue',
|
||||
'自定义动作': 'ExecuteAction',
|
||||
'比较变量': 'BlackboardCompare',
|
||||
'变量存在': 'BlackboardExists',
|
||||
'随机概率': 'RandomProbability',
|
||||
'执行条件': 'ExecuteCondition'
|
||||
};
|
||||
|
||||
return typeMap[displayName] || displayName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始执行
|
||||
*/
|
||||
start(): void {
|
||||
if (!this.runtime || !this.treeData) {
|
||||
logger.error('未构建行为树');
|
||||
return;
|
||||
}
|
||||
|
||||
this.isRunning = true;
|
||||
this.isPaused = false;
|
||||
this.executionLogs = [];
|
||||
this.lastStatuses.clear();
|
||||
this.persistentStatuses.clear();
|
||||
this.tickCount = 0;
|
||||
|
||||
this.runtime.resetAllStates();
|
||||
this.runtime.isRunning = true;
|
||||
|
||||
// 开始新的执行路径
|
||||
useExecutionStatsStore.getState().startNewPath();
|
||||
|
||||
this.addLog('开始执行行为树', 'info');
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停执行
|
||||
*/
|
||||
pause(): void {
|
||||
this.isPaused = true;
|
||||
this.isRunning = false;
|
||||
if (this.runtime) {
|
||||
this.runtime.isRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复执行
|
||||
*/
|
||||
resume(): void {
|
||||
this.isPaused = false;
|
||||
this.isRunning = true;
|
||||
if (this.runtime) {
|
||||
this.runtime.isRunning = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 停止执行
|
||||
*/
|
||||
stop(): void {
|
||||
this.isRunning = false;
|
||||
this.isPaused = false;
|
||||
|
||||
if (this.runtime) {
|
||||
this.runtime.isRunning = false;
|
||||
this.runtime.resetAllStates();
|
||||
}
|
||||
|
||||
// 结束当前执行路径
|
||||
useExecutionStatsStore.getState().endCurrentPath();
|
||||
|
||||
this.addLog('行为树已停止', 'info');
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行一帧
|
||||
*/
|
||||
tick(deltaTime: number): void {
|
||||
if (!this.isRunning || this.isPaused || !this.runtime) {
|
||||
return;
|
||||
}
|
||||
|
||||
Time.update(deltaTime);
|
||||
this.tickCount++;
|
||||
|
||||
this.scene.update();
|
||||
this.collectExecutionStatus();
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集所有节点的执行状态
|
||||
*/
|
||||
private collectExecutionStatus(): void {
|
||||
if (!this.callback || !this.runtime || !this.treeData) return;
|
||||
|
||||
const rootState = this.runtime.getNodeState(this.rootNodeId);
|
||||
let rootCurrentStatus: 'running' | 'success' | 'failure' | 'idle' = 'idle';
|
||||
|
||||
if (rootState) {
|
||||
switch (rootState.status) {
|
||||
case TaskStatus.Running:
|
||||
rootCurrentStatus = 'running';
|
||||
break;
|
||||
case TaskStatus.Success:
|
||||
rootCurrentStatus = 'success';
|
||||
break;
|
||||
case TaskStatus.Failure:
|
||||
rootCurrentStatus = 'failure';
|
||||
break;
|
||||
default:
|
||||
rootCurrentStatus = 'idle';
|
||||
}
|
||||
}
|
||||
|
||||
const rootLastStatus = this.lastStatuses.get(this.rootNodeId);
|
||||
|
||||
if (rootLastStatus &&
|
||||
(rootLastStatus === 'success' || rootLastStatus === 'failure') &&
|
||||
rootCurrentStatus === 'running') {
|
||||
this.persistentStatuses.clear();
|
||||
this.executionOrders.clear();
|
||||
}
|
||||
|
||||
const statuses: ExecutionStatus[] = [];
|
||||
|
||||
for (const [nodeId, nodeData] of this.treeData.nodes.entries()) {
|
||||
const state = this.runtime.getNodeState(nodeId);
|
||||
|
||||
let currentStatus: 'running' | 'success' | 'failure' | 'idle' = 'idle';
|
||||
|
||||
if (state) {
|
||||
switch (state.status) {
|
||||
case TaskStatus.Success:
|
||||
currentStatus = 'success';
|
||||
break;
|
||||
case TaskStatus.Failure:
|
||||
currentStatus = 'failure';
|
||||
break;
|
||||
case TaskStatus.Running:
|
||||
currentStatus = 'running';
|
||||
break;
|
||||
default:
|
||||
currentStatus = 'idle';
|
||||
}
|
||||
}
|
||||
|
||||
const persistentStatus = this.persistentStatuses.get(nodeId) || 'idle';
|
||||
const lastStatus = this.lastStatuses.get(nodeId);
|
||||
|
||||
let displayStatus: 'running' | 'success' | 'failure' | 'idle' = currentStatus;
|
||||
|
||||
if (currentStatus === 'running') {
|
||||
displayStatus = 'running';
|
||||
this.persistentStatuses.set(nodeId, 'running');
|
||||
} else if (currentStatus === 'success') {
|
||||
displayStatus = 'success';
|
||||
this.persistentStatuses.set(nodeId, 'success');
|
||||
} else if (currentStatus === 'failure') {
|
||||
displayStatus = 'failure';
|
||||
this.persistentStatuses.set(nodeId, 'failure');
|
||||
} else if (currentStatus === 'idle') {
|
||||
if (persistentStatus !== 'idle') {
|
||||
displayStatus = persistentStatus;
|
||||
} else if (this.executionOrders.has(nodeId)) {
|
||||
displayStatus = 'success';
|
||||
this.persistentStatuses.set(nodeId, 'success');
|
||||
} else {
|
||||
displayStatus = 'idle';
|
||||
}
|
||||
}
|
||||
|
||||
// 检测状态变化
|
||||
const hasStateChanged = lastStatus !== currentStatus;
|
||||
|
||||
// 从运行时状态读取执行顺序
|
||||
if (state?.executionOrder !== undefined && !this.executionOrders.has(nodeId)) {
|
||||
this.executionOrders.set(nodeId, state.executionOrder);
|
||||
logger.info(`[ExecutionOrder READ] ${nodeData.name} | ID: ${nodeId} | Order: ${state.executionOrder}`);
|
||||
}
|
||||
|
||||
// 集成执行统计记录
|
||||
if (hasStateChanged) {
|
||||
// 从 idle/success/failure 到 running:记录节点开始
|
||||
if (currentStatus === 'running' && lastStatus !== 'running') {
|
||||
const executionOrder = state?.executionOrder ?? 0;
|
||||
useExecutionStatsStore.getState().recordNodeStart(nodeId, executionOrder);
|
||||
|
||||
// 检查断点
|
||||
logger.info(`[Breakpoint Debug] Node ${nodeData.name} (${nodeId}) started running`);
|
||||
logger.info(`[Breakpoint Debug] Breakpoints count:`, this.breakpoints.size);
|
||||
logger.info(`[Breakpoint Debug] Has breakpoint:`, this.breakpoints.has(nodeId));
|
||||
|
||||
const breakpoint = this.breakpoints.get(nodeId);
|
||||
if (breakpoint) {
|
||||
logger.info(`[Breakpoint Debug] Breakpoint found, enabled:`, breakpoint.enabled);
|
||||
if (breakpoint.enabled) {
|
||||
this.addLog(`断点触发: ${nodeData.name}`, 'warning', nodeId);
|
||||
logger.info(`[Breakpoint Debug] Calling onBreakpointHit callback:`, !!this.onBreakpointHit);
|
||||
if (this.onBreakpointHit) {
|
||||
this.onBreakpointHit(nodeId, nodeData.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 从 running 到 success/failure:记录节点结束
|
||||
else if (lastStatus === 'running' && (currentStatus === 'success' || currentStatus === 'failure')) {
|
||||
useExecutionStatsStore.getState().recordNodeEnd(nodeId, currentStatus);
|
||||
}
|
||||
}
|
||||
|
||||
// 记录状态变化日志
|
||||
if (hasStateChanged && currentStatus !== 'idle') {
|
||||
this.onNodeStatusChanged(nodeId, nodeData.name, lastStatus || 'idle', currentStatus);
|
||||
}
|
||||
|
||||
this.lastStatuses.set(nodeId, currentStatus);
|
||||
|
||||
statuses.push({
|
||||
nodeId,
|
||||
status: displayStatus,
|
||||
executionOrder: this.executionOrders.get(nodeId)
|
||||
});
|
||||
}
|
||||
|
||||
const currentBlackboardVars = this.getBlackboardVariables();
|
||||
this.callback(statuses, this.executionLogs, currentBlackboardVars);
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点状态变化时记录日志
|
||||
*/
|
||||
private onNodeStatusChanged(
|
||||
nodeId: string,
|
||||
nodeName: string,
|
||||
oldStatus: string,
|
||||
newStatus: string
|
||||
): void {
|
||||
if (newStatus === 'running') {
|
||||
this.addLog(`[${nodeName}](${nodeId}) 开始执行`, 'info', nodeId);
|
||||
} else if (newStatus === 'success') {
|
||||
this.addLog(`[${nodeName}](${nodeId}) 执行成功`, 'success', nodeId);
|
||||
} else if (newStatus === 'failure') {
|
||||
this.addLog(`[${nodeName}](${nodeId}) 执行失败`, 'error', nodeId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加日志
|
||||
*/
|
||||
private addLog(message: string, level: 'info' | 'success' | 'error' | 'warning', nodeId?: string): void {
|
||||
this.executionLogs.push({
|
||||
timestamp: Date.now(),
|
||||
message,
|
||||
level,
|
||||
nodeId
|
||||
});
|
||||
|
||||
if (this.executionLogs.length > 1000) {
|
||||
this.executionLogs.shift();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前tick计数
|
||||
*/
|
||||
getTickCount(): number {
|
||||
return this.tickCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取黑板变量
|
||||
*/
|
||||
getBlackboardVariables(): Record<string, any> {
|
||||
if (!this.runtime) return {};
|
||||
|
||||
const variables: Record<string, any> = {};
|
||||
|
||||
for (const name of this.blackboardKeys) {
|
||||
variables[name] = this.runtime.getBlackboardValue(name);
|
||||
}
|
||||
|
||||
return variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新黑板变量
|
||||
*/
|
||||
updateBlackboardVariable(key: string, value: any): void {
|
||||
if (!this.runtime) {
|
||||
logger.warn('无法更新黑板变量:未构建行为树');
|
||||
return;
|
||||
}
|
||||
|
||||
this.runtime.setBlackboardValue(key, value);
|
||||
logger.info(`黑板变量已更新: ${key} = ${JSON.stringify(value)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置断点
|
||||
*/
|
||||
setBreakpoints(breakpoints: Map<string, Breakpoint>): void {
|
||||
this.breakpoints = breakpoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置断点触发回调
|
||||
*/
|
||||
setBreakpointCallback(callback: BreakpointCallback | null): void {
|
||||
this.onBreakpointHit = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理资源
|
||||
*/
|
||||
cleanup(): void {
|
||||
this.stop();
|
||||
this.nodeIdMap.clear();
|
||||
this.lastStatuses.clear();
|
||||
this.persistentStatuses.clear();
|
||||
this.blackboardKeys = [];
|
||||
|
||||
if (this.entity) {
|
||||
this.entity.destroy();
|
||||
this.entity = null;
|
||||
}
|
||||
|
||||
// 卸载旧的行为树资产
|
||||
if (this.treeData) {
|
||||
this.assetManager.unloadAsset(this.treeData.id);
|
||||
}
|
||||
|
||||
this.runtime = null;
|
||||
this.treeData = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查节点的执行器是否存在
|
||||
*/
|
||||
hasExecutor(implementationType: string): boolean {
|
||||
const registry = this.executionSystem.getExecutorRegistry();
|
||||
return registry.has(implementationType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁
|
||||
*/
|
||||
destroy(): void {
|
||||
this.cleanup();
|
||||
}
|
||||
}
|
||||
125
packages/behavior-tree-editor/src/utils/DOMCache.ts
Normal file
125
packages/behavior-tree-editor/src/utils/DOMCache.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
type NodeExecutionStatus = 'idle' | 'running' | 'success' | 'failure';
|
||||
|
||||
export class DOMCache {
|
||||
private nodeElements: Map<string, Element> = new Map();
|
||||
private connectionElements: Map<string, Element> = new Map();
|
||||
private lastNodeStatus: Map<string, NodeExecutionStatus> = new Map();
|
||||
private statusTimers: Map<string, number> = new Map();
|
||||
|
||||
getNode(nodeId: string): Element | undefined {
|
||||
let element = this.nodeElements.get(nodeId);
|
||||
if (!element) {
|
||||
element = document.querySelector(`[data-node-id="${nodeId}"]`) || undefined;
|
||||
if (element) {
|
||||
this.nodeElements.set(nodeId, element);
|
||||
}
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
getConnection(connectionKey: string): Element | undefined {
|
||||
let element = this.connectionElements.get(connectionKey);
|
||||
if (!element) {
|
||||
element = document.querySelector(`[data-connection-id="${connectionKey}"]`) || undefined;
|
||||
if (element) {
|
||||
this.connectionElements.set(connectionKey, element);
|
||||
}
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
getLastStatus(nodeId: string): NodeExecutionStatus | undefined {
|
||||
return this.lastNodeStatus.get(nodeId);
|
||||
}
|
||||
|
||||
setLastStatus(nodeId: string, status: NodeExecutionStatus): void {
|
||||
this.lastNodeStatus.set(nodeId, status);
|
||||
}
|
||||
|
||||
hasStatusChanged(nodeId: string, newStatus: NodeExecutionStatus): boolean {
|
||||
return this.lastNodeStatus.get(nodeId) !== newStatus;
|
||||
}
|
||||
|
||||
getStatusTimer(nodeId: string): number | undefined {
|
||||
return this.statusTimers.get(nodeId);
|
||||
}
|
||||
|
||||
setStatusTimer(nodeId: string, timerId: number): void {
|
||||
this.statusTimers.set(nodeId, timerId);
|
||||
}
|
||||
|
||||
clearStatusTimer(nodeId: string): void {
|
||||
const timerId = this.statusTimers.get(nodeId);
|
||||
if (timerId) {
|
||||
clearTimeout(timerId);
|
||||
this.statusTimers.delete(nodeId);
|
||||
}
|
||||
}
|
||||
|
||||
clearAllStatusTimers(): void {
|
||||
this.statusTimers.forEach((timerId) => clearTimeout(timerId));
|
||||
this.statusTimers.clear();
|
||||
}
|
||||
|
||||
clearNodeCache(): void {
|
||||
this.nodeElements.clear();
|
||||
}
|
||||
|
||||
clearConnectionCache(): void {
|
||||
this.connectionElements.clear();
|
||||
}
|
||||
|
||||
clearStatusCache(): void {
|
||||
this.lastNodeStatus.clear();
|
||||
}
|
||||
|
||||
clearAll(): void {
|
||||
this.clearNodeCache();
|
||||
this.clearConnectionCache();
|
||||
this.clearStatusCache();
|
||||
this.clearAllStatusTimers();
|
||||
}
|
||||
|
||||
removeNodeClasses(nodeId: string, ...classes: string[]): void {
|
||||
const element = this.getNode(nodeId);
|
||||
if (element) {
|
||||
element.classList.remove(...classes);
|
||||
}
|
||||
}
|
||||
|
||||
addNodeClasses(nodeId: string, ...classes: string[]): void {
|
||||
const element = this.getNode(nodeId);
|
||||
if (element) {
|
||||
element.classList.add(...classes);
|
||||
}
|
||||
}
|
||||
|
||||
hasNodeClass(nodeId: string, className: string): boolean {
|
||||
const element = this.getNode(nodeId);
|
||||
return element?.classList.contains(className) || false;
|
||||
}
|
||||
|
||||
setConnectionAttribute(connectionKey: string, attribute: string, value: string): void {
|
||||
const element = this.getConnection(connectionKey);
|
||||
if (element) {
|
||||
element.setAttribute(attribute, value);
|
||||
}
|
||||
}
|
||||
|
||||
getConnectionAttribute(connectionKey: string, attribute: string): string | null {
|
||||
const element = this.getConnection(connectionKey);
|
||||
return element?.getAttribute(attribute) || null;
|
||||
}
|
||||
|
||||
forEachNode(callback: (element: Element, nodeId: string) => void): void {
|
||||
this.nodeElements.forEach((element, nodeId) => {
|
||||
callback(element, nodeId);
|
||||
});
|
||||
}
|
||||
|
||||
forEachConnection(callback: (element: Element, connectionKey: string) => void): void {
|
||||
this.connectionElements.forEach((element, connectionKey) => {
|
||||
callback(element, connectionKey);
|
||||
});
|
||||
}
|
||||
}
|
||||
192
packages/behavior-tree-editor/src/utils/RuntimeLoader.ts
Normal file
192
packages/behavior-tree-editor/src/utils/RuntimeLoader.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import { BehaviorTreeAssetManager, BehaviorTreeData } from '@esengine/behavior-tree';
|
||||
import { BehaviorTreeSerializer } from '../infrastructure/serialization/BehaviorTreeSerializer';
|
||||
import { BehaviorTree } from '../domain/models/BehaviorTree';
|
||||
|
||||
/**
|
||||
* 运行时加载配置
|
||||
*/
|
||||
export interface RuntimeLoaderConfig {
|
||||
assetManager: BehaviorTreeAssetManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* 行为树运行时加载器
|
||||
*
|
||||
* 提供便捷的方法将编辑器导出的行为树加载到运行时
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const assetManager = Core.services.resolve(BehaviorTreeAssetManager);
|
||||
* const loader = new RuntimeLoader({ assetManager });
|
||||
*
|
||||
* // 从JSON字符串加载
|
||||
* const treeData = loader.loadFromJSON(jsonString);
|
||||
*
|
||||
* // 从文件加载(需要提供读取方法)
|
||||
* const jsonContent = await readFile('path/to/tree.btree');
|
||||
* const treeData = loader.loadFromJSON(jsonContent);
|
||||
*
|
||||
* // 使用加载的行为树
|
||||
* const entity = scene.createEntity('AI');
|
||||
* const btComponent = entity.addComponent(BehaviorTreeRuntimeComponent);
|
||||
* btComponent.setTreeData(treeData);
|
||||
* ```
|
||||
*/
|
||||
export class RuntimeLoader {
|
||||
private assetManager: BehaviorTreeAssetManager;
|
||||
private serializer: BehaviorTreeSerializer;
|
||||
|
||||
constructor(config: RuntimeLoaderConfig) {
|
||||
this.assetManager = config.assetManager;
|
||||
this.serializer = new BehaviorTreeSerializer();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从编辑器JSON字符串加载行为树
|
||||
*
|
||||
* @param json 编辑器保存的JSON字符串
|
||||
* @returns 加载的行为树数据
|
||||
*/
|
||||
loadFromJSON(json: string): BehaviorTreeData {
|
||||
return this.assetManager.loadFromEditorJSON(json);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量加载多个行为树
|
||||
*
|
||||
* @param jsonList JSON字符串列表
|
||||
* @returns 成功加载的数量
|
||||
*/
|
||||
loadMultiple(jsonList: string[]): number {
|
||||
return this.assetManager.loadMultipleFromEditorJSON(jsonList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已加载的行为树
|
||||
*
|
||||
* @param assetId 资产ID
|
||||
* @returns 行为树数据,如果未找到返回undefined
|
||||
*/
|
||||
getTree(assetId: string): BehaviorTreeData | undefined {
|
||||
return this.assetManager.getAsset(assetId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查行为树是否已加载
|
||||
*
|
||||
* @param assetId 资产ID
|
||||
* @returns 是否已加载
|
||||
*/
|
||||
isLoaded(assetId: string): boolean {
|
||||
return this.assetManager.hasAsset(assetId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载行为树
|
||||
*
|
||||
* @param assetId 资产ID
|
||||
* @returns 是否成功卸载
|
||||
*/
|
||||
unload(assetId: string): boolean {
|
||||
return this.assetManager.unloadAsset(assetId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有已加载的行为树
|
||||
*/
|
||||
clearAll(): void {
|
||||
this.assetManager.clearAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有已加载的行为树ID
|
||||
*
|
||||
* @returns 资产ID列表
|
||||
*/
|
||||
getAllLoadedIds(): string[] {
|
||||
return this.assetManager.getAllAssetIds();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已加载的行为树数量
|
||||
*
|
||||
* @returns 数量
|
||||
*/
|
||||
getLoadedCount(): number {
|
||||
return this.assetManager.getAssetCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证JSON格式是否有效
|
||||
*
|
||||
* @param json JSON字符串
|
||||
* @returns 验证结果
|
||||
*/
|
||||
validateJSON(json: string): { valid: boolean; error?: string } {
|
||||
try {
|
||||
const obj = JSON.parse(json);
|
||||
|
||||
if (!obj.nodes || !Array.isArray(obj.nodes)) {
|
||||
return { valid: false, error: '缺少nodes字段或格式不正确' };
|
||||
}
|
||||
|
||||
if (!obj.metadata) {
|
||||
return { valid: false, error: '缺少metadata字段' };
|
||||
}
|
||||
|
||||
if (obj.nodes.length === 0) {
|
||||
return { valid: false, error: '行为树没有节点' };
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
} catch (error) {
|
||||
return {
|
||||
valid: false,
|
||||
error: error instanceof Error ? error.message : '无效的JSON格式'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从编辑器BehaviorTree对象导出为运行时资产JSON
|
||||
*
|
||||
* @param tree 编辑器行为树对象
|
||||
* @returns JSON字符串
|
||||
*/
|
||||
exportTreeToJSON(tree: BehaviorTree): string {
|
||||
const result = this.serializer.exportToRuntimeAsset(tree, 'json');
|
||||
if (typeof result !== 'string') {
|
||||
throw new Error('导出失败:期望字符串格式');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从编辑器BehaviorTree对象导出为运行时资产二进制
|
||||
*
|
||||
* @param tree 编辑器行为树对象
|
||||
* @returns 二进制数据
|
||||
*/
|
||||
exportTreeToBinary(tree: BehaviorTree): Uint8Array {
|
||||
const result = this.serializer.exportToRuntimeAsset(tree, 'binary');
|
||||
if (!(result instanceof Uint8Array)) {
|
||||
throw new Error('导出失败:期望二进制格式');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建运行时加载器的工厂函数
|
||||
*
|
||||
* @param assetManager 行为树资产管理器
|
||||
* @returns 运行时加载器实例
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const loader = createRuntimeLoader(assetManager);
|
||||
* ```
|
||||
*/
|
||||
export function createRuntimeLoader(assetManager: BehaviorTreeAssetManager): RuntimeLoader {
|
||||
return new RuntimeLoader({ assetManager });
|
||||
}
|
||||
61
packages/behavior-tree-editor/src/utils/portUtils.ts
Normal file
61
packages/behavior-tree-editor/src/utils/portUtils.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { RefObject } from 'react';
|
||||
import { Node as BehaviorTreeNode } from '../domain/models/Node';
|
||||
import { createLogger } from '@esengine/ecs-framework';
|
||||
|
||||
const logger = createLogger('portUtils');
|
||||
|
||||
/**
|
||||
* 获取端口在画布世界坐标系中的位置
|
||||
* 直接从 DOM 元素获取实际渲染位置,避免硬编码和手动计算
|
||||
*/
|
||||
export function getPortPosition(
|
||||
canvasRef: RefObject<HTMLDivElement>,
|
||||
canvasOffset: { x: number; y: number },
|
||||
canvasScale: number,
|
||||
nodes: BehaviorTreeNode[],
|
||||
nodeId: string,
|
||||
propertyName?: string,
|
||||
portType: 'input' | 'output' = 'output',
|
||||
draggingNodeId?: string | null,
|
||||
dragDelta?: { dx: number; dy: number },
|
||||
selectedNodeIds?: string[]
|
||||
): { x: number; y: number } | null {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return null;
|
||||
|
||||
const node = nodes.find((n: BehaviorTreeNode) => n.id === nodeId);
|
||||
if (!node) return null;
|
||||
|
||||
// 构造端口选择器
|
||||
let portSelector: string;
|
||||
|
||||
if (propertyName) {
|
||||
// 属性端口:使用 data-property 属性定位
|
||||
portSelector = `[data-node-id="${nodeId}"][data-property="${propertyName}"]`;
|
||||
} else {
|
||||
// 节点端口:使用 data-port-type 属性定位
|
||||
const portTypeAttr = portType === 'input' ? 'node-input' : 'node-output';
|
||||
portSelector = `[data-node-id="${nodeId}"][data-port-type="${portTypeAttr}"]`;
|
||||
}
|
||||
|
||||
const portElement = canvas.querySelector(portSelector) as HTMLElement;
|
||||
if (!portElement) {
|
||||
logger.warn(`Port not found: ${portSelector}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// 获取端口和画布的屏幕矩形
|
||||
const portRect = portElement.getBoundingClientRect();
|
||||
const canvasRect = canvas.getBoundingClientRect();
|
||||
|
||||
// 计算端口中心相对于画布的屏幕坐标
|
||||
const screenX = portRect.left + portRect.width / 2 - canvasRect.left;
|
||||
const screenY = portRect.top + portRect.height / 2 - canvasRect.top;
|
||||
|
||||
// 转换为世界坐标
|
||||
// 屏幕坐标到世界坐标的转换:world = (screen - offset) / scale
|
||||
const worldX = (screenX - canvasOffset.x) / canvasScale;
|
||||
const worldY = (screenY - canvasOffset.y) / canvasScale;
|
||||
|
||||
return { x: worldX, y: worldY };
|
||||
}
|
||||
Reference in New Issue
Block a user