MassBattle Docsv1.19.20

UMassBattleAgentTraceProcessor

UCLASS Processor

Source/MassBattle/Public/Processors/MassBattleAgentTraceProcessor.h

概述 Overview

Agent 的索敌与拾取检测处理器。两阶段并行模型:① 并行收集阶段按冷却/行为状态(Common/Sleep/Patrol/Reinforce/Chase 参数集)筛选需要索敌的 agent,生成 FTraceJobData(成本估算用于负载均衡,按估算成本降序);② 并行执行阶段(MBParallelFor Unbalanced)按 ETraceMode 执行索敌——TargetIsPlayer_0 直接检测玩家(距离/高度/角度/可见性),SectorTraceByTraits 经哈希网格扇形扫描 + 查询过滤 + 可见性检查,命中时用实体自身 RandomStream 从保留候选中随机选一个写 FTracing.TraceResult(WriteTarget),未命中 ClearTarget(无记忆模式,goal 缓存保留)。同时把 FTracingShared(玩家相机位置/FOV/投影因子/玩家实体)写入共享 fragment 供 LOD 与渲染使用。索敌事件(Begin/End)进 OnTraceQueue。Gather 拾取检测独立于索敌:网格圆柱扫描 Ready 战利品,按 LootQuery 过滤后认领进 FGathering.CurrentTargets。

Agent target-acquisition and loot-gathering detector. Two-phase parallel model: ① the parallel gather phase filters agents needing a trace by cooldown/behavior state (Common/Sleep/Patrol/Reinforce/Chase parameter sets) and builds FTraceJobData (with cost estimation for load balancing, sorted by estimated cost descending); ② the parallel execution phase (MBParallelFor Unbalanced) traces per ETraceMode — TargetIsPlayer_0 checks the player directly (distance/height/angle/visibility), SectorTraceByTraits scans the hash grid sector with query filtering and visibility checks; on hit, one result is picked randomly using the entity's own RandomStream and written to FTracing.TraceResult (WriteTarget); on miss, ClearTarget (no memory mode — the goal cache persists). FTracingShared (player camera location/FOV/projection factor/player entity) is written into the shared fragment for LOD and rendering. Trace events (Begin/End) go to OnTraceQueue. Loot gathering is independent of tracing: a grid cylinder scan over Ready-state loot, filtered by LootQuery, claims targets into FGathering.CurrentTargets.

继承 Inheritance

UMassProcessor → UMassBattleAgentTraceProcessor

公开方法 Public Methods

UMassBattleAgentTraceProcessor 构造函数

构造函数。设置 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.

ConfigureQueries virtual void

初始化实体查询:All<FAgentTag> + None<FAppearingTag, FDyingTag>(出现/死亡中的 agent 排除)+ All<FLocating, FRotating, FScaling, FCollider, FSleep, FTrace, FChase, FVisualizing, FAttacking, FAgentEvent, FAgentDebug, FStatistics, FDeterminism, FGather>(MARO) + All<FPatrol, FTracing, FPatrolling, FEntityFlagFragment, FTracingShared, FGathering>(MARW)。

Initializes the entity query: All<FAgentTag> + None<FAppearingTag, FDyingTag> (appearing/dying agents excluded) + All<FLocating, FRotating, FScaling, FCollider, FSleep, FTrace, FChase, FVisualizing, FAttacking, FAgentEvent, FAgentDebug, FStatistics, FDeterminism, FGather>(MARO) + All<FPatrol, FTracing, FPatrolling, FEntityFlagFragment, FTracingShared, FGathering>(MARW).

Input
参数 Param类型 Type说明 Description
EntityManagerconst TSharedRef<FMassEntityManager>Mass 实体管理器,查询初始化目标。Mass entity manager; query initialization target.
Output

无返回值。副作用:EntityQuery 注册进处理器。

No return value. Side effect: EntityQuery registered with the processor.

Execute virtual void

每 tick 执行入口。取 MB / MA / 哈希网格子系统(缺失返回),只在 ESubFrame::Subtick0 执行。流程:① 玩家数据采集:从 Player 0 的 Pawn/控制器/相机管理器取相机位置(Simulate 模式用编辑器视口相机覆盖)、FOV、视口宽高比 → ProjectionFactor = AspectRatio / tan(FOV/2);从 UMassBattleAgentComponent 取玩家实体句柄,有效且存活时写 PlayerHandle / PlayerLocation(用实体 PreLocation,非 Actor 位置——引擎运行时跨进程不确定)/ PlayerRadius / bPlayerIsValid 进 FTracingShared(并写回查询共享 fragment);② 并行收集:逐 agent 跳过 PendingDestroy/未激活;调试绘制(Editor);AgentsChaseAttack 硬锁定(ActiveChaseAttackTaskID != 0 && !bChaseAttackInterruptible)时把 TraceResult 钉在 LockedTarget 并刷新位置缓存,跳过索敌;初始化延迟(RandomDelayOnInit 消费实体流);冷却到 0 时选 FEffectiveTraceParams(按行为状态),检查当前目标有效性(距离/查询匹配/FMassBattleQuery),bSkipTraceWhileTargetValid 时做 LOS 预检(被遮挡丢目标);按行为状态决定 bShouldTrace 与冷却(Common/Sleep/Patrol/Reinforce/Chase);生成 FTraceJobData(成本估算:半径平方 × 优先级层数 × 障碍系数)与 Trace Begin 事件;③ 排序与并行执行:按估算成本降序(MBParallelFor Unbalanced),按模式执行——TargetIsPlayer_0:脚底高度差 ≤ FinalHeight → 距离平方 ≤ 半径平方 → 2D 夹角 ≤ 角度/2 → (可选)LineTrace/SphereTrace 可见性 → WriteTarget;SectorTraceByTraits:NeighborGrid.SectorTraceForAgents(KeepCount 保留、查询过滤、忽略自身)→ 命中则 RandomStream.RandRange 随机选一个 WriteTarget(位置取目标 PreLocation),未命中 ClearTarget;Trace End 事件(成功/失败);④ Gather 拾取:Gather.bEnable 且非 Dying/Appearing、槽位未满时,网格 SphereTraceForLootCellsSorted 取候选格 → 逐 loot 检查激活/可收集/未被认领/LootQuery 匹配/圆柱范围 → 认领前 AvailableSlots 个进 Gathering.CurrentTargets。

Per-tick entry. Resolves MB / MA / the hash grid subsystem (returns early if missing), gated on ESubFrame::Subtick0. Flow: ① player data collection: camera location from Player 0's pawn/controller/camera manager (Simulate mode overrides with the editor viewport camera), FOV, viewport aspect → ProjectionFactor = AspectRatio / tan(FOV/2); the player entity handle from UMassBattleAgentComponent, valid+alive → writes PlayerHandle / PlayerLocation (entity PreLocation, NOT Actor location — engine-runtime, non-deterministic across processes) / PlayerRadius / bPlayerIsValid into FTracingShared (also written back to the query shared fragment); ② parallel gather: per agent, skip PendingDestroy/inactive; debug drawing (Editor); AgentsChaseAttack HARD lock (ActiveChaseAttackTaskID != 0 && !bChaseAttackInterruptible) pins TraceResult to LockedTarget and refreshes the location cache, skipping the trace; init delay (RandomDelayOnInit consumes the entity stream); when the cooldown hits 0, pick FEffectiveTraceParams (by behavior state), check current-target validity (distance / query match), LOS pre-check under bSkipTraceWhileTargetValid (occluded → drop target); decide bShouldTrace and the cooldown by behavior state (Common/Sleep/Patrol/Reinforce/Chase); build FTraceJobData (cost estimate: radius squared × priority levels × obstacle factor) and the Trace Begin event; ③ sort and parallel execution: descending estimated cost (MBParallelFor Unbalanced), per mode — TargetIsPlayer_0: feet height diff ≤ FinalHeight → dist sq ≤ radius sq → 2D angle ≤ angle/2 → (optional) LineTrace/SphereTrace visibility → WriteTarget; SectorTraceByTraits: NeighborGrid.SectorTraceForAgents (KeepCount results, query filter, self ignored) → on hit pick one via RandomStream.RandRange and WriteTarget (location from the target's PreLocation), on miss ClearTarget; Trace End event (success/fail); ④ loot gathering: when Gather.bEnable, not Dying/Appearing, and slots remain, SphereTraceForLootCellsSorted gathers candidate cells → per loot: active/can-collect/not claimed/LootQuery match/cylinder range → claim up to AvailableSlots into Gathering.CurrentTargets.

Input
参数 Param类型 Type说明 Description
EntityManagerFMassEntityManager&实体管理器。Entity manager.
ContextFMassExecutionContext&执行上下文,提供 fragment 视图与实体遍历。Execution context providing fragment views and entity iteration.
Output

无返回值。副作用:写全部命中实体的 FTracing(TraceResult / TimeLeft / 位置缓存)与 FTracingShared(玩家数据);向 FGathering.CurrentTargets 认领战利品;向 MB.OnTraceQueue 与各调试队列写入。

No return value. Side effects: writes FTracing (TraceResult / TimeLeft / location cache) on every matched entity and FTracingShared (player data); claims loot into FGathering.CurrentTargets; writes to MB.OnTraceQueue and the debug queues.

成员变量 Members

FEffectiveTraceParams struct (头文件公开)

按 Agent 当前行为状态选出的有效索敌参数(TraceRadius / bCheckObstacle / CheckRadius / CoolDown)——单一事实来源,保证 validity 校验、LOS 预检与成本估算读到一致值。

Effective trace parameters for the agent's current behavior state (TraceRadius / bCheckObstacle / CheckRadius / CoolDown) — single source of truth so validity checks, LOS pre-checks, and cost estimates read consistent values.

FTraceJobData struct (头文件公开)

索敌任务记录:实体句柄 + 14 个 fragment 指针(只读配置与可写运行时)+ EstimatedCost(并行负载均衡的相对成本,越大越重)。

Trace job record: entity handle + 14 fragment pointers (read-only configs and writable runtime) + EstimatedCost (relative cost for parallel load balancing, higher = heavier).

FTraceScratchContext struct (头文件公开)

索敌任务处理的线程本地临时上下文(消除 gather lambda 与 job lambda 中的 TArray 分配):LocalJobs / LocalTraceEvents(chunk 级)与 Results / IgnoreList / VisibilityResults / LootCells / LootInRange(job 级)。ResetPerChunk() / ResetPerJob() 复位并预分配。

Thread-local scratch context for trace job processing (eliminates TArray allocations in the per-chunk gather lambda and per-job parallel lambda): LocalJobs / LocalTraceEvents (chunk-level) and Results / IgnoreList / VisibilityResults / LootCells / LootInRange (job-level). ResetPerChunk() / ResetPerJob() reset with pre-allocation.

EntityQuery / TraceJobs FMassEntityQuery / FParallelGatherer<FTraceJobData> (private)

EntityQuery 为主查询;TraceJobs 收集任务,并行执行前 Merge + 成本降序排序。

EntityQuery is the main query; TraceJobs gathers jobs, merged and sorted by descending cost before parallel execution.

管线角色 Pipeline Role

注册于 UMassBattleSubsystem 的 SimStages[0](阶段起点),与 Behavior 处理器同阶段、先于其执行(阶段顺序 [0] Trace+Behavior → [1] Projectile → …)。只在 Subtick0 子帧运行。产物被以下消费者使用:Behavior 处理器读 FTracing.TraceResult 驱动追击/攻击状态;Move 处理器读 LastKnownTargetLocation 作追击目标点;FTracingShared(相机/投影因子)驱动 AgentRenderProcessor 的 LOD 与 HostMonoProcessor 的玩家相关逻辑。网格数据来自 GridUpdateProcessor 帧起始重建的网格;硬锁定由 UMassBattleBPTaskAgentsChaseAttack 经 ActiveChaseAttackTaskID / LockedTarget 写入。

Registered in UMassBattleSubsystem's SimStages[0] (stage start), same stage as and before the Behavior processor (order [0] Trace+Behavior → [1] Projectile → …). Runs only on the Subtick0 sub-frame. Consumers: the Behavior processor reads FTracing.TraceResult to drive chase/attack states; the Move processor reads LastKnownTargetLocation as the chase goal; FTracingShared (camera/projection factor) drives LOD in AgentRenderProcessor and player-related logic in HostMonoProcessor. Grid data comes from the grids rebuilt by GridUpdateProcessor at start of frame; the hard lock is written by UMassBattleBPTaskAgentsChaseAttack via ActiveChaseAttackTaskID / LockedTarget.