Files
esengine/extensions/cocos/cocos-ecs/assets/scripts/components/BehaviorTreeManager.ts

286 lines
9.8 KiB
TypeScript
Raw Normal View History

import { _decorator, Component, resources, JsonAsset, Vec3 } from 'cc';
import { BehaviorTree, BehaviorTreeBuilder, Blackboard, BehaviorTreeJSONConfig, ExecutionContext, EventRegistry } from '@esengine/ai';
2025-06-24 19:34:37 +08:00
import { UnitController } from './UnitController';
import { RTSBehaviorHandler } from './RTSBehaviorHandler';
2025-06-24 19:34:37 +08:00
const { ccclass, property } = _decorator;
/**
*
* ExecutionContext
2025-06-24 19:34:37 +08:00
*/
interface GameExecutionContext extends ExecutionContext {
2025-06-24 19:34:37 +08:00
unitController: UnitController;
gameObject: any;
eventRegistry?: EventRegistry;
// 确保继承索引签名
[key: string]: unknown;
2025-06-24 19:34:37 +08:00
}
/**
* - 使@esengine/ai包管理行为树
*/
@ccclass('BehaviorTreeManager')
export class BehaviorTreeManager extends Component {
@property
debugMode: boolean = true;
@property
tickInterval: number = 0.1; // 行为树更新间隔(秒)- 10fps更新频率平衡性能和响应性
2025-06-24 19:34:37 +08:00
private behaviorTree: BehaviorTree<GameExecutionContext> | null = null;
private blackboard: Blackboard | null = null;
private context: GameExecutionContext | null = null;
private eventRegistry: EventRegistry | null = null;
2025-06-24 19:34:37 +08:00
private isLoaded: boolean = false;
private isRunning: boolean = false;
private lastTickTime: number = 0;
private unitController: UnitController | null = null;
private currentBehaviorTreeName: string = '';
private behaviorHandler: RTSBehaviorHandler | null = null;
2025-06-24 19:34:37 +08:00
/**
*
*/
async initializeBehaviorTree(behaviorTreeName: string, unitController: UnitController) {
this.currentBehaviorTreeName = behaviorTreeName;
this.unitController = unitController;
// 获取RTSBehaviorHandler组件
this.behaviorHandler = this.getComponent(RTSBehaviorHandler);
if (!this.behaviorHandler) {
console.error(`BehaviorTreeManager: 未找到RTSBehaviorHandler组件 - ${this.node.name}`);
return;
}
2025-06-24 19:34:37 +08:00
try {
await this.loadBehaviorTree(behaviorTreeName);
this.setupBlackboard();
this.isLoaded = true;
this.isRunning = true;
console.log(`✅ 行为树初始化成功: ${behaviorTreeName} for ${this.unitController.node.name}`);
console.log(` - 行为树: ${this.behaviorTree ? '已创建' : '未创建'}`);
console.log(` - 黑板变量: ${this.blackboard ? '已创建' : '未创建'}`);
console.log(` - 运行状态: ${this.isRunning ? '运行中' : '已停止'}`);
2025-06-24 19:34:37 +08:00
} catch (error) {
console.error(`行为树初始化失败: ${behaviorTreeName}`, error);
}
}
/**
*
*/
private async loadBehaviorTree(behaviorTreeName: string): Promise<void> {
return new Promise((resolve, reject) => {
const jsonPath = `${behaviorTreeName}.bt`;
console.log(`🔍 尝试加载行为树文件: ${jsonPath}`);
2025-06-24 19:34:37 +08:00
resources.load(jsonPath, JsonAsset, (err, asset) => {
if (err) {
console.error(`加载行为树文件失败: ${jsonPath}`, err);
reject(err);
return;
}
try {
const behaviorTreeData = asset.json as BehaviorTreeJSONConfig;
// 创建执行上下文
this.blackboard = new Blackboard();
this.eventRegistry = this.createEventRegistry();
2025-06-24 19:34:37 +08:00
this.context = {
blackboard: this.blackboard,
unitController: this.unitController!,
gameObject: this.node,
eventRegistry: this.eventRegistry
} as GameExecutionContext;
2025-06-24 19:34:37 +08:00
// 从JSON数据创建行为树
const buildResult = BehaviorTreeBuilder.fromBehaviorTreeConfig<GameExecutionContext>(behaviorTreeData, this.context);
this.behaviorTree = buildResult.tree;
2025-06-24 19:34:37 +08:00
this.blackboard = buildResult.blackboard;
resolve();
} catch (parseError) {
console.error(`创建行为树失败: ${jsonPath}`, parseError);
reject(parseError);
}
});
});
}
/**
*
*/
private createEventRegistry(): EventRegistry {
const registry = new EventRegistry();
// 注册简化的矿工行为事件处理器
const eventHandlers = {
// 矿工核心行为
'find-and-mine-ore': (context: any, params?: any) => this.callBehaviorHandler('onFindAndMineOre', params),
'store-ore': (context: any, params?: any) => this.callBehaviorHandler('onStoreOre', params),
'idle-behavior': (context: any, params?: any) => this.callBehaviorHandler('onIdleBehavior', params)
};
// 将事件处理器注册到EventRegistry
Object.entries(eventHandlers).forEach(([eventName, handler]) => {
registry.registerAction(eventName, handler);
});
return registry;
}
/**
*
*/
private callBehaviorHandler(methodName: string, params: any = {}): string {
if (!this.behaviorHandler) {
console.error(`BehaviorTreeManager: RTSBehaviorHandler未初始化 - ${this.node.name}`);
return 'failure';
}
try {
// 直接调用RTSBehaviorHandler的方法
const method = (this.behaviorHandler as any)[methodName];
if (typeof method === 'function') {
console.log(`🎯 调用行为处理器: ${methodName} (${this.node.name})`);
const result = method.call(this.behaviorHandler, params);
console.log(`📤 行为处理器返回: ${methodName} -> "${result}" (${this.node.name})`);
return result || 'success'; // 确保有返回值
} else {
console.error(`BehaviorTreeManager: 方法不存在: ${methodName}`);
return 'failure';
}
} catch (error) {
console.error(`BehaviorTreeManager: 调用方法失败: ${methodName}`, error);
return 'failure';
}
}
2025-06-24 19:34:37 +08:00
/**
*
*/
private setupBlackboard() {
if (!this.unitController || !this.blackboard) return;
// 设置矿工基础信息
2025-06-24 19:34:37 +08:00
this.blackboard.setValue('unitType', this.unitController.unitType);
this.blackboard.setValue('currentHealth', this.unitController.currentHealth);
this.blackboard.setValue('maxHealth', this.unitController.maxHealth);
this.blackboard.setValue('currentCommand', 'mine');
this.blackboard.setValue('hasOre', false);
2025-06-24 19:34:37 +08:00
this.blackboard.setValue('hasTarget', false);
this.blackboard.setValue('targetPosition', null);
this.blackboard.setValue('isMoving', false);
2025-06-24 19:34:37 +08:00
}
/**
*
*/
updateBlackboardValue(key: string, value: any) {
if (this.blackboard) {
this.blackboard.setValue(key, value);
}
}
/**
*
*/
getBlackboardValue(key: string): any {
return this.blackboard?.getValue(key);
}
/**
*
*/
getBlackboard(): Blackboard | null {
return this.blackboard;
}
/**
*
*/
getBehaviorTree(): BehaviorTree<GameExecutionContext> | null {
return this.behaviorTree;
}
/**
*
*/
update(deltaTime: number) {
if (!this.isLoaded || !this.isRunning || !this.behaviorTree || !this.blackboard) return;
// 控制更新频率
this.lastTickTime += deltaTime;
if (this.lastTickTime < this.tickInterval) return;
this.lastTickTime = 0;
// 更新矿工状态信息
2025-06-24 19:34:37 +08:00
if (this.unitController) {
this.blackboard.setValue('currentHealth', this.unitController.currentHealth);
this.blackboard.setValue('currentCommand', this.unitController.currentCommand);
this.blackboard.setValue('hasTarget', this.unitController.targetPosition && !this.unitController.targetPosition.equals(Vec3.ZERO));
2025-06-24 19:34:37 +08:00
this.blackboard.setValue('targetPosition', this.unitController.targetPosition);
this.blackboard.setValue('isMoving', this.unitController.targetPosition && !this.unitController.targetPosition.equals(Vec3.ZERO));
2025-06-24 19:34:37 +08:00
}
// 执行行为树
try {
this.behaviorTree.tick(deltaTime);
} catch (error) {
console.error(`行为树执行错误: ${this.node.name}`, error);
2025-06-24 19:34:37 +08:00
}
}
/**
*
*/
pause() {
this.isRunning = false;
}
/**
*
*/
resume() {
if (this.isLoaded) {
this.isRunning = true;
}
}
/**
*
*/
stop() {
this.isRunning = false;
}
/**
*
*/
async reloadBehaviorTree() {
if (this.currentBehaviorTreeName && this.unitController) {
this.stop();
await this.initializeBehaviorTree(this.currentBehaviorTreeName, this.unitController);
}
}
/**
*
*/
reset() {
if (this.behaviorTree) {
this.behaviorTree.reset();
}
}
onDestroy() {
this.stop();
this.behaviorTree = null;
this.blackboard = null;
this.context = null;
}
}