MassBattle Docsv1.19.20

AMassBattleNetworkPlayerControllerBase

UCLASS

Source/MassBattle/Public/Network/MassBattleNetworkPlayerControllerBase.h

概述 Overview

内置网络 RPC 的 PlayerController 基类——客户端↔服务器控制面。上行(Server, Reliable):锁步命令(Server_SendNetCommand,含自动分流上行)、失步报告、hash 上报、快照上传、ack、resync 请求/结果、流场基底全量重发请求(ServerRequestFlowFieldFullResync,配客户端节流包装 RequestFlowFieldFullResync);下行(Client, Reliable):单播锁步命令、追帧(ClientFastForward)、TCP 快照控制平面(ClientBeginTcpSnapshotResync)与 TCP 预连接握手(ClientConnectTcpTransport)。所有服务器落地先取 PlayerState->GetPlayerId() 盖章后转发给 AMassBattleNetworkGameModeBase——本类不持有模拟逻辑,只做传输与盖章。

PlayerController base class with built-in network RPCs — the client↔server control plane. Uplink (Server, Reliable): lockstep commands (Server_SendNetCommand, including the auto-flood uplink), desync reports, hash reports, snapshot uploads, acks, resync requests/results, and flow-field substrate full-resend requests (ServerRequestFlowFieldFullResync, with the client-side throttled wrapper RequestFlowFieldFullResync); downlink (Client, Reliable): unicast lockstep commands, fast-forward (ClientFastForward), the TCP snapshot control plane (ClientBeginTcpSnapshotResync) and the TCP pre-connect handshake (ClientConnectTcpTransport). Every server-side landing stamps PlayerState->GetPlayerId() and forwards to AMassBattleNetworkGameModeBase — this class holds no simulation logic, only transport and stamping.

继承 Inheritance

APlayerController → AMassBattleNetworkPlayerControllerBase

方法 Methods

Server_SendNetCommand Server, Reliable UFUNCTION void (const FMassBattleNetCommand& Cmd)

内部 RPC(非 BP)——所有上行锁步命令的统一入口。落地:取 GetPlayerIndex() 盖章 ValidatedCmd.PlayerIndex 后转发 GM->ReceivePlayerCommand 做 K-buffer 调度。BP 侧请用 SendLockstepCommandToServer 便捷版。

Internal RPC (not BP) — the unified entry for all uplink lockstep commands. On landing: stamps ValidatedCmd.PlayerIndex with GetPlayerIndex() and forwards to GM->ReceivePlayerCommand for K-buffer scheduling. BP should use the SendLockstepCommandToServer convenience version.

Input
参数 Param类型 Type说明 Description
Cmdconst FMassBattleNetCommand&上行命令(PlayerIndex 在落地时被覆写盖章)。Uplink command (PlayerIndex overwritten at landing).
Output

无返回值。副作用:盖章并转发 GameMode;GameMode 非 AMassBattleNetworkGameModeBase 时静默丢弃。

No return value. Side effects: stamping and GameMode forwarding; silently dropped when the GameMode is not AMassBattleNetworkGameModeBase.

SendLockstepCommandToServer void (BlueprintCallable)

客户端→服务器锁步指令便捷版。自动分流:序列化负载 ≥ MassBattle.AutoFloodSwitchBytes(默认 16KB)时,负载打包压缩为 TCP 上传块(SendLockstepDataBlockToServer,BlockId = AllocLocalBlockId 的 LocalBlockId),命令只带 DataBlockId/DataBlockCrc/ExtraDeferTicks 经 Server_SendNetCommand 上行——服务器汇聚时把 LocalBlockId 重映射为 ServerBlockId 并回广播(发送方像任意客户端一样收到);小负载直接经现有可靠 Server RPC 上行。

Client→server lockstep command convenience. Auto-flood: when the serialized payload ≥ MassBattle.AutoFloodSwitchBytes (default 16KB), the payload is packed/compressed into a TCP upload block (SendLockstepDataBlockToServer, BlockId = AllocLocalBlockId's LocalBlockId) and the command carries only DataBlockId/DataBlockCrc/ExtraDeferTicks via Server_SendNetCommand — the server remaps LocalBlockId → ServerBlockId on convergence and rebroadcasts (the sender receives it like any client); small payloads go through the existing reliable Server RPC.

Input
参数 Param类型 Type说明 Description
CommandTagFName命令标签。Command tag.
NamePayloadconst TArray<FName>&名称载荷。Name payload.
IntPayloadconst TArray<int32>&整数载荷。Integer payload.
FloatPayloadconst TArray<float>&浮点载荷。Float payload.
ExtraDeferTicksint32K-buffer 之外额外推迟执行的 tick 数(默认 0);可用于自动分流大块传输余量。Extra ticks to defer beyond the K-buffer (default 0); handy for auto-flood large-block transit headroom.
Output

无返回值。副作用:上行 RPC(或 TCP 上传块 + 引用命令);MB 不存在时静默返回。

No return value. Side effects: uplink RPC (or TCP upload block + reference command); silently returns when MB is missing.

ServerReportDesync Server, Reliable UFUNCTION void (int32 TickCount, int64 LocalHash)

客户端主动报告失步。落地:盖章玩家索引后转发 GM->ReportClientDesync——服务器比对 hash,不一致则记录失步并隔离该客户端。

Client-reported desync. On landing: stamps the player index and forwards to GM->ReportClientDesync — the server compares hashes and records/quarantines on mismatch.

Input
参数 Param类型 Type说明 Description
TickCountint32失步 tick。The diverging tick.
LocalHashint64客户端本地 hash。Client local hash.
Output

无返回值。副作用:转发 GameMode。

No return value. Side effect: GameMode forwarding.

ServerReportHash Server, Reliable UFUNCTION void (int32 TickCount, int64 Hash)

DedicatedServer:上报本地模拟 hash 用于投票。落地:盖章后转发 GM->ReportClientHash → relay 聚合。

DedicatedServer: reports the local simulation hash for voting. On landing: stamped and forwarded to GM->ReportClientHash → relay aggregation.

Input
参数 Param类型 Type说明 Description
TickCountint32hash 对应 tick。Tick of the hash.
Hashint64本地模拟 hash。Local simulation hash.
Output

无返回值。副作用:转发 GameMode。

No return value. Side effect: GameMode forwarding.

ServerUploadSnapshot Server, Reliable UFUNCTION void (int32 TickCount, const TArray<uint8>& CompressedSnapshot)

DedicatedServer:上传压缩快照用于灾备。落地:盖章后转发 GM->ReceiveSnapshotUpload(入口验证大小与 tick 窗口)。

DedicatedServer: uploads a compressed snapshot for disaster recovery. On landing: stamped and forwarded to GM->ReceiveSnapshotUpload (entry validation of size and tick window).

Input
参数 Param类型 Type说明 Description
TickCountint32快照对应 tick。Tick of the snapshot.
CompressedSnapshotconst TArray<uint8>&压缩快照字节。Compressed snapshot bytes.
Output

无返回值。副作用:转发 GameMode。

No return value. Side effect: GameMode forwarding.

ServerAckTick Server, Reliable UFUNCTION void (int32 TickCount, int64 LocalHash)

客户端心跳确认:上报已模拟到的最新 tick 及本地哈希;服务器据此做步调控制(pacing)、延迟追踪与 bPacedMode 超时踢人。落地:盖章后转发 GM->AckClientTick——推进 ack 追踪并在 hash 不一致时隔离。失步校验链路中每个 tick 都经此上报(见 EvaluateDeferredDesyncChecks)。

Client heartbeat ack: reports the latest tick simulated along with the local hash; the server uses acks for pacing, lag tracking and the bPacedMode timeout kick. On landing: stamped and forwarded to GM->AckClientTick — advances ack tracking and quarantines on hash mismatch. Every tick in the desync-validation chain reports through this (see EvaluateDeferredDesyncChecks).

Input
参数 Param类型 Type说明 Description
TickCountint32已确认执行的 tick。Acked tick.
LocalHashint64该 tick 的本地 hash(未校验阶段为服务端期望值)。Local hash of the tick (server expected while unvalidated).
Output

无返回值。副作用:转发 GameMode。

No return value. Side effect: GameMode forwarding.

ServerRequestResync Server, Reliable UFUNCTION void (int32 ClientTickCount)

客户端请求重同步(客户端自恢复失败后发出)。落地:盖章后转发 GM->HandleClientResyncRequest 进入服务端 resync 调度。

Client resync request (sent after client self-recovery fails). On landing: stamped and forwarded to GM->HandleClientResyncRequest for server-side resync scheduling.

Input
参数 Param类型 Type说明 Description
ClientTickCountint32客户端当前 tick。Client's current tick.
Output

无返回值。副作用:转发 GameMode。

No return value. Side effect: GameMode forwarding.

ServerResyncComplete Server, Reliable UFUNCTION void (int32 PlayerIndex)

客户端通知 resync 完成。落地:忽略传入 PlayerIndex,以 PlayerState 的 PlayerId 为准转发 GM->OnClientResyncComplete。

Client notifies resync completion. On landing: the passed PlayerIndex is ignored; the PlayerState PlayerId is authoritative and forwarded to GM->OnClientResyncComplete.

Input
参数 Param类型 Type说明 Description
PlayerIndexint32调用参数(落地时被忽略,改用 PlayerState 的 PlayerId)。Call parameter (ignored at landing; the PlayerState PlayerId is used instead).
Output

无返回值。副作用:转发 GameMode 触发完成清理与延迟生成冲刷。

No return value. Side effect: GameMode forwarding triggering completion cleanup and deferred spawn flush.

ServerReportResyncResult Server, Reliable UFUNCTION void (int32 PayloadTick, bool bSuccess)

客户端报告 resync 结果(非 TCP 路径)。落地:以 PlayerState 的 PlayerId 盖章转发 GM->OnClientResyncResult。

Client reports a resync result (non-TCP path). On landing: stamped with the PlayerState PlayerId and forwarded to GM->OnClientResyncResult.

Input
参数 Param类型 Type说明 Description
PayloadTickint32快照捕获 tick。Snapshot capture tick.
bSuccessbool是否成功。Whether it succeeded.
Output

无返回值。副作用:转发 GameMode。

No return value. Side effect: GameMode forwarding.

ClientReceiveLockstepCommand Client, Reliable UFUNCTION void (const FMassBattleNetCommand& Cmd)

服务器向本客户端单播一条锁步指令(SendLockstepCommandToClient 的下行落地)。非权威端(HasAuthority() 为 false)才处理:入队 EnqueueNetCommand。

Server unicast of one lockstep command to this client (the downlink landing of SendLockstepCommandToClient). Handled only on non-authority (HasAuthority() false): enqueues via EnqueueNetCommand.

Input
参数 Param类型 Type说明 Description
Cmdconst FMassBattleNetCommand&锁步命令。The lockstep command.
Output

无返回值。副作用:命令入队(权威端忽略)。

No return value. Side effect: command enqueue (ignored on authority).

ClientFastForward Client, Reliable UFUNCTION void (int32 TargetTick)

服务器命令客户端追帧到目标 tick。非权威端调用 Net->BeginFastForward(TargetTick, MB) 进入快进状态机。

Server directs the client to fast-forward to a target tick. Non-authority calls Net->BeginFastForward(TargetTick, MB) to enter the fast-forward state machine.

Input
参数 Param类型 Type说明 Description
TargetTickint32追帧目标 tick。Fast-forward target tick.
Output

无返回值。副作用:触发客户端快进(权威端忽略)。

No return value. Side effect: client fast-forward trigger (ignored on authority).

ClientBeginTcpSnapshotResync Client, Reliable UFUNCTION void (int32 SnapshotId, int32 PlayerSlot, int32 PayloadTick, int32 TargetTick, int32 ServerPort, int32 SessionToken, int32 TotalCompressedSize, int32 TotalUncompressedSize, uint32 Crc)

TCP 快照控制平面:服务器通知客户端将通过 TCP 接收快照。流程:确认玩家角色快照模板(EnsurePlayerCharacterSnapshotTemplate,失败仅警告不阻挡——逐 agent 模板可能已经 Agent.Spawn 预注册存在);EnterDesyncRecovery 进入恢复暂停;EnsureSnapshotTcpTransport 惰性创建客户端传输;传输缺失或已连接失败时上报失败;未连接则从 NetConnection->URL.Host 取服务器地址(空则 127.0.0.1)调 ConnectClient(非阻塞,含连接/认证截止);连接建立后等待 TCP 快照到达(由 OnSnapshotBytesReceived 反序列化并排队应用)。

TCP snapshot control plane: the server tells the client to expect a snapshot over TCP. Flow: confirms the player-character snapshot template (EnsurePlayerCharacterSnapshotTemplate; failure only warns — per-agent templates may already exist via Agent.Spawn pre-registration); EnterDesyncRecovery enters the recovery pause; EnsureSnapshotTcpTransport lazily creates the client transport; a missing transport or failed connect reports failure; otherwise the server host is taken from NetConnection->URL.Host (fallback 127.0.0.1) and ConnectClient runs (non-blocking, with connect/auth deadlines); once connected the client waits for the TCP snapshot (deserialized and queued for apply via OnSnapshotBytesReceived).

Input
参数 Param类型 Type说明 Description
SnapshotIdint32传输 ID(与 TCP 帧头一致)。Transfer ID (matches the TCP frame header).
PlayerSlotint32目标玩家槽位(认证用)。Target player slot (auth).
PayloadTickint32快照捕获 tick。Snapshot capture tick.
TargetTickint32应用快照的目标 tick。Tick to apply the snapshot at.
ServerPortint32TCP 监听端口。TCP listen port.
SessionTokenint32会话认证令牌。Session auth token.
TotalCompressedSizeint32压缩字节总数(当前仅日志)。Total compressed bytes (currently logged only).
TotalUncompressedSizeint32解压字节总数(当前仅日志)。Total uncompressed bytes (currently logged only).
Crcuint32压缩数据 CRC(当前仅日志)。Compressed-data CRC (currently logged only).
Output

无返回值。副作用:进入恢复暂停、创建/复用客户端传输、发起连接;失败路径上报 ServerReportTcpSnapshotResult(false)。

No return value. Side effects: recovery pause, client transport create/reuse, connection initiation; the failure path reports ServerReportTcpSnapshotResult(false).

ClientConnectTcpTransport Client, Reliable UFUNCTION void (int32 ServerPort, int32 PlayerSlot, int32 SessionToken)

TCP 预连接握手:服务器在 PostLogin 分配槽位后立即下发,在任何大载荷锁步命令(自动分流)或 resync 需要之前先建立客户端快照/块 socket——缺了它 socket 要等首次 resync 才出现,期间自动分流上行块被静默丢弃(无 socket)、下行广播也跳过该客户端。实现:权威端直接返回(监听服务器主机共享服务端模拟);EnsureSnapshotTcpTransport 惰性创建传输后,若未连接则从 NetConnection->URL.Host 取服务器地址(空则 127.0.0.1)调 ConnectClient。连接失败非致命——传输 Tick 的节流自动重连会用保存的端点持续重试。

TCP pre-connect handshake: sent from PostLogin right after slot allocation, establishing the client's snapshot/block socket BEFORE any large-payload lockstep command (auto-flood) or resync needs it — without this the socket only appears on the first resync, until then auto-flood uplink blocks are silently dropped (no socket) and downlink broadcasts skip the client. Implementation: returns immediately on authority (the listen-server host shares the server sim); after EnsureSnapshotTcpTransport lazily creates the transport, if not yet connected it takes the server host from NetConnection->URL.Host (fallback 127.0.0.1) and calls ConnectClient. Connect failure is non-fatal — the throttled auto-reconnect in the transport Tick keeps retrying with the saved endpoint.

Input
参数 Param类型 Type说明 Description
ServerPortint32TCP 监听端口。TCP listen port.
PlayerSlotint32玩家槽位(认证用)。Player slot (auth).
SessionTokenint32会话认证令牌。Session auth token.
Output

无返回值。副作用:惰性创建并连接客户端 TCP 传输;已连接(resync 先行)或权威端时无操作。

No return value. Side effects: lazily creates and connects the client TCP transport; no-op when already connected (resync raced ahead) or on authority.

ServerReportTcpSnapshotResult Server, Reliable UFUNCTION void (int32 SnapshotId, int32 PayloadTick, bool bSuccess)

客户端向服务器报告 TCP 快照结果(成功 ack 或失败)。落地:以 PlayerState 的 PlayerId 盖章转发 GM->OnClientResyncResult——成功时其清理 ClientsWithPendingResync 并冲刷延迟生成。

Client reports the TCP snapshot result back to the server (success ack or failure). On landing: stamped with the PlayerState PlayerId and forwarded to GM->OnClientResyncResult — on success it clears ClientsWithPendingResync and flushes deferred spawns.

Input
参数 Param类型 Type说明 Description
SnapshotIdint32传输 ID(当前未使用)。Transfer ID (currently unused).
PayloadTickint32快照捕获 tick。Snapshot capture tick.
bSuccessbool是否成功。Whether it succeeded.
Output

无返回值。副作用:转发 GameMode。

No return value. Side effect: GameMode forwarding.

ServerRequestFlowFieldFullResync Server, Reliable UFUNCTION void (FName FieldKey)

流场基底修复请求(非锁步命令):客户端已应用的流场基底版本与差分基准脱节(跳过差分的晚加入端、分叉链)时,请求该场的显式全量重发。基底修复带版本且幂等,无需确定性定序。落地:取 PlayerState->GetPlayerId() 盖章(缺失 -1)后转发 GM->HandleFlowFieldFullResyncRequest——服务器侧节流在该 GameMode 内。

Flow-field substrate repair request (NOT a lockstep command): when the client's applied flow-field substrate version missed a delta's base (skipped-delta late joiner, forked chain), it asks for an explicit FULL re-send of that field. Substrate repair is versioned + idempotent and needs no deterministic ordering. On landing: stamps PlayerState->GetPlayerId() (-1 if missing) and forwards to GM->HandleFlowFieldFullResyncRequest — the server-side throttle lives in that GameMode.

Input
参数 Param类型 Type说明 Description
FieldKeyFName需要全量重发的 AFlowField 名。FName of the AFlowField needing a full re-send.
Output

无返回值。副作用:转发 GameMode;GameMode 非 AMassBattleNetworkGameModeBase 时静默丢弃。

No return value. Side effect: GameMode forwarding; silently dropped when the GameMode is not AMassBattleNetworkGameModeBase.

RequestFlowFieldFullResync void (FName FieldKey)

ServerRequestFlowFieldFullResync 的客户端侧节流包装:把连续被拒的差分链收敛为每 5 秒窗口、每场一次修复请求(服务器侧 GameMode 门限按场跨所有端收敛,此处保持单端安静)。仅客户端入口(ROLE_AutonomousProxy,FieldKey 为 None 时直接返回);任意客户端导入失败路径均可调用,重复调用安全。窗口内重复请求直接吞掉,过期则记录墙钟时间并发起 Server RPC。

Client-side throttled wrapper for ServerRequestFlowFieldFullResync: collapses a stuck chain of rejected deltas into one repair request per 5-second window per field (the server-side GameMode gate throttles per field across ALL peers; this one keeps a single peer quiet). Client-side entry only (ROLE_AutonomousProxy; returns immediately when FieldKey is None); safe to call repeatedly from any client-side import-failure path. Repeat requests inside the window are swallowed; an expired window records the wall-clock time and fires the Server RPC.

Input
参数 Param类型 Type说明 Description
FieldKeyFName需要全量重发的流场名。Name of the flow field needing a full re-send.
Output

无返回值。副作用:写入 LastFFFullResyncRequestTimes 节流表;窗口过期时上行 ServerRequestFlowFieldFullResync。

No return value. Side effects: writes the LastFFFullResyncRequestTimes throttle map; uplinks ServerRequestFlowFieldFullResync when the window expired.

GetPlayerIndex int32 () const (BlueprintPure)

返回 PlayerState->GetPlayerId();PlayerState 缺失时返回 -1。

Returns PlayerState->GetPlayerId(); -1 when the PlayerState is missing.

Input

无参数。

No parameters.

Output

返回玩家索引;无 PlayerState 时 -1。

Returns the player index; -1 without a PlayerState.

ResolveControlledAgent bool (FEntityHandle& OutHandle)

把 AgentUniqueID 解析为当前有效的实体句柄:AgentUniqueID < 0 或 UMassBattleNetworkSubsystem::LookupEntityByUniqueID 查不到有效实体时返回 false;成功时写入并返回 AgentHandle。

Resolves AgentUniqueID into the currently valid entity handle: returns false when AgentUniqueID < 0 or UMassBattleNetworkSubsystem::LookupEntityByUniqueID finds no valid entity; on success writes and returns AgentHandle.

Input
参数 Param类型 Type说明 Description
OutHandleFEntityHandle&输出句柄。Output handle.
Output

返回是否解析成功。副作用:成功时覆写 AgentHandle 与 OutHandle。

Returns whether resolution succeeded. Side effects: overwrites AgentHandle and OutHandle on success.

成员变量 Members

ControlledMassBattleCharacter TWeakObjectPtr<ACharacter> (BlueprintReadOnly)

本地玩家控制的 MassBattle Character 弱引用。

Weak reference to the local player's controlled MassBattle Character.

bControlledAgentActive bool (BlueprintReadOnly)

受控 agent 是否激活(IsControlledAgentActive() 访问器)。

Whether the controlled agent is active (read via IsControlledAgentActive()).

AgentHandle FEntityHandle (BlueprintReadWrite)

本地玩家的 Mass agent 实体句柄,ResolveControlledAgent 成功时写入。

Local player's Mass agent entity handle, written by ResolveControlledAgent on success.

AgentUniqueID int32 (BlueprintReadWrite)

缓存的本玩家 agent UniqueID,用于网络指令载荷与实体解析(默认 -1 = 未设置)。

Cached UniqueID of the local player's agent, used in net command payloads and entity resolution (default -1 = unset).

LastSentAgentTransformTick int32

CC 模式下 Enhanced Input 同步 AgentTransform 的限频记录(上次发送 tick,默认 -1)。

Rate-limit record for AgentTransform sync from BP Enhanced Input in CC mode (last sent tick, default -1).

LastFFFullResyncRequestTimes TMap<FName, double>

RequestFlowFieldFullResync 的按场墙钟节流表(场名 → 上次请求时间)。

Per-field wall-clock throttle map for RequestFlowFieldFullResync (field name → last request time).

管线角色 Pipeline Role

上行链路:BP 经 SendLockstepCommandToServer(或 UMassBattleFuncLib::SendLockstepCommandToServer,MassBattleFuncLib.cpp:785 转发到本函数)发指令 → Server_SendNetCommand → GM->ReceivePlayerCommand K-buffer 排程 → flush tick 经 AMassBattleNetworkGameStateBase::MulticastCommandToClients 广播 → 双端 ExecuteNetCommand 执行。失步链路:客户端 EvaluateDeferredDesyncChecks(GameStateBase)每 tick 经 ServerAckTick 上报;本地恢复失败后经 ServerRequestResync 请求服务端快照。 下行链路:服务器 SendLockstepCommandToClient → ClientReceiveLockstepCommand;快照控制面由 DispatchSnapshotViaTcp_Async 成功派发后调 ClientBeginTcpSnapshotResync(GameModeBase.cpp:554)——客户端据此建立 TCP 连接,快照字节到达后由 UMassBattleNetworkSubsystem::OnSnapshotBytesReceived 反序列化、QueueSnapshotApply 应用,最后 ServerReportTcpSnapshotResult 确认(成功路径驱动 OnClientResyncResult(true))。

Uplink: BP sends via SendLockstepCommandToServer (or UMassBattleFuncLib::SendLockstepCommandToServer, forwarding at MassBattleFuncLib.cpp:785) → Server_SendNetCommand → GM->ReceivePlayerCommand K-buffer scheduling → broadcast at flush ticks via AMassBattleNetworkGameStateBase::MulticastCommandToClients → both peers execute via ExecuteNetCommand. Desync path: the client's EvaluateDeferredDesyncChecks (GameStateBase) reports every tick via ServerAckTick; after local recovery fails it requests a server snapshot via ServerRequestResync. Downlink: server SendLockstepCommandToClient → ClientReceiveLockstepCommand; the snapshot control plane is driven by DispatchSnapshotViaTcp_Async, which calls ClientBeginTcpSnapshotResync after a successful dispatch (GameModeBase.cpp:554) — the client then establishes the TCP connection; once the snapshot bytes arrive, UMassBattleNetworkSubsystem::OnSnapshotBytesReceived deserializes and QueueSnapshotApplys, and finally ServerReportTcpSnapshotResult confirms (the success path drives OnClientResyncResult(true)).