diff --git a/CONTEXT.md b/CONTEXT.md index bf9f9ce..9eb98c9 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -12,6 +12,7 @@ Single Source of Truth for the Unreal Engine 5.5-5.7 Blueprint-based Modular Gam - **State:** [`BPC_StateManager`](docs/architecture/bpc-statemanager.md) — Central state authority (42 exclusive action states, 18 overlay states). Systems query `IsActionPermitted(Tag)` instead of checking other systems directly. - **Animation:** GASP Motion Matching + overlay notifies. Full catalog in [`docs/architecture/animation-catalog.md`](docs/architecture/animation-catalog.md) - **Audio:** 150+ sound triggers + 14-surface material table. Full catalog in [`docs/architecture/sound-catalog.md`](docs/architecture/sound-catalog.md) +- **Networking:** Server-authoritative replication model. Full architecture in [`docs/architecture/multiplayer-networking.md`](docs/architecture/multiplayer-networking.md) ## Directory Structure ``` @@ -91,13 +92,14 @@ docs/ 09-ai-systems.md # AI, perception & encounters explained 10-adaptive-systems.md # Adaptive environment & atmosphere explained 11-16-systems.md # Meta, Settings, Polish, Data Assets, Input, State explained - architecture/ # Architecture & Design Documents (6 files) + architecture/ # Architecture & Design Documents (7 files) bpc-statemanager.md # BPC_StateManager full spec + Chooser Table Audit metasounds-audio-system.md # MetaSounds audio architecture (mix buses, room zones, settings) animation-catalog.md # Animation requirements for all 135 systems sound-catalog.md # Sound/audio requirements for all 135 systems enhanced-input-system.md # Enhanced Input System architecture hud-overview.md # HUD system architecture — 14 widgets, wiring, integration points + multiplayer-networking.md # Multiplayer networking architecture — authority model, RPCs, prediction CLEAN_SLATE_PLAN.md # Clean slate refactoring plan reports/ # Condensed audit reports blueprint_condensed_summary.md # ASK agent audit of all 129 files @@ -106,7 +108,7 @@ docs/ enhanced-input-system.md bpc-statemanager.md # NEW — State Manager implementation checklist ``` -**Total: 135 numbered Blueprint files + 5 enums + 5 Data Assets + TEMPLATE.md + AUDIT_REPORT.md + INDEX.md + 11 developer docs + 6 architecture docs + 1 audit report = 164 files in 18 directory groups** +**Total: 135 numbered Blueprint files + 5 enums + 5 Data Assets + TEMPLATE.md + AUDIT_REPORT.md + INDEX.md + 11 developer docs + 7 architecture docs + 1 audit report = 165 files in 18 directory groups** ## Naming Conventions | Prefix | Type | @@ -143,6 +145,7 @@ docs/ 12. **State Gating via Data Asset** — All gating rules in `DA_StateGatingTable`. Designers modify rules without touching blueprints. 13. **Force Stack Pattern** — Death, cutscenes, void space push state onto a force stack; `RestorePreviousState()` pops back. 14. **Animation Notify Contract** — 14 named notifies required in montages for framework synchronization (see [`animation-catalog.md`](docs/architecture/animation-catalog.md)). +15. **Server-Authoritative Replication** — All state mutations gated by `HasAuthority()`. Clients request via `Server_` RPCs; servers validate and replicate via `RepNotify`. See [`multiplayer-networking.md`](docs/architecture/multiplayer-networking.md). ## Build Order (Dependency-Safe) - **Phase 0:** Foundation + Input (01-core, 15-input — 8 systems) @@ -161,7 +164,7 @@ docs/ - **Phase 13:** Polish (13-polish, 9 systems) - **Phase 14:** State Management (BPC_StateManager + 4 enums + 3 structs + DA_StateGatingTable — 130, 131) - **Phase 15:** MetaSounds Audio (SS_AudioManager + BP_RoomAudioZone + DA_AudioSettings + DA_RoomAcousticPreset — 132-135) -- **Phase 16:** Integration Pass — All systems updated to query `BPC_StateManager.IsActionPermitted()` instead of direct state checks. All audio calls routed through `SS_AudioManager` instead of `UGameplayStatics::PlaySound*`. +- **Phase 16:** Multiplayer Networking — All systems updated with `HasAuthority()` gates, `Server_` RPCs, `RepNotify` handlers, and client prediction patterns. See [`docs/architecture/multiplayer-networking.md`](docs/architecture/multiplayer-networking.md). ## Key Communication Rules 1. Gameplay Tags + Subsystem lookup (global, decoupled) @@ -199,9 +202,21 @@ No PR is accepted without these files being current. This ensures the animator, - **Deprecated:** `BPC_AudioAtmosphereController` (95) is phased out in favor of `SS_AudioManager`. - **Full Spec:** See [`docs/architecture/metasounds-audio-system.md`](docs/architecture/metasounds-audio-system.md) +## Multiplayer Networking Conventions +- **Authority Model:** Server-authoritative. All state mutations (`ApplyDamage`, `AddItem`, `SetDoorState`) execute on the server with `HasAuthority()` gate. Clients request state changes via `Server_` RPCs. +- **RPC Naming:** `Server_` (Client→Server), `Multicast_` (Server→All Clients), `Client_` (Server→Specific Client). All reliable unless marked otherwise. +- **RepNotify Pattern:** All replicated variables use `RepNotify` with `OnRep_` handlers that fire the same event dispatchers single-player code already binds to. UI widgets, audio, and effects need zero changes for multiplayer. +- **Client Prediction:** Cosmetic effects (muzzle flash, recoil, camera shake) play immediately on client. State values (health, ammo, stamina) are predicted but corrected via `RepNotify` if server disagrees. +- **Inventory Authority:** Server validates all add/remove/transfer operations against slot space, weight capacity, and stack limits. Client predicts UI; server corrects via `OnRep_Slots`. +- **AI Server-Only:** Behavior trees run on server. Position/rotation/animations replicate via standard Actor replication. Perception events replicate for client awareness indicators. +- **UI Local Only:** All `WBP_*` widgets are local per-client. They bind to replicated dispatchers — no networking code in widgets. +- **Anti-Cheat:** Server validates all state-changing RPCs. Never trust client-provided values (damage amount, item quantity, target actor). Re-validate conditions server-side. +- **Full Spec:** See [`docs/architecture/multiplayer-networking.md`](docs/architecture/multiplayer-networking.md) + ## Clean Slate Refactoring Status - **Branch:** `refactor/clean-slate` - **Phases 1-7:** COMPLETE — all 127 files created, renamed, reorganized, renumbered - **Phase 8-13:** COMPLETE — AUDIT_REPORT updated, CONTEXT.md updated, verification, final commit - **Phase 14-15:** COMPLETE — State Management (130-131) + MetaSounds Audio (132-135) blueprint specs created +- **Phase 16:** IN PROGRESS — Multiplayer Networking: all 135 blueprint specs being updated with replication stubs, RPC definitions, and server-authoritative patterns. Developer docs updated. Architecture doc created at [`docs/architecture/multiplayer-networking.md`](docs/architecture/multiplayer-networking.md) - **Remaining:** Cross-reference pass across all 135 files; deprecated BPC_AudioAtmosphereController (95) references to update \ No newline at end of file diff --git a/docs/architecture/multiplayer-networking.md b/docs/architecture/multiplayer-networking.md new file mode 100644 index 0000000..457297f --- /dev/null +++ b/docs/architecture/multiplayer-networking.md @@ -0,0 +1,315 @@ +# 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.* diff --git a/docs/blueprints/01-core/01_GI_GameTagRegistry.md b/docs/blueprints/01-core/01_GI_GameTagRegistry.md index 893fef6..f7787d9 100644 --- a/docs/blueprints/01-core/01_GI_GameTagRegistry.md +++ b/docs/blueprints/01-core/01_GI_GameTagRegistry.md @@ -186,4 +186,12 @@ This asset does not talk to other systems directly. All communication is passive 5. Add variables `TagNamespace` (FText) and `bIsFrameworkTag` (bool). 6. Implement the functions listed in Section 6 as Blueprint Callable / Pure nodes. 7. Document all tag namespaces from Section 10 in the asset's description. -8. Save and run the validation test. \ No newline at end of file +8. Save and run the validation test. + +--- + +## 15. Multiplayer Networking + +**Replication: None needed.** This Data Asset is read-only configuration. All clients load identical copies from disk. GameplayTag data lives in `DefaultGameplayTags.ini` which is identical on all instances. + +**Authority: N/A.** No runtime state changes. \ No newline at end of file diff --git a/docs/blueprints/01-core/02_FL_GameUtilities.md b/docs/blueprints/01-core/02_FL_GameUtilities.md index 649dc6c..6b213c2 100644 --- a/docs/blueprints/01-core/02_FL_GameUtilities.md +++ b/docs/blueprints/01-core/02_FL_GameUtilities.md @@ -137,4 +137,14 @@ All functions can be called from Construction Scripts since they are pure (no wo 2. `GetSubsystemSafe` returns `None` instead of crashing when a subsystem doesn't exist. 3. `FormatTime(3661.0)` returns `01:01:01`. 4. `LogDebug` prints to both the output log and the viewport in editor builds. -5. `LogDebug` produces no output in a shipping build. \ No newline at end of file +5. `LogDebug` produces no output in a shipping build. + +--- + +## Multiplayer Networking + +**Replication: None needed.** This is a static BlueprintFunctionLibrary with no state. All functions are callable from any Blueprint on any side (client or server). + +**Authority: N/A.** Functions are context-free. World-context operations work identically on server and client. + +**Note:** `GetSubsystemSafe()` returns local subsystems. On clients, only client-side subsystems are available. Never rely on a server-only subsystem being available on a client. \ No newline at end of file diff --git a/docs/blueprints/01-core/03_I_InterfaceLibrary.md b/docs/blueprints/01-core/03_I_InterfaceLibrary.md index 8f901fa..f9bdc19 100644 --- a/docs/blueprints/01-core/03_I_InterfaceLibrary.md +++ b/docs/blueprints/01-core/03_I_InterfaceLibrary.md @@ -393,4 +393,22 @@ Objects with continuous adjustment values rather than binary states. Pressure va 2. An actor with [`I_Persistable`] saves and restores its state correctly through the save system. 3. An actor can implement multiple interfaces simultaneously without conflicts. 4. Calling an interface function on an actor that doesn't implement it safely returns the default value (no crash). -5. All interface functions are accessible via the Blueprint node context menu under their category name. \ No newline at end of file +5. All interface functions are accessible via the Blueprint node context menu under their category name. + +--- + +## Multiplayer Networking + +**Replication: None needed.** Interfaces are communication contracts — they define function signatures, not data. Interface calls work identically on client and server. + +**Key Rule:** When calling an interface function that modifies state (e.g. `I_Interactable.Execute_OnInteract`), the caller must either: +- Be on the server (HasAuthority check), OR +- Call through a `Server_` RPC wrapper that validates and executes the interface function server-side + +**Example:** +``` +Client calls: Server_Interact(TargetActor) + → Server validates range, conditions + → Server calls: I_Interactable.Execute_OnInteract(TargetActor) + → State changes replicate back via RepNotify +``` \ No newline at end of file diff --git a/docs/blueprints/01-core/04_GI_GameFramework.md b/docs/blueprints/01-core/04_GI_GameFramework.md index 2e57672..7282e9f 100644 --- a/docs/blueprints/01-core/04_GI_GameFramework.md +++ b/docs/blueprints/01-core/04_GI_GameFramework.md @@ -214,4 +214,45 @@ flowchart TD - Add new subsystems to the init list; they are auto-initialized by UE's GameInstanceSubsystem system. - The `SessionFlags` map lets you add per-project transient state without modifying this class. - For multi-world / split-screen, treat this as a single-instance singleton per application session. -- `PlatformType` can be overridden via command-line switch `-Platform=Steam` in packaging scripts. \ No newline at end of file +- `PlatformType` can be overridden via command-line switch `-Platform=Steam` in packaging scripts. + +--- + +## 11. Multiplayer Networking + +### Replicated Variables + +| Variable | Type | Condition | Description | +|----------|------|-----------|-------------| +| `CurrentGamePhase` | `E_GamePhase` | `Replicated Using OnRep_GamePhase` | Replicated phase; OnRep fires dispatcher for all clients | +| `ActiveSaveSlotIndex` | `Integer` | `Replicated` | Synced save slot | +| `PlatformType` | `E_PlatformType` | `Replicated` | Platform info for cross-play filtering | + +### Authority Notes + +| Function | Authority | Notes | +|----------|-----------|-------| +| `SetGamePhase` | `Server` | Clients cannot change game phase. OnRep broadcasts to all. | +| `SetSessionFlag` | `Server` | Session flags are server-authoritative. | +| `GetSubsystem` | `Any` | Read-only — safe for clients. Returns subsystems that exist per-side. | +| `InitPlatformServices` | `Any` | Runs on each instance; platform type synced. | + +### Server RPCs + +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_SetGamePhase` | Client→Server | Client requests phase change (e.g. player pauses). Server validates and sets. | + +### Client Prediction + +- GamePhase transitions are server-authoritative with no client prediction. +- Clients bind to `OnGamePhaseChanged` dispatcher (fired by `OnRep_GamePhase`) — same as single-player. +- `SessionFlags` are not predicted; clients read after server sets them. + +### OnRep Handlers + +``` +OnRep_GamePhase(NewPhase) + → Broadcast OnGamePhaseChanged(NewPhase) + → All systems react exactly as in single-player +``` \ No newline at end of file diff --git a/docs/blueprints/01-core/05_GM_CoreGameMode.md b/docs/blueprints/01-core/05_GM_CoreGameMode.md index e06da39..8430a31 100644 --- a/docs/blueprints/01-core/05_GM_CoreGameMode.md +++ b/docs/blueprints/01-core/05_GM_CoreGameMode.md @@ -178,4 +178,43 @@ flowchart TD - **`TriggerEnding`** is the only project-specific hook — override to handle unique ending sequences - **`bPauseAllowed`** can be extended to a tag-based system for finer control - For multiplayer, extend to derive from a replicated GameMode base -- The entire class is project-agnostic — drop into any UE5 project and configure class references \ No newline at end of file +- The entire class is project-agnostic — drop into any UE5 project and configure class references + +--- + +## Multiplayer Networking + +### Parent Class +Derive from `GameMode` (not `GameModeBase`) in multiplayer. `GameMode` is replicated — `GameModeBase` is not. All default class references and spawn logic remain identical. + +### Replicated Variables +| Variable | Type | Condition | Description | +|----------|------|-----------|-------------| +| `CurrentChapterTag` | `GameplayTag` | `Replicated Using OnRep_ChapterTag` | Synced chapter for all clients | +| `bPauseAllowed` | `Boolean` | `Replicated` | Whether pause is permitted | + +### Authority Notes +| Function | Authority | Notes | +|----------|-----------|-------| +| `TransitionToChapter` | `Server` | Chapter transitions are server-only. OnRep syncs chapter tag to clients. | +| `HandlePlayerDead` | `Server` | Death is server-authoritative. Routes respawn or game-over. | +| `SetPauseAllowed` | `Server` | Pause permission is server-controlled. | +| `TriggerGameOver` | `Server` | Game-over sequence runs on server. | +| `TriggerEnding` | `Server` | Ending determination is server-authoritative. | + +### Server RPCs +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_PauseRequest` | Client→Server | Client requests pause. Server checks `bPauseAllowed`, pauses if permitted. | + +### Client Prediction +- Chapter transitions: no client prediction — loading screen runs on all clients. +- Death routing: clients see death animation via multicast; respawn is server-driven. +- Pause: server-authoritative with client request. + +### OnRep Handlers +``` +OnRep_ChapterTag(NewTag) + → Update GS_CoreGameState.ActiveChapterTag + → Broadcast OnChapterTransition +``` \ No newline at end of file diff --git a/docs/blueprints/01-core/06_GS_CoreGameState.md b/docs/blueprints/01-core/06_GS_CoreGameState.md index de44d66..d34e81e 100644 --- a/docs/blueprints/01-core/06_GS_CoreGameState.md +++ b/docs/blueprints/01-core/06_GS_CoreGameState.md @@ -267,4 +267,46 @@ flowchart TD --- +## 11. Multiplayer Networking + +### Full Replication Map + +All 5 state variables are replicated with `OnRep` handlers. GS_CoreGameState is the **primary replicated state bus** — every system that needs shared state writes through this object. + +| Variable | Replication | OnRep Handler | Writer (Authority) | Consumer | +|----------|-------------|---------------|---------------------|----------| +| `ElapsedPlayTime` | `Replicated Using` | `OnRep_ElapsedPlayTime` → dispatcher | Tick (server-only) | RunHistoryTracker, HUD | +| `ActiveChapterTag` | `Replicated Using` | `OnRep_ActiveChapterTag` → dispatcher | GM_CoreGameMode | NarrativeSystem, HUD | +| `ActiveNarrativePhase` | `Replicated Using` | `OnRep_ActiveNarrativePhase` → dispatcher | BPC_NarrativeStateSystem | UI, narrative triggers | +| `bEncounterActive` | `Replicated Using` | `OnRep_EncounterActive` → dispatcher | BPC_EncounterDirector | HUD, atmosphere controller | +| `ActiveObjectiveTags` | `Replicated Using` | `OnRep_ActiveObjectiveTags` → dispatcher | BPC_ObjectiveSystem | WBP_ObjectiveDisplay, journal | + +### Authority Notes + +- **All setter functions are Server-only.** Call with `HasAuthority()` check. +- **All getter functions are Any.** Clients can read replicated state freely. +- **OnRep fires dispatcher** — consumers bind to dispatcher, not variable. Identical SP/MP code path. +- **Tick accumulation** is server-only (ElapsedPlayTime). Clients receive time via OnRep. + +### Server RPCs (None) + +GS_CoreGameState is a passive state bus. Clients never call RPCs on it directly — they call RPCs on the systems that write to it (e.g. `BPC_ObjectiveSystem.Server_CompleteObjective`). + +### Multicast Events (None) + +All state changes replicate via standard variable replication + OnRep dispatcher. No separate multicast needed. + +### Cross-System Flow (Multiplayer) +``` +Client: Player completes objective + → Server_CompleteObjective RPC on BPC_ObjectiveSystem + → Server validates completion conditions + → Server calls GS_CoreGameState.RemoveActiveObjectiveTag + → Variable replicates to all clients + → OnRep_ActiveObjectiveTags fires OnObjectiveTagsChanged + → WBP_ObjectiveDisplay (local per-client) refreshes +``` + +--- + *Blueprint Spec v1.0 — GS_CoreGameState for UE5.5-5.7* \ No newline at end of file diff --git a/docs/blueprints/01-core/07_DA_ItemData.md b/docs/blueprints/01-core/07_DA_ItemData.md index a257d19..c474fc4 100644 --- a/docs/blueprints/01-core/07_DA_ItemData.md +++ b/docs/blueprints/01-core/07_DA_ItemData.md @@ -182,4 +182,12 @@ flowchart LR --- +## Multiplayer Networking + +**Replication: None needed.** `DA_ItemData` is a PrimaryDataAsset — read-only configuration loaded identically on all clients. No runtime state. + +**Authority: N/A.** All clients load the same asset data from disk. Inventory operations that reference item data are server-authoritative (see `BPC_InventorySystem`). + +--- + *Blueprint Spec v1.0 — DA_ItemData for UE5.5-5.7* \ No newline at end of file diff --git a/docs/blueprints/02-player/08_BPC_HealthSystem.md b/docs/blueprints/02-player/08_BPC_HealthSystem.md index 369bb4f..4615b85 100644 --- a/docs/blueprints/02-player/08_BPC_HealthSystem.md +++ b/docs/blueprints/02-player/08_BPC_HealthSystem.md @@ -337,4 +337,70 @@ flowchart TD --- +## 11. Multiplayer Networking (Expanded) + +### Replicated Variables (Existing + New) + +| Variable | Type | Condition | Description | +|----------|------|-----------|-------------| +| `CurrentHealth` | `Float` | `Replicated Using OnRep_CurrentHealth` | Clients sync via OnRep → dispatcher | +| `DeathState` | `E_DeathState` | `Replicated Using OnRep_DeathState` | Death state synced; OnRep triggers death effects | +| `bIsInvincible` | `Boolean` | `Replicated` | Invincibility visible to other players | +| `MaxHealth` | `Float` | `Replicated` | Synced for UI percentage calculations | + +### Server RPCs + +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_ApplyDamage` | Client→Server | Client reports taking damage. Server validates source, range, damage type. | +| `Server_ApplyHealing` | Client→Server | Client requests healing. Server validates heal source, applies. | +| `Server_KillInstant` | Client→Server | Only accepted from authoritative sources (GM, traps). Client calls are rejected. | + +### Authority Gates + +``` +Function ApplyDamage(DamageEvent) + Switch HasAuthority + Authority: + → Calculate resistance, apply damage, fire dispatchers + Remote: + → Return (clients never modify health directly) + → Server_ApplyDamage is called by damage source (weapon/trap), not victim + +Function ApplyHealing(HealAmount) + Switch HasAuthority + Authority: + → Apply healing, fire dispatchers + Remote: + → Return + → Consumable use calls Server_UseConsumable → server calls ApplyHealing +``` + +### Client Prediction + +- **Health bar:** Client predicts damage flash on hit; server-corrected value arrives via `OnRep_CurrentHealth`. +- **Death:** No prediction. `OnRep_DeathState` triggers all death effects (screen fade, ragdoll). +- **Healing:** Client shows green flash immediately + predicted health; server corrects within one RTT. +- **Invincibility:** Visual effect (shield shimmer) is local cosmetic; state is replicated. + +### OnRep Handlers + +``` +OnRep_CurrentHealth() + → Broadcast OnHealthChanged(OldHealth, CurrentHealth, Delta) + → UI updates identically to single-player path + +OnRep_DeathState() + → Broadcast OnDeathStateChanged(OldState, NewState) + → If Dead: play death animation, screen effects, notify GM +``` + +### Anti-Cheat + +- Server validates all `Server_ApplyDamage` calls: check instigator range, weapon fire rate, damage type validity. +- Server never trusts `DamageEvent.BaseAmount` from client — always recalculates from weapon data. +- `Server_KillInstant` is only callable from server-authoritative systems (traps, death zones, GM). + +--- + *Blueprint Spec: Health System. Conforms to TEMPLATE.md v1.0 — part of the UE5 Modular Game Framework.* \ No newline at end of file diff --git a/docs/blueprints/02-player/09_BPC_StaminaSystem.md b/docs/blueprints/02-player/09_BPC_StaminaSystem.md index 9d46d81..0acdcab 100644 --- a/docs/blueprints/02-player/09_BPC_StaminaSystem.md +++ b/docs/blueprints/02-player/09_BPC_StaminaSystem.md @@ -326,6 +326,41 @@ flowchart TD - The drain rate map supports runtime modification for buffs/debuffs (e.g. Adrenaline reduces sprint cost). - UI widgets should bind to OnStaminaChanged for smooth bar animation, not tick polling. - For multiplayer: Server authorises all DrainStamina calls; client predicts and corrects on repnotify. + +--- + +## 11. Multiplayer Networking (Expanded) + +### Server RPCs + +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_DrainStamina` | Client→Server | Client requests stamina drain for action. Server validates MinStamina, applies. | +| `Server_StartContinuousDrain` | Client→Server | Client starts sprinting. Server begins drain timer. | +| `Server_StopContinuousDrain` | Client→Server | Client stops sprinting. Server stops drain, begins regen. | +| `Server_RestoreStamina` | Client→Server | Client uses stamina item. Server validates item, applies restore. | + +### Authority Gates + +``` +Function DrainStamina(ActionType) + If HasAuthority: + → Check cooldown, MinStamina + → Apply drain, update exhaustion, fire dispatchers + Else: + → Client predicts stamina bar decrease for responsiveness + → Server_ RPC called; server corrects via OnRep if wrong + +Function SetMaxStamina(NewMax, bMaintainRatio) + If NOT HasAuthority → Return + → Apply change, fire dispatchers, auto-replicates +``` + +### Client Prediction + +- **Stamina bar:** Client predicts decrease on sprint/jump. Server corrects via `OnRep_CurrentStamina`. +- **Exhaustion:** ExhaustionState replicated. Client plays breathing audio locally. +- **Cooldowns:** Server-authoritative. Client shows cooldown timer after server confirms action. - Exhaustion state can drive conditional audio: heavy breathing, heart-beat, fatigue voice lines. --- diff --git a/docs/blueprints/02-player/10_BPC_StressSystem.md b/docs/blueprints/02-player/10_BPC_StressSystem.md index c9fe888..d8e1920 100644 --- a/docs/blueprints/02-player/10_BPC_StressSystem.md +++ b/docs/blueprints/02-player/10_BPC_StressSystem.md @@ -337,6 +337,28 @@ flowchart TD - Stress tiers can gate narrative content — questgivers behave differently based on player stress. - Hallucination types can be configured via Data Asset (DA_HallucinationConfig). - For multiplayer: Stress is server-authoritative; clients receive tier changes for local effects. + +--- + +## 11. Multiplayer Networking (Expanded) + +### Server RPCs +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_AddStress` | Client→Server | Client reports stress event. Server validates source, applies. | +| `Server_AddStressSource` | Client→Server | Client enters enemy proximity zone. Server adds/updates source. | +| `Server_RemoveStressSource` | Client→Server | Client leaves enemy zone. Server removes source. | +| `Server_SetSafeZone` | Client→Server | Client reports safe zone status. Server validates, applies decay. | + +### Authority +- **Server** calculates total stress from all sources, updates tier, replicates. +- **Client** plays local hallucination/audio effects based on replicated tier. +- `ForcePanic()` is server-only (narrative system calls it directly on server). + +### Client Prediction +- Stress bar: predicted on client, corrected by `OnRep_CurrentStress`. +- Hallucinations: randomly triggered by client based on replicated tier (cosmetic only). +- Safe zone: server-authoritative; clients see OnSafeZoneChanged dispatcher. - The HealthDeficitMultiplier creates a death spiral feel — use carefully for horror pacing. - Safe zones double as narrative checkpoints and stress recovery areas. diff --git a/docs/blueprints/02-player/11_BPC_MovementStateSystem.md b/docs/blueprints/02-player/11_BPC_MovementStateSystem.md index b90e4b6..8de18f4 100644 --- a/docs/blueprints/02-player/11_BPC_MovementStateSystem.md +++ b/docs/blueprints/02-player/11_BPC_MovementStateSystem.md @@ -320,4 +320,33 @@ flowchart TD --- +## 11. Multiplayer Networking (Expanded) + +### Replication +Movement state is natively handled by `CharacterMovementComponent` replication. `BPC_MovementStateSystem` replicates state enums for non-movement consumers (UI, camera, audio). + +| Variable | Condition | Notes | +|----------|-----------|-------| +| `CurrentPosture` | `Replicated Using OnRep_Posture` | Synced posture for other players' animation | +| `CurrentMovementMode` | `Replicated Using OnRep_MovementMode` | Synced mode for audio/camera systems | +| CMC velocity | Native replication | Position/velocity handled by CharacterMovementComponent | + +### Server RPCs +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_SetMovementMode` | Client→Server | Client requests mode change. Server validates against MovementSettings. | +| `Server_SetPosture` | Client→Server | Client requests posture change. Server validates ceiling clearance. | +| `Server_SetSprinting` | Client→Server | Client toggles sprint. Server checks stamina before authorizing. | + +### Authority +- `SetMovementMode` and `SetPosture` check `HasAuthority()` before modifying state. +- Movement penalties (`ApplyMovementPenalty`) are server-authoritative. +- `CanTransitionToPosture` is read-only; clients can call for local prediction. + +### Client Prediction +- Posture/mode transitions: client predicts movement locally; server validates. +- Footstep sounds: local calculation based on replicated state. + +--- + *Blueprint Spec: Movement State System. Conforms to TEMPLATE.md v1.0 — part of the UE5 Modular Game Framework.* \ No newline at end of file diff --git a/docs/blueprints/02-player/12_BPC_HidingSystem.md b/docs/blueprints/02-player/12_BPC_HidingSystem.md index 4555e54..c9b15c4 100644 --- a/docs/blueprints/02-player/12_BPC_HidingSystem.md +++ b/docs/blueprints/02-player/12_BPC_HidingSystem.md @@ -321,6 +321,30 @@ flowchart TD - The LOS trace channel should be custom (e.g., DetectionChannel) to ignore small props. - Breath-hold mechanic adds depth to stealth gameplay near enemies. - For multiplayer: only the hiding player knows their state; other players see a generic "occupado" on the spot. + +--- + +## 11. Multiplayer Networking (Expanded) + +### Server RPCs +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_EnterHideSpot` | Client→Server | Client requests entering hide spot. Server validates slot availability, proximity. | +| `Server_ExitHideSpot` | Client→Server | Client requests exiting. Server validates, teleports player, replicates. | +| `Server_StartPeek` | Client→Server | Client starts peeking. Server validates peek ability, starts duration timer. | +| `Server_StopPeek` | Client→Server | Client stops peeking. Server returns to Hidden state. | +| `Server_TryBreathHold` | Client→Server | Client holds breath. Server validates, applies noise reduction on server. | + +### Authority +- `EnterHideSpot`, `ExitHideSpot` are server-authoritative. +- `IsPlayerDetectable` is server-only — AI runs on server. +- `PerformLOSCheck` runs on server; results multicast to clients for UI feedback. +- `ForceKickFromHide` is server-only (triggered by enemy discovery / damage). + +### Client Prediction +- Enter/exit animations: client predicts; server confirms via replicated `CurrentHideState`. +- Peek: camera offset is local; state replicated. +- Hide spot occupation: `I_HidingSpot.OccupantPawn` is replicated — other clients see "Occupied". - Hide spots with bBlocksStress = true can double as narrative safe rooms. --- diff --git a/docs/blueprints/02-player/13_BPC_EmbodimentSystem.md b/docs/blueprints/02-player/13_BPC_EmbodimentSystem.md index ba7ce6e..841c3ca 100644 --- a/docs/blueprints/02-player/13_BPC_EmbodimentSystem.md +++ b/docs/blueprints/02-player/13_BPC_EmbodimentSystem.md @@ -255,4 +255,21 @@ flowchart TD --- +## 11. Multiplayer Networking + +**Replication: Minimal.** Embodiment is primarily local rendering. Only visibility mode and overlay state sync for shared visual consistency. + +| Variable | Condition | Purpose | +|----------|-----------|---------| +| `CurrentVisibility` | `Replicated` | Other clients see correct body visibility (FullBody in mirrors/death) | +| `CurrentOverlay` | `Replicated` | Blood/water visible to other players | +| Arms IK, wall proximity, overlay blending | **Local only** | First-person rendering is per-client | + +### Authority +- `SetVisibilityMode` is server-authoritative for replicated variable; client applies local mesh changes. +- `ApplyOverlay` and `ClearOverlay` are server-authoritative. +- `CheckWallProximity` and `ApplyOverlayBlendTick` are **local only**. + +--- + *Blueprint Spec: Embodiment System. Conforms to TEMPLATE.md v1.0 — part of the UE5 Modular Game Framework.* \ No newline at end of file diff --git a/docs/blueprints/02-player/14_BPC_CameraStateLayer.md b/docs/blueprints/02-player/14_BPC_CameraStateLayer.md index ac36020..6399dfb 100644 --- a/docs/blueprints/02-player/14_BPC_CameraStateLayer.md +++ b/docs/blueprints/02-player/14_BPC_CameraStateLayer.md @@ -326,4 +326,22 @@ flowchart TD --- +## 11. Multiplayer Networking + +**Replication: State only — effects are local.** Camera FOV blending, shake, and post-processing are per-client experiences. Only the state enum syncs. + +| Variable | Condition | Purpose | +|----------|-----------|---------| +| `CurrentCameraState` | `Replicated` | Synced for shared context (e.g., all players know someone is aiming) | + +### Authority +- `RequestCameraState` can be called by client; state replicates to all. +- `PlayCameraShake`, `ApplyPostProcessOverride`, `BlendToTargetFOV` are **local only**. +- FOV pulse, head bob, camera offset blending are **local only**. + +### Client Prediction +- Camera is inherently local — no prediction needed. State changes replicate for other players' awareness. + +--- + *Blueprint Spec: Camera State Layer. Conforms to TEMPLATE.md v1.0 — part of the UE5 Modular Game Framework.* \ No newline at end of file diff --git a/docs/blueprints/02-player/15_BPC_PlayerMetricsTracker.md b/docs/blueprints/02-player/15_BPC_PlayerMetricsTracker.md index 978eb7f..af2230e 100644 --- a/docs/blueprints/02-player/15_BPC_PlayerMetricsTracker.md +++ b/docs/blueprints/02-player/15_BPC_PlayerMetricsTracker.md @@ -332,4 +332,26 @@ flowchart TD --- +## 11. Multiplayer Networking + +### Replication +| Variable | Condition | Purpose | +|----------|-----------|---------| +| `CurrentSnapshot` | `Replicated` | Synced for scoreboard, playstyle classification | + +### Authority +- **Server** accumulates all metrics (listens to gameplay dispatchers server-side). +- **Server** creates periodic snapshots and replicates. +- **Clients** only read metrics (for local HUD/scoreboard display). + +### Server RPCs +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_LogEvent` | Client→Server | Client reports a metric event. Server validates before recording. | + +### Anti-Cheat +- Server validates `Server_LogEvent` calls: damage dealt must match server calculations, distance traveled must be plausible, item pickups validated by inventory system. + +--- + *Blueprint Spec: Player Metrics Tracker. Conforms to TEMPLATE.md v1.0 — part of the UE5 Modular Game Framework.* \ No newline at end of file diff --git a/docs/blueprints/03-interaction/16_BPC_InteractionDetector.md b/docs/blueprints/03-interaction/16_BPC_InteractionDetector.md index e74f6d5..8222e72 100644 --- a/docs/blueprints/03-interaction/16_BPC_InteractionDetector.md +++ b/docs/blueprints/03-interaction/16_BPC_InteractionDetector.md @@ -379,4 +379,29 @@ flowchart TD --- +## 11. Multiplayer Networking (Expanded) + +### Replication +| Variable | Condition | Purpose | +|----------|-----------|---------| +| `CurrentTarget` | `Replicated` | Synced target for UI (other players see what you're looking at) | + +### Server RPCs +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_PerformInteraction` | Client→Server | Client requests interaction. Server validates range, conditions, then calls I_Interactable. | + +### Authority +- **Detection** (trace, sorting, target selection): runs locally per client. +- **Interaction execution**: server-authoritative. Client calls `Server_PerformInteraction`; server validates and executes. +- `ForceSetTarget`: server-only for scripted interactions. +- `HighlightTarget`: local cosmetic effect per client. + +### Client Prediction +- Interaction prompt: shown immediately based on local trace. +- Hold progress: shown locally; server confirms completion. +- Blocked feedback: shown locally if conditions fail client-side; server may also reject. + +--- + *Blueprint Spec: Interaction Detector. Conforms to TEMPLATE.md v1.0 — part of the UE5 Modular Game Framework.* \ No newline at end of file diff --git a/docs/blueprints/03-interaction/17_I_HidingSpot.md b/docs/blueprints/03-interaction/17_I_HidingSpot.md index 1fe2c3a..1e220f6 100644 --- a/docs/blueprints/03-interaction/17_I_HidingSpot.md +++ b/docs/blueprints/03-interaction/17_I_HidingSpot.md @@ -283,4 +283,26 @@ sequenceDiagram --- +## 10. Multiplayer Networking + +### Replicated Variables +| Variable | Condition | Purpose | +|----------|-----------|---------| +| `bOccupied` | `Replicated` | Other clients see spot as occupied | +| `LockedByPlayer` | `Replicated` | Synced lock state | +| `OccupantPawn` | `Replicated` | Who is hiding here (for third-person visibility) | +| `bIsVisible` | `Replicated` | Spot availability synced | + +### Authority +- `OnPlayerEntered`/`OnPlayerExited` are called by the server-authoritative `BPC_HidingSystem`. +- `LockSpot`/`UnlockSpot` are server-only. +- `GetOccupancyStatus` is read-only, safe for any side. + +### Server RPCs +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_ClaimSpot` | Client→Server | Client requests occupying spot. Server validates availability. | + +--- + *Blueprint Spec: Hiding Spot Interface & Actor. Conforms to TEMPLATE.md v1.0 — part of the UE5 Modular Game Framework.* \ No newline at end of file diff --git a/docs/blueprints/03-interaction/19_BP_DoorActor.md b/docs/blueprints/03-interaction/19_BP_DoorActor.md index c493f16..985ebdd 100644 --- a/docs/blueprints/03-interaction/19_BP_DoorActor.md +++ b/docs/blueprints/03-interaction/19_BP_DoorActor.md @@ -336,4 +336,38 @@ Player Presses Interact - This renamed file (formerly `BPC_InteractableDoorComponent`) is now an Actor-based system (`BP_DoorActor`) as per Master Section 3.5. - The door actor encapsulates all door logic directly rather than as an ActorComponent. -- Cross-references updated: `BPC_InventoryComponent` → `BPC_InventorySystem`, `BPC_LeverPuzzleComponent` → `BP_PuzzleDeviceActor`. \ No newline at end of file +- Cross-references updated: `BPC_InventoryComponent` → `BPC_InventorySystem`, `BPC_LeverPuzzleComponent` → `BP_PuzzleDeviceActor`. + +--- + +## 13. Multiplayer Networking (Expanded) + +### Server RPCs + +| RPC | Direction | Description | +|-----|-----------|-------------| +| `Server_Interact` | Client→Server | Client requests door interaction. Server validates range, state, lock, then executes TryOpen/TryClose. | +| `Server_DamageBarricade` | Client→Server | Client deals damage to barricade. Server validates damage source, applies to barricade health. | +| `Server_TryUnlock` | Client→Server | Client attempts unlock with key item. Server validates inventory, consumes item if configured. | + +### Authority Gates + +``` +Interact_Implementation + If NOT HasAuthority: + → Call Server_Interact(DoorActor) + → Return (client prediction: show prompt, wait for OnRep) + // Server executes authoritative logic + → TryOpen / TryClose / TryUnlock + → OnRep broadcasts to all clients +``` + +### Client Prediction +- **Interaction:** Client calls `Server_Interact` RPC; server validates and changes state. +- **Animation:** `OnRep_DoorState` triggers animation on all clients identically. +- **Locked feedback:** Played locally by client when server rejects interaction. + +### Anti-Cheat +- Server validates player is within interaction range before opening door. +- Server validates key item is in player inventory before unlocking. +- Server validates barricade damage source. \ No newline at end of file diff --git a/docs/blueprints/INDEX.md b/docs/blueprints/INDEX.md index 93dd7f6..cbea798 100644 --- a/docs/blueprints/INDEX.md +++ b/docs/blueprints/INDEX.md @@ -301,4 +301,10 @@ Below are the most cross-referenced systems — these are the ones the State Man --- -*Master Blueprint Index v3.0 — The single reference document for every file in the framework. Now 135 files with State Management + MetaSounds Audio systems.* +*Master Blueprint Index v3.1 — The single reference document for every file in the framework. Now 135 files with State Management, MetaSounds Audio, and Multiplayer Networking support.* + +--- + +## Multiplayer Networking + +See [`docs/architecture/multiplayer-networking.md`](../architecture/multiplayer-networking.md) for the full networking architecture specification. All blueprint specs include replication stubs, Server RPCs, and authority patterns. Developer docs include Multiplayer Networking sections per category. diff --git a/docs/developer/01-core-foundation.md b/docs/developer/01-core-foundation.md index 74f0c8d..5dbc69a 100644 --- a/docs/developer/01-core-foundation.md +++ b/docs/developer/01-core-foundation.md @@ -377,4 +377,28 @@ MainMenu → Loading → InGame ⇄ Paused --- +## Multiplayer Networking + +### Category Authority Map +| System | Role | Authority | +|--------|------|-----------| +| `GI_GameFramework` | GamePhase, session flags | Server sets; clients read via replicated dispatcher | +| `GM_CoreGameMode` | Player spawning, chapter transitions, death routing | Server-only (extends replicated GameMode) | +| `GS_CoreGameState` | Shared session state bus | **Fully replicated** — 5 vars with OnRep handlers | +| `GI_GameTagRegistry` | Tag documentation | Read-only config — identical on all clients | +| `FL_GameUtilities` | Static utilities | No state — callable from any side | +| `I_InterfaceLibrary` | Communication contracts | Interface calls work on any side; mutators must check authority | +| `DA_ItemData` | Item definitions | Read-only Data Asset — identical on all clients | + +### Key Patterns +- **GS_CoreGameState as Replication Hub:** All shared session state (chapter, phase, objectives, encounter status) writes through GS_CoreGameState which auto-replicates to all clients via OnRep → dispatcher. +- **GamePhase transitions are server-authoritative:** `SetGamePhase()` checks `HasAuthority()`. Clients receive phase changes via `OnRep_GamePhase` → `OnGamePhaseChanged` dispatcher. +- **Interface calls route through server:** `I_Interactable.Execute_OnInteract` must be called server-side. Clients call `Server_Interact` RPC → server validates → calls interface. +- **Data Assets are client-ready:** All `DA_*` assets load identically on all instances from disk. No replication needed. + +### Full Spec +See [`docs/architecture/multiplayer-networking.md`](../architecture/multiplayer-networking.md) Section 3.1. + +--- + *Developer Reference v1.0 — 01 Core Foundation Systems. Companion to docs/blueprints/01-core/ specs.* diff --git a/docs/developer/02-player-systems.md b/docs/developer/02-player-systems.md index e33b80f..201aa7f 100644 --- a/docs/developer/02-player-systems.md +++ b/docs/developer/02-player-systems.md @@ -453,4 +453,33 @@ Exposed → Entering → Hidden ⇄ Peeking → Exiting → Exposed --- +## Multiplayer Networking + +### Category Authority Map +| System | Authority Pattern | Client Prediction | +|--------|------------------|-------------------| +| `BPC_HealthSystem` | Server-authoritative damage/healing/death | Client predicts damage flash; server corrects health via OnRep | +| `BPC_StaminaSystem` | Server-authoritative drain/restore | Client predicts bar decrease; server corrects via OnRep | +| `BPC_StressSystem` | Server-authoritative stress accumulation | Client plays local hallucinations; server is canonical | +| `BPC_MovementStateSystem` | Server-authoritative mode/posture | Native CMC replication handles position/velocity | +| `BPC_HidingSystem` | Server-authoritative enter/exit/peek | Client predicts animation; server validates slot availability | +| `BPC_EmbodimentSystem` | Minimal — visibility/overlay state only synced | Rendering is local per-client | +| `BPC_CameraStateLayer` | State enum only synced | FOV, shake, post-process are local per-client | +| `BPC_PlayerMetricsTracker` | Server accumulates; snapshot replicates | No client prediction needed | + +### Key Server RPCs +- `Server_ApplyDamage` / `Server_ApplyHealing` — validated by server before health modification +- `Server_DrainStamina` / `Server_StartContinuousDrain` — validated against MinStamina thresholds +- `Server_AddStress` / `Server_AddStressSource` — stress sources validated server-side +- `Server_SetMovementMode` / `Server_SetPosture` — validated against MovementSettings +- `Server_EnterHideSpot` / `Server_ExitHideSpot` — validated against slot availability + +### Multiplayer Cascade +The cascade (Health→Stress→Camera→Movement) works identically in multiplayer because each system fires the same dispatchers regardless of whether the state change came from local mutation or `OnRep`. No special-case multiplayer code needed in the cascade chain. + +### Full Spec +See [`docs/architecture/multiplayer-networking.md`](../architecture/multiplayer-networking.md) Section 3.2. + +--- + *Developer Reference v1.0 — 02 Player Systems. Companion to docs/blueprints/02-player/ specs.* diff --git a/docs/developer/03-interaction-systems.md b/docs/developer/03-interaction-systems.md index 8de802b..679cd33 100644 --- a/docs/developer/03-interaction-systems.md +++ b/docs/developer/03-interaction-systems.md @@ -241,4 +241,31 @@ Barricaded → (break) → Closed --- +## Multiplayer Networking + +### Category Authority Map +| System | Authority | Client Request Pattern | +|--------|-----------|----------------------| +| `BPC_InteractionDetector` | Detection runs locally; interaction validated by server | `Server_PerformInteraction` RPC | +| `BP_DoorActor` | Server-authoritative state machine | `Server_Interact` → server validates → OnRep animates | +| `BP_PuzzleDeviceActor` | Server-authoritative | `Server_TrySolution` RPC | +| `BPC_ContextualTraversalSystem` | Client-predicted movement | Server validates traversal target | +| `BPC_PhysicsDragSystem` | Client-predicted physics | Server periodically corrects position | +| `BPC_UsableWorldObjectSystem` | Server-authoritative toggle/adjust | `Server_Use` RPC | + +### Interaction Flow (Multiplayer) +``` +Client looks at door → local trace detects it → shows "Press E" +Client presses E → calls Server_Interact(DoorActor) +Server: validates range, door state, lock + → If valid: door state changes → RepNotify broadcasts + → All clients: OnRep plays door animation + → If locked: server rejects, Client_ShowError RPC to requesting client +``` + +### Full Spec +See [`docs/architecture/multiplayer-networking.md`](../architecture/multiplayer-networking.md) Section 3.3. + +--- + *Developer Reference v1.0 — 03 Interaction Systems. Companion to docs/blueprints/03-interaction/ specs.* diff --git a/docs/developer/04-inventory-systems.md b/docs/developer/04-inventory-systems.md index 00f13f6..6f7a2b8 100644 --- a/docs/developer/04-inventory-systems.md +++ b/docs/developer/04-inventory-systems.md @@ -240,4 +240,29 @@ --- +## Multiplayer Networking + +### Category Authority Map +| 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, 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 | + +### Server RPCs +- `Server_AddItem`, `Server_RemoveItem`, `Server_UseItem`, `Server_DropItem`, `Server_TransferItem` +- `Server_EquipItem`, `Server_UnequipItem` +- `Server_LootContainer`, `Server_PickupItem` + +### Inventory Replication Strategy +- **Slots array** replicated with `OnRep_Slots` → recalculates weight, fires `OnInventoryChanged` +- **Client predicts UI** (item moves visually on drag-drop); server validates and corrects via OnRep +- **Server validates all transactions** against slot space, weight capacity, stack limits, and category restrictions +- **Cooldowns** managed locally (not replicated) but validated on server for authoritative actions + +--- + *Developer Reference v1.0 — 04 Inventory Systems. Companion to docs/blueprints/04-inventory/ specs.* diff --git a/docs/developer/05-saveload-systems.md b/docs/developer/05-saveload-systems.md index 68aa3e8..4b8f17e 100644 --- a/docs/developer/05-saveload-systems.md +++ b/docs/developer/05-saveload-systems.md @@ -184,3 +184,24 @@ --- *Developer Reference v1.0 — 05 Save/Load Systems. Companion to docs/blueprints/05-saveload/ specs.* + +--- + +## Multiplayer Networking + +### Category Authority Map +| System | Authority | Notes | +|--------|-----------|-------| +| `SS_SaveManager` | Server triggers save/load | Clients receive restored state via GS_CoreGameState replication | +| `BP_Checkpoint` | Server validates activation | Active checkpoint replicates to all | +| `BPC_DeathHandlingSystem` | Server determines death outcome | Death animation multicast; respawn is server-driven | +| `BPC_PlayerRespawnSystem` | Server executes respawn | Client receives respawn state via replication | +| `BPC_PersistentCorpseSystem` | Server spawns corpse actor | Corpse replicated to all clients | +| `BPC_PersistentWorldStateRecorder` | Server records changes | State changes replicated via individual actor RepNotify | +| `BPC_RunHistoryTracker` | Server tracks; snapshot replicates | For scoreboard display | + +### Key Multiplayer Considerations +- **Save/Load is server-coordinated.** Only server triggers save/load. Clients receive restored state via GS_CoreGameState and actor replication. +- **Death is server-authoritative.** Runs on server, determines outcome, multicasts death events. +- **Alt Death Space** (separate level): server calls `ClientTravel` for all clients. +- **Corpses** are replicated actors — all clients see them. diff --git a/docs/developer/06-ui-systems.md b/docs/developer/06-ui-systems.md index b80f4bb..e07ef49 100644 --- a/docs/developer/06-ui-systems.md +++ b/docs/developer/06-ui-systems.md @@ -154,4 +154,23 @@ Binds to `BPC_InteractionDetector.OnTargetFound/Lost` and `OnHoldProgressUpdated --- +## Multiplayer Networking + +**All UI is local per-client. Zero networking code in widgets.** + +### UI Networking Pattern +``` +Server state changes → replicated variable → OnRep fires dispatcher + → Widget (local) already bound to that dispatcher + → Widget updates with zero multiplayer awareness +``` + +### Category Rules +- **WBP_* Widgets:** Local only. Bind to replicated dispatchers from gameplay systems. Use the same binding code as single-player. +- **SS_UIManager:** Local per-client. Menu stack is per-player — different players can be in different menus. +- **Input mode changes:** Handled per-client by `SS_EnhancedInputManager` listening to game phase dispatchers. +- **HUD visibility:** Each client independently determines what to show based on their replicated state (e.g., hiding player sees different HUD than exposed player). + +--- + *Developer Reference v1.0 — 06 UI Systems. Companion to docs/blueprints/06-ui/ specs.* diff --git a/docs/developer/07-narrative-systems.md b/docs/developer/07-narrative-systems.md index 767eda3..c2062b0 100644 --- a/docs/developer/07-narrative-systems.md +++ b/docs/developer/07-narrative-systems.md @@ -130,4 +130,26 @@ --- +## Multiplayer Networking + +### Category Authority Map +| System | Authority | Replication | +|--------|-----------|-------------| +| `BPC_NarrativeStateSystem` | Server sets flags | Flags replicate via GS_CoreGameState or replicated array | +| `BPC_ObjectiveSystem` | Server activates/completes | Active objectives in GS_CoreGameState.ActiveObjectiveTags | +| `BPC_DialoguePlaybackSystem` | Server sequences dialogue | Line index replicated; clients play audio locally | +| `BPC_DialogueChoiceSystem` | Client selects → Server processes | Server validates choice availability against flags | +| `BPC_BranchingConsequenceSystem` | Server executes consequences | Results sync to all clients | +| `BPC_CutsceneBridge` | Server triggers → Multicast to all | All clients enter cutscene simultaneously | +| `BP_NarrativeTriggerVolume` | Server validates overlap | Overlap events replicate; triggers execute on server | +| `BPC_EndingAccumulator` | Server accumulates; evaluates at end | Ending result syncs to all | + +### Key Patterns +- **Narrative flags** are GameplayTags stored in replicated arrays — all clients see flag changes. +- **Dialogue choices** flow: Client selects → `Server_SelectChoice` RPC → server validates → executes consequences → state replicates to all. +- **Cutscenes** are synchronized: server triggers, all clients enter cutscene via multicast. +- **Objectives** route through `GS_CoreGameState` which already has full replication. + +--- + *Developer Reference v1.0 — 07 Narrative Systems. Companion to docs/blueprints/07-narrative/ specs.* diff --git a/docs/developer/08-weapons-systems.md b/docs/developer/08-weapons-systems.md index e01704d..12873bf 100644 --- a/docs/developer/08-weapons-systems.md +++ b/docs/developer/08-weapons-systems.md @@ -136,4 +136,41 @@ Holstered → Equipping → Ready ⇄ Firing → Reloading → Ready --- +## Multiplayer Networking + +### Category Authority Map +| System | Authority | Client Prediction | +|--------|-----------|-------------------| +| `BP_WeaponBase` | Server-authoritative state machine | Client predicts fire animation/muzzle flash | +| `BPC_AmmoComponent` | Server-authoritative ammo | Client predicts count; server corrects via OnRep | +| `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 animation; server validates ammo state | +| `BPC_RecoilSystem` | **Local only** | Recoil is cosmetic; no replication needed | +| `BPC_DamageReceptionSystem` | Server calculates damage | HealthSystem is authoritative | +| `BPC_HitReactionSystem` | Server triggers → multicast animation | All clients see flinch/stagger | +| `BPC_CombatFeedbackComponent` | **Local only** | Hit markers, kill confirm are per-client | +| `BPC_ShieldDefenseSystem` | Server validates block/parry | Shield state replicated | + +### Weapon Fire Flow (Multiplayer) +``` +Client presses Fire: + 1. Client predicts: play fire anim, muzzle flash, recoil immediately + 2. Client calls Server_StartFire() RPC + 3. Server validates: weapon state Ready, has ammo, not on cooldown + 4. Server: trace/damage calc, consume ammo → RepNotify ammo to all + 5. Server: Multicast fire FX to other clients + 6. Client receives OnRep_Ammo → corrects if prediction was wrong +``` + +### Server RPCs +- `Server_StartFire`, `Server_StopFire`, `Server_StartReload`, `Server_EquipWeapon`, `Server_HolsterWeapon` + +### Anti-Cheat +- Server validates fire rate (timer between Server_StartFire calls must exceed weapon fire rate) +- Server never trusts client damage calculations — always recalculates from weapon data +- Server validates ammo count before allowing fire (prevents infinite ammo cheat) + +--- + *Developer Reference v1.0 — 08 Weapons Systems. Companion to docs/blueprints/08-weapons/ specs.* diff --git a/docs/developer/09-ai-systems.md b/docs/developer/09-ai-systems.md index 61ae058..ce00169 100644 --- a/docs/developer/09-ai-systems.md +++ b/docs/developer/09-ai-systems.md @@ -115,4 +115,33 @@ --- +## Multiplayer Networking + +### AI is Server-Only + +**All AI logic runs on the server.** Behavior trees, perception, memory, and state machines execute on the server only. Clients receive: +- **Position/Rotation/Animation:** via standard Actor replication +- **Alert level:** replicated for client awareness UI (detection meter, investigation icon) +- **Health:** replicated for client health bars +- **Perception events:** replicated for client awareness indicators only (cosmetic) + +### Category Authority Map +| System | Runs On | Replicated To Clients | +|--------|---------|----------------------| +| `AI_BaseAgentController` | Server | Position, rotation, animation | +| `BP_EnemyBase` | Server | Health, state, mesh | +| `BPC_AlertSystem` | Server | Alert level enum for UI | +| `BPC_AIStateMachine` | Server | Current state for animation | +| `BPC_AIPerceptionSystem` | Server | Detection events → client awareness indicators | +| `BPC_AIMemorySystem` | Server | LastKnownLocation → client investigation UI | +| `BPC_BehaviourVariantSelector` | Server (at spawn) | Variant choice for client animation matching | +| `BP_PatrolPath` | Read-only | Spline data is static; identical on all clients | + +### Client Awareness +- Clients receive perception events (enemy detected player, heard sound) as **cosmetic indicators** — red detection bar, investigation icon, audio cue. +- The actual AI behavior (investigate, engage, flee) runs on server only. +- Clients never run behavior trees — they only display the results. + +--- + *Developer Reference v1.0 — 09 AI Systems. Companion to docs/blueprints/09-ai/ specs.* diff --git a/docs/developer/10-adaptive-systems.md b/docs/developer/10-adaptive-systems.md index c2739f4..97ce367 100644 --- a/docs/developer/10-adaptive-systems.md +++ b/docs/developer/10-adaptive-systems.md @@ -146,4 +146,32 @@ --- +## Multiplayer Networking + +### Category Authority Map +| System | Authority | Replication | +|--------|-----------|-------------| +| `BPC_AdaptiveEnvironmentDirector` | Server coordinates | Atmosphere state replicates | +| `BPC_AtmosphereStateController` | Server sets tier | Clients play local audio/lighting per tier | +| `BPC_DifficultyManager` | Server adjusts | Difficulty params replicate | +| `BPC_FearSystem` | Server-authoritative | AI fear behavior runs on server | +| `BPC_ScareEventSystem` | Server triggers → Multicast | All clients play scare FX simultaneously | +| `BPC_RareEventSystem` | Server selects → Multicast | All clients see rare event | +| `BPC_LightEventController` | Server triggers | Replicated for synchronized lighting | +| `BPC_MemoryDriftSystem` | **Local only** | Hallucinations are per-player experience | +| `BPC_PacingDirector` | Server controls | Intensity band replicates | +| `BPC_PlaystyleClassifier` | Server classifies | Classification replicates | +| `BPC_PerformanceScaler` | **Local only** | Per-client hardware adaptation | +| `SS_AudioManager` | **Local playback** | Gameplay parameters (heart rate, tension) sync from server | +| `BP_RoomAudioZone` | **Local only** | Each client applies room acoustics based on their position | +| `BPC_ProceduralEncounter` | Server generates | Spawned actors replicate normally | + +### Key Patterns +- **Atmosphere is server-controlled, locally rendered.** Server sets atmosphere tier → clients play local audio/lighting/FX. +- **Scare events are synchronized via multicast** — all players experience the scare at the same moment. +- **Per-player systems** (MemoryDrift, PerformanceScaler) are strictly local. +- **Audio is local playback** — only gameplay parameters sync from server; sound assets loaded locally. + +--- + *Developer Reference v1.0 — 10 Adaptive Systems. Companion to docs/blueprints/10-adaptive/ specs.* diff --git a/docs/developer/11-16-systems.md b/docs/developer/11-16-systems.md index 327113a..fe93c82 100644 --- a/docs/developer/11-16-systems.md +++ b/docs/developer/11-16-systems.md @@ -109,3 +109,40 @@ --- *Developer Reference v1.0 — Categories 11-16 Systems. Companion to docs/blueprints/ specs.* + +--- + +## Multiplayer Networking + +### Category 11-12: Meta & Settings +| System | Authority | +|--------|-----------| +| `BPC_ProgressStatTracker` | Server accumulates; snapshot replicates for scoreboard | +| `SS_AchievementSystem` | Server validates unlocks; client receives unlock notifications | +| `BPC_AccessibilitySettings` | **Local per-client** — each player's accessibility preferences | +| `SS_SettingsSystem` | Settings save per-client; key bindings are local | + +### Category 13: Polish +| System | Authority | +|--------|-----------| +| `BPC_AnalyticsTracker` | **Local only** — per-client telemetry | +| `BPC_DevCheatManager` | **Local only** — but cheats that affect world must be server-validated | +| `BPC_ErrorHandler` | **Local only** — per-client error handling | +| `BPC_FPSCounter` | **Local only** — per-client performance | +| `BPC_LoadingScreen` | **Local only** — but sync'd via GamePhase | +| `BPC_TutorialSystem` | **Local per-client** — tutorial progression is per-player | +| `WBP_CreditsScreen`, `WBP_DebugMenu`, `WBP_SplashScreen` | **Local only** | + +### Category 14: Data Assets +All `DA_*` Data Assets are **read-only configuration** — loaded identically on all clients. No replication needed. + +### Category 15: Input +| System | Authority | +|--------|-----------| +| `SS_EnhancedInputManager` | **Local per-client.** Input mapping contexts, key rebinding, and input mode are per-player. Context priority stack is per-client. | + +### Category 16: State Management +| System | Authority | +|--------|-----------| +| `BPC_StateManager` | **Server-authoritative.** All state change requests go through server. `IsActionPermitted()` is read-only — safe for client prediction. `RequestStateChange()` must be server-validated. | +| `DA_StateGatingTable` | Read-only Data Asset — identical on all clients. Server uses it for validation; clients use it for prediction of gating results. | diff --git a/docs/developer/INDEX.md b/docs/developer/INDEX.md index 8246b3a..fe2f067 100644 --- a/docs/developer/INDEX.md +++ b/docs/developer/INDEX.md @@ -1,6 +1,6 @@ # Developer Reference — UE5 Modular Game Framework -**Version:** 1.0 | **Generated:** 2026-05-19 | **Files:** 14 (1 index + 2 overview + 10 category docs + 1 combined) +**Version:** 1.1 | **Generated:** 2026-05-19 | **Files:** 14 (1 index + 2 overview + 10 category docs + 1 combined) | **Networking:** All docs include multiplayer sections This directory contains developer-facing reference documentation for every system in the framework. Unlike the blueprint spec files (which define *what* to build), these documents explain *how each system works internally* — the data flow, state machines, integration points, and design rationale. Use these when you need to understand a system's behavior to implement, debug, or extend it. @@ -178,6 +178,7 @@ docs/developer/ 2. **Implementing a system?** Find it in the quick reference above, then read its category document. 3. **Debugging?** Each category doc includes a data flow section showing how data moves between systems. 4. **Need implementation patterns?** See [`implementation-patterns.md`](implementation-patterns.md) for common UE5 Blueprint patterns. +5. **Multiplayer networking?** See [`../architecture/multiplayer-networking.md`](../architecture/multiplayer-networking.md) for the full networking architecture. Every category doc has a Multiplayer Networking section. ## Relationship to Spec Files diff --git a/docs/developer/architecture-overview.md b/docs/developer/architecture-overview.md index 2f12825..a958b6b 100644 --- a/docs/developer/architecture-overview.md +++ b/docs/developer/architecture-overview.md @@ -153,4 +153,45 @@ The 16 build phases follow dependency order: --- +## Multiplayer Networking Architecture + +The framework is built server-authoritative from the ground up. See [`docs/architecture/multiplayer-networking.md`](../architecture/multiplayer-networking.md) for the full specification. + +### How Networking Fits the Layers + +``` +┌────────────────────────────────────────────────────────────────┐ +│ LOCAL-ONLY LAYER (never replicated) │ +│ WBP_* Widgets, Camera, Embodiment, Debug, Analytics, Tutorials │ +├────────────────────────────────────────────────────────────────┤ +│ REPLICATED STATE LAYER (server-authoritative) │ +│ GS_CoreGameState (chapter, objectives, encounter, time) │ +│ Player Components (health, stamina, stress, movement, hide) │ +│ World Actors (doors, containers, pickups, puzzles) │ +│ Inventory (slots, weight, equipment) │ +│ Narrative (flags, dialogue state, objectives) │ +│ AI (position, alert state, health — behavior trees on server) │ +│ Adaptive (atmosphere tier, tension, difficulty params) │ +├────────────────────────────────────────────────────────────────┤ +│ CLIENT PREDICTION LAYER (cosmetic, corrected by server) │ +│ Weapon fire FX, muzzle flash, recoil, hit markers │ +│ Stamina bar, health bar (predicted; RepNotify corrects) │ +│ Door animations (predicted; OnRep confirms) │ +├────────────────────────────────────────────────────────────────┤ +│ SERVER-ONLY LAYER │ +│ AI Behavior Trees, Damage Calculation, Loot Generation │ +│ Save/Load coordination, State Gating validation │ +└────────────────────────────────────────────────────────────────┘ +``` + +### Key Multiplayer Principles +1. **HasAuthority() gate** on every mutator function +2. **Server_ RPC** for client→server requests +3. **RepNotify** fires same dispatchers as SP code — UI needs zero changes +4. **Client prediction** for responsiveness; server correction for correctness +5. **AI runs on server** only — replicated to clients via Actor replication +6. **UI is local per-client** — binds to replicated dispatchers + +--- + *Architecture Overview v1.0 — Start here before reading category-specific developer docs.* diff --git a/docs/developer/implementation-patterns.md b/docs/developer/implementation-patterns.md index 43dab93..9a1f851 100644 --- a/docs/developer/implementation-patterns.md +++ b/docs/developer/implementation-patterns.md @@ -292,4 +292,96 @@ --- +## Multiplayer Networking Patterns + +### Pattern 11: Server Authority Gate + +**When to Use:** Every function that modifies replicated state. + +**Blueprint Implementation:** +``` +[Function: ApplyDamage(DamageEvent)] + Switch HasAuthority + Authority: + → Execute authoritative logic (damage calc, health modification) + → Fire dispatchers + Remote: + → Return (client cannot modify replicated state directly) + → Client calls Server_ RPC to request the change +``` + +**Key Rule:** Never modify a replicated variable without `HasAuthority()` check. + +### Pattern 12: Server RPC Wrapper + +**When to Use:** Client needs to request a state change from the server. + +**Blueprint Implementation:** +``` +[Client Event Graph — Input: Interact pressed] + → Call Server_Interact(TargetActor) // RPC: Run on Server, Reliable + +[Server RPC: Server_Interact(TargetActor)] + Switch HasAuthority + Authority: + → Validate distance, conditions + → Call I_Interactable.Execute_OnInteract(TargetActor, Instigator) + → State changes replicate automatically +``` + +**Naming:** All Server RPCs prefixed with `Server_`. + +### Pattern 13: OnRep Dispatcher Relay + +**When to Use:** Any replicated variable that should trigger the same effects as single-player. + +**Blueprint Implementation:** +``` +[Variable: CurrentHealth] + Replication: Replicated Using OnRep_CurrentHealth + +[Function: OnRep_CurrentHealth] + → Broadcast OnHealthChanged(OldHealth, CurrentHealth, Delta) + → UI, audio, effects react exactly as in single-player path + → No multiplayer-specific code in consumer systems +``` + +**Key Rule:** `OnRep_` fires the SAME dispatcher the SP mutation code fires. Zero consumer changes needed. + +### Pattern 14: Client Prediction with Correction + +**When to Use:** Actions that need instant feedback (firing, using items, interacting). + +**Blueprint Implementation:** +``` +[Client: Input → Fire pressed] + → Client prediction: play fire animation, muzzle flash, reduce ammo display + → Call Server_StartFire() + +[Server: Server_StartFire()] + → Validate weapon state, ammo, cooldown + → If valid: execute authoritative fire logic, consume ammo + → If invalid: log warning, return (client will be corrected via OnRep) + +[Client: OnRep_Ammo] + → If server count matches client prediction: no visible change + → If different: correct ammo display, stop fire animation +``` + +### Pattern 15: Multicast for Cosmetic Events + +**When to Use:** Server needs to trigger a cosmetic-only event on all clients. + +**Blueprint Implementation:** +``` +[Server: Explosion triggered] + → Multicast_PlayExplosionFX(Location, Radius) + → All clients play VFX, SFX, camera shake locally + → No replication of individual particles +``` + +**Key Rule:** Multicast is for **cosmetic only** — never use for state changes. State changes replicate via variable RepNotify. + +--- + *Implementation Patterns v1.0 — Reference when building blueprint specs into UE5 Blueprint assets.*