UMassBattleAgentBehaviorProcessor
Source/MassBattle/Public/Processors/MassBattleAgentBehaviorProcessor.h
概述 Overview
统一行为处理器:把 Appear / Sleep / Patrol / Attack / Chase / Reinforce / Return / Idle 集成进单一活动行为状态机(能力层 Move/Trace 与反应层 Hit/Death 保持独立)。九个 Section 逐段执行:目标有效性统一门控(FTracing.TraceResult 有效+存活+有血量,每帧刷新 LastKnownTargetLocation 供 Move 追击)、Appear 出生(动画/溶解曲线/OnAppearFinish 切换)、Sleep 唤醒(禁用/发现目标/受击唤醒)、Patrol 巡逻(随机可达点 + 移动/等待计时 + OnPatrolRoundEnd)、Attack 攻击(Aim→PreCast→PostCast→Cooling 状态机,胶囊表面距离判定,减速影响攻速,命中判定与三种伤害施加,自杀模式)、Chase 追击(MaxChaseDistance 实时距离放弃 + OnLostTarget 过渡)、Reinforce 共享视野支援(指挥中心快照最近目标查询 + 卡死检测)、Return 完成事件、Idle 单一写点。ApplyBehaviorSwitch 统一执行旗标互斥与状态复位。所有 RNG 消耗(动画槽选取、巡逻目标)在锁步事件 tick 用实体自身 RandomStream。每帧更新各行为状态计数与 CommanderSnapshots(支援上报按指挥中心分组)。
Unified behavior processor: integrates Appear / Sleep / Patrol / Attack / Chase / Reinforce / Return / Idle into a single active-behavior state machine (the Move/Trace capability layer and Hit/Death reaction layer stay separate). Nine sections run in sequence: unified target-validity gating (FTracing.TraceResult valid + alive + has HP, refreshing LastKnownTargetLocation every frame for the Move processor's chase goal), Appear birth (anim / dissolve curves / OnAppearFinish switch), Sleep wake (disabled / target found / wake-on-hit), Patrol (random reachable goal + move/wait timers + OnPatrolRoundEnd), Attack (Aim→PreCast→PostCast→Cooling state machine, capsule surface-distance checks, slow affecting attack speed, hit-time checks with three damage shapes, suicide modes), Chase (MaxChaseDistance live-distance give-up + OnLostTarget transition), Reinforce shared-vision (nearest shared target from commander snapshots + stuck detection), Return completion event, and Idle with a single write site. ApplyBehaviorSwitch performs flag mutual exclusion and state reset uniformly. All RNG consumption (anim slot picks, patrol goals) happens at lockstep-driven ticks using the entity's own RandomStream. Each frame updates per-behavior-state counts and CommanderSnapshots (reinforce reports grouped by command center).
继承 Inheritance
公开方法 Public Methods
构造函数。设置 bAutoRegisterWithProcessingPhases = false(手动派发)、bRequiresGameThreadExecution = true、ExecutionFlags = Standalone | Server | Client。
Constructor. Sets bAutoRegisterWithProcessingPhases = false (manually dispatched), bRequiresGameThreadExecution = true, and ExecutionFlags = Standalone | Server | Client.
Input
无参数。
No parameters.
Output
无返回值。副作用:注册为手动派发、游戏线程专用的处理器。
No return value. Side effect: registers as a manually-dispatched, game-thread-only processor.
初始化实体查询:All<FAgentTag> + All<FDeath, FBehavior, FAppear, FSleep, FChase, FLocating, FScaling, FCollider, FTrace, FNavigation, FMove, FReturn, FReinforce, FVisualizing, FDebuff, FDamage, FDefence, FDebuffing, FAgentEvent, FAgentDebug, FRotating>(MARO) + All<FBehaving, FStatistics, FDeterminism, FDying, FAppearing, FAnimating, FTracing, FPatrol, FPatrolling, FNavigating, FMoving, FReturning, FReinforcing, FAttack, FAttacking, FEntityFlagFragment>(MARW) + All<FCurveShared, FAnimShared>(MARO)。
Initializes the entity query: All<FAgentTag> + All<FDeath, FBehavior, FAppear, FSleep, FChase, FLocating, FScaling, FCollider, FTrace, FNavigation, FMove, FReturn, FReinforce, FVisualizing, FDebuff, FDamage, FDefence, FDebuffing, FAgentEvent, FAgentDebug, FRotating>(MARO) + All<FBehaving, FStatistics, FDeterminism, FDying, FAppearing, FAnimating, FTracing, FPatrol, FPatrolling, FNavigating, FMoving, FReturning, FReinforcing, FAttack, FAttacking, FEntityFlagFragment>(MARW) + All<FCurveShared, FAnimShared>(MARO).
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
EntityManager | const TSharedRef<FMassEntityManager> | Mass 实体管理器,查询初始化目标。Mass entity manager; query initialization target. |
Output
无返回值。副作用:EntityQuery 注册进处理器。
No return value. Side effect: EntityQuery registered with the processor.
每 tick 执行入口。取 MB / MBH / MA(缺失返回),只在 ESubFrame::Subtick1 执行(消费同 tick Trace 的 Subtick0 结果,先于 move 分区 1)。记录 MB.AgentCount。逐实体九个 Section:① 目标门控:TraceResult 有效+存活+有血量 → bHasValidTarget,每帧刷新 LastKnownTargetLocation;② Appear:初始化时执行生成批(BehaviorState=Appearing,bFilterByAnim)、出现动画/溶解曲线、到 RealAppearDuration + Delay 且旗标全清后按 OnAppearFinish 切换;③ Sleep:禁用 / 发现目标 / OnSleepWake(受击唤醒)三种唤醒路径;④ Patrol:到达判定(飞行 2D / 地面 3D)后等待 WaitTimeLeft,超时按 OnPatrolRoundEnd(默认继续巡逻)切换;移动超时 MoveTimeLeft 重选随机可达点;⑤ Attack:未攻击时胶囊表面距离 ≤ Range 触发 ApplyBehaviorSwitch(Attack);Aim 状态校验目标有效/距离/夹角(AimTimeRange.X/Y 瞄准最短/最长时限,超时且无有效角度 → 冷却并标记 bAimFailed);PreCast 执行生成批(Projectile/Actor/Fx/Sound,含 SpeedMultiplier 攻速减速)并选攻击动画;PostCast 在 ATKTime ≥ RealTimeOfHit(分动画命中时刻)时判定 RangeToleranceHit / AngleToleranceHit 后按 Sweep/Point/Radial 施加伤害;SuicideATK/Despawn 自杀;冷却完成(CoolTime == CoolDown)清 Attacking 旗标 + 置 PauseAnimChange;目标失效路径统一走 OnLostTarget(Reinforce 可用时优先)或 Reinforce;⑥ Chase:有效目标且未超 MaxChaseDistance 且未攻击 → Chase(Attack 优先);目标丢失/超距 → 一次性 OnLostTarget 过渡 + 立即重索;⑦ Reinforce:无自己目标时查 MB.CommanderSnapshots 选最近共享目标(过自身 Trace.Query);维持阶段做路径/距离卡死检测(StuckTimeout),丢失则重新查询,无目标按 OnLostTarget 退出;⑧ Return:消费 bJustFinished 跨帧信号按 OnReturnFinish 切换;⑨ Idle:单一写点,互斥求反;⑩ 调试绘制(Editor):行为标签/巡逻圆/攻击范围/目标连线/唯一 ID/选中状态。帧末:更新四个行为计数,ReinforceReportGatherer.Merge() → 确定性排序(CommandCenter UID → Target UID,键预提取)→ 构建 CommanderSnapshots;八类事件 append 到对应队列。
Per-tick entry. Resolves MB / MBH / MA (returns early if missing), gated on ESubFrame::Subtick1 (consumes the same-tick Subtick0 Trace results, runs before move partition 1). Records MB.AgentCount. Per-entity nine sections: ① target gating: TraceResult valid + alive + has HP → bHasValidTarget, refreshing LastKnownTargetLocation each frame; ② Appear: on init fires spawn batches (BehaviorState=Appearing, bFilterByAnim), appear anim / dissolve curves, at RealAppearDuration + Delay with all flags clear switches per OnAppearFinish; ③ Sleep: three wake paths — disabled / target found / OnSleepWake (wake-on-hit); ④ Patrol: after arrival (2D when flying, 3D on ground) waits WaitTimeLeft, on timeout switches per OnPatrolRoundEnd (default keeps patrolling); move timeout MoveTimeLeft re-picks a random reachable goal; ⑤ Attack: when not attacking and capsule surface distance ≤ Range → ApplyBehaviorSwitch(Attack); the Aim state validates target / distance / angle (AimTimeRange.X/Y min/max aim time; timeout without a valid angle → cooldown with bAimFailed); PreCast fires spawn batches (Projectile/Actor/Fx/Sound with SpeedMultiplier attack-speed slow) and picks the attack anim; PostCast at ATKTime ≥ RealTimeOfHit (per-anim hit moment) checks RangeToleranceHit / AngleToleranceHit and applies Sweep/Point/Radial damage; SuicideATK/Despawn self-destruct; cooldown completion (CoolTime == CoolDown) clears Attacking and sets PauseAnimChange; target-loss paths transition via OnLostTarget (Reinforce preferred when available) or Reinforce; ⑥ Chase: valid target within MaxChaseDistance and not attacking → Chase (Attack wins); target lost / too far → one-shot OnLostTarget transition + immediate retrace; ⑦ Reinforce: without an own target, queries MB.CommanderSnapshots for the nearest shared target (passing own Trace.Query); the maintain phase runs path/distance stuck detection (StuckTimeout), re-queries on loss, exits via OnLostTarget when no targets remain; ⑧ Return: consumes the bJustFinished cross-frame signal and switches per OnReturnFinish; ⑨ Idle: single write site, negation of the mutual-exclusion set; ⑩ debug drawing (Editor): behavior labels / patrol circles / attack range / target lines / UID / selection state. At frame end: updates the four behavior counts, ReinforceReportGatherer.Merge() → deterministic sort (CommandCenter UID → Target UID, keys pre-extracted) → builds CommanderSnapshots; eight event kinds append to their queues.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
EntityManager | FMassEntityManager& | 实体管理器。Entity manager. |
Context | FMassExecutionContext& | 执行上下文,提供 fragment 视图与实体遍历。Execution context providing fragment views and entity iteration. |
Output
无返回值。副作用:写全部命中实体的行为旗标 / FBehaving / FAttacking / FPatrolling 等;向 MBH 生成批、MB 的 DmgGatherer / 八类事件队列 / ReinforceReportGatherer / 调试队列写入;更新 MB.AgentCount 与四个行为计数、重建 CommanderSnapshots。
No return value. Side effects: writes behavior flags / FBehaving / FAttacking / FPatrolling etc. on all matched entities; writes to MBH spawn batches, MB's DmgGatherer / eight event queues / ReinforceReportGatherer / debug queues; updates MB.AgentCount and the four behavior counts; rebuilds CommanderSnapshots.
巡逻随机可达点选取:最多 Patrol.MaxPickAttempts 次,角度/距离取自 Patrol.PatrolRange.X/Y 环形区域(FRandomStream 消费)。飞行:候选点向下投影 navmesh 后加 Moving.FlyingHeight 作 3D 悬停点(全失败回退原始点并返回 true);地面:接受第一个 Z 投影到 navmesh 的点(加胶囊中心高度偏移),全失败返回 false(调用方静止、下轮重试)。不做 IsValidPath 门控——流场网格小于巡逻范围时会把全部候选拒掉,导致无限等待循环。
Random reachable patrol-goal selection: up to Patrol.MaxPickAttempts tries, angle/distance drawn from the Patrol.PatrolRange.X/Y annulus (consuming the FRandomStream). Flying: projects the candidate down to the navmesh and adds Moving.FlyingHeight as a 3D hover point (falls back to the raw point and returns true on total failure); ground: accepts the first candidate whose Z projects onto the navmesh (plus capsule-center height offset), returns false on total failure (caller stands still and retries next round). No IsValidPath gating — a flow-field grid smaller than the patrol range would reject all candidates and lock the agent in an endless wait cycle.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
Patrol / Locating / Navigating / Stream / OutGoal / Move / Moving / Collider / Scaling / ColliderUp | 多参数 | 巡逻配置、位置、导航、随机流、输出目标点、移动配置/状态、碰撞体、缩放与 up 向量。Patrol config, location, navigation, random stream, output goal, move config/state, collider, scaling, and the up vector. |
Output
返回是否找到可达点(飞行总是 true)。副作用:OutGoal 被写入、消费随机流。
Returns whether a reachable goal was found (always true when flying). Side effects: OutGoal written, random stream consumed.
两条有限线段间平方最短距离(Eberly 钳制参数法),退化段(点)与平行段均处理。
Squared closest distance between two finite line segments (Eberly's clamped-parametric solution); handles degenerate (point) and parallel segments.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
P0 / P1 / Q0 / Q1 | const FVector ×4 | 两条线段的端点。Endpoints of the two segments. |
Output
返回平方距离(无副作用)。
Returns the squared distance (no side effects).
两胶囊表面最短距离(闵可夫斯基和恒等:胶囊 = 线段 ⊕ 球)= max(0, 线段距 − 半径A − 半径B);表面相交返回 0。攻击距离/夹角判定的核心几何。
Closest surface-to-surface distance between two capsules (Minkowski-sum identity: capsule = segment ⊕ sphere) = max(0, segment distance − RadiusA − RadiusB); returns 0 when surfaces overlap. Core geometry for attack range/angle checks.
Input
| 参数 Param | 类型 Type | 说明 Description |
|---|---|---|
CenterA/AxisA/ShaftHalfLenA/RadiusA 与 B 组 | const FVector ×4, float ×4 | 两胶囊的中心、轴向、半杆长与半径。Both capsules' centers, axes, shaft half-lengths, and radii. |
Output
返回表面距离(相交为 0)。
Returns the surface distance (0 when overlapping).
管线角色 Pipeline Role
注册于 UMassBattleSubsystem 的 SimStages[0],与 Trace 处理器同阶段、先于 Projectile(SimStages[1]):行为生成的 projectile 与 launch 集合供 Projectile 阶段同帧处理,造成的伤害供 SimStages[2] 的 Debuff+Reaction 消费。只在 Subtick1 子帧运行。依赖:Trace 处理器(FTracing.TraceResult 索敌结果,Subtick0)、GridUpdateProcessor 的网格、MBH 的生成批;产物被 Move 处理器(Moving.Goal 追击/巡逻目标)、Reaction 处理器(DmgGatherer)、AgentRenderProcessor(FAnimating 动画槽)消费。CommanderSnapshots 供本处理器下一帧的 Reinforce 查询。
Registered in UMassBattleSubsystem's SimStages[0], same stage as the Trace processor and before Projectile (SimStages[1]): projectiles and launch collections spawned by behavior are processed by the Projectile stage the same frame; the damage it causes feeds the Debuff+Reaction stage (SimStages[2]). Runs only on the Subtick1 sub-frame. Dependencies: the Trace processor (FTracing.TraceResult, Subtick0), the grids from GridUpdateProcessor, and MBH spawn batches; outputs consumed by the Move processor (Moving.Goal chase/patrol goals), the Reaction processor (DmgGatherer), and AgentRenderProcessor (FAnimating anim slots). CommanderSnapshots feeds the next frame's Reinforce queries.