@esengine/behavior-tree 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs DELETED
@@ -1,2 +0,0 @@
1
- import{Component as e,Serialize as t,IgnoreSerialization as n,ECSComponent as r,Serializable as o,createLogger as i,Core as a,EntitySystem as s,Matcher as c,Time as d,ECSSystem as l,BinarySerializer as u,WorldManager as h}from"@esengine/ecs-framework";var p;!function(e){e[e.Invalid=0]="Invalid",e[e.Success=1]="Success",e[e.Failure=2]="Failure",e[e.Running=3]="Running"}(p||(p={}));const g={Composite:"composite",Decorator:"decorator",Action:"action",Condition:"condition"};var m,f,y,b;function S(){return{status:p.Invalid,currentChildIndex:0}}function C(e,t,n,r){var o,i=arguments.length,a=i<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function v(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}!function(e){e.Sequence="sequence",e.Selector="selector",e.Parallel="parallel",e.ParallelSelector="parallel-selector",e.RandomSequence="random-sequence",e.RandomSelector="random-selector"}(m||(m={})),function(e){e.Inverter="inverter",e.Repeater="repeater",e.UntilSuccess="until-success",e.UntilFail="until-fail",e.AlwaysSucceed="always-succeed",e.AlwaysFail="always-fail",e.Conditional="conditional",e.Cooldown="cooldown",e.Timeout="timeout"}(f||(f={})),function(e){e.None="none",e.Self="self",e.LowerPriority="lower-priority",e.Both="both"}(y||(y={})),function(e){e.String="string",e.Number="number",e.Boolean="boolean",e.Vector2="vector2",e.Vector3="vector3",e.Object="object",e.Array="array"}(b||(b={}));let T=class extends e{constructor(){super(...arguments),this.treeAssetId="",this.autoStart=!0,this.isRunning=!1,this.nodeStates=new Map,this.blackboard=new Map,this.blackboardObservers=new Map,this.activeNodeIds=new Set,this.needsReset=!1,this.nodesToAbort=new Set}getNodeState(e){return this.nodeStates.has(e)||this.nodeStates.set(e,S()),this.nodeStates.get(e)}resetNodeState(e){const t=this.getNodeState(e);t.status=p.Invalid,t.currentChildIndex=0,delete t.startTime,delete t.lastExecutionTime,delete t.repeatCount,delete t.cachedResult,delete t.shuffledIndices,delete t.isAborted,delete t.lastConditionResult,delete t.observedKeys}resetAllStates(){this.nodeStates.clear(),this.activeNodeIds.clear()}getBlackboardValue(e){return this.blackboard.get(e)}setBlackboardValue(e,t){const n=this.blackboard.get(e);this.blackboard.set(e,t),n!==t&&this.notifyBlackboardChange(e,t,n)}hasBlackboardKey(e){return this.blackboard.has(e)}initializeBlackboard(e){e&&e.forEach(((e,t)=>{this.blackboard.has(t)||this.blackboard.set(t,e)}))}clearBlackboard(){this.blackboard.clear()}start(){this.isRunning=!0,this.resetAllStates()}stop(){this.isRunning=!1,this.activeNodeIds.clear()}pause(){this.isRunning=!1}resume(){this.isRunning=!0}observeBlackboard(e,t,n){const r={nodeId:e,keys:new Set(t),callback:n};for(const e of t)this.blackboardObservers.has(e)||this.blackboardObservers.set(e,[]),this.blackboardObservers.get(e).push(r)}unobserveBlackboard(e){for(const t of this.blackboardObservers.values()){const n=t.findIndex((t=>t.nodeId===e));-1!==n&&t.splice(n,1)}}notifyBlackboardChange(e,t,n){const r=this.blackboardObservers.get(e);if(r)for(const o of r)try{o.callback(e,t,n)}catch(e){console.error(`黑板观察者回调错误 (节点: ${o.nodeId}):`,e)}}requestAbort(e){this.nodesToAbort.add(e)}shouldAbort(e){return this.nodesToAbort.has(e)}clearAbortRequest(e){this.nodesToAbort.delete(e)}clearAllAbortRequests(){this.nodesToAbort.clear()}};C([t(),v("design:type",String)],T.prototype,"treeAssetId",void 0),C([t(),v("design:type",Boolean)],T.prototype,"autoStart",void 0),C([n(),v("design:type",Boolean)],T.prototype,"isRunning",void 0),C([n(),v("design:type",Map)],T.prototype,"nodeStates",void 0),C([n(),v("design:type",Map)],T.prototype,"blackboard",void 0),C([n(),v("design:type",Map)],T.prototype,"blackboardObservers",void 0),C([n(),v("design:type",Set)],T.prototype,"activeNodeIds",void 0),C([n(),v("design:type",Boolean)],T.prototype,"needsReset",void 0),C([n(),v("design:type",Set)],T.prototype,"nodesToAbort",void 0),T=C([r("BehaviorTreeRuntime"),o({version:1})],T);const N=i("BehaviorTreeAssetManager");class x{constructor(){this.assets=new Map}loadAsset(e){this.assets.has(e.id)&&N.warn(`行为树资产已存在,将被覆盖: ${e.id}`),this.assets.set(e.id,e),N.info(`行为树资产已加载: ${e.name} (${e.nodes.size}个节点)`)}getAsset(e){return this.assets.get(e)}hasAsset(e){return this.assets.has(e)}unloadAsset(e){const t=this.assets.delete(e);return t&&N.info(`行为树资产已卸载: ${e}`),t}clearAll(){this.assets.clear(),N.info("所有行为树资产已清空")}getAssetCount(){return this.assets.size}getAllAssetIds(){return Array.from(this.assets.keys())}dispose(){this.clearAll()}}class k{static getValue(e,t,n){const{nodeData:r,runtime:o}=e;if(r.bindings&&r.bindings[t]){const e=r.bindings[t],i=o.getBlackboardValue(e);return void 0!==i?i:n}const i=r.config[t];return void 0!==i?i:n}static hasBinding(e,t){return!(!e.nodeData.bindings||!e.nodeData.bindings[t])}static getBindingKey(e,t){return e.nodeData.bindings?.[t]}}class A{constructor(){this.executors=new Map}register(e,t){this.executors.has(e)&&console.warn(`执行器已存在,将被覆盖: ${e}`),this.executors.set(e,t)}get(e){return this.executors.get(e)}has(e){return this.executors.has(e)}unregister(e){return this.executors.delete(e)}clear(){this.executors.clear()}}class w{static register(e,t){this.metadataMap.set(t.implementationType,t),this.executorClassMap.set(e,t.implementationType),this.executorConstructors.set(t.implementationType,e)}static getMetadata(e){return this.metadataMap.get(e)}static getAllMetadata(){return Array.from(this.metadataMap.values())}static getByCategory(e){return this.getAllMetadata().filter((t=>t.category===e))}static getByNodeType(e){return this.getAllMetadata().filter((t=>t.nodeType===e))}static getImplementationType(e){return this.executorClassMap.get(e)}static getExecutorConstructor(e){return this.executorConstructors.get(e)}static getAllExecutorConstructors(){return new Map(this.executorConstructors)}}function D(e){return function(t){w.register(t,e)}}w.metadataMap=new Map,w.executorClassMap=new Map,w.executorConstructors=new Map;let I=class{execute(e){const{nodeData:t,state:n}=e;if(!t.children||0===t.children.length)return p.Success;for(;n.currentChildIndex<t.children.length;){const r=t.children[n.currentChildIndex],o=e.executeChild(r);if(o===p.Running)return p.Running;if(o===p.Failure)return n.currentChildIndex=0,p.Failure;n.currentChildIndex++}return n.currentChildIndex=0,p.Success}reset(e){e.state.currentChildIndex=0}};I=C([D({implementationType:"Sequence",nodeType:g.Composite,displayName:"序列",description:"按顺序执行子节点,全部成功才成功",category:"Composite"})],I);let B=class{execute(e){const{nodeData:t,state:n}=e;if(!t.children||0===t.children.length)return p.Failure;for(;n.currentChildIndex<t.children.length;){const r=t.children[n.currentChildIndex],o=e.executeChild(r);if(o===p.Running)return p.Running;if(o===p.Success)return n.currentChildIndex=0,p.Success;n.currentChildIndex++}return n.currentChildIndex=0,p.Failure}reset(e){e.state.currentChildIndex=0}};B=C([D({implementationType:"Selector",nodeType:g.Composite,displayName:"选择器",description:"按顺序执行子节点,任一成功则成功",category:"Composite"})],B);let R=class{execute(e){const{nodeData:t}=e,n=k.getValue(e,"successPolicy","all"),r=k.getValue(e,"failurePolicy","one");if(!t.children||0===t.children.length)return p.Success;let o=!1,i=0,a=0;for(const n of t.children){const t=e.executeChild(n);t===p.Running?o=!0:t===p.Success?i++:t===p.Failure&&a++}return"one"===n&&i>0?(this.stopAllChildren(e),p.Success):"all"===n&&i===t.children.length?p.Success:"one"===r&&a>0?(this.stopAllChildren(e),p.Failure):"all"===r&&a===t.children.length?p.Failure:o?p.Running:p.Success}stopAllChildren(e){const{nodeData:t,runtime:n}=e;if(t.children)for(const e of t.children)n.activeNodeIds.delete(e),n.resetNodeState(e)}reset(e){const{nodeData:t,runtime:n}=e;if(t.children)for(const e of t.children)n.resetNodeState(e)}};R=C([D({implementationType:"Parallel",nodeType:g.Composite,displayName:"并行",description:"同时执行所有子节点",category:"Composite",configSchema:{successPolicy:{type:"string",default:"all",description:"成功策略",options:["all","one"]},failurePolicy:{type:"string",default:"one",description:"失败策略",options:["all","one"]}}})],R);let F=class{execute(e){const{nodeData:t}=e,n=k.getValue(e,"failurePolicy","all");if(!t.children||0===t.children.length)return p.Failure;let r=!1,o=0,i=0;for(const n of t.children){const t=e.executeChild(n);t===p.Running?r=!0:t===p.Success?o++:t===p.Failure&&i++}return o>0?(this.stopAllChildren(e),p.Success):"one"===n&&i>0?(this.stopAllChildren(e),p.Failure):"all"===n&&i===t.children.length?p.Failure:r?p.Running:p.Failure}stopAllChildren(e){const{nodeData:t,runtime:n}=e;if(t.children)for(const e of t.children)n.activeNodeIds.delete(e),n.resetNodeState(e)}reset(e){const{nodeData:t,runtime:n}=e;if(t.children)for(const e of t.children)n.resetNodeState(e)}};F=C([D({implementationType:"ParallelSelector",nodeType:g.Composite,displayName:"并行选择器",description:"并行执行子节点,任一成功则成功",category:"Composite",configSchema:{failurePolicy:{type:"string",default:"all",description:"失败策略",options:["all","one"]}}})],F);let V=class{execute(e){const{nodeData:t,state:n}=e;if(!t.children||0===t.children.length)return p.Success;for(n.shuffledIndices&&0!==n.shuffledIndices.length||(n.shuffledIndices=this.shuffleIndices(t.children.length));n.currentChildIndex<n.shuffledIndices.length;){const r=n.shuffledIndices[n.currentChildIndex],o=t.children[r],i=e.executeChild(o);if(i===p.Running)return p.Running;if(i===p.Failure)return n.currentChildIndex=0,delete n.shuffledIndices,p.Failure;n.currentChildIndex++}return n.currentChildIndex=0,delete n.shuffledIndices,p.Success}shuffleIndices(e){const t=Array.from({length:e},((e,t)=>t));for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1)),r=t[e];t[e]=t[n],t[n]=r}return t}reset(e){e.state.currentChildIndex=0,delete e.state.shuffledIndices}};V=C([D({implementationType:"RandomSequence",nodeType:g.Composite,displayName:"随机序列",description:"随机顺序执行子节点,全部成功才成功",category:"Composite"})],V);let M=class{execute(e){const{nodeData:t,state:n}=e;if(!t.children||0===t.children.length)return p.Failure;for(n.shuffledIndices&&0!==n.shuffledIndices.length||(n.shuffledIndices=this.shuffleIndices(t.children.length));n.currentChildIndex<n.shuffledIndices.length;){const r=n.shuffledIndices[n.currentChildIndex],o=t.children[r],i=e.executeChild(o);if(i===p.Running)return p.Running;if(i===p.Success)return n.currentChildIndex=0,delete n.shuffledIndices,p.Success;n.currentChildIndex++}return n.currentChildIndex=0,delete n.shuffledIndices,p.Failure}shuffleIndices(e){const t=Array.from({length:e},((e,t)=>t));for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1)),r=t[e];t[e]=t[n],t[n]=r}return t}reset(e){e.state.currentChildIndex=0,delete e.state.shuffledIndices}};M=C([D({implementationType:"RandomSelector",nodeType:g.Composite,displayName:"随机选择器",description:"随机顺序执行子节点,任一成功则成功",category:"Composite"})],M);let $=class{execute(e){const{nodeData:t}=e;if(!t.children||0===t.children.length)return p.Failure;const n=t.children[0],r=e.executeChild(n);return r===p.Running?p.Running:r===p.Success?p.Failure:r===p.Failure?p.Success:p.Failure}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}};$=C([D({implementationType:"Inverter",nodeType:g.Decorator,displayName:"反转",description:"反转子节点的执行结果",category:"Decorator"})],$);let E=class{execute(e){const{nodeData:t,state:n,runtime:r}=e,o=k.getValue(e,"repeatCount",1),i=k.getValue(e,"endOnFailure",!1);if(!t.children||0===t.children.length)return p.Success;const a=t.children[0];n.repeatCount||(n.repeatCount=0);const s=e.executeChild(a);if(s===p.Running)return p.Running;if(s===p.Failure&&i)return n.repeatCount=0,p.Failure;n.repeatCount++,r.resetNodeState(a);return-1===o||n.repeatCount<o?p.Running:(n.repeatCount=0,p.Success)}reset(e){delete e.state.repeatCount,e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}};E=C([D({implementationType:"Repeater",nodeType:g.Decorator,displayName:"重复",description:"重复执行子节点指定次数",category:"Decorator",configSchema:{repeatCount:{type:"number",default:1,description:"重复次数(-1表示无限循环)",supportBinding:!0},endOnFailure:{type:"boolean",default:!1,description:"子节点失败时是否结束"}}})],E);let O=class{execute(e){const{nodeData:t}=e;if(!t.children||0===t.children.length)return p.Success;const n=t.children[0];return e.executeChild(n)===p.Running?p.Running:p.Success}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}};O=C([D({implementationType:"AlwaysSucceed",nodeType:g.Decorator,displayName:"总是成功",description:"无论子节点结果如何都返回成功",category:"Decorator"})],O);let q=class{execute(e){const{nodeData:t}=e;if(!t.children||0===t.children.length)return p.Failure;const n=t.children[0];return e.executeChild(n)===p.Running?p.Running:p.Failure}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}};q=C([D({implementationType:"AlwaysFail",nodeType:g.Decorator,displayName:"总是失败",description:"无论子节点结果如何都返回失败",category:"Decorator"})],q);let P=class{execute(e){const{nodeData:t,runtime:n}=e;if(!t.children||0===t.children.length)return p.Failure;const r=t.children[0],o=e.executeChild(r);return o===p.Running?p.Running:o===p.Success?p.Success:(n.resetNodeState(r),p.Running)}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}};P=C([D({implementationType:"UntilSuccess",nodeType:g.Decorator,displayName:"直到成功",description:"重复执行子节点直到成功",category:"Decorator"})],P);let j=class{execute(e){const{nodeData:t,runtime:n}=e;if(!t.children||0===t.children.length)return p.Success;const r=t.children[0],o=e.executeChild(r);return o===p.Running?p.Running:o===p.Failure?p.Failure:(n.resetNodeState(r),p.Running)}reset(e){e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}};j=C([D({implementationType:"UntilFail",nodeType:g.Decorator,displayName:"直到失败",description:"重复执行子节点直到失败",category:"Decorator"})],j);let z=class{execute(e){const{nodeData:t,runtime:n,state:r}=e;if(!t.children||0===t.children.length)return p.Failure;const o=k.getValue(e,"blackboardKey",""),i=k.getValue(e,"expectedValue"),a=k.getValue(e,"operator","equals"),s=t.abortType||y.None;if(!o)return p.Failure;const c=n.getBlackboardValue(o),d=this.evaluateCondition(c,i,a),l=r.status===p.Running;if(s!==y.None&&(r.observedKeys&&0!==r.observedKeys.length||(r.observedKeys=[o],this.setupObserver(e,o,i,a,s)),void 0!==r.lastConditionResult&&r.lastConditionResult!==d&&(d?this.handleConditionBecameTrue(e,s):l&&this.handleConditionBecameFalse(e,s))),r.lastConditionResult=d,!d)return p.Failure;const u=t.children[0];return e.executeChild(u)}evaluateCondition(e,t,n){switch(n){case"equals":return e===t;case"notEquals":return e!==t;case"greaterThan":return e>t;case"lessThan":return e<t;case"greaterOrEqual":return e>=t;case"lessOrEqual":return e<=t;default:return!1}}setupObserver(e,t,n,r,o){const{nodeData:i,runtime:a}=e;a.observeBlackboard(i.id,[t],((t,i)=>{const a=this.evaluateCondition(i,n,r),s=e.state.lastConditionResult;void 0!==s&&s!==a&&(a?this.handleConditionBecameTrue(e,o):this.handleConditionBecameFalse(e,o)),e.state.lastConditionResult=a}))}handleConditionBecameTrue(e,t){t!==y.LowerPriority&&t!==y.Both||this.requestAbortLowerPriority(e)}handleConditionBecameFalse(e,t){const{nodeData:n,runtime:r}=e;t!==y.Self&&t!==y.Both||n.children&&n.children.length>0&&r.requestAbort(n.children[0])}requestAbortLowerPriority(e){const{runtime:t}=e;t.requestAbort("__lower_priority__")}reset(e){const{nodeData:t,runtime:n,state:r}=e;r.observedKeys&&r.observedKeys.length>0&&(n.unobserveBlackboard(t.id),delete r.observedKeys),delete r.lastConditionResult,t.children&&t.children.length>0&&n.resetNodeState(t.children[0])}};z=C([D({implementationType:"Conditional",nodeType:g.Decorator,displayName:"条件",description:"根据条件决定是否执行子节点",category:"Decorator",configSchema:{blackboardKey:{type:"string",default:"",description:"黑板变量名"},expectedValue:{type:"object",description:"期望值",supportBinding:!0},operator:{type:"string",default:"equals",description:"比较运算符",options:["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual"]},abortType:{type:"string",default:"none",description:"中止类型",options:["none","self","lower-priority","both"]}}})],z);let J=class{execute(e){const{nodeData:t,state:n,totalTime:r}=e;if(!t.children||0===t.children.length)return p.Failure;const o=k.getValue(e,"cooldownTime",1);if(void 0!==n.lastExecutionTime){if(r-n.lastExecutionTime<o)return p.Failure}const i=t.children[0],a=e.executeChild(i);return a===p.Running?p.Running:a===p.Success?(n.lastExecutionTime=r,p.Success):p.Failure}reset(e){delete e.state.lastExecutionTime,e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}};J=C([D({implementationType:"Cooldown",nodeType:g.Decorator,displayName:"冷却",description:"子节点执行成功后进入冷却时间",category:"Decorator",configSchema:{cooldownTime:{type:"number",default:1,description:"冷却时间(秒)",min:0,supportBinding:!0}}})],J);let K=class{execute(e){const{nodeData:t,state:n,totalTime:r}=e;if(!t.children||0===t.children.length)return p.Failure;const o=k.getValue(e,"timeout",1);void 0===n.startTime&&(n.startTime=r);if(r-n.startTime>=o)return delete n.startTime,p.Failure;const i=t.children[0],a=e.executeChild(i);return a===p.Running?p.Running:(delete n.startTime,a)}reset(e){delete e.state.startTime,e.nodeData.children&&e.nodeData.children.length>0&&e.runtime.resetNodeState(e.nodeData.children[0])}};K=C([D({implementationType:"Timeout",nodeType:g.Decorator,displayName:"超时",description:"限制子节点的执行时间",category:"Decorator",configSchema:{timeout:{type:"number",default:1,description:"超时时间(秒)",min:0,supportBinding:!0}}})],K);class U{static register(e,t){this.services.set(e,t)}static get(e){return this.services.get(e)}static has(e){return this.services.has(e)}static unregister(e){return this.services.delete(e)}}U.services=new Map;let _=class{execute(e){const{nodeData:t,state:n,totalTime:r}=e;if(!t.children||0===t.children.length)return p.Failure;const o=k.getValue(e,"serviceName",""),i=k.getValue(e,"tickInterval",0);if(!o)return p.Failure;const a=U.get(o);if(!a)return console.warn(`未找到Service: ${o}`),p.Failure;n.status!==p.Running&&(n.startTime=r,n.lastExecutionTime=r,a.onServiceStart&&a.onServiceStart(e));(0===i||void 0!==n.lastExecutionTime&&r-n.lastExecutionTime>=i)&&(a.onServiceTick(e),n.lastExecutionTime=r);const s=t.children[0],c=e.executeChild(s);return c!==p.Running&&a.onServiceEnd&&a.onServiceEnd(e),c}reset(e){const{nodeData:t,runtime:n,state:r}=e,o=k.getValue(e,"serviceName","");if(o){const t=U.get(o);t&&t.onServiceEnd&&t.onServiceEnd(e)}delete r.startTime,delete r.lastExecutionTime,t.children&&t.children.length>0&&n.resetNodeState(t.children[0])}};_=C([D({implementationType:"Service",nodeType:g.Decorator,displayName:"Service",description:"在子节点执行期间持续运行后台逻辑",category:"Decorator",configSchema:{serviceName:{type:"string",default:"",description:"Service名称"},tickInterval:{type:"number",default:0,description:"Service更新间隔(秒,0表示每帧更新)",supportBinding:!0}}})],_);let L=class{execute(e){const{state:t,totalTime:n}=e,r=k.getValue(e,"duration",1);return t.startTime?n-t.startTime>=r?p.Success:p.Running:(t.startTime=n,p.Running)}reset(e){delete e.state.startTime}};L=C([D({implementationType:"Wait",nodeType:g.Action,displayName:"等待",description:"等待指定时间后返回成功",category:"Action",configSchema:{duration:{type:"number",default:1,description:"等待时长(秒)",min:0,supportBinding:!0}}})],L);let W=class{execute(e){const{runtime:t}=e,n=k.getValue(e,"message",""),r=k.getValue(e,"logLevel","info"),o=this.replaceBlackboardVariables(n,t);return this.log(o,r),p.Success}replaceBlackboardVariables(e,t){return e.includes("{")&&e.includes("}")?e.replace(/\{([\w.]{1,100})\}/g,((e,n)=>{const r=t.getBlackboardValue(n.trim());return void 0!==r?String(r):`{${n}}`})):e}log(e,t){switch(t){case"error":console.error(e);break;case"warn":console.warn(e);break;default:console.log(e)}}};W=C([D({implementationType:"Log",nodeType:g.Action,displayName:"日志",description:"输出日志信息",category:"Action",configSchema:{message:{type:"string",default:"",description:"日志消息,支持{key}占位符引用黑板变量",supportBinding:!0},logLevel:{type:"string",default:"info",description:"日志级别",options:["info","warn","error"]}}})],W);let G=class{execute(e){const{runtime:t}=e,n=k.getValue(e,"key",""),r=k.getValue(e,"value");return n?(t.setBlackboardValue(n,r),p.Success):p.Failure}};G=C([D({implementationType:"SetBlackboardValue",nodeType:g.Action,displayName:"设置黑板值",description:"设置黑板中的变量值",category:"Action",configSchema:{key:{type:"string",default:"",description:"黑板变量名"},value:{type:"object",description:"要设置的值",supportBinding:!0}}})],G);let H=class{execute(e){const{runtime:t}=e,n=k.getValue(e,"key",""),r=k.getValue(e,"operation","add"),o=k.getValue(e,"value",0);if(!n)return p.Failure;const i=t.getBlackboardValue(n)||0;let a;switch(r){case"add":a=i+o;break;case"subtract":a=i-o;break;case"multiply":a=i*o;break;case"divide":a=0!==o?i/o:i;break;case"set":a=o;break;default:return p.Failure}return t.setBlackboardValue(n,a),p.Success}};H=C([D({implementationType:"ModifyBlackboardValue",nodeType:g.Action,displayName:"修改黑板值",description:"对黑板中的数值进行运算",category:"Action",configSchema:{key:{type:"string",default:"",description:"黑板变量名"},operation:{type:"string",default:"add",description:"运算类型",options:["add","subtract","multiply","divide","set"]},value:{type:"number",default:0,description:"操作数",supportBinding:!0}}})],H);let Q=class{execute(e){const{runtime:t,entity:n}=e,r=k.getValue(e,"actionName","");if(!r)return p.Failure;const o=t.getBlackboardValue(`action_${r}`);if(!o||"function"!=typeof o)return p.Failure;try{return o(n)}catch(e){return console.error(`ExecuteAction failed: ${e}`),p.Failure}}};Q=C([D({implementationType:"ExecuteAction",nodeType:g.Action,displayName:"执行动作",description:"执行自定义动作逻辑",category:"Action",configSchema:{actionName:{type:"string",default:"",description:"动作名称(黑板中action_前缀的函数)"}}})],Q);let X=class{constructor(){this.assetManager=null}getAssetManager(){return this.assetManager||(this.assetManager=a.services.resolve(x)),this.assetManager}execute(e){const{runtime:t,state:n,entity:r}=e,o=k.getValue(e,"treeAssetId",""),i=k.getValue(e,"shareBlackboard",!0);if(!o)return p.Failure;const a=this.getAssetManager().getAsset(o);if(!a)return console.warn(`未找到子树资产: ${o}`),p.Failure;const s=a.nodes.get(a.rootNodeId);if(!s)return console.warn(`子树根节点未找到: ${a.rootNodeId}`),p.Failure;if(!i&&n.status!==p.Running&&a.blackboardVariables)for(const[e,n]of a.blackboardVariables.entries())t.hasBlackboardKey(e)||t.setBlackboardValue(e,n);const c={entity:r,nodeData:s,state:t.getNodeState(s.id),runtime:t,treeData:a,deltaTime:e.deltaTime,totalTime:e.totalTime,executeChild:n=>{const o=a.nodes.get(n);if(!o)return console.warn(`子树节点未找到: ${n}`),p.Failure;const i={entity:r,nodeData:o,state:t.getNodeState(n),runtime:t,treeData:a,deltaTime:e.deltaTime,totalTime:e.totalTime,executeChild:c.executeChild};return this.executeSubTreeNode(i)}};return this.executeSubTreeNode(c)}executeSubTreeNode(e){const{nodeData:t,runtime:n}=e,r=n.getNodeState(t.id);if(!t.children||0===t.children.length)return p.Success;const o=t.children[r.currentChildIndex],i=e.executeChild(o);return i===p.Running?p.Running:i===p.Failure?(r.currentChildIndex=0,p.Failure):(r.currentChildIndex++,r.currentChildIndex>=t.children.length?(r.currentChildIndex=0,p.Success):p.Running)}reset(e){const t=k.getValue(e,"treeAssetId","");if(t){const n=this.getAssetManager().getAsset(t);if(n){const t=n.nodes.get(n.rootNodeId);if(t&&(e.runtime.resetNodeState(t.id),t.children))for(const n of t.children)e.runtime.resetNodeState(n)}}}};X=C([D({implementationType:"SubTree",nodeType:g.Action,displayName:"子树",description:"引用并执行其他行为树",category:"Special",configSchema:{treeAssetId:{type:"string",default:"",description:"要执行的行为树资产ID",supportBinding:!0},shareBlackboard:{type:"boolean",default:!0,description:"是否共享黑板数据"}}})],X);let Y=class{execute(e){const{runtime:t}=e,n=k.getValue(e,"key",""),r=k.getValue(e,"compareValue"),o=k.getValue(e,"operator","equals");if(!n)return p.Failure;const i=t.getBlackboardValue(n);return this.compare(i,r,o)?p.Success:p.Failure}compare(e,t,n){switch(n){case"equals":return e===t;case"notEquals":return e!==t;case"greaterThan":return e>t;case"lessThan":return e<t;case"greaterOrEqual":return e>=t;case"lessOrEqual":return e<=t;default:return!1}}};Y=C([D({implementationType:"BlackboardCompare",nodeType:g.Condition,displayName:"黑板比较",description:"比较黑板中的值",category:"Condition",configSchema:{key:{type:"string",default:"",description:"黑板变量名"},compareValue:{type:"object",description:"比较值",supportBinding:!0},operator:{type:"string",default:"equals",description:"比较运算符",options:["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual"]}}})],Y);let Z=class{execute(e){const{runtime:t}=e,n=k.getValue(e,"key",""),r=k.getValue(e,"checkNull",!1);if(!n)return p.Failure;const o=t.getBlackboardValue(n);return void 0===o||r&&null===o?p.Failure:p.Success}};Z=C([D({implementationType:"BlackboardExists",nodeType:g.Condition,displayName:"黑板存在",description:"检查黑板中是否存在指定的键",category:"Condition",configSchema:{key:{type:"string",default:"",description:"黑板变量名"},checkNull:{type:"boolean",default:!1,description:"检查是否为null"}}})],Z);let ee=class{execute(e){const t=k.getValue(e,"probability",.5),n=Math.max(0,Math.min(1,t));return Math.random()<n?p.Success:p.Failure}};ee=C([D({implementationType:"RandomProbability",nodeType:g.Condition,displayName:"随机概率",description:"根据概率返回成功或失败",category:"Condition",configSchema:{probability:{type:"number",default:.5,description:"成功概率(0-1)",min:0,max:1,supportBinding:!0}}})],ee);let te=class{execute(e){const{runtime:t,entity:n}=e,r=k.getValue(e,"conditionName","");if(!r)return p.Failure;const o=t.getBlackboardValue(`condition_${r}`);if(!o||"function"!=typeof o)return p.Failure;try{return o(n)?p.Success:p.Failure}catch(e){return console.error(`ExecuteCondition failed: ${e}`),p.Failure}}};te=C([D({implementationType:"ExecuteCondition",nodeType:g.Condition,displayName:"执行条件",description:"执行自定义条件逻辑",category:"Condition",configSchema:{conditionName:{type:"string",default:"",description:"条件名称(黑板中condition_前缀的函数)"}}})],te);let ne=class extends s{constructor(){super(c.empty().all(T)),this.assetManager=a.services.resolve(x),this.executorRegistry=new A,this.registerBuiltInExecutors()}registerBuiltInExecutors(){const e=w.getAllExecutorConstructors();for(const[t,n]of e)try{const e=new n;this.executorRegistry.register(t,e)}catch(e){this.logger.error(`注册执行器失败: ${t}`,e)}}getExecutorRegistry(){return this.executorRegistry}process(e){for(const t of e){const e=t.getComponent(T);if(!e.isRunning)continue;const n=this.assetManager.getAsset(e.treeAssetId);n?(e.needsReset&&(e.resetAllStates(),e.needsReset=!1),this.executeTree(t,e,n)):this.logger.warn(`未找到行为树资产: ${e.treeAssetId}`)}}executeTree(e,t,n){const r=n.nodes.get(n.rootNodeId);if(!r)return void this.logger.error(`未找到根节点: ${n.rootNodeId}`);this.executeNode(e,t,r,n)!==p.Running?t.needsReset=!0:t.needsReset=!1}executeNode(e,t,n,r){const o=t.getNodeState(n.id);if(t.shouldAbort(n.id)){t.clearAbortRequest(n.id),o.isAborted=!0;const i=this.executorRegistry.get(n.implementationType);if(i&&i.reset){const o=this.createContext(e,t,n,r);i.reset(o)}return t.activeNodeIds.delete(n.id),o.status=p.Failure,p.Failure}t.activeNodeIds.add(n.id),o.isAborted=!1;const i=this.executorRegistry.get(n.implementationType);if(!i)return this.logger.error(`未找到执行器: ${n.implementationType}`),o.status=p.Failure,p.Failure;const a=this.createContext(e,t,n,r);try{const e=i.execute(a);return o.status=e,e!==p.Running&&(t.activeNodeIds.delete(n.id),i.reset&&i.reset(a)),e}catch(e){return this.logger.error(`执行节点时发生错误: ${n.name}`,e),o.status=p.Failure,t.activeNodeIds.delete(n.id),p.Failure}}createContext(e,t,n,r){return{entity:e,nodeData:n,state:t.getNodeState(n.id),runtime:t,treeData:r,deltaTime:d.deltaTime,totalTime:d.totalTime,executeChild:n=>{const o=r.nodes.get(n);return o?this.executeNode(e,t,o,r):(this.logger.warn(`未找到子节点: ${n}`),p.Failure)}}}executeChildren(e,t){const{nodeData:n,treeData:r,entity:o,runtime:i}=e;if(!n.children||0===n.children.length)return[];const a=[],s=t||Array.from({length:n.children.length},((e,t)=>t));for(const e of s){if(e>=n.children.length)continue;const t=n.children[e],s=r.nodes.get(t);if(!s){this.logger.warn(`未找到子节点: ${t}`),a.push(p.Failure);continue}const c=this.executeNode(o,i,s,r);a.push(c)}return a}};ne=C([l("BehaviorTreeExecution"),v("design:paramtypes",[])],ne);class re{static start(e,t,n=!0){a.services.resolve(x).loadAsset(t);let r=e.getComponent(T);if(r||(r=new T,e.addComponent(r)),r.treeAssetId=t.id,r.autoStart=n,t.blackboardVariables)for(const[e,n]of t.blackboardVariables.entries())r.setBlackboardValue(e,n);n&&(r.isRunning=!0)}static stop(e){const t=e.getComponent(T);t&&(t.isRunning=!1,t.resetAllStates())}static pause(e){const t=e.getComponent(T);t&&(t.isRunning=!1)}static resume(e){const t=e.getComponent(T);t&&(t.isRunning=!0)}static restart(e){const t=e.getComponent(T);t&&(t.resetAllStates(),t.isRunning=!0)}}class oe{constructor(e){this.nodeStack=[],this.nodeIdCounter=0,this.treeData={id:`tree_${Date.now()}`,name:e,rootNodeId:"",nodes:new Map,blackboardVariables:new Map}}static create(e="BehaviorTree"){return new oe(e)}defineBlackboardVariable(e,t){return this.treeData.blackboardVariables||(this.treeData.blackboardVariables=new Map),this.treeData.blackboardVariables.set(e,t),this}sequence(e){return this.addCompositeNode("Sequence",e||"Sequence")}selector(e){return this.addCompositeNode("Selector",e||"Selector")}parallel(e,t){return this.addCompositeNode("Parallel",e||"Parallel",t)}parallelSelector(e,t){return this.addCompositeNode("ParallelSelector",e||"ParallelSelector",t)}randomSequence(e){return this.addCompositeNode("RandomSequence",e||"RandomSequence")}randomSelector(e){return this.addCompositeNode("RandomSelector",e||"RandomSelector")}inverter(e){return this.addDecoratorNode("Inverter",e||"Inverter")}repeater(e,t){return this.addDecoratorNode("Repeater",t||"Repeater",{repeatCount:e})}alwaysSucceed(e){return this.addDecoratorNode("AlwaysSucceed",e||"AlwaysSucceed")}alwaysFail(e){return this.addDecoratorNode("AlwaysFail",e||"AlwaysFail")}untilSuccess(e){return this.addDecoratorNode("UntilSuccess",e||"UntilSuccess")}untilFail(e){return this.addDecoratorNode("UntilFail",e||"UntilFail")}conditional(e,t,n,r){return this.addDecoratorNode("Conditional",r||"Conditional",{blackboardKey:e,expectedValue:t,operator:n||"equals"})}cooldown(e,t){return this.addDecoratorNode("Cooldown",t||"Cooldown",{cooldownTime:e})}timeout(e,t){return this.addDecoratorNode("Timeout",t||"Timeout",{timeout:e})}wait(e,t){return this.addActionNode("Wait",t||"Wait",{duration:e})}log(e,t){return this.addActionNode("Log",t||"Log",{message:e})}setBlackboardValue(e,t,n){return this.addActionNode("SetBlackboardValue",n||"SetBlackboardValue",{key:e,value:t})}modifyBlackboardValue(e,t,n,r){return this.addActionNode("ModifyBlackboardValue",r||"ModifyBlackboardValue",{key:e,operation:t,value:n})}executeAction(e,t){return this.addActionNode("ExecuteAction",t||"ExecuteAction",{actionName:e})}blackboardCompare(e,t,n,r){return this.addConditionNode("BlackboardCompare",r||"BlackboardCompare",{key:e,compareValue:t,operator:n||"equals"})}blackboardExists(e,t){return this.addConditionNode("BlackboardExists",t||"BlackboardExists",{key:e})}randomProbability(e,t){return this.addConditionNode("RandomProbability",t||"RandomProbability",{probability:e})}executeCondition(e,t){return this.addConditionNode("ExecuteCondition",t||"ExecuteCondition",{conditionName:e})}end(){return this.nodeStack.length>0&&this.nodeStack.pop(),this}build(){if(!this.treeData.rootNodeId)throw new Error("No root node defined. Add at least one node to the tree.");return this.treeData}addCompositeNode(e,t,n={}){const r=this.generateNodeId(),o={id:r,name:t,nodeType:g.Composite,implementationType:e,children:[],config:n};if(this.treeData.nodes.set(r,o),this.treeData.rootNodeId||(this.treeData.rootNodeId=r),this.nodeStack.length>0){const e=this.nodeStack[this.nodeStack.length-1],t=this.treeData.nodes.get(e);t&&t.children&&t.children.push(r)}return this.nodeStack.push(r),this}addDecoratorNode(e,t,n={}){const r=this.generateNodeId(),o={id:r,name:t,nodeType:g.Decorator,implementationType:e,children:[],config:n};if(this.treeData.nodes.set(r,o),this.treeData.rootNodeId||(this.treeData.rootNodeId=r),this.nodeStack.length>0){const e=this.nodeStack[this.nodeStack.length-1],t=this.treeData.nodes.get(e);t&&t.children&&t.children.push(r)}return this.nodeStack.push(r),this}addActionNode(e,t,n={}){const r=this.generateNodeId(),o={id:r,name:t,nodeType:g.Action,implementationType:e,config:n};if(this.treeData.nodes.set(r,o),this.treeData.rootNodeId||(this.treeData.rootNodeId=r),this.nodeStack.length>0){const e=this.nodeStack[this.nodeStack.length-1],t=this.treeData.nodes.get(e);t&&t.children&&t.children.push(r)}return this}addConditionNode(e,t,n={}){const r=this.generateNodeId(),o={id:r,name:t,nodeType:g.Condition,implementationType:e,config:n};if(this.treeData.nodes.set(r,o),this.treeData.rootNodeId||(this.treeData.rootNodeId=r),this.nodeStack.length>0){const e=this.nodeStack[this.nodeStack.length-1],t=this.treeData.nodes.get(e);t&&t.children&&t.children.push(r)}return this}generateNodeId(){return"node_"+this.nodeIdCounter++}}const ie={String:"string",Number:"number",Boolean:"boolean",Select:"select",Blackboard:"blackboard",Code:"code",Variable:"variable",Asset:"asset"};class ae{static getAllTemplates(){return w.getAllMetadata().map((e=>this.convertMetadataToTemplate(e)))}static getTemplate(e,t){return this.getAllTemplates().find((n=>{if(n.type!==e)return!1;const r=n.defaultConfig;switch(e){case g.Composite:return r.compositeType===t;case g.Decorator:return r.decoratorType===t;case g.Action:return r.actionType===t;case g.Condition:return r.conditionType===t;default:return!1}}))}static convertMetadataToTemplate(e){const t=this.convertConfigSchemaToProperties(e.configSchema||{}),n={nodeType:this.nodeTypeToString(e.nodeType)};switch(e.nodeType){case g.Composite:n.compositeType=e.implementationType;break;case g.Decorator:n.decoratorType=e.implementationType;break;case g.Action:n.actionType=e.implementationType;break;case g.Condition:n.conditionType=e.implementationType}if(e.configSchema)for(const[t,r]of Object.entries(e.configSchema)){const e=r;void 0!==e.default&&(n[t]=e.default)}const{icon:r,color:o}=this.getIconAndColorByType(e.nodeType,e.category||"");return{type:e.nodeType,displayName:e.displayName,category:e.category||this.getCategoryByNodeType(e.nodeType),description:e.description||"",className:e.implementationType,icon:r,color:o,defaultConfig:n,properties:t}}static convertConfigSchemaToProperties(e){const t=[];for(const[n,r]of Object.entries(e)){const e={name:n,type:this.mapFieldTypeToPropertyType(r),label:n};void 0!==r.description&&(e.description=r.description),void 0!==r.default&&(e.defaultValue=r.default),void 0!==r.min&&(e.min=r.min),void 0!==r.max&&(e.max=r.max),void 0!==r.allowMultipleConnections&&(e.allowMultipleConnections=r.allowMultipleConnections),r.options&&(e.options=r.options.map((e=>({label:e,value:e})))),r.supportBinding&&(e.renderConfig={component:"BindableInput",props:{supportBinding:!0}}),t.push(e)}return t}static mapFieldTypeToPropertyType(e){if(e.options&&e.options.length>0)return ie.Select;switch(e.type){case"string":case"array":case"object":default:return ie.String;case"number":return ie.Number;case"boolean":return ie.Boolean}}static nodeTypeToString(e){switch(e){case g.Composite:return"composite";case g.Decorator:return"decorator";case g.Action:return"action";case g.Condition:return"condition";default:return"unknown"}}static getCategoryByNodeType(e){switch(e){case g.Composite:return"组合";case g.Decorator:return"装饰器";case g.Action:return"动作";case g.Condition:return"条件";default:return"其他"}}static getIconAndColorByType(e,t){switch(e){case g.Composite:return{icon:"GitBranch",color:"#1976d2"};case g.Decorator:return{icon:"Settings",color:"#fb8c00"};case g.Action:return{icon:"Play",color:"#388e3c"};case g.Condition:return{icon:"HelpCircle",color:"#d32f2f"};default:return{icon:"Circle",color:"#757575"}}}}class se{static validate(e){const t=[],n=[];if(e.version||t.push("Missing version field"),e.metadata&&e.metadata.name||t.push("Missing or invalid metadata"),e.rootNodeId||t.push("Missing rootNodeId"),e.nodes&&Array.isArray(e.nodes)){const r=new Set;e.nodes.find((t=>t.id===e.rootNodeId))||t.push(`Root node '${e.rootNodeId}' not found in nodes array`);for(const n of e.nodes)if(n.id){if(r.has(n.id)&&t.push(`Duplicate node id: ${n.id}`),r.add(n.id),n.nodeType||t.push(`Node ${n.id} missing nodeType`),n.children)for(const r of n.children)e.nodes.find((e=>e.id===r))||t.push(`Node ${n.id} references non-existent child: ${r}`)}else t.push("Node missing id field");const o=new Set([e.rootNodeId]),i=t=>{const n=e.nodes.find((e=>e.id===t));if(n&&n.children)for(const e of n.children)o.add(e),i(e)};i(e.rootNodeId);for(const t of e.nodes)o.has(t.id)||n.push(`Orphaned node detected: ${t.id} (${t.name})`)}else t.push("Missing or invalid nodes array");if(e.blackboard&&Array.isArray(e.blackboard)){const n=new Set;for(const r of e.blackboard)r.name?(n.has(r.name)&&t.push(`Duplicate blackboard variable: ${r.name}`),n.add(r.name),r.type||t.push(`Blackboard variable ${r.name} missing type`)):t.push("Blackboard variable missing name")}if(e.propertyBindings&&Array.isArray(e.propertyBindings)){const n=new Set(e.nodes.map((e=>e.id))),r=new Set(e.blackboard?.map((e=>e.name))||[]);for(const o of e.propertyBindings)n.has(o.nodeId)||t.push(`Property binding references non-existent node: ${o.nodeId}`),r.has(o.variableName)||t.push(`Property binding references non-existent variable: ${o.variableName}`),o.propertyName||t.push("Property binding missing propertyName")}const r={valid:0===t.length};return t.length>0&&(r.errors=t),n.length>0&&(r.warnings=n),r}static getStats(e){let t=0,n=0,r=0,o=0;for(const i of e.nodes)switch(i.nodeType){case g.Action:t++;break;case g.Condition:n++;break;case g.Composite:r++;break;case g.Decorator:o++}const i=(t,n=0)=>{const r=e.nodes.find((e=>e.id===t));if(!r||!r.children||0===r.children.length)return n;let o=n;for(const e of r.children){const t=i(e,n+1);o=Math.max(o,t)}return o};return{nodeCount:e.nodes.length,actionCount:t,conditionCount:n,compositeCount:r,decoratorCount:o,blackboardVariableCount:e.blackboard?.length||0,propertyBindingCount:e.propertyBindings?.length||0,maxDepth:i(e.rootNodeId)}}}const ce=i("EditorFormatConverter");class de{static toAsset(e,t){ce.info("开始转换编辑器格式到资产格式");const n=this.findRootNode(e.nodes);if(!n)throw new Error("未找到根节点");const r={name:t?.name||e.metadata?.name||"Untitled Behavior Tree",version:t?.version||e.version||"1.0.0"},o=t?.description||e.metadata?.description;o&&(r.description=o);const i=t?.createdAt||e.metadata?.createdAt;i&&(r.createdAt=i);const a=t?.modifiedAt||(new Date).toISOString();a&&(r.modifiedAt=a);const s=this.convertNodes(e.nodes),c=this.convertBlackboard(e.blackboard),d=this.convertPropertyBindings(e.connections,e.nodes,c),l={version:"1.0.0",metadata:r,rootNodeId:n.id,nodes:s,blackboard:c};return d.length>0&&(l.propertyBindings=d),ce.info(`转换完成: ${s.length}个节点, ${c.length}个黑板变量, ${d.length}个属性绑定`),l}static findRootNode(e){return e.find((e=>"根节点"===e.template.category||"root"===e.data.nodeType))||null}static convertNodes(e){return e.map((e=>this.convertNode(e)))}static convertNode(e){const t={...e.data};return delete t.nodeType,e.template.className&&(t.className=e.template.className),{id:e.id,name:e.template.displayName||e.data.name||"Node",nodeType:e.template.type,data:t,children:e.children||[]}}static convertBlackboard(e){const t=[];for(const[n,r]of Object.entries(e)){const e=this.inferBlackboardType(r);t.push({name:n,type:e,defaultValue:r})}return t}static inferBlackboardType(e){return"number"==typeof e?b.Number:"string"==typeof e?b.String:"boolean"==typeof e?b.Boolean:b.Object}static convertPropertyBindings(e,t,n){const r=[],o=new Set(n.map((e=>e.name))),i=e.filter((e=>"property"===e.connectionType));for(const e of i){const n=t.find((t=>t.id===e.from)),i=t.find((t=>t.id===e.to));if(!n||!i||!e.toProperty){ce.warn(`跳过无效的属性连接: from=${e.from}, to=${e.to}`);continue}let a;"blackboard-variable"===n.data.nodeType?a=n.data.variableName:e.fromProperty&&(a=e.fromProperty),a?o.has(a)?r.push({nodeId:i.id,propertyName:e.toProperty,variableName:a}):ce.warn(`属性绑定引用了不存在的黑板变量: ${a}`):ce.warn(`无法确定变量名: from节点=${n.template.displayName}`)}return r}static fromAsset(e){ce.info("开始转换资产格式到编辑器格式");const t=this.convertNodesFromAsset(e.nodes),n={};for(const t of e.blackboard)n[t.name]=t.defaultValue;const r=this.convertPropertyBindingsToConnections(e.propertyBindings||[]),o=this.buildNodeConnections(e.nodes);r.push(...o);const i={name:e.metadata.name};e.metadata.description&&(i.description=e.metadata.description),e.metadata.createdAt&&(i.createdAt=e.metadata.createdAt),e.metadata.modifiedAt&&(i.modifiedAt=e.metadata.modifiedAt);const a={version:e.metadata.version,metadata:i,nodes:t,connections:r,blackboard:n,canvasState:{offset:{x:0,y:0},scale:1}};return ce.info(`转换完成: ${t.length}个节点, ${r.length}个连接`),a}static convertNodesFromAsset(e){return e.map(((e,t)=>{const n={x:100+t%5*250,y:100+150*Math.floor(t/5)},r={displayName:e.name,category:this.inferCategory(e.nodeType),type:e.nodeType};return e.data.className&&(r.className=e.data.className),{id:e.id,template:r,data:{...e.data},position:n,children:e.children}}))}static inferCategory(e){switch(e){case g.Action:return"动作";case g.Condition:return"条件";case g.Composite:return"组合";case g.Decorator:return"装饰器";default:return"其他"}}static convertPropertyBindingsToConnections(e){const t=[];for(const n of e)t.push({from:"blackboard",to:n.nodeId,toProperty:n.propertyName,connectionType:"property"});return t}static buildNodeConnections(e){const t=[];for(const n of e)for(const e of n.children)t.push({from:n.id,to:e,connectionType:"node"});return t}}const le=i("BehaviorTreeAssetSerializer");class ue{static serialize(e,t={format:"json",pretty:!0}){if(!1!==t.validate){const t=se.validate(e);if(!t.valid){const e=t.errors?.join(", ")||"Unknown error";throw new Error(`资产验证失败: ${e}`)}t.warnings&&t.warnings.length>0&&le.warn(`资产验证警告: ${t.warnings.join(", ")}`)}return"json"===t.format?this.serializeToJSON(e,t.pretty):this.serializeToBinary(e)}static serializeToJSON(e,t=!0){try{const n=t?JSON.stringify(e,null,2):JSON.stringify(e);return le.info(`已序列化为JSON: ${n.length} 字符`),n}catch(e){throw new Error(`JSON序列化失败: ${e}`)}}static serializeToBinary(e){try{const t=u.encode(e);return le.info(`已序列化为二进制: ${t.length} 字节`),t}catch(e){throw new Error(`二进制序列化失败: ${e}`)}}static deserialize(e,t={validate:!0,strict:!0}){let n;try{n="string"==typeof e?this.deserializeFromJSON(e):this.deserializeFromBinary(e)}catch(e){throw new Error(`反序列化失败: ${e}`)}if(!1!==t.validate){const e=se.validate(n);if(!e.valid){const n=e.errors?.join(", ")||"Unknown error";if(t.strict)throw new Error(`资产验证失败: ${n}`);le.error(`资产验证失败: ${n}`)}e.warnings&&e.warnings.length>0&&le.warn(`资产验证警告: ${e.warnings.join(", ")}`)}return n}static deserializeFromJSON(e){try{const t=JSON.parse(e);if(!t.rootNodeId&&t.nodes&&t.connections){le.info("检测到编辑器格式,正在转换为运行时资产格式...");const e=t,n=de.toAsset(e);return le.info(`已从编辑器格式转换: ${n.nodes.length} 个节点`),n}{const e=t;return le.info(`已从运行时资产格式反序列化: ${e.nodes.length} 个节点`),e}}catch(e){throw new Error(`JSON解析失败: ${e}`)}}static deserializeFromBinary(e){try{const t=u.decode(e);return le.info(`已从二进制反序列化: ${t.nodes.length} 个节点`),t}catch(e){throw new Error(`二进制解码失败: ${e}`)}}static detectFormat(e){return"string"==typeof e?"json":"binary"}static getInfo(e){try{const t=this.detectFormat(e);let n;n="json"===t?JSON.parse(e):u.decode(e);const r=e.length;return{format:t,name:n.metadata.name,version:n.version,nodeCount:n.nodes.length,blackboardVariableCount:n.blackboard.length,size:r}}catch(e){return le.error(`获取资产信息失败: ${e}`),null}}static convert(e,t,n=!0){const r=this.deserialize(e,{validate:!1});return this.serialize(r,{format:t,pretty:n,validate:!1})}static compareSize(e,t){const n=e.length,r=t.length,o=n-r;return{jsonSize:n,binarySize:r,compressionRatio:o/n*100,savedBytes:o}}}class he{constructor(){this.variables=new Map}dispose(){this.variables.clear()}defineVariable(e,t,n,r){const o={name:e,type:t,value:n,readonly:r?.readonly??!1};void 0!==r?.description&&(o.description=r.description),this.variables.set(e,o)}getValue(e){const t=this.variables.get(e);return t?.value}setValue(e,t,n=!1){const r=this.variables.get(e);return!!r&&(!(r.readonly&&!n)&&(r.value=t,!0))}hasVariable(e){return this.variables.has(e)}removeVariable(e){return this.variables.delete(e)}getVariableNames(){return Array.from(this.variables.keys())}getAllVariables(){return Array.from(this.variables.values())}clear(){this.variables.clear()}setVariables(e){for(const[t,n]of Object.entries(e)){const e=this.variables.get(t);e&&!e.readonly&&(e.value=n)}}getVariables(e){const t={};for(const n of e){const e=this.getValue(n);void 0!==e&&(t[n]=e)}return t}exportConfig(){return{version:"1.0",variables:Array.from(this.variables.values())}}importConfig(e){this.variables.clear();for(const t of e.variables)this.variables.set(t.name,t)}toJSON(){return JSON.stringify(this.exportConfig(),null,2)}static fromJSON(e){return JSON.parse(e)}}class pe{constructor(){this.name="@esengine/behavior-tree",this.version="1.0.0",this.worldManager=null,this.services=null}async install(e,t){this.services=t,t.registerSingleton(he),t.registerSingleton(x),this.worldManager=t.resolve(h)}async uninstall(){this.services&&(this.services.unregister(he),this.services.unregister(x)),this.worldManager=null,this.services=null}setupScene(e){e.addSystem(new ne)}setupAllScenes(){if(!this.worldManager)throw new Error("Plugin not installed");const e=this.worldManager.getAllWorlds();for(const t of e)for(const e of t.getAllScenes())this.setupScene(e)}}export{y as AbortType,q as AlwaysFailExecutor,O as AlwaysSucceedExecutor,x as BehaviorTreeAssetManager,ue as BehaviorTreeAssetSerializer,se as BehaviorTreeAssetValidator,oe as BehaviorTreeBuilder,ne as BehaviorTreeExecutionSystem,pe as BehaviorTreePlugin,T as BehaviorTreeRuntimeComponent,re as BehaviorTreeStarter,k as BindingHelper,Y as BlackboardCompare,Z as BlackboardExists,b as BlackboardValueType,m as CompositeType,z as ConditionalExecutor,J as CooldownExecutor,f as DecoratorType,de as EditorFormatConverter,Q as ExecuteAction,te as ExecuteCondition,he as GlobalBlackboardService,$ as InverterExecutor,W as LogAction,H as ModifyBlackboardValue,D as NodeExecutorMetadata,A as NodeExecutorRegistry,w as NodeMetadataRegistry,ae as NodeTemplates,g as NodeType,R as ParallelExecutor,F as ParallelSelectorExecutor,ie as PropertyType,ee as RandomProbability,M as RandomSelectorExecutor,V as RandomSequenceExecutor,E as RepeaterExecutor,B as SelectorExecutor,I as SequenceExecutor,_ as ServiceDecorator,U as ServiceRegistry,G as SetBlackboardValue,X as SubTreeExecutor,p as TaskStatus,K as TimeoutExecutor,j as UntilFailExecutor,P as UntilSuccessExecutor,L as WaitAction,S as createDefaultRuntimeState};
2
- //# sourceMappingURL=index.mjs.map