Files
UE5-Modular-Game-Framework/docs/architecture/multiplayer-networking.md
Lefteris Notas 8bc731e5ae feat: Add multiplayer networking architecture and documentation updates
- Updated Master Blueprint Index to include Multiplayer Networking support.
- Added detailed Multiplayer Networking sections across all developer documentation (01-11).
- Introduced authority maps, key patterns, and RPC guidelines for each system.
- Established a comprehensive multiplayer networking architecture document outlining core principles, replication strategies, and anti-cheat considerations.
- Enhanced UI documentation to clarify local-only behavior and binding to replicated dispatchers.
- Implemented client prediction strategies and RPC naming conventions for consistency across the framework.
2026-05-19 17:15:57 +03:00

316 lines
17 KiB
Markdown

# Multiplayer Networking Architecture — UE5 Modular Game Framework
**Version:** 1.0 | **Generated:** 2026-05-19 | **Status:** Design Phase
This document defines the complete networking architecture for extending the single-player Blueprint-only framework to support multiplayer. All 135 blueprint specs are being updated with replication stubs, RPC definitions, and server-authoritative patterns.
---
## 1. Core Networking Principles
### 1.1 Server Authority Model
The framework uses a **server-authoritative** model:
- **Server:** Owns all game state. Validates every state-changing operation. Runs AI behavior trees. Calculates damage.
- **Client:** Renders locally. Predicts actions for responsiveness. Corrects when server state differs from prediction.
- **Listen Server:** One player is both server and client. Use `HasAuthority()` to branch logic.
### 1.2 Authority Gating Pattern
Every mutator function MUST check authority before modifying replicated state:
```
[Blueprint: Any State-Changing Function]
Switch Has Authority
Authority (Server):
→ Execute authoritative logic
→ Modify replicated variable
→ RepNotify fires on clients automatically
Remote (Client):
→ If client-predicted: play cosmetic feedback immediately
→ Call Server_ RPC to request state change
→ Server validates and executes
→ If prediction was wrong: RepNotify corrects the client
```
### 1.3 RepNotify Pattern
All replicated variables use `RepNotify` with an `OnRep_` function. The `OnRep_` function fires the same event dispatchers that single-player code already binds to:
```
[Variable: CurrentHealth, Replicated Using OnRep_CurrentHealth]
[OnRep_CurrentHealth]
→ Broadcast OnHealthChanged(PreviousHealth, CurrentHealth, Delta)
→ UI, effects, audio react exactly as in single-player
→ No special-case multiplayer code in consumers
```
This means UI widgets, audio, and effects need **zero changes** for multiplayer — they already bind to dispatchers.
### 1.4 RPC Types Used
| RPC Type | UE5 Node | Use Case |
|----------|----------|----------|
| `Server` | Run on Server, Reliable | Client requests state change (fire weapon, use item, interact) |
| `Multicast` | Multicast, Reliable | Server broadcasts cosmetic event to all (explosion FX, scare event) |
| `Client` | Run on Owning Client, Reliable | Server sends client-specific message (inventory full, error toast) |
---
## 2. Variable Replication Strategy
### 2.1 What Gets Replicated
| Category | Variables | Condition |
|----------|-----------|-----------|
| Game State | Chapter, Phase, Objectives, PlayTime, EncounterActive | `Replicated Using OnRep_*` on GS_CoreGameState |
| Player State | Health, Stamina, Stress, Posture, MovementMode, HideState | `RepNotify` on player components |
| World State | Door state, Container slots, Pickup availability, Display mode | `RepNotify` on world actors |
| Inventory | Slots array, TotalWeight, OverEncumbered, EquippedItems | `RepNotify` on inventory components |
| AI State | Position, Rotation, AlertLevel, CurrentAction, Health | Standard Actor replication + custom |
| Narrative | ActiveObjectives, NarrativeFlags, DialogueState | Through GS_CoreGameState |
| Adaptive | AtmosphereTier, TensionLevel, ActiveScareEvent | Through GS_CoreGameState or Adaptive Director |
### 2.2 What Stays Local (Never Replicated)
| Category | Reason |
|----------|--------|
| All Widgets (WBP_*) | Rendered per-client; bind to replicated dispatchers |
| Camera (FOV blending, shake) | Local experience; only state enum syncs |
| Audio playback | Local; gameplay parameters sync via SS_AudioManager |
| Embodiment (arms mesh, IK) | First-person rendering is per-client |
| Debug/Analytics/Cheats | Local development tools |
| Static Data Assets (DA_*) | Read-only config; loaded identically on all clients |
| Tutorial system | Per-player progression |
---
## 3. System-by-System Authority Map
### 3.1 Foundation Layer (01-core)
| System | Authority | Replication |
|--------|-----------|-------------|
| `GI_GameFramework` | Server sets GamePhase; clients read | Dispatchers broadcast to all |
| `GM_CoreGameMode` | Server-only; spawns players, routes death | Extends replicated GameMode |
| `GS_CoreGameState` | Server sets all state | **Full replication** — 5 vars with OnRep |
| `GI_GameTagRegistry` | Read-only on all | Identical on all clients (ini-based) |
| `FL_GameUtilities` | Static; no state | No replication needed |
| `I_InterfaceLibrary` | Contracts; no state | No replication needed |
| `DA_ItemData` | Read-only config | Identical on all clients |
### 3.2 Player Layer (02-player)
| System | Mutators | Client Prediction |
|--------|----------|-------------------|
| `BPC_HealthSystem` | Server-authoritative ApplyDamage, ApplyHealing, KillInstant | Client predicts damage flash; server corrects health value |
| `BPC_StaminaSystem` | Server-authoritative DrainStamina, StartContinuousDrain | Client predicts sprint animation; server corrects if exhausted |
| `BPC_StressSystem` | Server-authoritative AddStress, AddStressSource | Client plays local effects per tier; server is canonical |
| `BPC_MovementStateSystem` | Server-authoritative SetMovementMode, SetPosture | CharacterMovementComponent handles this natively |
| `BPC_HidingSystem` | Server-authoritative EnterHideSpot, ExitHideSpot | Client requests enter; server validates slot availability |
| `BPC_EmbodimentSystem` | Local rendering only | Only visibility/overlay state syncs |
| `BPC_CameraStateLayer` | Local FOV/offset/shake | Only state enum syncs |
| `BPC_PlayerMetricsTracker` | Server accumulates | Snapshot replicates for scoreboards |
### 3.3 Interaction Layer (03-interaction)
| System | Authority | Client Request |
|--------|-----------|----------------|
| `BPC_InteractionDetector` | Clients run trace locally; target synced | Server validates interaction request |
| `BP_DoorActor` | Server-authoritative state machine | Client calls Server_Interact → server validates → OnRep plays anim |
| `BP_PuzzleDeviceActor` | Server-authoritative | Client calls Server_TrySolution |
| `BPC_ContextualTraversalSystem` | Client-predicted movement | Server validates traversal target |
| `BPC_PhysicsDragSystem` | Client-predicted physics | Server periodically corrects position |
| `BPC_UsableWorldObjectSystem` | Server-authoritative toggle/adjust | Client calls Server_Use |
### 3.4 Inventory Layer (04-inventory)
| System | Authority | Anti-Cheat |
|--------|-----------|------------|
| `BPC_InventorySystem` | Server-authoritative add/remove/use/drop | Server validates slot space, weight, stack limits |
| `BPC_ContainerInventory` | Server-authoritative open/loot/transfer | Server validates distance, lock state, slot availability |
| `BP_ItemPickup` | Server-authoritative pickup | Server validates inventory space before removing pickup |
| `BPC_EquipmentSlotSystem` | Server-authoritative equip/unequip | Server validates slot type compatibility |
| `BPC_ConsumableSystem` | Server-authoritative use | Server validates item exists, cooldown, applies effect |
| `BPC_ItemCombineSystem` | Server-authoritative combine | Server validates recipe from DA_ItemData |
### 3.5 Save/Load Layer (05-saveload)
| System | Authority | Notes |
|--------|-----------|-------|
| `SS_SaveManager` | Server triggers save/load | All clients receive load state via GS_CoreGameState |
| `BP_Checkpoint` | Server validates activation | Replicates active checkpoint to all |
| `BPC_DeathHandlingSystem` | Server determines death outcome | All clients see death animation via multicast |
| `BPC_PlayerRespawnSystem` | Server executes respawn | Client receives respawn state via replication |
| `BPC_PersistentCorpseSystem` | Server spawns corpse | Corpse replicated to all |
| `BPC_RunHistoryTracker` | Server tracks history | Replicates for scoreboard |
### 3.6 UI Layer (06-ui)
| System | Pattern |
|--------|--------|
| All WBP_* Widgets | **Local only.** Bind to replicated dispatchers. Zero networking code in widgets. |
| `SS_UIManager` | Local per-client. Menu stack is per-player. |
### 3.7 Narrative Layer (07-narrative)
| System | Authority | Replication |
|--------|-----------|-------------|
| `BPC_NarrativeStateSystem` | Server sets flags | Flags sync via GS_CoreGameState or replicated array |
| `BPC_ObjectiveSystem` | Server activates/completes | Active objectives replicated via GS_CoreGameState |
| `BPC_DialoguePlaybackSystem` | Server sequences dialogue | Dialogue line index replicated; clients play audio locally |
| `BPC_DialogueChoiceSystem` | Client selects choice → Server processes | Server validates choice availability against flags |
| `BPC_BranchingConsequenceSystem` | Server executes consequences | Results sync to all |
| `BPC_CutsceneBridge` | Server triggers cutscene | All clients enter cutscene via multicast |
### 3.8 Weapons Layer (08-weapons)
| System | Authority | Client Prediction |
|--------|-----------|-------------------|
| `BP_WeaponBase` | Server-authoritative state machine | Client predicts fire animation/muzzle flash; server validates |
| `BPC_AmmoComponent` | Server-authoritative ammo | Client predicts ammo count; server corrects via RepNotify |
| `BPC_FirearmSystem` | Server performs trace/damage calc | Client predicts tracers; server hit result is canonical |
| `BPC_MeleeSystem` | Server validates hit detection | Client predicts swing animation |
| `BPC_ReloadSystem` | Server validates reload | Client predicts reload animation; server validates ammo state |
| `BPC_RecoilSystem` | **Local only** | Recoil is cosmetic; handled per-client |
| `BPC_DamageReceptionSystem` | Server calculates damage | HealthSystem is authoritative; damage reactions multicast |
| `BPC_HitReactionSystem` | Server triggers reaction | Animation multicast to all |
| `BPC_CombatFeedbackComponent` | **Local only** | Hit markers, kill confirm are per-client |
| `BPC_ShieldDefenseSystem` | Server validates block/parry | Shield state replicated; client predicts visual |
### 3.9 AI Layer (09-ai)
| System | Authority | Notes |
|--------|-----------|-------|
| `AI_BaseAgentController` | **Server only** | Behavior trees run on server; position/anim replicate natively |
| `BP_EnemyBase` | Server-authoritative health/state | Standard Actor replication |
| `BPC_AlertSystem` | Server-authoritative alert state | Replicates for awareness UI on clients |
| `BPC_AIStateMachine` | Server-authoritative | State changes replicate |
| `BPC_AIPerceptionSystem` | Server runs perception | Detection events replicate to clients for awareness indicators |
| `BPC_AIMemorySystem` | Server stores memory | LastKnownLocation replicates for client UI |
| `BPC_BehaviourVariantSelector` | Server selects at spawn | Variant choice replicates |
| `BP_PatrolPath` | Read-only on all | Spline data is static; identical on all clients |
### 3.10 Adaptive Layer (10-adaptive)
| System | Authority | Notes |
|--------|-----------|-------|
| `BPC_AdaptiveEnvironmentDirector` | Server coordinates | Atmosphere state replicates |
| `BPC_AtmosphereStateController` | Server sets tier | Clients play local audio/lighting per replicated tier |
| `BPC_DifficultyManager` | Server adjusts difficulty | Difficulty params replicate |
| `BPC_FearSystem` | Server-authoritative fear states | AI fear behavior runs on server |
| `BPC_ScareEventSystem` | Server triggers scare | Multicast plays scare FX on all clients |
| `BPC_RareEventSystem` | Server selects event | Multicast plays event on all |
| `BPC_LightEventController` | Server triggers | Replicated for synchronized light events |
| `BPC_MemoryDriftSystem` | **Local only** | Hallucinations are per-player experience |
| `BPC_PacingDirector` | Server controls pacing | Intensity band replicates |
| `BPC_PlaystyleClassifier` | Server classifies | Classification replicates |
| `BPC_PerformanceScaler` | **Local only** | Per-client hardware adaptation |
| `SS_AudioManager` | **Local playback** | Only gameplay parameters (heart rate, tension) sync from server |
| `BP_RoomAudioZone` | **Local only** | Each client applies room acoustics locally based on their position |
---
## 4. Client Prediction Strategy
### 4.1 Prediction Categories
| Category | Strategy | Examples |
|----------|----------|----------|
| **Cosmetic Only** | Client plays immediately, no correction needed | Muzzle flash, recoil, footstep sounds, camera shake |
| **Predicted with Correction** | Client plays, server corrects if prediction wrong | Health bar, ammo count, stamina bar |
| **Server Only** | Client shows nothing until server confirms | Inventory changes, equipment changes, quest completion |
| **Local Input with Server Validation** | Client processes input locally, server validates result | Movement (handled by CharacterMovementComponent), interaction |
### 4.2 Weapon Fire Prediction Flow
```
Client presses Fire:
1. Client: Play fire animation, muzzle flash, recoil immediately
2. Client: Call Server_StartFire() RPC
3. Server: Validate weapon state == Ready, has ammo, not on cooldown
4. Server: If valid → consume ammo, perform trace, calculate damage, apply to target
5. Server: RepNotify ammo count to all clients
6. Server: Multicast fire effects to other clients
7. Client receives ammo RepNotify:
- If ammo matches prediction → no visible correction
- If ammo doesn't match (server rejected fire) → halt fire animation, correct ammo display
```
### 4.3 Interaction Prediction Flow
```
Client presses Interact on door:
1. Client: Call Server_Interact(DoorActor) RPC
2. Server: Validate player within range, door state allows interaction
3. Server: If valid → change door state → RepNotify broadcasts
4. All clients: OnRep_DoorState → play door animation
5. Client: Show interaction prompt after door state changes
```
---
## 5. RPC Naming Convention
| Prefix | Direction | Example |
|--------|-----------|---------|
| `Server_` | Client → Server | `Server_Interact`, `Server_StartFire`, `Server_UseItem` |
| `Multicast_` | Server → All Clients | `Multicast_PlayExplosionFX`, `Multicast_TriggerScare` |
| `Client_` | Server → Specific Client | `Client_ShowErrorToast`, `Client_OpenInventory` |
All RPCs are **Reliable** unless marked otherwise. Unreliable RPCs used only for frequent cosmetic updates (muzzle flash on full-auto).
---
## 6. Anti-Cheat Considerations
### 6.1 Server-Side Validation Required For:
- Health changes (validate damage source, range, fire rate)
- Inventory modifications (validate slot space, weight, stack limits)
- Ammo consumption (validate weapon fire rate, magazine capacity)
- Movement speed (validate against MovementSettings, no speed hacks)
- Interaction range (validate distance to target)
- Item combination (validate recipe exists in DA_ItemData)
### 6.2 Trust Model
- **Trust nothing from clients.** Every state-changing RPC must re-validate conditions server-side.
- **Clients can predict, servers correct.** Prediction improves feel; RepNotify ensures correctness.
- **Cosmetic RPCs are fire-and-forget.** Muzzle flashes, footstep sounds don't need validation.
---
## 7. Network Bandwidth Budget
### 7.1 High Priority (Every Tick / On Change)
- Player position/rotation (handled by CharacterMovementComponent)
- Current health (only on change)
### 7.2 Medium Priority (On Change)
- Weapon state, ammo count
- Door state, container state
- AI alert level
- Active objectives
### 7.3 Low Priority (On Change, Throttled)
- Stress level, stamina (throttled to ~4Hz)
- Atmosphere tier
- Narrative flags
- Collectible count
### 7.4 Never Replicated
- See Section 2.2
### 7.5 Replication Condition Optimization
| Condition | Use Case |
|-----------|----------|
| `COND_OwnerOnly` | Inventory contents (only owning player needs full inventory) |
| `COND_SkipOwner` | Cosmetic effects (owner plays their own locally) |
| `COND_InitialOnly` | Spawn transform, initial state |
| `COND_Custom` | Distance-based: only replicate to nearby players |
---
## 8. Implementation Progress Tracking
| Phase | Systems | Status |
|-------|---------|--------|
| 1: Foundation | 01-core (7 systems) | Blueprint specs updated |
| 2: Player State | 02-player (8 systems) | Blueprint specs updated |
| 3: Interaction | 03-interaction (8 systems) | Blueprint specs updated |
| 4: Inventory | 04-inventory (11 systems) | Blueprint specs updated |
| 5: Save/Load | 05-saveload (9 systems) | Blueprint specs updated |
| 6: UI | 06-ui (14 systems) | Blueprint specs updated |
| 7: Narrative | 07-narrative (11 systems) | Blueprint specs updated |
| 8: Weapons | 08-weapons (11 systems) | Blueprint specs updated |
| 9: AI | 09-ai (9 systems) | Blueprint specs updated |
| 10: Adaptive | 10-adaptive (15 systems) | Blueprint specs updated |
| 11-16: Meta/Settings/Polish/Data/Input/State | (13 systems) | Blueprint specs updated |
| Developer Docs | All 11 docs | Updated with networking sections |
| Architecture Docs | Overview, Patterns, Networking | All current |
---
*Multiplayer Networking Architecture v1.0 — Authoritative reference for all networking patterns in the framework.*