@esengine/behavior-tree 1.0.0 → 1.0.2

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 s,ECSComponent as n,Serializable as o,Core as i,createLogger as r,EntitySystem as a,Matcher as c,Time as d,WorldManager as l,SceneSerializer as u}from"@esengine/ecs-framework";function h(e,t,s,n){var o,i=arguments.length,r=i<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,s):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,s,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(r=(i<3?o(r):i>3?o(t,s,r):o(t,s))||r);return i>3&&r&&Object.defineProperty(t,s,r),r}function p(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}var m,y,f,g,b,v;!function(e){e[e.Invalid=0]="Invalid",e[e.Success=1]="Success",e[e.Failure=2]="Failure",e[e.Running=3]="Running"}(m||(m={})),function(e){e.Composite="composite",e.Decorator="decorator",e.Action="action",e.Condition="condition"}(y||(y={})),function(e){e.Sequence="sequence",e.Selector="selector",e.Parallel="parallel",e.ParallelSelector="parallel-selector",e.RandomSequence="random-sequence",e.RandomSelector="random-selector"}(f||(f={})),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"}(g||(g={})),function(e){e.None="none",e.Self="self",e.LowerPriority="lower-priority",e.Both="both"}(b||(b={})),function(e){e.String="string",e.Number="number",e.Boolean="boolean",e.Vector2="vector2",e.Vector3="vector3",e.Object="object",e.Array="array"}(v||(v={}));class w{static registerNodeClass(e,t){const s=`${t.category}:${t.displayName}`;this.nodeClasses.set(s,{metadata:t,constructor:e})}static getAllNodeClasses(){return Array.from(this.nodeClasses.values())}static getNodeClass(e,t){const s=`${e}:${t}`;return this.nodeClasses.get(s)?.constructor}static clear(){this.nodeClasses.clear()}}function C(e){return function(t){const s={...e,className:t.name};return w.registerNodeClass(t,s),t}}function S(e){return function(t,s){t.constructor.__nodeProperties||(t.constructor.__nodeProperties=[]),t.constructor.__nodeProperties.push({name:s,...e})}}w.nodeClasses=new Map;const T=S;function N(){return w.getAllNodeClasses().map((({metadata:e,constructor:t})=>{const s=t.__nodeProperties||[],n={nodeType:e.type.toLowerCase()},o=new t,i=s.map((e=>{const t=o[e.name];return void 0!==t&&(n[e.name]=t),{...e,defaultValue:void 0!==t?t:e.defaultValue}}));switch(e.type){case y.Composite:n.compositeType=e.displayName;break;case y.Decorator:n.decoratorType=e.displayName;break;case y.Action:n.actionType=e.displayName;break;case y.Condition:n.conditionType=e.displayName}return{type:e.type,displayName:e.displayName,category:e.category,icon:e.icon,description:e.description,color:e.color,className:e.className,requiresChildren:e.requiresChildren,defaultConfig:n,properties:i}}))}function k(){w.clear()}let B=class extends e{constructor(){super(...arguments),this.actionCode="return TaskStatus.Success;",this.parameters={}}getFunction(){if(!this.compiledFunction&&this.actionCode)try{const e=new Function("entity","blackboard","deltaTime","parameters","TaskStatus",`\n const { Success, Failure, Running, Invalid } = TaskStatus;\n try {\n ${this.actionCode}\n } catch (error) {\n return TaskStatus.Failure;\n }\n `);this.compiledFunction=(t,s,n)=>e(t,s,n,this.parameters,m)||m.Success}catch(e){return}return this.compiledFunction}setFunction(e){this.compiledFunction=e}};h([S({label:"动作代码",type:"code",description:"JavaScript 代码,返回 TaskStatus",required:!0}),t(),p("design:type",String)],B.prototype,"actionCode",void 0),h([t(),p("design:type",Object)],B.prototype,"parameters",void 0),h([s(),p("design:type",Function)],B.prototype,"compiledFunction",void 0),B=h([C({displayName:"自定义动作",category:"动作",type:y.Action,icon:"Code",description:"执行自定义代码",color:"#FFC107"}),n("ExecuteAction"),o({version:1})],B);let x=class extends e{constructor(){super(...arguments),this.waitTime=1,this.elapsedTime=0}reset(){this.elapsedTime=0}};h([S({label:"等待时间",type:"number",min:0,step:.1,description:"等待时间(秒)",required:!0}),t(),p("design:type",Number)],x.prototype,"waitTime",void 0),h([s(),p("design:type",Number)],x.prototype,"elapsedTime",void 0),x=h([C({displayName:"等待",category:"动作",type:y.Action,icon:"Clock",description:"等待指定时间",color:"#9E9E9E"}),n("WaitAction"),o({version:1})],x);let A=class extends e{constructor(){super(...arguments),this.message="Hello",this.level="log",this.includeEntityInfo=!1}};h([S({label:"消息",type:"string",required:!0}),t(),p("design:type",String)],A.prototype,"message",void 0),h([S({label:"级别",type:"select",options:[{label:"Log",value:"log"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"}]}),t(),p("design:type",String)],A.prototype,"level",void 0),h([S({label:"包含实体信息",type:"boolean"}),t(),p("design:type",Boolean)],A.prototype,"includeEntityInfo",void 0),A=h([C({displayName:"日志",category:"动作",type:y.Action,icon:"FileText",description:"输出日志消息",color:"#673AB7"}),n("LogAction"),o({version:1})],A);let E=class extends e{constructor(){super(...arguments),this.variableName="",this.value="",this.force=!1}};var I;h([S({label:"变量名",type:"variable",required:!0}),t(),p("design:type",String)],E.prototype,"variableName",void 0),h([S({label:"值",type:"string",description:"可以使用 {{varName}} 引用其他变量"}),t(),p("design:type",Object)],E.prototype,"value",void 0),h([t(),p("design:type",String)],E.prototype,"sourceVariable",void 0),h([t(),p("design:type",Boolean)],E.prototype,"force",void 0),E=h([C({displayName:"设置变量",category:"动作",type:y.Action,icon:"Edit",description:"设置黑板变量的值",color:"#3F51B5"}),n("SetBlackboardValueAction"),o({version:1})],E),function(e){e.Add="add",e.Subtract="subtract",e.Multiply="multiply",e.Divide="divide",e.Modulo="modulo",e.Append="append",e.Remove="remove"}(I||(I={}));let R=class extends e{constructor(){super(...arguments),this.variableName="",this.operation=I.Add,this.operand=0,this.force=!1}};var $;h([S({label:"变量名",type:"variable",required:!0}),t(),p("design:type",String)],R.prototype,"variableName",void 0),h([S({label:"操作类型",type:"select",options:[{label:"加法",value:"add"},{label:"减法",value:"subtract"},{label:"乘法",value:"multiply"},{label:"除法",value:"divide"},{label:"取模",value:"modulo"},{label:"追加",value:"append"},{label:"移除",value:"remove"}]}),t(),p("design:type",String)],R.prototype,"operation",void 0),h([S({label:"操作数",type:"string",description:"可以是固定值或变量引用 {{varName}}"}),t(),p("design:type",Object)],R.prototype,"operand",void 0),h([t(),p("design:type",Boolean)],R.prototype,"force",void 0),R=h([C({displayName:"修改变量",category:"动作",type:y.Action,icon:"Calculator",description:"对黑板变量执行数学或逻辑操作",color:"#FF9800"}),n("ModifyBlackboardValueAction"),o({version:1})],R),function(e){e.Equal="equal",e.NotEqual="notEqual",e.Greater="greater",e.GreaterOrEqual="greaterOrEqual",e.Less="less",e.LessOrEqual="lessOrEqual",e.Contains="contains",e.Matches="matches"}($||($={}));let F=class extends e{constructor(){super(...arguments),this.variableName="",this.operator=$.Equal,this.compareValue=null,this.invertResult=!1}};h([S({label:"变量名",type:"variable",required:!0}),t(),p("design:type",String)],F.prototype,"variableName",void 0),h([S({label:"运算符",type:"select",options:[{label:"等于",value:"equal"},{label:"不等于",value:"notEqual"},{label:"大于",value:"greater"},{label:"大于等于",value:"greaterOrEqual"},{label:"小于",value:"less"},{label:"小于等于",value:"lessOrEqual"},{label:"包含",value:"contains"},{label:"正则匹配",value:"matches"}]}),t(),p("design:type",String)],F.prototype,"operator",void 0),h([S({label:"比较值",type:"string",description:"可以是固定值或变量引用 {{varName}}"}),t(),p("design:type",Object)],F.prototype,"compareValue",void 0),h([S({label:"反转结果",type:"boolean"}),t(),p("design:type",Boolean)],F.prototype,"invertResult",void 0),F=h([C({displayName:"比较变量",category:"条件",type:y.Condition,icon:"Scale",description:"比较黑板变量与指定值",color:"#2196F3"}),n("BlackboardCompareCondition"),o({version:1})],F);let L=class extends e{constructor(){super(...arguments),this.variableName="",this.checkNotNull=!1,this.invertResult=!1}};h([S({label:"变量名",type:"variable",required:!0}),t(),p("design:type",String)],L.prototype,"variableName",void 0),h([S({label:"检查非空",type:"boolean",description:"检查值不为 null/undefined"}),t(),p("design:type",Boolean)],L.prototype,"checkNotNull",void 0),h([S({label:"反转结果",type:"boolean",description:"检查不存在"}),t(),p("design:type",Boolean)],L.prototype,"invertResult",void 0),L=h([C({displayName:"检查变量存在",category:"条件",type:y.Condition,icon:"Search",description:"检查黑板变量是否存在",color:"#00BCD4"}),n("BlackboardExistsCondition"),o({version:1})],L);let U=class extends e{constructor(){super(...arguments),this.probability=.5,this.alwaysRandomize=!0}evaluate(){return(this.alwaysRandomize||void 0===this.cachedResult)&&(this.cachedResult=Math.random()<this.probability),this.cachedResult}reset(){this.cachedResult=void 0}};h([S({label:"成功概率",type:"number",min:0,max:1,step:.1,description:"0.0 - 1.0",required:!0}),t(),p("design:type",Number)],U.prototype,"probability",void 0),h([S({label:"总是重新随机",type:"boolean",description:"false则第一次随机后固定结果"}),t(),p("design:type",Boolean)],U.prototype,"alwaysRandomize",void 0),U=h([C({displayName:"随机概率",category:"条件",type:y.Condition,icon:"Dice",description:"根据概率返回成功或失败",color:"#E91E63"}),n("RandomProbabilityCondition"),o({version:1})],U);let P=class extends e{constructor(){super(...arguments),this.parameters={},this.invertResult=!1}getFunction(){if(!this.compiledFunction&&this.conditionCode)try{const e=new Function("entity","blackboard","deltaTime","parameters",`\n try {\n ${this.conditionCode}\n } catch (error) {\n return false;\n }\n `);this.compiledFunction=(t,s,n)=>Boolean(e(t,s,n,this.parameters))}catch(e){return}return this.compiledFunction}setFunction(e){this.compiledFunction=e}};h([S({label:"条件代码",type:"code",description:"JavaScript 代码,返回 boolean",required:!0}),t(),p("design:type",String)],P.prototype,"conditionCode",void 0),h([t(),p("design:type",Object)],P.prototype,"parameters",void 0),h([S({label:"反转结果",type:"boolean"}),t(),p("design:type",Boolean)],P.prototype,"invertResult",void 0),h([s(),p("design:type",Function)],P.prototype,"compiledFunction",void 0),P=h([C({displayName:"自定义条件",category:"条件",type:y.Condition,icon:"Code",description:"执行自定义条件代码",color:"#9C27B0"}),n("ExecuteCondition"),o({version:1})],P);let M=class extends e{constructor(){super(...arguments),this.compositeType=f.Sequence,this.shuffledIndices=[],this.reshuffleOnRestart=!0}getNextChildIndex(e,t){return this.compositeType===f.RandomSequence||this.compositeType===f.RandomSelector?((0===this.shuffledIndices.length||0===e&&this.reshuffleOnRestart)&&this.shuffleIndices(t),e<this.shuffledIndices.length?this.shuffledIndices[e]:t):e}shuffleIndices(e){this.shuffledIndices=Array.from({length:e},((e,t)=>t));for(let e=this.shuffledIndices.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[this.shuffledIndices[e],this.shuffledIndices[t]]=[this.shuffledIndices[t],this.shuffledIndices[e]]}}resetShuffle(){this.shuffledIndices=[]}};h([t(),p("design:type",String)],M.prototype,"compositeType",void 0),M=h([n("CompositeNode"),o({version:1})],M);let D=class extends M{constructor(){super(),this.abortType=b.None,this.compositeType=f.Sequence}};h([S({label:"中止类型",type:"select",description:"条件变化时的中止行为",options:[{label:"无",value:"none"},{label:"自身",value:"self"},{label:"低优先级",value:"lower-priority"},{label:"两者",value:"both"}]}),t(),p("design:type",String)],D.prototype,"abortType",void 0),D=h([C({displayName:"序列",category:"组合",type:y.Composite,icon:"List",description:"按顺序执行子节点,全部成功才成功",color:"#4CAF50"}),n("SequenceNode"),o({version:1}),p("design:paramtypes",[])],D);let V=class extends M{constructor(){super(),this.abortType=b.None,this.compositeType=f.Selector}};h([S({label:"中止类型",type:"select",description:"条件变化时的中止行为",options:[{label:"无",value:"none"},{label:"自身",value:"self"},{label:"低优先级",value:"lower-priority"},{label:"两者",value:"both"}]}),t(),p("design:type",String)],V.prototype,"abortType",void 0),V=h([C({displayName:"选择",category:"组合",type:y.Composite,icon:"GitBranch",description:"按顺序执行子节点,任一成功则成功",color:"#8BC34A"}),n("SelectorNode"),o({version:1}),p("design:paramtypes",[])],V);let z=class extends M{constructor(){super(),this.successPolicy="all",this.failurePolicy="one",this.compositeType=f.Parallel}};h([S({label:"成功策略",type:"select",description:"多少个子节点成功时整体成功",options:[{label:"全部成功",value:"all"},{label:"任意一个成功",value:"one"}]}),t(),p("design:type",String)],z.prototype,"successPolicy",void 0),h([S({label:"失败策略",type:"select",description:"多少个子节点失败时整体失败",options:[{label:"任意一个失败",value:"one"},{label:"全部失败",value:"all"}]}),t(),p("design:type",String)],z.prototype,"failurePolicy",void 0),z=h([C({displayName:"并行",category:"组合",type:y.Composite,icon:"Layers",description:"同时执行所有子节点",color:"#CDDC39"}),n("ParallelNode"),o({version:1}),p("design:paramtypes",[])],z);let O=class extends M{constructor(){super(),this.failurePolicy="all",this.compositeType=f.ParallelSelector}};h([S({label:"失败策略",type:"select",description:"多少个子节点失败时整体失败",options:[{label:"任意一个失败",value:"one"},{label:"全部失败",value:"all"}]}),t(),p("design:type",String)],O.prototype,"failurePolicy",void 0),O=h([C({displayName:"并行选择",category:"组合",type:y.Composite,icon:"Sparkles",description:"并行执行子节点,任一成功则成功",color:"#FFC107"}),n("ParallelSelectorNode"),o({version:1}),p("design:paramtypes",[])],O);let q=class extends M{constructor(){super(),this.reshuffleOnRestart=!0,this.compositeType=f.RandomSequence}};h([S({label:"重启时重新洗牌",type:"boolean",description:"每次重启时是否重新随机子节点顺序"}),t(),p("design:type",Boolean)],q.prototype,"reshuffleOnRestart",void 0),q=h([C({displayName:"随机序列",category:"组合",type:y.Composite,icon:"Shuffle",description:"随机顺序执行子节点序列",color:"#FF5722"}),n("RandomSequenceNode"),o({version:1}),p("design:paramtypes",[])],q);let j=class extends M{constructor(){super(),this.reshuffleOnRestart=!0,this.compositeType=f.RandomSelector}};h([S({label:"重启时重新洗牌",type:"boolean",description:"每次重启时是否重新随机子节点顺序"}),t(),p("design:type",Boolean)],j.prototype,"reshuffleOnRestart",void 0),j=h([C({displayName:"随机选择",category:"组合",type:y.Composite,icon:"Dices",description:"随机顺序执行子节点选择",color:"#F44336"}),n("RandomSelectorNode"),o({version:1}),p("design:paramtypes",[])],j);let W=class extends M{constructor(){super(...arguments),this.assetId="",this.inheritParentBlackboard=!0,this.propagateFailure=!0,this.preload=!0,this.subTreeCompleted=!1,this.subTreeResult=m.Invalid}getSubTreeRoot(){return this.subTreeRoot}setSubTreeRoot(e){this.subTreeRoot=e,this.subTreeCompleted=!1,this.subTreeResult=m.Invalid}markSubTreeCompleted(e){this.subTreeCompleted=!0,this.subTreeResult=e}isSubTreeCompleted(){return this.subTreeCompleted}getSubTreeResult(){return this.subTreeResult}reset(){this.subTreeRoot=void 0,this.subTreeCompleted=!1,this.subTreeResult=m.Invalid}resetCompletionState(){this.subTreeCompleted=!1,this.subTreeResult=m.Invalid}validate(){const e=[];return this.assetId&&""!==this.assetId.trim()||e.push("SubTree 节点必须指定资产ID"),e}};h([S({label:"资产ID",type:"asset",description:"要引用的行为树资产ID"}),t(),p("design:type",String)],W.prototype,"assetId",void 0),h([S({label:"继承父黑板",type:"boolean",description:"子树是否可以访问父树的黑板变量"}),t(),p("design:type",Boolean)],W.prototype,"inheritParentBlackboard",void 0),h([S({label:"传播失败",type:"boolean",description:"子树失败时是否传播失败状态"}),t(),p("design:type",Boolean)],W.prototype,"propagateFailure",void 0),h([S({label:"预加载",type:"boolean",description:"在行为树启动时预加载子树,避免运行时加载延迟"}),t(),p("design:type",Boolean)],W.prototype,"preload",void 0),W=h([C({displayName:"子树",category:"组合",type:y.Composite,icon:"GitBranch",description:"引用并执行外部行为树文件(不支持静态子节点)",color:"#FF9800",requiresChildren:!1}),n("SubTreeNode"),o({version:1})],W);let J=class extends e{constructor(){super(...arguments),this.decoratorType=g.Inverter}};h([t(),p("design:type",String)],J.prototype,"decoratorType",void 0),J=h([n("DecoratorNode"),o({version:1})],J);let G=class extends J{constructor(){super(),this.decoratorType=g.Inverter}};G=h([C({displayName:"反转",category:"装饰器",type:y.Decorator,icon:"RotateCcw",description:"反转子节点的执行结果",color:"#607D8B"}),n("InverterNode"),o({version:1}),p("design:paramtypes",[])],G);let H=class extends J{constructor(){super(),this.repeatCount=1,this.endOnFailure=!1,this.currentRepeatCount=0,this.decoratorType=g.Repeater}incrementRepeat(){this.currentRepeatCount++}shouldContinueRepeat(){return-1===this.repeatCount||this.currentRepeatCount<this.repeatCount}reset(){this.currentRepeatCount=0}};h([S({label:"重复次数",type:"number",min:-1,step:1,description:"-1表示无限重复",required:!0}),t(),p("design:type",Number)],H.prototype,"repeatCount",void 0),h([S({label:"失败时停止",type:"boolean",description:"子节点失败时是否停止重复"}),t(),p("design:type",Boolean)],H.prototype,"endOnFailure",void 0),h([s(),p("design:type",Number)],H.prototype,"currentRepeatCount",void 0),H=h([C({displayName:"重复",category:"装饰器",type:y.Decorator,icon:"Repeat",description:"重复执行子节点指定次数",color:"#9E9E9E"}),n("RepeaterNode"),o({version:1}),p("design:paramtypes",[])],H);let _=class extends J{constructor(){super(),this.decoratorType=g.UntilSuccess}};_=h([C({displayName:"直到成功",category:"装饰器",type:y.Decorator,icon:"CheckCircle",description:"重复执行子节点直到成功",color:"#4CAF50"}),n("UntilSuccessNode"),o({version:1}),p("design:paramtypes",[])],_);let K=class extends J{constructor(){super(),this.decoratorType=g.UntilFail}};K=h([C({displayName:"直到失败",category:"装饰器",type:y.Decorator,icon:"XCircle",description:"重复执行子节点直到失败",color:"#F44336"}),n("UntilFailNode"),o({version:1}),p("design:paramtypes",[])],K);let X=class extends J{constructor(){super(),this.decoratorType=g.AlwaysSucceed}};X=h([C({displayName:"总是成功",category:"装饰器",type:y.Decorator,icon:"ThumbsUp",description:"无论子节点结果如何都返回成功",color:"#8BC34A"}),n("AlwaysSucceedNode"),o({version:1}),p("design:paramtypes",[])],X);let Z=class extends J{constructor(){super(),this.decoratorType=g.AlwaysFail}};Z=h([C({displayName:"总是失败",category:"装饰器",type:y.Decorator,icon:"ThumbsDown",description:"无论子节点结果如何都返回失败",color:"#FF5722"}),n("AlwaysFailNode"),o({version:1}),p("design:paramtypes",[])],Z);let Q=class extends J{constructor(){super(),this.shouldReevaluate=!0,this.decoratorType=g.Conditional}evaluateCondition(e,t){if(!this.conditionCode)return!1;if(!this.compiledCondition)try{const e=new Function("entity","blackboard",`\n try {\n return Boolean(${this.conditionCode});\n } catch (error) {\n return false;\n }\n `);this.compiledCondition=(t,s)=>Boolean(e(t,s))}catch(e){return!1}return this.compiledCondition(e,t)}setConditionFunction(e){this.compiledCondition=e}};h([S({label:"条件代码",type:"code",description:"JavaScript 代码,返回 boolean",required:!0}),t(),p("design:type",String)],Q.prototype,"conditionCode",void 0),h([S({label:"重新评估条件",type:"boolean",description:"每次执行时是否重新评估条件"}),t(),p("design:type",Boolean)],Q.prototype,"shouldReevaluate",void 0),h([s(),p("design:type",Function)],Q.prototype,"compiledCondition",void 0),Q=h([C({displayName:"条件装饰器",category:"装饰器",type:y.Decorator,icon:"Filter",description:"基于条件判断是否执行子节点",color:"#3F51B5"}),n("ConditionalNode"),o({version:1}),p("design:paramtypes",[])],Q);let Y=class extends J{constructor(){super(),this.cooldownTime=1,this.lastExecutionTime=0,this.decoratorType=g.Cooldown}canExecute(e){return 0===this.lastExecutionTime||e-this.lastExecutionTime>=this.cooldownTime}recordExecution(e){this.lastExecutionTime=e}reset(){this.lastExecutionTime=0}};h([S({label:"冷却时间",type:"number",min:0,step:.1,description:"冷却时间(秒)",required:!0}),t(),p("design:type",Number)],Y.prototype,"cooldownTime",void 0),h([s(),p("design:type",Number)],Y.prototype,"lastExecutionTime",void 0),Y=h([C({displayName:"冷却",category:"装饰器",type:y.Decorator,icon:"Timer",description:"在冷却时间内阻止子节点执行",color:"#00BCD4"}),n("CooldownNode"),o({version:1}),p("design:paramtypes",[])],Y);let ee=class extends J{constructor(){super(),this.timeoutDuration=5,this.startTime=0,this.decoratorType=g.Timeout}recordStartTime(e){0===this.startTime&&(this.startTime=e)}isTimeout(e){return 0!==this.startTime&&e-this.startTime>=this.timeoutDuration}reset(){this.startTime=0}};h([S({label:"超时时间",type:"number",min:0,step:.1,description:"超时时间(秒)",required:!0}),t(),p("design:type",Number)],ee.prototype,"timeoutDuration",void 0),h([s(),p("design:type",Number)],ee.prototype,"startTime",void 0),ee=h([C({displayName:"超时",category:"装饰器",type:y.Decorator,icon:"Clock",description:"子节点执行超时则返回失败",color:"#FF9800"}),n("TimeoutNode"),o({version:1}),p("design:paramtypes",[])],ee);let te=class extends e{constructor(){super(...arguments),this.nodeType=y.Action,this.nodeName="Node",this.status=m.Invalid,this.currentChildIndex=0}reset(){this.status=m.Invalid,this.currentChildIndex=0}invalidate(){this.reset()}};h([t(),p("design:type",String)],te.prototype,"nodeType",void 0),h([t(),p("design:type",String)],te.prototype,"nodeName",void 0),h([s(),p("design:type",Number)],te.prototype,"status",void 0),h([s(),p("design:type",Number)],te.prototype,"currentChildIndex",void 0),te=h([n("BehaviorTreeNode"),o({version:1})],te);class se{constructor(){this.variables=new Map}dispose(){this.variables.clear()}defineVariable(e,t,s,n){this.variables.set(e,{name:e,type:t,value:s,readonly:n?.readonly??!1,description:n?.description})}getValue(e){const t=this.variables.get(e);return t?.value}setValue(e,t,s=!1){const n=this.variables.get(e);return!!n&&(!(n.readonly&&!s)&&(n.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,s]of Object.entries(e)){const e=this.variables.get(t);e&&!e.readonly&&(e.value=s)}}getVariables(e){const t={};for(const s of e){const e=this.getValue(s);void 0!==e&&(t[s]=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)}}let ne=class extends e{constructor(){super(...arguments),this.variables=new Map,this.useGlobalBlackboard=!0}defineVariable(e,t,s,n){this.variables.set(e,{name:e,type:t,value:s,readonly:n?.readonly??!1,description:n?.description})}getValue(e){const t=this.variables.get(e);return void 0!==t?t.value:this.useGlobalBlackboard?i.services.resolve(se).getValue(e):void 0}getLocalValue(e){const t=this.variables.get(e);return t?.value}setValue(e,t,s=!1){const n=this.variables.get(e);return n?!(n.readonly&&!s)&&(n.value=t,!0):!!this.useGlobalBlackboard&&i.services.resolve(se).setValue(e,t,s)}setLocalValue(e,t,s=!1){const n=this.variables.get(e);return!!n&&(!(n.readonly&&!s)&&(n.value=t,!0))}hasVariable(e){return!!this.variables.has(e)||!!this.useGlobalBlackboard&&i.services.resolve(se).hasVariable(e)}hasLocalVariable(e){return this.variables.has(e)}removeVariable(e){return this.variables.delete(e)}getVariableNames(){return Array.from(this.variables.keys())}clear(){this.variables.clear()}setUseGlobalBlackboard(e){this.useGlobalBlackboard=e}isUsingGlobalBlackboard(){return this.useGlobalBlackboard}getAllVariables(){const e=Array.from(this.variables.values());if(this.useGlobalBlackboard){const t=i.services.resolve(se).getAllVariables(),s=new Set(this.variables.keys()),n=t.filter((e=>!s.has(e.name)));return[...e,...n]}return e}static getGlobalBlackboard(){return i.services.resolve(se)}};h([t(),p("design:type",Map)],ne.prototype,"variables",void 0),ne=h([n("Blackboard"),o({version:1})],ne);let oe=class extends e{};oe=h([n("ActiveNode")],oe);class ie extends e{constructor(){super(...arguments),this.bindings=new Map}addBinding(e,t){this.bindings.set(e,t)}getBinding(e){return this.bindings.get(e)}hasBinding(e){return this.bindings.has(e)}clearBindings(){this.bindings.clear()}}let re=class extends e{constructor(){super(...arguments),this.messages=[]}addMessage(e,t="log"){this.messages.push({timestamp:Date.now(),message:e,level:t})}clear(){this.messages=[]}};re=h([n("LogOutput")],re);let ae=class extends e{constructor(){super(...arguments),this.assetId="",this.assetVersion="",this.assetName="",this.loadedAt=0,this.description=""}initialize(e,t,s){this.assetId=e,this.assetVersion=t,this.assetName=s||e,this.loadedAt=Date.now()}};h([t(),p("design:type",String)],ae.prototype,"assetId",void 0),h([t(),p("design:type",String)],ae.prototype,"assetVersion",void 0),h([t(),p("design:type",String)],ae.prototype,"assetName",void 0),h([t(),p("design:type",Number)],ae.prototype,"loadedAt",void 0),h([t(),p("design:type",String)],ae.prototype,"description",void 0),ae=h([n("BehaviorTreeAssetMetadata"),o({version:1})],ae);let ce=class extends M{constructor(){super(),this.compositeType=f.Sequence}};ce=h([C({displayName:"根节点",category:"根节点",type:y.Composite,icon:"TreePine",description:"行为树的根节点",color:"#FFD700"}),n("RootNode"),o({version:1}),p("design:paramtypes",[])],ce);const de=new TextEncoder;function le(e,t,s){e.length>50?function(e,t,s){de.encodeInto(e,t.subarray(s))}(e,t,s):function(e,t,s){const n=e.length;let o=s,i=0;for(;i<n;){let s=e.charCodeAt(i++);if(4294967168&s){if(4294965248&s){if(s>=55296&&s<=56319&&i<n){const t=e.charCodeAt(i);56320==(64512&t)&&(++i,s=((1023&s)<<10)+(1023&t)+65536)}4294901760&s?(t[o++]=s>>18&7|240,t[o++]=s>>12&63|128,t[o++]=s>>6&63|128):(t[o++]=s>>12&15|224,t[o++]=s>>6&63|128)}else t[o++]=s>>6&31|192;t[o++]=63&s|128}else t[o++]=s}}(e,t,s)}function ue(e,t,s){let n=t;const o=n+s,i=[];let r="";for(;n<o;){const t=e[n++];if(128&t)if(192==(224&t)){const s=63&e[n++];i.push((31&t)<<6|s)}else if(224==(240&t)){const s=63&e[n++],o=63&e[n++];i.push((31&t)<<12|s<<6|o)}else if(240==(248&t)){let s=(7&t)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++];s>65535&&(s-=65536,i.push(s>>>10&1023|55296),s=56320|1023&s),i.push(s)}else i.push(t);else i.push(t);i.length>=4096&&(r+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(r+=String.fromCharCode(...i)),r}const he=new TextDecoder;function pe(e,t,s){return s>200?function(e,t,s){const n=e.subarray(t,t+s);return he.decode(n)}(e,t,s):ue(e,t,s)}class me{constructor(e,t){this.type=e,this.data=t}}class ye extends Error{constructor(e){super(e);const t=Object.create(ye.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ye.name})}}const fe=4294967295;function ge(e,t,s){const n=Math.floor(s/4294967296),o=s;e.setUint32(t,n),e.setUint32(t+4,o)}function be(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}const ve={type:-1,encode:function(e){if(e instanceof Date){return function({sec:e,nsec:t}){if(e>=0&&t>=0&&e<=17179869183){if(0===t&&e<=4294967295){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e),t}{const s=e/4294967296,n=4294967295&e,o=new Uint8Array(8),i=new DataView(o.buffer);return i.setUint32(0,t<<2|3&s),i.setUint32(4,n),o}}{const s=new Uint8Array(12),n=new DataView(s.buffer);return n.setUint32(0,t),ge(n,4,e),s}}(function(e){const t=e.getTime(),s=Math.floor(t/1e3),n=1e6*(t-1e3*s),o=Math.floor(n/1e9);return{sec:s+o,nsec:n-1e9*o}}(e))}return null},decode:function(e){const t=function(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:{const e=t.getUint32(0);return{sec:4294967296*(3&e)+t.getUint32(4),nsec:e>>>2}}case 12:return{sec:be(t,4),nsec:t.getUint32(0)};default:throw new ye(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${e.length}`)}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}};class we{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ve)}register({type:e,encode:t,decode:s}){if(e>=0)this.encoders[e]=t,this.decoders[e]=s;else{const n=-1-e;this.builtInEncoders[n]=t,this.builtInDecoders[n]=s}}tryToEncode(e,t){for(let s=0;s<this.builtInEncoders.length;s++){const n=this.builtInEncoders[s];if(null!=n){const o=n(e,t);if(null!=o){return new me(-1-s,o)}}}for(let s=0;s<this.encoders.length;s++){const n=this.encoders[s];if(null!=n){const o=n(e,t);if(null!=o){return new me(s,o)}}}return e instanceof me?e:null}decode(e,t,s){const n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,s):new me(t,e)}}function Ce(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):function(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}(e)?new Uint8Array(e):Uint8Array.from(e)}we.defaultCodec=new we;class Se{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??we.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??100,this.initialBufferSize=e?.initialBufferSize??2048,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Se({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered){return this.clone().encodeSharedRef(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered){return this.clone().encode(e)}try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.useBigInt64&&"bigint"==typeof e?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)}resizeBuffer(e){const t=new ArrayBuffer(e),s=new Uint8Array(t),n=new DataView(t);s.set(this.bytes),this.view=n,this.bytes=s}encodeNil(){this.writeU8(192)}encodeBoolean(e){!1===e?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error(`Too long string: ${e} bytes in UTF-8`);this.writeU8(219),this.writeU32(e)}}encodeString(e){const t=function(e){const t=e.length;let s=0,n=0;for(;n<t;){let o=e.charCodeAt(n++);if(4294967168&o)if(4294965248&o){if(o>=55296&&o<=56319&&n<t){const t=e.charCodeAt(n);56320==(64512&t)&&(++n,o=((1023&o)<<10)+(1023&t)+65536)}s+=4294901760&o?4:3}else s+=2;else s++}return s}(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),le(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const s=this.extensionCodec.tryToEncode(e,this.context);if(null!=s)this.encodeExtension(s);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`);this.encodeMap(e,t)}}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large binary: ${t}`);this.writeU8(198),this.writeU32(t)}const s=Ce(e);this.writeU8a(s)}encodeArray(e,t){const s=e.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else{if(!(s<4294967296))throw new Error(`Too large array: ${s}`);this.writeU8(221),this.writeU32(s)}for(const s of e)this.doEncode(s,t+1)}countWithoutUndefined(e,t){let s=0;for(const n of t)void 0!==e[n]&&s++;return s}encodeMap(e,t){const s=Object.keys(e);this.sortKeys&&s.sort();const n=this.ignoreUndefined?this.countWithoutUndefined(e,s):s.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else{if(!(n<4294967296))throw new Error(`Too large map object: ${n}`);this.writeU8(223),this.writeU32(n)}for(const n of s){const s=e[n];this.ignoreUndefined&&void 0===s||(this.encodeString(n),this.doEncode(s,t+1))}}encodeExtension(e){if("function"==typeof e.data){const t=e.data(this.pos+6),s=t.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);return this.writeU8(201),this.writeU32(s),this.writeI8(e.type),void this.writeU8a(t)}const t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error(`Too large extension object: ${t}`);this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),function(e,t,s){const n=s/4294967296,o=s;e.setUint32(t,n),e.setUint32(t+4,o)}(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ge(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function Te(e){return`${e<0?"-":""}0x${Math.abs(e).toString(16).padStart(2,"0")}`}const Ne="array",ke="map_key",Be="map_value",xe=e=>{if("string"==typeof e||"number"==typeof e)return e;throw new ye("The type of key must be string or number but "+typeof e)};class Ae{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=Ne,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=ke,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Ne){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===ke||e.type===Be){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Ee=new DataView(new ArrayBuffer(0)),Ie=new Uint8Array(Ee.buffer);try{Ee.getInt8(0)}catch(e){if(!(e instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Re=new RangeError("Insufficient data"),$e=new class{constructor(e=16,t=16){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let e=0;e<this.maxKeyLength;e++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,s){const n=this.caches[s-1];e:for(const o of n){const n=o.bytes;for(let o=0;o<s;o++)if(n[o]!==e[t+o])continue e;return o.str}return null}store(e,t){const s=this.caches[e.length-1],n={bytes:e,str:t};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=n:s.push(n)}decode(e,t,s){const n=this.find(e,t,s);if(null!=n)return this.hit++,n;this.miss++;const o=ue(e,t,s),i=Uint8Array.prototype.slice.call(e,t,t+s);return this.store(i,o),o}};class Fe{constructor(e){this.totalPos=0,this.pos=0,this.view=Ee,this.bytes=Ie,this.headByte=-1,this.stack=new Ae,this.entered=!1,this.extensionCodec=e?.extensionCodec??we.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??fe,this.maxBinLength=e?.maxBinLength??fe,this.maxArrayLength=e?.maxArrayLength??fe,this.maxMapLength=e?.maxMapLength??fe,this.maxExtLength=e?.maxExtLength??fe,this.keyDecoder=void 0!==e?.keyDecoder?e.keyDecoder:$e,this.mapKeyConverter=e?.mapKeyConverter??xe}clone(){return new Fe({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=-1,this.stack.reset()}setBuffer(e){const t=Ce(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(-1!==this.headByte||this.hasRemaining(1)){const t=this.bytes.subarray(this.pos),s=Ce(e),n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),this.setBuffer(n)}else this.setBuffer(e)}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:s}=this;return new RangeError(`Extra ${t.byteLength-s} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered){return this.clone().decode(e)}try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){const t=this.clone();yield*t.decodeMulti(e)}else try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered){return this.clone().decodeAsync(e)}try{this.entered=!0;let t,s=!1;for await(const n of e){if(s)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(n);try{t=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return t}const{headByte:n,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${Te(n)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){const s=this.clone();yield*s.decodeMultiAsync(e,t)}else try{this.entered=!0;let s=t,n=-1;for await(const o of e){if(t&&0===n)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),s&&(n=this.readArraySize(),s=!1,this.complete());try{for(;yield this.doDecodeSync(),0!==--n;);}catch(e){if(!(e instanceof RangeError))throw e}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const s=e-128;if(0!==s){this.pushMapState(s),this.complete();continue e}t={}}else if(e<160){const s=e-144;if(0!==s){this.pushArrayState(s),this.complete();continue e}t=[]}else{const s=e-160;t=this.decodeString(s,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.useBigInt64?this.readU64AsBigInt():this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.useBigInt64?this.readI64AsBigInt():this.readI64();else if(217===e){const e=this.lookU8();t=this.decodeString(e,1)}else if(218===e){const e=this.lookU16();t=this.decodeString(e,2)}else if(219===e){const e=this.lookU32();t=this.decodeString(e,4)}else if(220===e){const e=this.readU16();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(221===e){const e=this.readU32();if(0!==e){this.pushArrayState(e),this.complete();continue e}t=[]}else if(222===e){const e=this.readU16();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(223===e){const e=this.readU32();if(0!==e){this.pushMapState(e),this.complete();continue e}t={}}else if(196===e){const e=this.lookU8();t=this.decodeBinary(e,1)}else if(197===e){const e=this.lookU16();t=this.decodeBinary(e,2)}else if(198===e){const e=this.lookU32();t=this.decodeBinary(e,4)}else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e){const e=this.lookU8();t=this.decodeExtension(e,1)}else if(200===e){const e=this.lookU16();t=this.decodeExtension(e,2)}else{if(201!==e)throw new ye(`Unrecognized type byte: ${Te(e)}`);{const e=this.lookU32();t=this.decodeExtension(e,4)}}this.complete();const s=this.stack;for(;s.length>0;){const e=s.top();if(e.type===Ne){if(e.array[e.position]=t,e.position++,e.position!==e.size)continue e;t=e.array,s.release(e)}else{if(e.type===ke){if("__proto__"===t)throw new ye("The key __proto__ is not allowed");e.key=this.mapKeyConverter(t),e.type=Be;continue e}if(e.map[e.key]=t,e.readCount++,e.readCount!==e.size){e.key=null,e.type=ke;continue e}t=e.map,s.release(e)}}return t}}readHeadByte(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=-1}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new ye(`Unrecognized array type byte: ${Te(e)}`)}}pushMapState(e){if(e>this.maxMapLength)throw new ye(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ye(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){if(e>this.maxStrLength)throw new ye(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Re;const s=this.pos+t;let n;return n=this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?this.keyDecoder.decode(this.bytes,s,e):pe(this.bytes,s,e),this.pos+=t+e,n}stateIsMapKey(){if(this.stack.length>0){return this.stack.top().type===ke}return!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new ye(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Re;const s=this.pos+t,n=this.bytes.subarray(s,s+e);return this.pos+=t+e,n}decodeExtension(e,t){if(e>this.maxExtLength)throw new ye(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const s=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,s,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=(t=this.view,s=this.pos,4294967296*t.getUint32(s)+t.getUint32(s+4));var t,s;return this.pos+=8,e}readI64(){const e=be(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Le(e,t){return new Fe(t).decode(e)}class Ue{static validate(e){const t=[],s=[];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 n=new Set;e.nodes.find((t=>t.id===e.rootNodeId))||t.push(`Root node '${e.rootNodeId}' not found in nodes array`);for(const s of e.nodes)if(s.id){if(n.has(s.id)&&t.push(`Duplicate node id: ${s.id}`),n.add(s.id),s.nodeType||t.push(`Node ${s.id} missing nodeType`),s.children)for(const n of s.children)e.nodes.find((e=>e.id===n))||t.push(`Node ${s.id} references non-existent child: ${n}`)}else t.push("Node missing id field");const o=new Set([e.rootNodeId]),i=t=>{const s=e.nodes.find((e=>e.id===t));if(s&&s.children)for(const e of s.children)o.add(e),i(e)};i(e.rootNodeId);for(const t of e.nodes)o.has(t.id)||s.push(`Orphaned node detected: ${t.id} (${t.name})`)}else t.push("Missing or invalid nodes array");if(e.blackboard&&Array.isArray(e.blackboard)){const s=new Set;for(const n of e.blackboard)n.name?(s.has(n.name)&&t.push(`Duplicate blackboard variable: ${n.name}`),s.add(n.name),n.type||t.push(`Blackboard variable ${n.name} missing type`)):t.push("Blackboard variable missing name")}if(e.propertyBindings&&Array.isArray(e.propertyBindings)){const s=new Set(e.nodes.map((e=>e.id))),n=new Set(e.blackboard?.map((e=>e.name))||[]);for(const o of e.propertyBindings)s.has(o.nodeId)||t.push(`Property binding references non-existent node: ${o.nodeId}`),n.has(o.variableName)||t.push(`Property binding references non-existent variable: ${o.variableName}`),o.propertyName||t.push("Property binding missing propertyName")}return{valid:0===t.length,errors:t.length>0?t:void 0,warnings:s.length>0?s:void 0}}static getStats(e){let t=0,s=0,n=0,o=0;for(const i of e.nodes)switch(i.nodeType){case y.Action:t++;break;case y.Condition:s++;break;case y.Composite:n++;break;case y.Decorator:o++}const i=(t,s=0)=>{const n=e.nodes.find((e=>e.id===t));if(!n||!n.children||0===n.children.length)return s;let o=s;for(const e of n.children){const t=i(e,s+1);o=Math.max(o,t)}return o};return{nodeCount:e.nodes.length,actionCount:t,conditionCount:s,compositeCount:n,decoratorCount:o,blackboardVariableCount:e.blackboard?.length||0,propertyBindingCount:e.propertyBindings?.length||0,maxDepth:i(e.rootNodeId)}}}const Pe=r("EditorFormatConverter");class Me{static toAsset(e,t){Pe.info("开始转换编辑器格式到资产格式");const s=this.findRootNode(e.nodes);if(!s)throw new Error("未找到根节点");const n={name:t?.name||e.metadata?.name||"Untitled Behavior Tree",description:t?.description||e.metadata?.description,version:t?.version||e.version||"1.0.0",createdAt:t?.createdAt||e.metadata?.createdAt,modifiedAt:t?.modifiedAt||(new Date).toISOString()},o=this.convertNodes(e.nodes),i=this.convertBlackboard(e.blackboard),r=this.convertPropertyBindings(e.connections,e.nodes,i),a={version:"1.0.0",metadata:n,rootNodeId:s.id,nodes:o,blackboard:i,propertyBindings:r.length>0?r:void 0};return Pe.info(`转换完成: ${o.length}个节点, ${i.length}个黑板变量, ${r.length}个属性绑定`),a}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,{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[s,n]of Object.entries(e)){const e=this.inferBlackboardType(n);t.push({name:s,type:e,defaultValue:n})}return t}static inferBlackboardType(e){return"number"==typeof e?v.Number:"string"==typeof e?v.String:"boolean"==typeof e?v.Boolean:v.Object}static convertPropertyBindings(e,t,s){const n=[],o=new Set(s.map((e=>e.name))),i=e.filter((e=>"property"===e.connectionType));for(const e of i){const s=t.find((t=>t.id===e.from)),i=t.find((t=>t.id===e.to));if(!s||!i||!e.toProperty){Pe.warn(`跳过无效的属性连接: from=${e.from}, to=${e.to}`);continue}let r;"blackboard-variable"===s.data.nodeType?r=s.data.variableName:e.fromProperty&&(r=e.fromProperty),r?o.has(r)?n.push({nodeId:i.id,propertyName:e.toProperty,variableName:r}):Pe.warn(`属性绑定引用了不存在的黑板变量: ${r}`):Pe.warn(`无法确定变量名: from节点=${s.template.displayName}`)}return n}static fromAsset(e){Pe.info("开始转换资产格式到编辑器格式");const t=this.convertNodesFromAsset(e.nodes),s={};for(const t of e.blackboard)s[t.name]=t.defaultValue;const n=this.convertPropertyBindingsToConnections(e.propertyBindings||[],e.nodes),o=this.buildNodeConnections(e.nodes);n.push(...o);const i={version:e.metadata.version,metadata:{name:e.metadata.name,description:e.metadata.description,createdAt:e.metadata.createdAt,modifiedAt:e.metadata.modifiedAt},nodes:t,connections:n,blackboard:s,canvasState:{offset:{x:0,y:0},scale:1}};return Pe.info(`转换完成: ${t.length}个节点, ${n.length}个连接`),i}static convertNodesFromAsset(e){return e.map(((e,t)=>{const s={x:100+t%5*250,y:100+150*Math.floor(t/5)};return{id:e.id,template:{displayName:e.name,category:this.inferCategory(e.nodeType),type:e.nodeType},data:{...e.data},position:s,children:e.children}}))}static inferCategory(e){switch(e){case y.Action:return"动作";case y.Condition:return"条件";case y.Composite:return"组合";case y.Decorator:return"装饰器";default:return"其他"}}static convertPropertyBindingsToConnections(e,t){const s=[];for(const t of e)s.push({from:"blackboard",to:t.nodeId,toProperty:t.propertyName,connectionType:"property"});return s}static buildNodeConnections(e){const t=[];for(const s of e)for(const e of s.children)t.push({from:s.id,to:e,connectionType:"node"});return t}}const De=r("BehaviorTreeAssetSerializer");class Ve{static serialize(e,t={format:"json",pretty:!0}){if(!1!==t.validate){const t=Ue.validate(e);if(!t.valid){const e=t.errors?.join(", ")||"Unknown error";throw new Error(`资产验证失败: ${e}`)}t.warnings&&t.warnings.length>0&&De.warn(`资产验证警告: ${t.warnings.join(", ")}`)}return"json"===t.format?this.serializeToJSON(e,t.pretty):this.serializeToBinary(e)}static serializeToJSON(e,t=!0){try{const s=t?JSON.stringify(e,null,2):JSON.stringify(e);return De.info(`已序列化为JSON: ${s.length} 字符`),s}catch(e){throw new Error(`JSON序列化失败: ${e}`)}}static serializeToBinary(e){try{const n=(t=e,new Se(s).encodeSharedRef(t));return De.info(`已序列化为二进制: ${n.length} 字节`),n}catch(e){throw new Error(`二进制序列化失败: ${e}`)}var t,s}static deserialize(e,t={validate:!0,strict:!0}){let s;try{s="string"==typeof e?this.deserializeFromJSON(e):this.deserializeFromBinary(e)}catch(e){throw new Error(`反序列化失败: ${e}`)}if(!1!==t.validate){const e=Ue.validate(s);if(!e.valid){const s=e.errors?.join(", ")||"Unknown error";if(t.strict)throw new Error(`资产验证失败: ${s}`);De.error(`资产验证失败: ${s}`)}e.warnings&&e.warnings.length>0&&De.warn(`资产验证警告: ${e.warnings.join(", ")}`)}return s}static deserializeFromJSON(e){try{const t=JSON.parse(e);if(!t.rootNodeId&&t.nodes&&t.connections){De.info("检测到编辑器格式,正在转换为运行时资产格式...");const e=t,s=Me.toAsset(e);return De.info(`已从编辑器格式转换: ${s.nodes.length} 个节点`),s}{const e=t;return De.info(`已从运行时资产格式反序列化: ${e.nodes.length} 个节点`),e}}catch(e){throw new Error(`JSON解析失败: ${e}`)}}static deserializeFromBinary(e){try{const t=Le(e);return De.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 s;s="json"===t?JSON.parse(e):Le(e);const n=e.length;return{format:t,name:s.metadata.name,version:s.version,nodeCount:s.nodes.length,blackboardVariableCount:s.blackboard.length,size:n}}catch(e){return De.error(`获取资产信息失败: ${e}`),null}}static convert(e,t,s=!0){const n=this.deserialize(e,{validate:!1});return this.serialize(n,{format:t,pretty:s,validate:!1})}static compareSize(e,t){const s=e.length,n=t.length,o=s-n;return{jsonSize:s,binarySize:n,compressionRatio:o/s*100,savedBytes:o}}}const ze=r("FileSystemAssetLoader");class Oe{constructor(e){this.cache=new Map,this.config={basePath:e.basePath,format:e.format,extension:e.extension||("json"===e.format?".btree.json":".btree.bin"),enableCache:e.enableCache??!0,readFile:e.readFile||this.defaultReadFile.bind(this)},this.config.basePath=this.config.basePath.replace(/\\/g,"/").replace(/\/$/,"")}async loadBehaviorTree(e){if(this.config.enableCache&&this.cache.has(e))return ze.debug(`从缓存加载资产: ${e}`),this.cache.get(e);ze.info(`加载行为树资产: ${e}`);try{const t=this.resolveAssetPath(e),s=await this.config.readFile(t),n={validate:!0,strict:!0},o=Ve.deserialize(s,n);return this.config.enableCache&&this.cache.set(e,o),ze.info(`成功加载资产: ${e}`),o}catch(t){throw ze.error(`加载资产失败: ${e}`,t),new Error(`Failed to load behavior tree asset '${e}': ${t}`)}}async exists(e){if(this.config.enableCache&&this.cache.has(e))return!0;try{const t=this.resolveAssetPath(e);return await this.config.readFile(t),!0}catch{return!1}}async preload(e){ze.info(`预加载 ${e.length} 个资产...`);const t=e.map((e=>this.loadBehaviorTree(e).catch((t=>{ze.warn(`预加载资产失败: ${e}`,t)}))));await Promise.all(t),ze.info("预加载完成")}unload(e){this.cache.has(e)&&(this.cache.delete(e),ze.debug(`卸载资产: ${e}`))}clearCache(){this.cache.clear(),ze.info("缓存已清空")}getCacheSize(){return this.cache.size}dispose(){this.clearCache()}resolveAssetPath(e){const t=e.replace(/^\/+/,"");return`${this.config.basePath}/${t}${this.config.extension}`}async defaultReadFile(e){if("undefined"!=typeof window&&"undefined"!=typeof fetch){const t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);if("binary"===this.config.format){const e=await t.arrayBuffer();return new Uint8Array(e)}return await t.text()}if("undefined"==typeof require)throw new Error("No default file reading implementation available. Please provide a custom readFile function in the config.");try{const t=require("fs").promises;if("binary"===this.config.format){const s=await t.readFile(e);return new Uint8Array(s)}return await t.readFile(e,"utf-8")}catch(t){throw new Error(`Failed to read file '${e}': ${t}`)}}}const qe=r("BehaviorTreeAssetLoader");class je{static instantiate(e,t,s={}){qe.info(`开始实例化行为树: ${e.metadata.name}`);const n=new Map;for(const t of e.nodes)n.set(t.id,t);const o=n.get(e.rootNodeId);if(!o)throw new Error(`未找到根节点: ${e.rootNodeId}`);const i=new Map,r=this.createEntityTree(o,n,i,t,s.namePrefix,s.asSubTree);return this.setupBlackboard(r,e.blackboard,s.blackboardOverrides),e.propertyBindings&&e.propertyBindings.length>0&&this.setupPropertyBindings(e.propertyBindings,i),qe.info(`行为树实例化完成: ${e.nodes.length} 个节点`),r}static createEntityTree(e,t,s,n,o,i,r=!0){const a=o?`${o}_${e.name}`:e.name,c=n.createEntity(a);s.set(e.id,c);const d=c.addComponent(new te);d.nodeType=e.nodeType,d.nodeName=e.name,this.addNodeComponents(c,e,i&&r);for(const r of e.children){const e=t.get(r);if(!e){qe.warn(`子节点未找到: ${r}`);continue}const a=this.createEntityTree(e,t,s,n,o,i,!1);c.addChild(a)}return c}static addNodeComponents(e,t,s=!1){const{nodeType:n,data:o,name:i}=t;qe.debug(`addNodeComponents: name=${i}, data.nodeType=${o.nodeType}, skipRootNode=${s}`),"root"===o.nodeType||"根节点"===i||"Root"===i?s?(qe.debug(`跳过为子树根节点添加 RootNode: ${i}`),this.addCompositeComponent(e,"序列",o)):(qe.debug(`添加 RootNode 组件: ${i}`),e.addComponent(new ce)):n===y.Composite?this.addCompositeComponent(e,i,o):n===y.Decorator?this.addDecoratorComponent(e,i,o):n===y.Action?this.addActionComponent(e,i,o):n===y.Condition&&this.addConditionComponent(e,i,o)}static addCompositeComponent(e,t,s){const n=t.toLowerCase();if(n.includes("sequence")||n.includes("序列")){e.addComponent(new D).abortType=s.abortType??b.None}else if(n.includes("selector")||n.includes("选择")){e.addComponent(new V).abortType=s.abortType??b.None}else if(n.includes("parallelselector")||n.includes("并行选择")){e.addComponent(new O).failurePolicy=s.failurePolicy??"one"}else if(n.includes("parallel")||n.includes("并行")){const t=e.addComponent(new z);t.successPolicy=s.successPolicy??"all",t.failurePolicy=s.failurePolicy??"one"}else n.includes("randomsequence")||n.includes("随机序列")?e.addComponent(new q):n.includes("randomselector")||n.includes("随机选择")?e.addComponent(new j):qe.warn(`未知的组合节点类型: ${t}`)}static addDecoratorComponent(e,t,s){const n=t.toLowerCase();if(n.includes("inverter")||n.includes("反转"))e.addComponent(new G);else if(n.includes("repeater")||n.includes("重复")){const t=e.addComponent(new H);t.repeatCount=s.repeatCount??-1,t.endOnFailure=s.endOnFailure??!1}else if(n.includes("untilsuccess")||n.includes("直到成功"))e.addComponent(new _);else if(n.includes("untilfail")||n.includes("直到失败"))e.addComponent(new K);else if(n.includes("alwayssucceed")||n.includes("总是成功"))e.addComponent(new X);else if(n.includes("alwaysfail")||n.includes("总是失败"))e.addComponent(new Z);else if(n.includes("conditional")||n.includes("条件装饰")){const t=e.addComponent(new Q);t.conditionCode=s.conditionCode??"",t.shouldReevaluate=s.shouldReevaluate??!0}else if(n.includes("cooldown")||n.includes("冷却")){e.addComponent(new Y).cooldownTime=s.cooldownTime??1}else if(n.includes("timeout")||n.includes("超时")){e.addComponent(new ee).timeoutDuration=s.timeoutDuration??1}else qe.warn(`未知的装饰器类型: ${t}`)}static addActionComponent(e,t,s){const n=t.toLowerCase();if(n.includes("wait")||n.includes("等待")){e.addComponent(new x).waitTime=s.waitTime??1}else if(n.includes("log")||n.includes("日志")){const t=e.addComponent(new A);t.message=s.message??"",t.level=s.level??"log"}else if(n.includes("setblackboard")||n.includes("setvalue")||n.includes("设置变量")){const t=e.addComponent(new E);t.variableName=s.variableName??"",t.value=s.value}else if(n.includes("modifyblackboard")||n.includes("modifyvalue")||n.includes("修改变量")){const t=e.addComponent(new R);t.variableName=s.variableName??"",t.operation=s.operation??"add",t.operand=s.operand??0}else if(n.includes("execute")||n.includes("自定义")){e.addComponent(new B).actionCode=s.actionCode??"return TaskStatus.Success;"}else qe.warn(`未知的动作类型: ${t}`)}static addConditionComponent(e,t,s){const n=t.toLowerCase();if(n.includes("compare")||n.includes("比较变量")){const t=e.addComponent(new F);t.variableName=s.variableName??"",t.operator=s.operator??$.Equal,t.compareValue=s.compareValue,t.invertResult=s.invertResult??!1}else if(n.includes("exists")||n.includes("变量存在")){const t=e.addComponent(new L);t.variableName=s.variableName??"",t.checkNotNull=s.checkNotNull??!1,t.invertResult=s.invertResult??!1}else if(n.includes("random")||n.includes("概率")){e.addComponent(new U).probability=s.probability??.5}else if(n.includes("execute")||n.includes("执行条件")){const t=e.addComponent(new P);t.conditionCode=s.conditionCode??"",t.invertResult=s.invertResult??!1}else qe.warn(`未知的条件类型: ${t}`)}static setupBlackboard(e,t,s){const n=e.addComponent(new ne);for(const e of t){const t=s&&void 0!==s[e.name]?s[e.name]:e.defaultValue;n.defineVariable(e.name,e.type,t,{readonly:e.readonly,description:e.description})}qe.info(`已设置黑板: ${t.length} 个变量`)}static setupPropertyBindings(e,t){for(const s of e){const e=t.get(s.nodeId);if(!e){qe.warn(`属性绑定引用的节点不存在: ${s.nodeId}`);continue}let n=e.getComponent(ie);n||(n=e.addComponent(new ie)),n.addBinding(s.propertyName,s.variableName)}qe.info(`已设置属性绑定: ${e.length} 个绑定`)}}var We,Je;!function(e){e[e.NotStarted=0]="NotStarted",e[e.Loading=1]="Loading",e[e.Completed=2]="Completed",e[e.Failed=3]="Failed"}(We||(We={}));class Ge extends a{constructor(){super(c.empty().all(te,oe)),this.preloadStates=new Map,this.preloadTasks=new Map,this.updateOrder=350}process(e){for(const t of e){const e=t.getComponent(te);e.nodeType===y.Composite&&(t.hasComponent(ce)&&this.executeRoot(t,e))}}executeRoot(e,t){const s=this.preloadStates.get(e.id)||We.NotStarted;if(s===We.NotStarted)return void this.startPreload(e,t);if(s===We.Loading)return void(t.status=m.Running);if(s===We.Failed)return t.status=m.Failure,void e.removeComponentByType(oe);const n=e.children;if(0===n.length)return void(t.status=m.Success);const o=n[0],i=o.getComponent(te);if(i)return o.hasComponent(oe)?void(i.status===m.Running?t.status=m.Running:i.status===m.Success?(t.status=m.Success,e.removeComponentByType(oe)):i.status===m.Failure&&(t.status=m.Failure,e.removeComponentByType(oe))):(o.addComponent(new oe),void(t.status=m.Running));t.status=m.Failure}startPreload(e,t){const s=this.scanSubTreeNodes(e);if(0===s.length)return this.preloadStates.set(e.id,We.Completed),void this.outputLog(e,"没有需要预加载的子树","info");this.preloadStates.set(e.id,We.Loading),t.status=m.Running,this.outputLog(e,`开始预加载 ${s.length} 个子树...`,"info");const n=this.preloadAllSubTrees(e,s);this.preloadTasks.set(e.id,n),n.then((()=>{this.preloadStates.set(e.id,We.Completed),this.outputLog(e,"所有子树预加载完成","info")})).catch((t=>{this.preloadStates.set(e.id,We.Failed),this.outputLog(e,`子树预加载失败: ${t.message}`,"error")}))}scanSubTreeNodes(e){const t=[],s=e.getComponent(W);s&&s.preload&&t.push({entity:e,subTree:s});for(const s of e.children)t.push(...this.scanSubTreeNodes(s));return t}async preloadAllSubTrees(e,t){if(!this.assetLoader)try{this.assetLoader=i.services.resolve(Oe)}catch(e){throw new Error("AssetLoader 未配置,无法预加载子树")}await Promise.all(t.map((({entity:t,subTree:s})=>this.preloadSingleSubTree(e,t,s))))}async preloadSingleSubTree(e,t,s){try{this.outputLog(e,`预加载子树: ${s.assetId}`,"info");const n=await this.assetLoader.loadBehaviorTree(s.assetId),o=je.instantiate(n,this.scene,{asSubTree:!0});s.setSubTreeRoot(o),t.addChild(o);o.addComponent(new ae).initialize(s.assetId,"1.0.0"),s.inheritParentBlackboard&&this.setupBlackboardInheritance(t,o),this.outputLog(e,`=== 预加载子树 ${s.assetId} 的内部结构 ===`,"info"),this.logSubTreeStructure(e,o,0),this.outputLog(e,"=== 预加载子树结构结束 ===","info"),this.outputLog(e,`✓ 子树 ${s.assetId} 预加载完成`,"info")}catch(t){throw this.outputLog(e,`✗ 子树 ${s.assetId} 预加载失败: ${t.message}`,"error"),t}}setupBlackboardInheritance(e,t){if(!this.findBlackboard(e))return;const s=t.getComponent(ne);s&&s.setUseGlobalBlackboard(!0)}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(ne);if(e)return e;t=t.parent}}findRootEntity(e){let t=e;for(;t;){if(!t.parent)return t;t=t.parent}return null}outputLog(e,t,s="info"){switch(s){case"info":default:this.logger.info(t);break;case"warn":this.logger.warn(t);break;case"error":this.logger.error(t)}const n=this.findRootEntity(e);if(n){const e=n.getComponent(re);e&&e.addMessage(t,s)}}logSubTreeStructure(e,t,s){const n=" ".repeat(s);t.getComponent(te);const o=t.components.map((e=>e.constructor.name)).find((e=>"BehaviorTreeNode"!==e&&"ActiveNode"!==e&&"BlackboardComponent"!==e&&"LogOutput"!==e&&"PropertyBindings"!==e&&"BehaviorTreeAssetMetadata"!==e))||"Unknown";let i=t.name;"Unknown"!==o&&(i=`${i} [${o}]`),this.outputLog(e,`${n}└─ ${i}`,"info"),t.children.length>0&&(this.outputLog(e,`${n} 子节点数: ${t.children.length}`,"info"),t.children.forEach((t=>{this.logSubTreeStructure(e,t,s+1)})))}onDestroy(){this.preloadStates.clear(),this.preloadTasks.clear(),super.onDestroy()}getLoggerName(){return"RootExecutionSystem"}}class He extends a{constructor(){super(c.empty().all(te,oe)),this.updateOrder=100}process(e){for(const t of e){const e=t.getComponent(te);e.nodeType===y.Action?this.executeAction(t,e):e.nodeType===y.Condition&&this.executeCondition(t,e)}}executeAction(e,t){let s=m.Failure;const{displayName:n,nodeIdShort:o}=this.getNodeInfo(e);e.hasComponent(x)?s=this.executeWaitAction(e):e.hasComponent(A)?s=this.executeLogAction(e):e.hasComponent(E)?s=this.executeSetBlackboardValue(e):e.hasComponent(R)?s=this.executeModifyBlackboardValue(e):e.hasComponent(B)?s=this.executeCustomAction(e):this.outputLog(e,"动作节点没有找到任何已知的动作组件","warn"),t.status=s;const i=s===m.Success?"Success":s===m.Failure?"Failure":s===m.Running?"Running":"Unknown";s!==m.Running&&this.outputLog(e,`[${n}#${o}] 执行完成 -> ${i}`,s===m.Success?"info":"warn"),s!==m.Running&&(this.deactivateNode(e),this.notifyParent(e))}executeWaitAction(e){const t=e.getComponent(x);e.getComponent(te);const{displayName:s,nodeIdShort:n}=this.getNodeInfo(e),o=this.resolvePropertyValue(e,"waitTime",t.waitTime);return t.elapsedTime+=d.deltaTime,this.outputLog(e,`[${s}#${n}] deltaTime=${d.deltaTime.toFixed(3)}s, elapsed=${t.elapsedTime.toFixed(3)}s/${o.toFixed(3)}s`,"info"),t.elapsedTime>=o?(t.reset(),this.outputLog(e,`[${s}#${n}] 等待完成,返回成功`,"info"),m.Success):m.Running}executeLogAction(e){const t=e.getComponent(A),s=e.getComponent(te);let n=this.resolvePropertyValue(e,"message",t.message);const{displayName:o,nodeIdShort:i}=this.getNodeInfo(e);switch(s&&(n=`[${o}#${i}] ${n}`),t.includeEntityInfo&&(n=`[Entity: ${e.name}] ${n}`),t.level){case"info":console.info(n);break;case"warn":console.warn(n);break;case"error":console.error(n);break;default:console.log(n)}const r=this.findRootEntity(e);if(r){const e=r.getComponent(re);e&&e.addMessage(n,t.level)}return m.Success}findRootEntity(e){let t=e;for(;t;){if(!t.parent)return t;t=t.parent}return null}executeSetBlackboardValue(e){const t=e.getComponent(E),s=this.findBlackboard(e);if(!s)return this.outputLog(e,"未找到黑板组件","warn"),m.Failure;let n;if(t.sourceVariable){if(!s.hasVariable(t.sourceVariable))return this.outputLog(e,`源变量不存在: ${t.sourceVariable}`,"warn"),m.Failure;n=s.getValue(t.sourceVariable)}else n=this.resolvePropertyValue(e,"value",t.value);return s.setValue(t.variableName,n,t.force)?m.Success:m.Failure}executeModifyBlackboardValue(e){const t=e.getComponent(R),s=this.findBlackboard(e);if(!s)return this.outputLog(e,"未找到黑板组件","warn"),m.Failure;if(!s.hasVariable(t.variableName))return this.outputLog(e,`变量不存在: ${t.variableName}`,"warn"),m.Failure;let n,o=s.getValue(t.variableName),i=this.resolvePropertyValue(e,"operand",t.operand);switch(t.operation){case I.Add:n=Number(o)+Number(i);break;case I.Subtract:n=Number(o)-Number(i);break;case I.Multiply:n=Number(o)*Number(i);break;case I.Divide:if(0===Number(i))return this.outputLog(e,"除数不能为0","warn"),m.Failure;n=Number(o)/Number(i);break;case I.Modulo:n=Number(o)%Number(i);break;case I.Append:if(Array.isArray(o))n=[...o,i];else{if("string"!=typeof o)return this.outputLog(e,`变量 ${t.variableName} 不支持 append 操作`,"warn"),m.Failure;n=o+i}break;case I.Remove:if(!Array.isArray(o))return this.outputLog(e,`变量 ${t.variableName} 不是数组,不支持 remove 操作`,"warn"),m.Failure;n=o.filter((e=>e!==i));break;default:return m.Failure}return s.setValue(t.variableName,n,t.force)?m.Success:m.Failure}executeCustomAction(e){const t=e.getComponent(B).getFunction();if(!t)return m.Failure;return t(e,this.findBlackboard(e),d.deltaTime)}executeCondition(e,t){let s=!1;const{displayName:n,nodeIdShort:o}=this.getNodeInfo(e);e.hasComponent(F)?s=this.evaluateBlackboardCompare(e):e.hasComponent(L)?s=this.evaluateBlackboardExists(e):e.hasComponent(U)?s=this.evaluateRandomProbability(e):e.hasComponent(P)?s=this.evaluateCustomCondition(e):this.outputLog(e,"条件节点没有找到任何已知的条件组件","warn"),t.status=s?m.Success:m.Failure;const i=s?"Success (true)":"Failure (false)";this.outputLog(e,`[${n}#${o}] 条件评估 -> ${i}`,s?"info":"warn"),this.deactivateNode(e),this.notifyParent(e)}evaluateBlackboardCompare(e){const t=e.getComponent(F),s=this.findBlackboard(e);if(!s||!s.hasVariable(t.variableName))return!1;const n=s.getValue(t.variableName);let o=this.resolvePropertyValue(e,"compareValue",t.compareValue),i=!1;switch(t.operator){case $.Equal:i=n===o;break;case $.NotEqual:i=n!==o;break;case $.Greater:i=n>o;break;case $.GreaterOrEqual:i=n>=o;break;case $.Less:i=n<o;break;case $.LessOrEqual:i=n<=o;break;case $.Contains:("string"==typeof n||Array.isArray(n))&&(i=n.includes(o));break;case $.Matches:if("string"==typeof n&&"string"==typeof o){i=new RegExp(o).test(n)}}return t.invertResult?!i:i}evaluateBlackboardExists(e){const t=e.getComponent(L),s=this.findBlackboard(e);if(!s)return!1;let n=s.hasVariable(t.variableName);if(n&&t.checkNotNull){const e=s.getValue(t.variableName);n=null!=e}return t.invertResult?!n:n}evaluateRandomProbability(e){const t=e.getComponent(U),s=this.resolvePropertyValue(e,"probability",t.probability);return(t.alwaysRandomize||void 0===t.cachedResult)&&(t.cachedResult=Math.random()<s),t.cachedResult}evaluateCustomCondition(e){const t=e.getComponent(P),s=t.getFunction();if(!s)return!1;const n=s(e,this.findBlackboard(e),d.deltaTime);return t.invertResult?!n:n}resolvePropertyValue(e,t,s){const n=e.getComponent(ie);if(!n||!n.hasBinding(t))return s;const o=n.getBinding(t),i=this.findBlackboard(e);if(!i)return this.outputLog(e,`[属性绑定] 未找到黑板组件,实体: ${e.name}`,"warn"),s;if(!i.hasVariable(o))return this.outputLog(e,`[属性绑定] 黑板变量不存在: ${o}`,"warn"),s;return i.getValue(o)}deactivateNode(e){e.removeComponentByType(oe)}notifyParent(e){e.parent&&e.parent.hasComponent(te)&&(e.parent.hasComponent(oe)||e.parent.addComponent(new oe))}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(ne);if(e)return e;t=t.parent}}getNodeInfo(e){let t="Node",s="";if(e.name&&e.name.includes("#")){const n=e.name.split("#");t=n[0],s=n[1]}else s=e.id.toString().substring(0,8);return{displayName:t,nodeIdShort:s}}outputLog(e,t,s="info"){switch(s){case"info":default:this.logger.info(t);break;case"warn":this.logger.warn(t);break;case"error":this.logger.error(t)}const n=this.findRootEntity(e);if(n){const e=n.getComponent(re);e&&e.addMessage(t,s)}}getLoggerName(){return"LeafExecutionSystem"}}class _e extends a{constructor(){super(c.empty().all(te,oe)),this.updateOrder=200}process(e){for(const t of e){const e=t.getComponent(te);if(e.nodeType!==y.Decorator)continue;const s=t.getComponentByType(J);s&&this.executeDecorator(t,e,s)}}executeDecorator(e,t,s){const n=e.children;if(0===n.length)return this.logger.warn("装饰器节点没有子节点"),t.status=m.Failure,void this.completeNode(e);const o=n[0],i=o.getComponent(te);if(!i)return t.status=m.Failure,void this.completeNode(e);switch(s.decoratorType){case g.Inverter:this.handleInverter(e,t,o,i);break;case g.Repeater:this.handleRepeater(e,t,s,o,i);break;case g.UntilSuccess:this.handleUntilSuccess(e,t,o,i);break;case g.UntilFail:this.handleUntilFail(e,t,o,i);break;case g.AlwaysSucceed:this.handleAlwaysSucceed(e,t,o,i);break;case g.AlwaysFail:this.handleAlwaysFail(e,t,o,i);break;case g.Conditional:this.handleConditional(e,t,s,o,i);break;case g.Cooldown:this.handleCooldown(e,t,s,o,i);break;case g.Timeout:this.handleTimeout(e,t,s,o,i);break;default:t.status=m.Failure,this.completeNode(e)}}handleInverter(e,t,s,n){s.hasComponent(oe)||s.addComponent(new oe),t.status=m.Running,n.status!==m.Success&&n.status!==m.Failure||(t.status=n.status===m.Success?m.Failure:m.Success,this.completeNode(e))}handleRepeater(e,t,s,n,o){const i=s,r=this.resolvePropertyValue(e,"repeatCount",i.repeatCount),a=this.resolvePropertyValue(e,"endOnFailure",i.endOnFailure);if(!n.hasComponent(oe))return n.addComponent(new oe),void(t.status=m.Running);if(o.status===m.Running)return void(t.status=m.Running);if(o.status===m.Failure&&a)return t.status=m.Failure,i.reset(),void this.completeNode(e);i.incrementRepeat();-1===r||i.currentRepeatCount<r?(o.invalidate(),n.addComponent(new oe),t.status=m.Running):(t.status=m.Success,i.reset(),this.completeNode(e))}handleUntilSuccess(e,t,s,n){if(!s.hasComponent(oe))return s.addComponent(new oe),void(t.status=m.Running);n.status!==m.Running?n.status===m.Success?(t.status=m.Success,this.completeNode(e)):(n.invalidate(),s.addComponent(new oe),t.status=m.Running):t.status=m.Running}handleUntilFail(e,t,s,n){if(!s.hasComponent(oe))return s.addComponent(new oe),void(t.status=m.Running);n.status!==m.Running?n.status===m.Failure?(t.status=m.Success,this.completeNode(e)):(n.invalidate(),s.addComponent(new oe),t.status=m.Running):t.status=m.Running}handleAlwaysSucceed(e,t,s,n){if(!s.hasComponent(oe))return s.addComponent(new oe),void(t.status=m.Running);n.status===m.Running?t.status=m.Running:(t.status=m.Success,this.completeNode(e))}handleAlwaysFail(e,t,s,n){if(!s.hasComponent(oe))return s.addComponent(new oe),void(t.status=m.Running);n.status===m.Running?t.status=m.Running:(t.status=m.Failure,this.completeNode(e))}handleConditional(e,t,s,n,o){return s.evaluateCondition(e,this.findBlackboard(e))?n.hasComponent(oe)?(t.status=o.status,void(o.status!==m.Running&&this.completeNode(e))):(n.addComponent(new oe),void(t.status=m.Running)):(t.status=m.Failure,void this.completeNode(e))}handleCooldown(e,t,s,n,o){const i=s,r=this.resolvePropertyValue(e,"cooldownTime",i.cooldownTime),a=d.totalTime-i.lastExecutionTime,c=0===i.lastExecutionTime||a>=r;return this.outputLog(e,`[冷却检查] Time.totalTime=${d.totalTime.toFixed(3)}, lastExecution=${i.lastExecutionTime.toFixed(3)}, cooldownTime=${r}, timeSince=${a.toFixed(3)}, canExecute=${c}, childStatus=${o.status}`,"info"),c?o.status!==m.Invalid&&o.status!==m.Running?(t.status=o.status,i.recordExecution(d.totalTime),this.outputLog(e,`[冷却记录] 记录执行时间: ${d.totalTime.toFixed(3)}, 下次可执行时间: ${(d.totalTime+r).toFixed(3)}`,"info"),void this.completeNode(e)):(n.hasComponent(oe)||n.addComponent(new oe),void(t.status=m.Running)):(t.status=m.Failure,void this.completeNode(e))}handleTimeout(e,t,s,n,o){const i=s,r=this.resolvePropertyValue(e,"timeoutDuration",i.timeoutDuration);i.recordStartTime(d.totalTime);return i.startTime>0&&d.totalTime-i.startTime>=r?(t.status=m.Failure,i.reset(),n.removeComponentByType(oe),void this.completeNode(e)):n.hasComponent(oe)?(t.status=o.status,void(o.status!==m.Running&&(i.reset(),this.completeNode(e)))):(n.addComponent(new oe),void(t.status=m.Running))}completeNode(e){e.removeComponentByType(oe),e.parent&&e.parent.hasComponent(te)&&(e.parent.hasComponent(oe)||e.parent.addComponent(new oe))}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(ne);if(e)return e;t=t.parent}}resolvePropertyValue(e,t,s){const n=e.getComponent(ie);if(!n||!n.hasBinding(t))return s;const o=n.getBinding(t),i=this.findBlackboard(e);return i&&i.hasVariable(o)?i.getValue(o):s}findRootEntity(e){let t=e;for(;t;){if(!t.parent)return t;t=t.parent}return null}outputLog(e,t,s="info"){switch(s){case"info":default:this.logger.info(t);break;case"warn":this.logger.warn(t);break;case"error":this.logger.error(t)}const n=this.findRootEntity(e);if(n){const e=n.getComponent(re);e&&e.addMessage(t,s)}}getLoggerName(){return"DecoratorExecutionSystem"}}class Ke extends a{constructor(){super(c.empty().all(te,oe).exclude(ce,W)),this.updateOrder=300}process(e){for(const t of e){const e=t.getComponent(te);if(e.nodeType!==y.Composite)continue;const s=t.getComponentByType(M);if(s)this.executeComposite(t,e,s);else{this.logger.warn(`复合节点 ${t.name} 没有找到复合节点组件`);const e=t.components.map((e=>e.constructor.name)).join(", ");this.logger.warn(` 组件列表: ${e}`)}}}executeComposite(e,t,s){const n=e.children;if(0===n.length)return t.status=m.Success,void this.completeNode(e);switch(s.compositeType){case f.Sequence:this.handleSequence(e,t,n);break;case f.Selector:this.handleSelector(e,t,n);break;case f.Parallel:this.handleParallel(e,t,n);break;case f.ParallelSelector:this.handleParallelSelector(e,t,n);break;case f.RandomSequence:this.handleRandomSequence(e,t,s,n);break;case f.RandomSelector:this.handleRandomSelector(e,t,s,n);break;default:t.status=m.Failure,this.completeNode(e)}}handleSequence(e,t,s){const n=e.getComponentByType(D);if(n&&n.abortType!==b.None&&this.shouldAbort(e,t,s,n.abortType))return void this.abortExecution(e,t,s);if(t.currentChildIndex>=s.length)return t.status=m.Success,t.currentChildIndex=0,void this.completeNode(e);const o=s[t.currentChildIndex],i=o.getComponent(te);return i?i.status===m.Invalid?(o.hasComponent(oe)||o.addComponent(new oe),void(t.status=m.Running)):void(i.status===m.Running?t.status=m.Running:i.status===m.Failure?(t.status=m.Failure,t.currentChildIndex=0,this.completeNode(e)):i.status===m.Success&&(i.reset(),t.currentChildIndex++,t.status=m.Running)):(t.status=m.Failure,void this.completeNode(e))}handleSelector(e,t,s){const n=e.getComponentByType(V);if(n&&n.abortType!==b.None&&this.shouldAbort(e,t,s,n.abortType))return void this.abortExecution(e,t,s);if(t.currentChildIndex>=s.length)return t.status=m.Failure,t.currentChildIndex=0,void this.completeNode(e);const o=s[t.currentChildIndex],i=o.getComponent(te);return i?i.status===m.Invalid?(o.hasComponent(oe)||o.addComponent(new oe),void(t.status=m.Running)):void(i.status===m.Running?t.status=m.Running:i.status===m.Success?(t.status=m.Success,t.currentChildIndex=0,this.completeNode(e)):i.status===m.Failure&&(i.reset(),t.currentChildIndex++,t.status=m.Running)):(t.status=m.Failure,void this.completeNode(e))}handleParallel(e,t,s){let n=!1,o=!1;for(const e of s){e.hasComponent(oe)||e.addComponent(new oe);const t=e.getComponent(te);t&&(t.status===m.Running?n=!0:t.status===m.Failure&&(o=!0))}n?t.status=m.Running:o?(t.status=m.Failure,t.currentChildIndex=0,this.completeNode(e)):(t.status=m.Success,t.currentChildIndex=0,this.completeNode(e))}handleParallelSelector(e,t,s){let n=!1,o=!1;for(const e of s){e.hasComponent(oe)||e.addComponent(new oe);const t=e.getComponent(te);t&&(t.status===m.Running?n=!0:t.status===m.Success&&(o=!0))}if(o){t.status=m.Success,t.currentChildIndex=0;for(const e of s)e.removeComponentByType(oe);this.completeNode(e)}else n?t.status=m.Running:(t.status=m.Failure,t.currentChildIndex=0,this.completeNode(e))}handleRandomSequence(e,t,s,n){const o=s.getNextChildIndex(t.currentChildIndex,n.length);if(o>=n.length)return t.status=m.Success,t.currentChildIndex=0,s.resetShuffle(),void this.completeNode(e);const i=n[o],r=i.getComponent(te);return r?r.status===m.Invalid?(i.hasComponent(oe)||i.addComponent(new oe),void(t.status=m.Running)):void(r.status===m.Running?t.status=m.Running:r.status===m.Failure?(t.status=m.Failure,t.currentChildIndex=0,s.resetShuffle(),this.completeNode(e)):r.status===m.Success&&(r.reset(),t.currentChildIndex++,t.status=m.Running)):(t.status=m.Failure,void this.completeNode(e))}handleRandomSelector(e,t,s,n){const o=s.getNextChildIndex(t.currentChildIndex,n.length);if(o>=n.length)return t.status=m.Failure,t.currentChildIndex=0,s.resetShuffle(),void this.completeNode(e);const i=n[o],r=i.getComponent(te);return r?r.status===m.Invalid?(i.hasComponent(oe)||i.addComponent(new oe),void(t.status=m.Running)):void(r.status===m.Running?t.status=m.Running:r.status===m.Success?(t.status=m.Success,t.currentChildIndex=0,s.resetShuffle(),this.completeNode(e)):r.status===m.Failure&&(r.reset(),t.currentChildIndex++,t.status=m.Running)):(t.status=m.Failure,void this.completeNode(e))}shouldAbort(e,t,s,n){const o=t.currentChildIndex;if(0===o)return!1;if(n===b.Self||n===b.Both)for(let e=0;e<o;e++){const t=s[e].getComponent(te);if(t&&t.nodeType===y.Condition&&t.status===m.Failure)return!0}if(n===b.LowerPriority||n===b.Both)for(let e=0;e<o;e++){const t=s[e],n=t.getComponent(te);if(n)if(n.nodeType===y.Condition){if(this.evaluateCondition(t,n))return!0}else if(n.nodeType===y.Composite&&t.children.length>0){const e=t.children[0],s=e.getComponent(te);if(s&&s.nodeType===y.Condition&&this.evaluateCondition(e,s))return!0}}return!1}evaluateCondition(e,t){if(t.nodeType!==y.Condition)return!1;let s=!1;return e.hasComponent(F)?s=this.evaluateBlackboardCompare(e):e.hasComponent(L)?s=this.evaluateBlackboardExists(e):e.hasComponent(U)?s=this.evaluateRandomProbability(e):e.hasComponent(P)&&(s=this.evaluateCustomCondition(e)),s}evaluateBlackboardCompare(e){const t=e.getComponent(F),s=this.findBlackboard(e);if(!s||!s.hasVariable(t.variableName))return!1;const n=s.getValue(t.variableName);let o=t.compareValue;"string"==typeof o&&(o=this.resolveVariableReferences(o,s));let i=!1;switch(t.operator){case $.Equal:i=n===o;break;case $.NotEqual:i=n!==o;break;case $.Greater:i=n>o;break;case $.GreaterOrEqual:i=n>=o;break;case $.Less:i=n<o;break;case $.LessOrEqual:i=n<=o;break;case $.Contains:("string"==typeof n||Array.isArray(n))&&(i=n.includes(o));break;case $.Matches:if("string"==typeof n&&"string"==typeof o){i=new RegExp(o).test(n)}}return t.invertResult?!i:i}evaluateBlackboardExists(e){const t=e.getComponent(L),s=this.findBlackboard(e);if(!s)return!1;let n=s.hasVariable(t.variableName);if(n&&t.checkNotNull){const e=s.getValue(t.variableName);n=null!=e}return t.invertResult?!n:n}evaluateRandomProbability(e){return e.getComponent(U).evaluate()}evaluateCustomCondition(e){const t=e.getComponent(P),s=t.getFunction();if(!s)return!1;const n=s(e,this.findBlackboard(e),0);return t.invertResult?!n:n}resolveVariableReferences(e,t){const s=e.match(/^{{\s*(\w+)\s*}}$/);if(s){const n=s[1];return t.hasVariable(n)?t.getValue(n):e}return e.replace(/\{\{(\w+)\}\}/g,((e,s)=>{if(t.hasVariable(s)){const n=t.getValue(s);return void 0!==n?String(n):e}return e}))}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(ne);if(e)return e;t=t.parent}}abortExecution(e,t,s){const n=t.currentChildIndex;if(n<s.length){const e=s[n];this.deactivateNode(e)}t.currentChildIndex=0,t.status=m.Running}deactivateNode(e){e.removeComponentByType(oe);const t=e.getComponent(te);t&&t.reset();for(const t of e.children)this.deactivateNode(t)}resetAllChildren(e){for(const t of e.children){const e=t.getComponent(te);e&&e.reset(),this.resetAllChildren(t)}}completeNode(e){e.removeComponentByType(oe);const t=e.getComponent(te);t&&t.nodeType===y.Composite&&this.resetAllChildren(e),e.parent&&e.parent.hasComponent(te)&&(e.parent.hasComponent(oe)||e.parent.addComponent(new oe))}getLoggerName(){return"CompositeExecutionSystem"}}!function(e){e.Idle="idle",e.Pending="pending",e.Loading="loading",e.Loaded="loaded",e.Failed="failed",e.Timeout="timeout",e.Cancelled="cancelled"}(Je||(Je={}));class Xe extends Error{constructor(e){super(e),this.name="TimeoutError"}}class Ze extends Error{constructor(e){super(e),this.name="CircularDependencyError"}}class Qe extends Error{constructor(e){super(e),this.name="EntityDestroyedError"}}const Ye=r("AssetLoadingManager");class et{constructor(){this.tasks=new Map,this.loadingStack=new Set,this.defaultOptions={timeoutMs:5e3,maxRetries:3,retryDelayBase:100,maxRetryDelay:2e3}}startLoading(e,t,s,n={}){const o={...this.defaultOptions,...n};if(n.parentAssetId&&this.detectCircularDependency(e,n.parentAssetId)){const t=new Ze(`检测到循环引用: ${n.parentAssetId} → ${e}\n加载栈: ${Array.from(this.loadingStack).join(" → ")}`);throw Ye.error(t.message),t}const i=this.tasks.get(e);if(i)return Ye.debug(`资产 ${e} 已在加载中,返回现有任务`),this.createHandle(i);const r={assetId:e,promise:null,startTime:Date.now(),lastRetryTime:0,retryCount:0,maxRetries:o.maxRetries,timeoutMs:o.timeoutMs,state:Je.Pending,parentEntityId:t.id,parentEntity:t,parentAssetId:n.parentAssetId};return this.loadingStack.add(e),r.promise=this.loadWithTimeoutAndRetry(r,s,o),r.state=Je.Loading,this.tasks.set(e,r),Ye.info(`开始加载资产: ${e}`,{timeoutMs:o.timeoutMs,maxRetries:o.maxRetries,parentAssetId:n.parentAssetId}),this.createHandle(r)}async loadWithTimeoutAndRetry(e,t,s){let n=null;for(let o=0;o<=e.maxRetries;o++){if(e.parentEntity.isDestroyed){const t=new Qe(`父实体已销毁,取消加载: ${e.assetId}`);throw e.state=Je.Cancelled,this.cleanup(e.assetId),Ye.warn(t.message),t}try{e.retryCount=o,e.lastRetryTime=Date.now(),Ye.debug(`加载尝试 ${o+1}/${e.maxRetries+1}: ${e.assetId}`);const s=await this.withTimeout(t(),e.timeoutMs,`加载资产 ${e.assetId} 超时(${e.timeoutMs}ms)`);return e.state=Je.Loaded,e.result=s,this.cleanup(e.assetId),Ye.info(`资产加载成功: ${e.assetId}`,{attempts:o+1,elapsedMs:Date.now()-e.startTime}),s}catch(t){if(n=t,t instanceof Xe)e.state=Je.Timeout,Ye.warn(`资产加载超时: ${e.assetId} (尝试 ${o+1})`);else{if(t instanceof Qe)throw t;Ye.warn(`资产加载失败: ${e.assetId} (尝试 ${o+1})`,t)}if(o===e.maxRetries)throw e.state=Je.Failed,e.error=n,this.cleanup(e.assetId),Ye.error(`资产加载最终失败: ${e.assetId}`,{attempts:o+1,error:n.message}),n;const i=Math.min(Math.pow(2,o)*s.retryDelayBase,s.maxRetryDelay);Ye.debug(`等待 ${i}ms 后重试...`),await this.delay(i)}}throw n}withTimeout(e,t,s){let n;const o=new Promise(((e,o)=>{n=setTimeout((()=>{o(new Xe(s))}),t)}));return Promise.race([e.then((e=>(clearTimeout(n),e))),o]).catch((e=>{throw clearTimeout(n),e}))}detectCircularDependency(e,t){return!!this.loadingStack.has(t)}getTaskState(e){return this.tasks.get(e)?.state??Je.Idle}getTask(e){return this.tasks.get(e)}cancelLoading(e){const t=this.tasks.get(e);t&&(t.state=Je.Cancelled,this.cleanup(e),Ye.info(`取消加载: ${e}`))}cleanup(e){const t=this.tasks.get(e);t&&(t.parentEntity=null),this.tasks.delete(e),this.loadingStack.delete(e)}delay(e){return new Promise((t=>setTimeout(t,e)))}createHandle(e){return{assetId:e.assetId,getState:()=>e.state,getError:()=>e.error,getProgress:()=>{const t=Date.now()-e.startTime,s=Math.max(0,e.timeoutMs-t);return{state:e.state,elapsedMs:t,remainingTimeoutMs:s,retryCount:e.retryCount,maxRetries:e.maxRetries}},cancel:()=>this.cancelLoading(e.assetId),promise:e.promise}}getLoadingAssets(){return Array.from(this.tasks.keys())}getStats(){const e=Array.from(this.tasks.values());return{totalTasks:e.length,loadingTasks:e.filter((e=>e.state===Je.Loading)).length,failedTasks:e.filter((e=>e.state===Je.Failed)).length,timeoutTasks:e.filter((e=>e.state===Je.Timeout)).length}}clear(){Ye.info("清空所有加载任务",this.getStats()),this.tasks.clear(),this.loadingStack.clear()}dispose(){this.clear()}}class tt extends a{constructor(e){super(c.empty().all(W,oe,te)),this.assetLoaderInitialized=!1,this.hasLoggedMissingAssetLoader=!1,this.loadingTasks=new Map,this.updateOrder=300,this.loadingManager=e||new et}onInitialize(){}process(e){for(const t of e){const e=t.getComponent(W),s=t.getComponent(te);this.executeSubTree(t,e,s)}}executeSubTree(e,t,s){const n=t.validate();if(n.length>0)return this.logger.error(`SubTree 节点配置错误: ${n.join(", ")}`),s.status=m.Failure,void this.completeNode(e);const o=t.getSubTreeRoot();if(o){const n=o.getComponent(te);if(n){const i=m[n.status],r=o.hasComponent(oe);if(this.outputLog(e,`检查预加载子树 ${t.assetId}: status=${i}, hasActive=${r}`,"info"),n.status===m.Invalid){if(this.outputLog(e,`使用预加载的子树: ${t.assetId}`,"info"),this.outputLog(e,`激活前:子树根节点 ${o.name} 有 ${o.children.length} 个子节点`,"info"),o.children.length>0){const t=o.children[0];this.outputLog(e,` 第一个子节点: ${t.name}`,"info")}o.hasComponent(oe)||(o.addComponent(new oe),this.outputLog(e,`为子树根节点添加 ActiveNode: ${o.name}`,"info"));const n=o.getComponent(te);return n&&(this.outputLog(e,`设置子树根节点状态: ${o.name} -> Running`,"info"),n.status=m.Running),this.outputLog(e,`激活后:子树根节点 ${o.name} 有 ${o.children.length} 个子节点`,"info"),this.outputLog(e,`激活预加载的子树: ${t.assetId}`,"info"),void(s.status=m.Running)}}this.updateSubTree(e,t,s)}else this.outputLog(e,`子树未预加载,开始运行时加载: ${t.assetId}`,"info"),this.loadAndInstantiateSubTree(e,t,s)}ensureAssetLoaderInitialized(){if(!this.assetLoaderInitialized)try{this.assetLoader=i.services.resolve(Oe),this.assetLoaderInitialized=!0,this.logger.debug("AssetLoader 已初始化")}catch(e){return this.assetLoaderInitialized=!0,this.assetLoader=void 0,this.hasLoggedMissingAssetLoader||(this.logger.warn("AssetLoader 未配置。SubTree 节点需要 AssetLoader 来加载子树资产。\n如果您在编辑器中,请确保已打开项目并配置了项目路径。\n如果您在运行时环境,请确保已正确注册 FileSystemAssetLoader 服务。"),this.hasLoggedMissingAssetLoader=!0),!1}return void 0!==this.assetLoader}loadAndInstantiateSubTree(e,t,s){if(!this.ensureAssetLoaderInitialized())return this.logger.debug("AssetLoader 不可用,SubTree 节点执行失败"),s.status=m.Failure,void this.completeNode(e);const n=t.assetId;let o=this.loadingTasks.get(e.id);if(o){switch(o.getState()){case Je.Loading:case Je.Pending:s.status=m.Running;const i=o.getProgress();return void(i.elapsedMs>1e3&&this.logger.debug(`子树加载中: ${n} (已耗时: ${Math.round(i.elapsedMs/1e3)}s, 重试: ${i.retryCount}/${i.maxRetries})`));case Je.Loaded:return void this.onLoadingComplete(e,t,s,o);case Je.Failed:case Je.Timeout:const r=o.getError();return this.outputLog(e,`子树加载失败: ${n} - ${r?.message||"未知错误"}`,"error"),s.status=m.Failure,this.loadingTasks.delete(e.id),void this.completeNode(e);case Je.Cancelled:return void this.loadingTasks.delete(e.id)}}this.startNewLoading(e,t,s)}startNewLoading(e,t,s){const n=t.assetId,o=this.getParentTreeAssetId(e);try{const t=this.loadingManager.startLoading(n,e,(()=>this.loadAsset(n)),{timeoutMs:5e3,maxRetries:2,parentAssetId:o});this.loadingTasks.set(e.id,t),s.status=m.Running,this.outputLog(e,`开始加载子树: ${n} (父树: ${o||"none"})`,"info")}catch(t){t instanceof Ze?this.outputLog(e,`检测到循环引用: ${t.message}`,"error"):this.outputLog(e,`启动加载失败: ${n}`,"error"),s.status=m.Failure,this.completeNode(e)}}onLoadingComplete(e,t,s,n){n.promise.then((s=>{if(e.isDestroyed)return this.logger.warn(`父实体已销毁,丢弃加载结果: ${n.assetId}`),void s.destroy();t.setSubTreeRoot(s),e.addChild(s);s.addComponent(new ae).initialize(n.assetId,"1.0.0"),t.inheritParentBlackboard&&this.setupBlackboardInheritance(e,s),this.outputLog(e,`子树 ${n.assetId} 加载成功并激活`,"info"),this.outputLog(e,`=== 子树 ${n.assetId} 内部结构 ===`,"info"),this.logSubTreeStructure(e,s,0),this.outputLog(e,"=== 子树结构结束 ===","info"),this.startSubTreeExecution(s,e),this.loadingTasks.delete(e.id)})).catch((e=>{e instanceof Qe||this.logger.error("意外错误:",e)}))}async loadAsset(e){if(!this.scene)throw new Error("Scene 不存在");const t=await this.assetLoader.loadBehaviorTree(e);return je.instantiate(t,this.scene,{asSubTree:!0})}setupBlackboardInheritance(e,t){if(!this.findBlackboard(e))return;const s=t.getComponent(ne);s&&s.setUseGlobalBlackboard(!0)}findBlackboard(e){let t=e;for(;t;){const e=t.getComponent(ne);if(e)return e;t=t.parent}}startSubTreeExecution(e,t){t&&this.outputLog(t,`子树根节点 ${e.name} 有 ${e.children.length} 个子节点`,"info"),e.hasComponent(oe)||(e.addComponent(new oe),t&&this.outputLog(t,`为子树根节点添加 ActiveNode: ${e.name}`,"info"));const s=e.getComponent(te);s&&(t&&this.outputLog(t,`设置子树根节点状态: ${e.name} -> Running`,"info"),s.status=m.Running)}updateSubTree(e,t,s){const n=t.getSubTreeRoot();if(!n)return;const o=n.getComponent(te);if(!o)return;const i=m[o.status];this.outputLog(e,`子树 ${t.assetId} 当前状态: ${i}`,"info"),o.status!==m.Running?this.onSubTreeCompleted(e,t,s,o.status):s.status=m.Running}onSubTreeCompleted(e,t,s,n){this.outputLog(e,`子树完成,状态: ${m[n]}`,"info"),this.outputLog(e,`完成前:SubTreeNode ${e.name} 有 ${e.children.length} 个子节点`,"info"),t.markSubTreeCompleted(n),n===m.Success?s.status=m.Success:n===m.Failure?t.propagateFailure?s.status=m.Failure:s.status=m.Success:s.status=n,this.cleanupSubTree(t),this.outputLog(e,`清理后:SubTreeNode ${e.name} 有 ${e.children.length} 个子节点`,"info"),this.completeNode(e)}cleanupSubTree(e){const t=e.getSubTreeRoot();t&&(e.preload?(this.logger.debug(`重置预加载子树以便复用: ${e.assetId}`),this.resetSubTreeRecursively(t),e.resetCompletionState()):(this.logger.debug(`销毁运行时加载的子树: ${e.assetId}`),t.destroy(),e.setSubTreeRoot(void 0),e.reset()))}resetSubTreeRecursively(e){e.hasComponent(oe)&&e.removeComponentByType(oe);const t=e.getComponent(te);t&&(t.status=m.Invalid);for(const t of e.children)this.resetSubTreeRecursively(t)}completeNode(e){e.removeComponentByType(oe),e.parent&&e.parent.hasComponent(te)&&(e.parent.hasComponent(oe)||e.parent.addComponent(new oe))}getParentTreeAssetId(e){let t=e;for(;t;){const e=t.getComponent(ae);if(e&&e.assetId)return e.assetId;t=t.parent}}onDestroy(){for(const e of this.loadingTasks.values())e.cancel();this.loadingTasks.clear(),super.onDestroy()}findRootEntity(e){let t=e;for(;t;){if(!t.parent)return t;t=t.parent}return null}outputLog(e,t,s="info"){switch(s){case"info":default:this.logger.info(t);break;case"warn":this.logger.warn(t);break;case"error":this.logger.error(t)}const n=this.findRootEntity(e);if(n){const e=n.getComponent(re);e&&e.addMessage(t,s)}}logSubTreeStructure(e,t,s){const n=" ".repeat(s);t.getComponent(te);const o=t.components.map((e=>e.constructor.name)).find((e=>"BehaviorTreeNode"!==e&&"ActiveNode"!==e&&"BlackboardComponent"!==e&&"LogOutput"!==e&&"PropertyBindings"!==e&&"BehaviorTreeAssetMetadata"!==e))||"Unknown";let i=t.name;"Unknown"!==o&&(i=`${i} [${o}]`),this.outputLog(e,`${n}└─ ${i}`,"info"),t.children.length>0&&(this.outputLog(e,`${n} 子节点数: ${t.children.length}`,"info"),t.children.forEach((t=>{this.logSubTreeStructure(e,t,s+1)})))}getLoggerName(){return"SubTreeExecutionSystem"}}var st;!function(e){e.BehaviorTree="behavior-tree",e.Blackboard="blackboard",e.Unknown="unknown"}(st||(st={}));class nt{constructor(){this.config=null,this.assetMap=new Map,this.assetPathMap=new Map}initialize(e){this.config=e,this.rebuildAssetMaps()}rebuildAssetMaps(){if(this.assetMap.clear(),this.assetPathMap.clear(),this.config)for(const e of this.config.assets)this.assetMap.set(e.id,e),this.assetPathMap.set(e.path,e)}getConfig(){return this.config}updateConfig(e){this.config=e,this.rebuildAssetMaps()}registerAsset(e){if(!this.config)throw new Error("工作区未初始化");const t=this.config.assets.find((t=>t.id===e.id));t?Object.assign(t,e):this.config.assets.push(e),this.rebuildAssetMaps()}unregisterAsset(e){if(!this.config)return;const t=this.config.assets.findIndex((t=>t.id===e));-1!==t&&(this.config.assets.splice(t,1),this.rebuildAssetMaps())}getAssetById(e){return this.assetMap.get(e)}getAssetByPath(e){return this.assetPathMap.get(e)}getAllAssets(){return this.config?.assets||[]}getAssetsByType(e){return this.getAllAssets().filter((t=>t.type===e))}getBehaviorTreeAssets(){return this.getAssetsByType(st.BehaviorTree)}getBlackboardAssets(){return this.getAssetsByType(st.Blackboard)}getAssetDependencies(e,t=new Set){if(t.has(e))return[];t.add(e);const s=this.getAssetById(e);if(!s)return[];const n=[];for(const e of s.dependencies){const s=this.getAssetById(e);s&&(n.push(s),n.push(...this.getAssetDependencies(e,t)))}return n}detectCircularDependency(e){const t=new Set,s=[],n=e=>{if(s.includes(e))return s.push(e),!0;if(t.has(e))return!1;t.add(e),s.push(e);const o=this.getAssetById(e);if(o)for(const e of o.dependencies)if(n(e))return!0;return s.pop(),!1};return n(e)?s:null}canAddDependency(e,t){const s=this.getAssetById(e);if(!s)return!1;const n=[...s.dependencies];s.dependencies.push(t);const o=null!==this.detectCircularDependency(e);return s.dependencies=n,!o}addAssetDependency(e,t){if(!this.canAddDependency(e,t))return!1;const s=this.getAssetById(e);return!!s&&(s.dependencies.includes(t)||s.dependencies.push(t),!0)}removeAssetDependency(e,t){const s=this.getAssetById(e);if(!s)return;const n=s.dependencies.indexOf(t);-1!==n&&s.dependencies.splice(n,1)}resolveAssetPath(e){return this.config?e.startsWith("/")||e.match(/^[A-Za-z]:/)?e:`${this.config.rootPath}/${e}`.replace(/\\/g,"/"):e}getRelativePath(e){if(!this.config)return e;const t=this.config.rootPath.replace(/\\/g,"/"),s=e.replace(/\\/g,"/");return s.startsWith(t)?s.substring(t.length+1):e}dispose(){this.config=null,this.assetMap.clear(),this.assetPathMap.clear()}}class ot{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(se),this.worldManager=t.resolve(l)}async uninstall(){this.services&&this.services.unregister(se),this.worldManager=null,this.services=null}setupScene(e){e.addSystem(new He),e.addSystem(new _e),e.addSystem(new Ke),e.addSystem(new tt)}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)}}class it{static start(e){if(!e.hasComponent(te))throw new Error("Entity must have BehaviorTreeNode component");e.hasComponent(oe)||e.addComponent(new oe)}static stop(e){this.stopRecursive(e)}static stopRecursive(e){e.hasComponent(oe)&&e.removeComponentByType(oe);const t=e.getComponent(te);t&&t.reset();for(const t of e.children)this.stopRecursive(t)}static pause(e){this.pauseRecursive(e)}static pauseRecursive(e){e.hasComponent(oe)&&e.removeComponentByType(oe);for(const t of e.children)this.pauseRecursive(t)}static resume(e){this.resumeRecursive(e)}static resumeRecursive(e){const t=e.getComponent(te);if(t){t.status===m.Running&&(e.hasComponent(oe)||e.addComponent(new oe));for(const t of e.children)this.resumeRecursive(t)}}static restart(e){this.stop(e),this.start(e)}static isRunning(e){return e.hasComponent(oe)}}class rt{constructor(e,t){this.entityStack=[],this.scene=e,this.currentEntity=e.createEntity(t)}static create(e,t="BehaviorTreeRoot"){return new rt(e,t)}blackboard(){return this.blackboardEntity=this.currentEntity,this.currentEntity.addComponent(new ne),this}defineVariable(e,t,s,n){if(!this.blackboardEntity)throw new Error("Must call blackboard() first");const o=this.blackboardEntity.getComponent(ne);return o&&o.defineVariable(e,t,s,n),this}endBlackboard(){return this.blackboardEntity=void 0,this}sequence(e="Sequence"){return this.composite(e,f.Sequence)}selector(e="Selector"){return this.composite(e,f.Selector)}parallel(e="Parallel"){return this.composite(e,f.Parallel)}parallelSelector(e="ParallelSelector"){return this.composite(e,f.ParallelSelector)}randomSequence(e="RandomSequence"){return this.composite(e,f.RandomSequence)}randomSelector(e="RandomSelector"){return this.composite(e,f.RandomSelector)}composite(e,t){this.entityStack.push(this.currentEntity);const s=this.scene.createEntity(e);this.currentEntity.addChild(s);const n=s.addComponent(new te);n.nodeType=y.Composite,n.nodeName=e;return s.addComponent(new M).compositeType=t,this.currentEntity=s,this}inverter(e="Inverter"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const s=t.addComponent(new te);return s.nodeType=y.Decorator,s.nodeName=e,t.addComponent(new G),this.currentEntity=t,this}repeater(e="Repeater",t=-1,s=!1){this.entityStack.push(this.currentEntity);const n=this.scene.createEntity(e);this.currentEntity.addChild(n);const o=n.addComponent(new te);o.nodeType=y.Decorator,o.nodeName=e;const i=n.addComponent(new H);return i.repeatCount=t,i.endOnFailure=s,this.currentEntity=n,this}untilSuccess(e="UntilSuccess"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const s=t.addComponent(new te);return s.nodeType=y.Decorator,s.nodeName=e,t.addComponent(new _),this.currentEntity=t,this}untilFail(e="UntilFail"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const s=t.addComponent(new te);return s.nodeType=y.Decorator,s.nodeName=e,t.addComponent(new K),this.currentEntity=t,this}alwaysSucceed(e="AlwaysSucceed"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const s=t.addComponent(new te);return s.nodeType=y.Decorator,s.nodeName=e,t.addComponent(new X),this.currentEntity=t,this}alwaysFail(e="AlwaysFail"){this.entityStack.push(this.currentEntity);const t=this.scene.createEntity(e);this.currentEntity.addChild(t);const s=t.addComponent(new te);return s.nodeType=y.Decorator,s.nodeName=e,t.addComponent(new Z),this.currentEntity=t,this}conditional(e,t){this.entityStack.push(this.currentEntity);const s=this.scene.createEntity(e);this.currentEntity.addChild(s);const n=s.addComponent(new te);n.nodeType=y.Decorator,n.nodeName=e;return s.addComponent(new Q).conditionCode=t,this.currentEntity=s,this}cooldown(e="Cooldown",t=1){this.entityStack.push(this.currentEntity);const s=this.scene.createEntity(e);this.currentEntity.addChild(s);const n=s.addComponent(new te);n.nodeType=y.Decorator,n.nodeName=e;return s.addComponent(new Y).cooldownTime=t,this.currentEntity=s,this}timeout(e="Timeout",t=5){this.entityStack.push(this.currentEntity);const s=this.scene.createEntity(e);this.currentEntity.addChild(s);const n=s.addComponent(new te);n.nodeType=y.Decorator,n.nodeName=e;return s.addComponent(new ee).timeoutDuration=t,this.currentEntity=s,this}wait(e,t="Wait"){const s=this.scene.createEntity(t);this.currentEntity.addChild(s);const n=s.addComponent(new te);n.nodeType=y.Action,n.nodeName=t;return s.addComponent(new x).waitTime=e,this}log(e,t="log",s="Log"){const n=this.scene.createEntity(s);this.currentEntity.addChild(n);const o=n.addComponent(new te);o.nodeType=y.Action,o.nodeName=s;const i=n.addComponent(new A);return i.message=e,i.level=t,this}setBlackboardValue(e,t,s="SetValue"){const n=this.scene.createEntity(s);this.currentEntity.addChild(n);const o=n.addComponent(new te);o.nodeType=y.Action,o.nodeName=s;const i=n.addComponent(new E);return i.variableName=e,i.value=t,this}modifyBlackboardValue(e,t,s,n="ModifyValue"){const o=this.scene.createEntity(n);this.currentEntity.addChild(o);const i=o.addComponent(new te);i.nodeType=y.Action,i.nodeName=n;const r=o.addComponent(new R);return r.variableName=e,r.operation=t,r.operand=s,this}action(e,t){const s=this.scene.createEntity(e);this.currentEntity.addChild(s);const n=s.addComponent(new te);n.nodeType=y.Action,n.nodeName=e;return s.addComponent(new B).setFunction(t),this}compareBlackboardValue(e,t,s,n="Compare"){const o=this.scene.createEntity(n);this.currentEntity.addChild(o);const i=o.addComponent(new te);i.nodeType=y.Condition,i.nodeName=n;const r=o.addComponent(new F);return r.variableName=e,r.operator=t,r.compareValue=s,this}checkBlackboardExists(e,t=!1,s="Exists"){const n=this.scene.createEntity(s);this.currentEntity.addChild(n);const o=n.addComponent(new te);o.nodeType=y.Condition,o.nodeName=s;const i=n.addComponent(new L);return i.variableName=e,i.checkNotNull=t,this}randomProbability(e,t="Random"){const s=this.scene.createEntity(t);this.currentEntity.addChild(s);const n=s.addComponent(new te);n.nodeType=y.Condition,n.nodeName=t;return s.addComponent(new U).probability=e,this}condition(e,t="Condition"){const s=this.scene.createEntity(t);this.currentEntity.addChild(s);const n=s.addComponent(new te);n.nodeType=y.Condition,n.nodeName=t;return s.addComponent(new P).setFunction(e),this}end(){if(0===this.entityStack.length)throw new Error("No parent node to return to");return this.currentEntity=this.entityStack.pop(),this}build(){for(;this.entityStack.length>0;)this.currentEntity=this.entityStack.pop();return this.currentEntity}}class at{static serialize(e,t=!0){if(!e.hasComponent(te))throw new Error("Entity must have BehaviorTreeNode component");if(!e.scene)throw new Error("Entity must be attached to a scene");return u.serialize(e.scene,{format:"json",pretty:t,includeMetadata:!0})}static deserialize(e,t){u.deserialize(e,t,{strategy:"merge"})}static toJSON(e,t=!0){const s=this.serialize(e,t);return JSON.stringify(s,null,t?2:0)}static fromJSON(e,t){this.deserialize(e,t)}static async saveToFile(e,t){throw this.toJSON(e,!0),new Error("saveToFile requires Tauri environment. Use toJSON() for manual saving.")}static async loadFromFile(e,t){throw new Error("loadFromFile requires Tauri environment. Use fromJSON() for manual loading.")}static validate(e){try{const t=JSON.parse(e);if(!t||"object"!=typeof t)return!1;if(!t.name||"number"!=typeof t.version||!Array.isArray(t.entities)||!Array.isArray(t.componentTypeRegistry))return!1;return t.entities.some((e=>e.components.some((e=>"BehaviorTreeNode"===e.type))))}catch{return!1}}static clone(e,t){const s=this.serialize(t),n=e.entities.count;this.deserialize(e,s);const o=Array.from(e.entities.buffer);for(let e=o.length-1;e>=n;e--){const t=o[e];if(t.hasComponent(te)&&!t.parent)return t}throw new Error("Failed to find cloned root entity")}}class ct{static getAllTemplates(){return N()}static getTemplate(e,t){return this.getAllTemplates().find((s=>{if(s.type!==e)return!1;const n=s.defaultConfig;switch(e){case y.Composite:return n.compositeType===t;case y.Decorator:return n.decoratorType===t;case y.Action:return n.actionType===t;case y.Condition:return n.conditionType===t;default:return!1}}))}}export{b as AbortType,oe as ActiveNode,Z as AlwaysFailNode,X as AlwaysSucceedNode,et as AssetLoadingManager,st as AssetType,C as BehaviorNode,S as BehaviorProperty,je as BehaviorTreeAssetLoader,ae as BehaviorTreeAssetMetadata,Ve as BehaviorTreeAssetSerializer,Ue as BehaviorTreeAssetValidator,rt as BehaviorTreeBuilder,te as BehaviorTreeNode,at as BehaviorTreePersistence,ot as BehaviorTreePlugin,it as BehaviorTreeStarter,F as BlackboardCompareCondition,ne as BlackboardComponent,L as BlackboardExistsCondition,v as BlackboardValueType,Ze as CircularDependencyError,$ as CompareOperator,Ke as CompositeExecutionSystem,M as CompositeNodeComponent,f as CompositeType,Q as ConditionalNode,Y as CooldownNode,_e as DecoratorExecutionSystem,J as DecoratorNodeComponent,g as DecoratorType,Me as EditorFormatConverter,Qe as EntityDestroyedError,B as ExecuteAction,P as ExecuteCondition,Oe as FileSystemAssetLoader,se as GlobalBlackboardService,G as InverterNode,He as LeafExecutionSystem,Je as LoadingState,A as LogAction,re as LogOutput,R as ModifyBlackboardValueAction,I as ModifyOperation,w as NodeClassRegistry,T as NodeProperty,ct as NodeTemplates,y as NodeType,z as ParallelNode,O as ParallelSelectorNode,ie as PropertyBindings,U as RandomProbabilityCondition,j as RandomSelectorNode,q as RandomSequenceNode,H as RepeaterNode,Ge as RootExecutionSystem,ce as RootNode,V as SelectorNode,D as SequenceNode,E as SetBlackboardValueAction,tt as SubTreeExecutionSystem,W as SubTreeNode,m as TaskStatus,Xe as TimeoutError,ee as TimeoutNode,K as UntilFailNode,_ as UntilSuccessNode,x as WaitAction,nt as WorkspaceService,k as clearRegisteredNodes,N as getRegisteredNodeTemplates};
2
- //# sourceMappingURL=index.mjs.map