### Connect to Server (C++) Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/start-multiplayer-game C++ code snippet demonstrating how to initiate a client connection to a server using ClientTravel in Unreal Engine. This requires obtaining a PlayerController instance. ```cpp // Assuming you are not already in the PlayerController (if you are, just call ClientTravel directly) APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0); PlayerController->ClientTravel("IPADDRESS", ETravelType::TRAVEL_Absolute); ``` -------------------------------- ### Starting Servers via Command Line (Bash) Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/start-multiplayer-game Command-line arguments for launching Unreal Engine projects as a listen server, dedicated server, or client. These commands utilize the editor and do not require cooked data. ```bash UE4Editor.exe ProjectName MapName?Listen -game UE4Editor.exe ProjectName MapName -server -game -log UE4Editor.exe ProjectName ServerIP -game ``` -------------------------------- ### Start Listen Server (Blueprint) Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/start-multiplayer-game Initiates a listen server by calling the OpenLevel node with the 'listen' option. This is a common method for setting up peer-to-peer multiplayer sessions directly from Blueprints. ```Blueprint OpenLevel Node - Level Name: "YourLevelName" - Options: "listen" ``` -------------------------------- ### Start Listen Server (C++) Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/start-multiplayer-game Starts a listen server in C++ by calling UGameplayStatics::OpenLevel. This function allows specifying the world, level name, and connection options like 'listen'. ```C++ UGameplayStatics::OpenLevel(GetWorld(), "LevelName", true, "listen"); ``` -------------------------------- ### Connect to Server (Blueprint) Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/start-multiplayer-game Connects a client to a running server using the Execute Console Command node. The command 'open IPADDRESS' is used, where IPADDRESS is the server's network address. ```Blueprint Execute Console Command Node - Command: "open IPADDRESS" ``` -------------------------------- ### BlueprintUE: Override ReadyToStartMatch Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/gamemode Implement custom logic to determine if the game is ready to start. This function is called automatically and allows checks like ensuring all players have connected. ```BlueprintUE /** * Called when the match is ready to start. * Override this function to implement custom logic for determining match readiness. * For example, check if all players have joined the server. * @return True if the match is ready to start, false otherwise. */ function bool ReadyToStartMatch() { // Custom logic to check player connection status and readiness // ... return Super.ReadyToStartMatch(); } ``` -------------------------------- ### Unreal Engine Connection Process Steps Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/start-multiplayer-game Outlines the major steps involved when a new client connects to a server in Unreal Engine. This includes the client request, server response, map loading, and GameMode/PlayerController lifecycle events like PreLogin, Login, and PostLogin. ```APIDOC Connection Process Steps: 1. Client sends a connect request to the server. 2. Server processes the request. If accepted, it sends the current map information to the client. 3. Server waits for the client to load the specified map. 4. Once the map is loaded, the Server locally calls `AgameMode::PreLogin`. - This method allows the GameMode to reject the connection. 5. If the connection is accepted by `PreLogin`, the Server calls `AgameMode::Login`. - This function is responsible for creating a `PlayerController` which is then replicated to the client. - The replicated `PlayerController` replaces the client's temporary placeholder `PlayerController`. - `APlayerController::BeginPlay` is called at this stage. - It is NOT safe to call RPC functions on the `PlayerController` yet; wait for `AgameMode::PostLogin`. 6. Assuming all previous steps were successful, `AgameMode::PostLogin` is called. - At this point, it is safe for the Server to initiate RPC calls on the `PlayerController`. ``` -------------------------------- ### BlueprintUE: GameMode Variables Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/gamemode Overview of key variables available in the GameMode class that can be configured via Class Defaults. These variables influence default player behavior, game start conditions, and option parsing. ```BlueprintUE /** * Default name assigned to connecting players. * Accessible via the APlayerState class. */ DefaultPlayerName: FString; /** * If true, delays the game start even if other readiness criteria are met. * Useful for waiting for specific conditions or player actions. */ bDelayedStart: bool; /** * A string containing options separated by '?'. * Can be passed via OpenLevel or ServerTravel. * Use ParseOption to extract specific values like 'MaxNumPlayers'. */ OptionsString: FString; /** * Parses a specific option from the OptionsString. * @param OptionName The name of the option to retrieve. * @return The value of the specified option, or an empty string if not found. */ function FString ParseOption(FString OptionName) { // Implementation to parse OptionsString // ... return ""; } ``` -------------------------------- ### C++ Unreal Engine Pawn TakeDamage Implementation and Replication Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/pawn Provides the C++ implementation for the TakeDamage function, which reduces the Pawn's Health and destroys the actor if Health drops to zero or below. It also includes the GetLifetimeReplicatedProps function to set up variable replication for Health. ```cpp // This function is required and the replicated specifier in the UPROPERTY macro causes it to be declared for us. We only need to implement it void ATestPawn::GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); // This tells UE that we want to replicate this variable DOREPLIFETIME(ATestPawn, Health); } float ATestPawn::TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) { const float ActualDamage = Super::TakeDamage(Damage, DamageEvent, EventInstigator, DamageCauser); // Lower the Health of the Player Health -= ActualDamage; // And destroy it if the Health is less or equal 0 if (Health <= 0.f) { Destroy(); } return ActualDamage; } ``` -------------------------------- ### Override ReadyToStartMatch in C++ UE++ Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/gamemode Demonstrates overriding the `ReadyToStartMatch_Implementation` function in a C++ Unreal Engine game mode. This function checks if the number of players matches the maximum allowed players before starting a match. It involves modifying both the header and CPP files. ```C++ // Header file of our AGameMode child class inside of the class declaration // Maximum Number of Players needed/allowed during this Match int32 MaxNumPlayers; // Override Implementation of ReadyToStartMatch virtual bool ReadyToStartMatch_Implementation() override; ``` ```C++ // CPP file of our GameMode child class bool ATestGameMode::ReadyToStartMatch_Implementation() { Super::ReadyToStartMatch(); return MaxNumPlayers == NumPlayers; } ``` -------------------------------- ### Get Online Session Interface Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Retrieves the online session interface, emphasizing the importance of passing the current UWorld to correctly handle multiple UWorlds, especially in the editor (PIE). ```cpp const IOnlineSessionPtr sessionInterface = Online::GetSessionInterface(GetWorld()); ``` -------------------------------- ### Server RPC Call Restriction Example Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/ownership Illustrates a common scenario where a client cannot directly call a Server RPC on an Actor it does not own. The workaround involves using the PlayerController to mediate the interaction. ```APIDOC Scenario: Client attempts to call a Server RPC on a Server-owned Actor. Problem: Server RPCs are dropped if the calling client does not own the target Actor. Example: Client cannot call 'Server_Interact' on a server-owned door. Solution Pattern: 1. Create a Server RPC within the PlayerController class. 2. When the client needs to interact with a server-owned Actor (e.g., a door): a. The client calls the Server RPC on its owned PlayerController. b. The PlayerController's Server RPC executes on the server. c. On the server, the PlayerController then calls an Interface function (e.g., 'Interact') on the target Actor (the door). Benefits: - Bypasses ownership restrictions for RPCs. - Centralizes interaction logic within the PlayerController. Related Concepts: - Actor Ownership - Server RPCs - Interfaces - PlayerController ``` -------------------------------- ### C++ RepNotify Function Implementation Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/replication Implements the 'OnRep_Health' function, which is called on clients when the 'Health' variable is replicated. This example checks if health is zero and plays a death animation. ```C++ void ATestCharacter::OnRep_Health() { if (Health <= 0.f) { PlayDeathAnimation(); } } ``` -------------------------------- ### C++ Unreal Engine Pawn Health Declaration Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/pawn Shows the C++ declaration for a replicated Health variable and the override signature for the TakeDamage event within an Unreal Engine Pawn class. ```cpp // Replicated Health variable UPROPERTY(Replicated) int32 Health; // Overriding the TakeDamage event virtual float TakeDamage(float Damage, struct FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) override; ``` -------------------------------- ### C++ Unreal Engine Possess Events Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/pawn Demonstrates the C++ virtual functions for handling possession events in Unreal Engine. PossessedBy is called when an actor is possessed, and UnPossessed is called when possession ends. ```cpp virtual void PossessedBy(AController* NewController); virtual void UnPossessed(); ``` -------------------------------- ### Initialize Session Settings Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Initializes a new FOnlineSessionSettings object to store session configuration. Users should review available settings and customize them as needed. ```cpp LastSessionSettings = MakeShareable(new FOnlineSessionSettings()); ``` -------------------------------- ### Session Management Method Implementation Pattern Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Outlines the common pattern for implementing session methods, involving a primary function to execute the session code, a callback function to receive responses from the OnlineSubsystem, and delegates with handles for managing callbacks. ```unrealengine /* * Pattern for implementing session methods: * * 1. Function to execute your Session code (e.g., CreateSession). * 2. Function to receive a callback from the OnlineSubsystem (e.g., OnCreateSessionComplete). * 3. Delegate to bind your function to (e.g., FOnCreateSessionCompleteDelegate). * 4. DelegateHandle to keep track of the Delegate and later unbind it (e.g., FDelegateHandle). * * Each Gist will only contain the Subsystem Class with the specific Method we are looking at. */ ``` -------------------------------- ### UUserWidget Overview Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/userwidget Provides an overview of UUserWidget, its purpose in Unreal Engine's UI system (UMG), its relationship with Slate, and its networking limitations. Widgets are local and do not replicate. ```APIDOC UUserWidget: Inherits From: Slate Used In: Unreal Motion Graphics (UMG) Availability: Local only Replication: Does not replicate, should not contain replication code. Gameplay Code: Preferably avoided, but may be necessary in some cases. Description: UUserWidgets are the fundamental building blocks for creating user interfaces within Unreal Engine using the Unreal Motion Graphics (UMG) system. They are built upon the Slate UI framework, which is also used for the Unreal Engine Editor itself. A key characteristic of UUserWidgets is their local scope; they are not replicated across the network and therefore should not contain any logic related to network replication. While it's best practice to keep gameplay logic separate, some game designs might necessitate including limited gameplay code within widgets. ``` -------------------------------- ### Access Online Subsystem Instance Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/online-subsystems Retrieves an instance of the Online Subsystem. This static accessor allows game code to obtain the currently active subsystem, defaulting to NAME_None if no specific subsystem is requested. ```cpp static IOnlineSubsystem* Get(const FName& SubsystemName = NAME_None); ``` -------------------------------- ### Create Session Blueprint Node Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management Details the 'CreateSession' Blueprint node for initiating a game session. It offers limited options but can be extended via plugins. This is a primary method for setting up sessions for players to find and join. ```APIDOC CreateSession: Description: Creates a new game session. Parameters: (None explicitly listed in text, but implies session settings are configured elsewhere) Output: OnSuccess: Exec pin called when session creation is successful. OnFailure: Exec pin called when session creation fails. Notes: Limited options available directly; extendable via plugins. For C++, use AGameSession::RegisterServer. ``` -------------------------------- ### APlayerController and GetPlayerController in Unreal Engine Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/playercontroller Details the APlayerController class, its role as the primary input handler and client-server link, and the nuances of the GetPlayerController function across different network configurations. ```APIDOC APlayerController: Purpose: The central class for handling player input and acting as the link between the player and the server. Each client possesses its own PlayerController, which exists on both the client and the server. Clients cannot access other clients' PlayerControllers, but the server maintains references to all client PlayerControllers. Input Handling: Pawn/Character specific input should be placed in APawn/ACharacter classes. Input that applies universally or when a Character object is not valid should reside in the PlayerController. GetPlayerController Function: Signature: UGameplayStatics::GetPlayerController(GetWorld(), 0) or GetPlayerController(0) Behavior: - On Listen-Server: Returns the Listen-Server's PlayerController. - On Client: Returns the Client's PlayerController. - On Dedicated Server: Returns the first Client's PlayerController. Note: The index '0' is intended for local players (e.g., splitscreen) and does not provide access to other clients' PlayerControllers. ``` -------------------------------- ### Add OnlineSubsystem Dependencies to Build.cs Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Adds 'OnlineSubsystem' and 'OnlineSubsystemUtils' modules as dependencies in the .Build.cs file. This is crucial for accessing session-related functionalities and helper functions provided by Unreal Engine's online subsystem. ```cpp PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "OnlineSubsystem", "OnlineSubsystemUtils" }); ``` -------------------------------- ### Include Online Session Interface Header Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Includes the necessary header file for accessing online session functionalities, including the FOnlineSessionSettings struct and delegate types. ```cpp #include "Interfaces/OnlineSessionInterface.h" ``` -------------------------------- ### BlueprintUE: Match State Management Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/gamemode Functions and events used to manage the game's MatchState. These are often called automatically based on conditions like 'ReadyToStartMatch' returning true, or can be invoked manually. ```BlueprintUE /** * Transitions the game to a new match state. * This function works in conjunction with the GameState class. * @param NewState The new FName representing the match state. */ function ChangeMatchState(FName NewState) { // Logic to update the game's current state // ... // Example: Set the GameState's MatchState property // GetGameState().SetMatchState(NewState); } /** * Called when the game transitions to a new state. * Can be used to perform actions specific to the new state. */ function OnMatchStateChanged(FName OldState, FName NewState) { // Actions to perform when state changes // ... Super.OnMatchStateChanged(OldState, NewState); } ``` -------------------------------- ### Configure DefaultEngine.ini for OnlineSubsystem Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp This snippet shows how to configure the DefaultEngine.ini file to specify the default OnlineSubsystem for Unreal Engine projects. It's crucial for session management, especially when moving away from the NULL subsystem. ```INI [OnlineSubsystem] DefaultPlatform=NULL PollingInterval=100 EnablePolling=1 ``` -------------------------------- ### Configure Default Online Platform Service Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/online-subsystems Specifies the default platform service to be loaded by the Online Subsystem. This setting in Engine.ini determines which platform's online features are prioritized when accessing the subsystem. ```ini [OnlineSubsystem] DefaultPlatformService = ``` -------------------------------- ### AHUD Class Overview Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes Explains that the AHUD (Heads-Up Display) class is exclusively available on each client and is accessed via the PlayerController. It is automatically spawned by the PlayerController to render game information. ```APIDOC AHUD: Description: Responsible for drawing the Heads-Up Display elements on the screen, such as health bars, scores, and crosshairs. Inheritance: AActor Notes: Client-only; typically accessed via PlayerController->GetHUD(). ``` -------------------------------- ### Online Session API Documentation Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management Provides an overview of key API functions for managing online sessions, including joining, matchmaking, and friend invitations. These functions are part of the Online Subsystem and are typically called from C++ or Blueprint. ```APIDOC IOnlineSession API Reference: // Joining Sessions JoinSession(PlayerNumber, SessionName, SearchResult) - Joins a specified online session. - Parameters: - PlayerNumber: The number of the player initiating the join. - SessionName: The name of the session to join. - SearchResult: The search result object containing session details. - Event: OnJoinSessionComplete Delegate fired upon completion. // Cloud-Based Matchmaking StartMatchmaking(ControllerNumber, SessionName, SessionSettings, SearchSettings) - Initiates the cloud-based matchmaking process. - Parameters: - ControllerNumber: The controller number of the player to matchmake. - SessionName: The name for the session to be created or joined. - SessionSettings: Settings for creating a new session if needed. - SearchSettings: Settings to use for searching against existing sessions. - Event: OnMatchmakingComplete Delegate fired upon completion, returning success status and session name. CancelMatchmaking(ControllerNumber, SessionName) - Cancels an ongoing matchmaking process. - Parameters: - ControllerNumber: The controller number of the player. - SessionName: The name of the session associated with the matchmaking. - Event: OnCancelMatchmakingCompletedelegate fired upon completion. // Following and Inviting Friends FindFriendSession(LocalPlayerNumber, FriendID) - Finds the session a specific friend is currently in. - Parameters: - LocalPlayerNumber: The number of the local player looking for the friend's session. - FriendID: The unique identifier of the friend. - Event: OnFindFriendSessionComplete Delegate fired with a SearchResult if the friend's session is found. SendSessionInviteToFriend(LocalPlayerNumber, SessionName, FriendID) - Sends a session invitation to a single friend. - Parameters: - LocalPlayerNumber: The number of the local player sending the invite. - SessionName: The name of the session to invite to. - FriendID: The ID of the friend to invite. SendSessionInviteToFriends(LocalPlayerNumber, SessionName, FriendIDs) - Sends session invitations to multiple friends. - Parameters: - LocalPlayerNumber: The number of the local player sending the invites. - SessionName: The name of the session to invite to. - FriendIDs: An array of friend IDs to invite. // Event for accepting invites OnSessionInviteAccepted Delegate - Fired when a friend accepts an invitation. - Provides a SearchResult for the session to join. ``` -------------------------------- ### AGameState Class Overview Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes Explains the AGameState class, which was also split into AGameStateBase and AGameState in UE 4.14. AGameStateBase provides essential features, while AGameState includes the full range of functionalities. ```APIDOC AGameState: Description: Represents the current state of the game, accessible by all clients. It holds information like scores, game time, and player statuses. Inheritance: AActor Notes: Replicated to all clients. ``` -------------------------------- ### Bind Create Session Complete Delegate Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Binds a subsystem function to the CreateSessionCompleteCallback delegate, ensuring callbacks are handled correctly. This pattern is repeated for other delegate types. ```cpp CreateSessionCompleteDelegate(FOnCreateSessionCompleteDelegate::CreateUObject(this, &ThisClass::OnCreateSessionCompleted)) ``` -------------------------------- ### Join Session via Blueprint Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management Demonstrates how to join a game session using Unreal Engine's Blueprint visual scripting system. It utilizes the 'JoinSession' node, which takes a SessionResult obtained from a 'FindSession' node and automatically transitions the player to the map upon successful connection. ```Blueprint JoinSession Node (Blueprint) Input: - SessionResult: The result of a previous 'FindSession' operation. Output: - OnSuccess: Executed when the session join is successful. - OnFailure: Executed when the session join fails. Description: This node is used in Blueprint to initiate joining a game session. It requires a valid SessionResult and handles the connection process, including map loading, automatically on success. ``` -------------------------------- ### Unreal Engine Session Management API Concepts Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Details key concepts and types used in Unreal Engine's online subsystem for session management, highlighting limitations and requirements for Blueprint exposure. This includes data structures, delegates, and callable functions. ```APIDOC Unreal Engine Session Management API Concepts: FOnlineSessionSearchResult: - Represents a single session found during a search. - Not a USTRUCT, which prevents direct exposure to Blueprints as a BlueprintAssignable delegate parameter. - Requires wrapping in a custom USTRUCT within a Function Library to be exposed to Blueprints. EOnJoinSessionCompleteResult: - Enum indicating the outcome of a session join attempt. - Cannot be directly exposed to Blueprints as a BlueprintAssignable delegate parameter. - Requires conversion to a custom UENUM for Blueprint compatibility. Delegates (e.g., DYNAMIC Multicast Delegate): - Used for asynchronous callbacks. - Require types that can be exposed to Blueprints. - If FOnlineSessionSearchResult is used as a delegate parameter, it must be wrapped. BlueprintCallable Functions: - Functions intended to be called from Blueprints. - If a function uses types like FOnlineSessionSearchResult, it must be wrapped in a USTRUCT to be BlueprintCallable. Function Library: - A class used to house static functions that can be exposed to Blueprints. - Often used to wrap C++ functionalities and data structures for Blueprint access. Related Concepts: - Create Session: Functionality to host a new game session. - Find Sessions: Functionality to search for existing game sessions. - Join Session: Functionality to connect to a found game session. - Destroy Session: Functionality to clean up an active session. - SEARCH_PRESENCE: A query setting to filter for player-hosted sessions. ``` -------------------------------- ### Online Subsystem Interfaces Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/online-subsystems Defines the core interfaces provided by the Online Subsystem for accessing platform-specific functionalities. Game code should check for interface availability as not all platforms implement all interfaces. ```APIDOC Online Subsystem Interfaces: - Profile: Interface definition for online services related to a User Profile and its metadata (Online Presence, Access Permissions, etc). - Friends: Interface definition for online services related to the maintenance of Friends and Friends Lists. - Sessions: Interface definition for online services related to managing a Session and its state. - Shared Cloud: Provides the Interface for sharing files already on the cloud with other users. - User Cloud: Provides the Interface for per-User Cloud file storage. ``` -------------------------------- ### Enable Replication in C++ Constructor Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/replication This C++ code snippet demonstrates how to enable replication for an AActor by setting the bReplicates and bReplicateMovement properties to true within the actor's constructor. Actors with these properties set to true will be replicated to all clients when spawned by the server. ```cpp ATestCharacter::ATestCharacter(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bReplicates = true; bReplicateMovement = true; } ``` -------------------------------- ### APlayerController CPP: RPC Implementation and BeginPlay Logic Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/playercontroller Implements the server RPC validation and execution for Server_IncreaseVariable, and includes logic in BeginPlay to call the RPC on the server. It checks if the controller is the local player before calling the RPC. ```cpp // Otherwise we can't access the GameState functions #include "TestGameState.h" // You will read later about RPCs and why '_Validate' is a thing bool ATestPlayerController::Server_IncreaseVariable_Validate() { return true; } // You will read later about RPCs and why '_Implementation' is a thing void ATestPlayerController::Server_IncreaseVariable_Implementation() { ATestGameState* GameState = Cast(UGameplayStatics::GetGameState(GetWorld())); GameState->IncreaseVariable(); } void ATestPlayerController::BeginPlay() { Super::BeginPlay(); // BeginPlay is called on every instance of an Actor, so also on the server version of this PlayerController. // We want to ensure, that only the local player calls this RPC. Again, this example doesn't necessarily make much sense // since we could just flip the condition and wouldn't need the RPC at all, but C++ Widget, you know... // We could also use "IsLocalPlayerController()" here if (Role < ROLE_Authority) { Server_IncreaseVariable(); } } ``` -------------------------------- ### Unreal Engine Replication Specifiers Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/gamestate Details the use of Unreal Engine's replication system for variables and functions. It explains the UPROPERTY(Replicated) specifier for marking variables to be replicated across the network and the DOREPLIFETIME macro for explicitly defining which properties are replicated. ```APIDOC UPROPERTY(Replicated) [VariableType] [VariableName]; - Marks a variable to be replicated from the server to clients. - Requires the GetLifetimeReplicatedProps function to be implemented. DOREPLIFETIME([ClassName], [VariableName]); - Explicitly registers a property for replication within the GetLifetimeReplicatedProps function. - Used to specify which UPROPERTY(Replicated) members should be synchronized. Example: // In Header: UPROPERTY(Replicated) int32 PlayerScore; // In CPP: void AMyActor::GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AMyActor, PlayerScore); } ``` -------------------------------- ### Unreal Actor Replication Variables Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/actor-relevancy-and-priority Demonstrates common replication settings for Unreal Engine Actors, including relevancy flags, movement replication, and network update parameters. These variables are typically configured in Actor class defaults or C++ implementations. ```C++ bOnlyRelevantToOwner = false; bAlwaysRelevant = false; bReplicateMovement = true; bNetLoadOnClient = true; bNetUseOwnerRelevancy = false; bReplicates = true; NetUpdateFrequency = 100.f; NetCullDistanceSquared = 225000000.f; NetPriority = 1.f; ``` -------------------------------- ### APlayerController Header: Server RPC and BeginPlay Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/playercontroller Defines a server RPC function (Server_IncreaseVariable) and overrides the BeginPlay function in a custom APlayerController class. The RPC is marked as unreliable and includes validation. ```cpp // Server RPC. You will read more about this in the RPC chapter UFUNCTION(Server, unreliable, WithValidation) void Server_IncreaseVariable(); // Also overriding the BeginPlay function for this example virtual void BeginPlay() override; ``` -------------------------------- ### BlueprintUE: Event OnPostLogin Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/gamemode This event is triggered every time a new player successfully logs into the game. It provides access to the connecting player's PlayerController for immediate interaction. ```BlueprintUE /** * Called when a new player has successfully logged in. * The PlayerController passed is owned by the connecting player's UConnection. * Use this to interact with the player, spawn a Pawn, or add them to a list. * @param NewPlayer The PlayerController of the newly connected player. */ event OnPostLogin(PlayerController NewPlayer) { // Example: Add the new player's controller to an array // PlayerControllerArray.Add(NewPlayer); // Example: Spawn a Pawn for the player // SpawnDefaultPawnForPlayer(NewPlayer); Super.OnPostLogin(NewPlayer); } ``` -------------------------------- ### UUserWidget (UMG Widget) Overview Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes Introduces UUserWidget as the fundamental component of Unreal Motion Graphics (UMG), Epic Games' UI system. These widgets are used to create and manage in-game user interfaces. ```APIDOC UUserWidget: Description: A base class for creating UI elements in Unreal Engine using the UMG system. Allows for visual design and programmatic control of UI. Inheritance: UObject Notes: Used for creating menus, HUD elements, and other interactive interfaces. ``` -------------------------------- ### UE++ PlayerState Property Management Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/playerstate Demonstrates the C++ header declarations and implementation for managing custom properties in Unreal Engine's APlayerState child classes. The `CopyProperties` function synchronizes data from one state to another, while `OverrideWith` applies properties from a source state to the current one. Ensure to use the 'override' specifier and call 'Super::' for proper inheritance. ```cpp // Header file of our APlayerState child class inside of the class declaration // Used to copy properties from the current PlayerState to the passed one virtual void CopyProperties(class APlayerState* PlayerState); // Used to override the current PlayerState with the properties of the passed one virtual void OverrideWith(class APlayerState* PlayerState); ``` ```cpp // CPP file of our APlayerState child class void ATestPlayerState::CopyProperties(class APlayerState* PlayerState) { Super::CopyProperties(PlayerState); if (IsValid(PlayerState)) { ATestPlayerState* TestPlayerState = Cast(PlayerState); if (IsValid(TestPlayerState)) { TestPlayerState->SomeVariable = SomeVariable; } } } void ATestPlayerState::OverrideWith(class APlayerState* PlayerState) { Super::OverrideWith(PlayerState); if (IsValid(PlayerState)) { ATestPlayerState* TestPlayerState = Cast(PlayerState); if (IsValid(TestPlayerState)) { SomeVariable = TestPlayerState->SomeVariable; } } } ``` -------------------------------- ### APlayerController Class Overview Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes Describes APlayerController as a central and complex class, particularly for client-side logic. It is the first class that a client 'owns' and manages player input and interaction with the game world. ```APIDOC APlayerController: Description: Represents the player's interface to the game. It handles input, possesses a Pawn, and manages UI elements. It's the primary point of client-side game logic. Inheritance: AController Notes: Exists on the client and server; crucial for input processing and client-specific actions. ``` -------------------------------- ### UE4 GameInstance Subsystem for Session Management Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Demonstrates the creation of a custom GameInstance Subsystem class, 'CSSessionSubsystem', inheriting from 'UGameInstanceSubsystem'. This class serves as a central hub for managing session-related logic and callbacks within the Unreal Engine framework. ```cpp // CSSessionSubsystem.h #pragma once #include "CoreMinimal.h" #include "Subsystems/GameInstanceSubsystem.h" #include "CSSessionSubsystem.generated.h" /** * */ UCLASS() class CPP SESSIONS_API UCSSessionSubsystem : public UGameInstanceSubsystem { GENERATED_BODY() public: // Constructor declaration UCSSessionSubsystem(); }; // CSSessionSubsystem.cpp #include "CSSessionSubsystem.h" #include "OnlineSubsystem.h" #include "OnlineSubsystemUtils.h" // Constructor definition UCSSessionSubsystem::UCSSessionSubsystem() { // Initialization logic if needed } ``` -------------------------------- ### Replication Conditions Reference Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/replication Lists and describes various conditions that can be applied to variable replication, controlling when and to whom a variable is sent. ```APIDOC Replication Conditions: COND_InitialOnly: This property will only attempt to send on the **initial bunch** COND_OwnerOnly: This property will only send to the **Actor's owner** COND_SkipOwner: This property send to every connection **EXCEPT** the owner COND_SimulatedOnly: This property will only send to **simulated** Actors COND_AutonomousOnly: This property will only send to **autonomous** Actors COND_SimulatedOrPhysics: This property will will send to simulated OR **bRepPhysics** Acto COND_InitialOrOwner: This property will send on the **initial bunch**, or to the **Actor's owner** COND_Custom: This property has no particular condition, but wants the ability to toggle on/off via **SetCustomIsActiveOverride** ``` -------------------------------- ### Override PostLogin in C++ UE++ Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/gamemode Shows how to override the `PostLogin` function in a C++ Unreal Engine game mode. This function is called when a new player logs in and is used here to add the player controller to a list. It requires changes in both the header and CPP files. ```C++ // Header file of our AGameMode child class inside of the class declaration // List of PlayerControllers UPROPERTY() TArray PlayerControllerList; // Overriding the PostLogin function virtual void PostLogin(APlayerController* NewPlayer) override; ``` ```C++ // CPP file of our GameMode child class void ATestGameMode::PostLogin(APlayerController* NewPlayer) { Super::PostLogin(NewPlayer); PlayerControllerList.Add(NewPlayer); } ``` -------------------------------- ### Find Sessions Blueprint Node Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management Covers the 'FindSessions' Blueprint node for discovering available game sessions. It allows specifying search parameters like the number of results and whether to search locally (LAN) or online. ```APIDOC FindSessions Node: Description: Searches for available game sessions based on specified criteria. Parameters: MaxResults: The maximum number of sessions to return. bIsLAN: Boolean to indicate if searching for LAN games (true) or online games (false). Output: OnSuccess: Exec pin called when the search operation completes. OnFailure: Exec pin called if the search operation fails. Notes: Enables classic server browser functionality. More advanced filtering can be achieved via plugins. ``` -------------------------------- ### AGameState CPP: Replication and Variable Increment Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes/playercontroller Implements the GetLifetimeReplicatedProps function to specify replication for OurVariable and defines the IncreaseVariable function to increment the replicated variable. This ensures the variable's state is synchronized across clients. ```cpp // This function is required and the replicated specifier in the UPROPERTY macro causes it to be declared for us. We only need to implement it void ATestGameState::GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); // This tells UE that we want to replicate this variable DOREPLIFETIME(ATestGameState, OurVariable); } void ATestGameState::IncreaseVariable() { OurVariable++; } ``` -------------------------------- ### C++ Registering Replicated Variables Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/replication Defines the GetLifetimeReplicatedProps function to specify which variables should be replicated. DOREPLIFETIME macro is used to register individual variables. ```C++ void ATestPlayerCharacter::GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); // Here we list the variables we want to replicate DOREPLIFETIME(ATestPlayerCharacter, Health); } ``` -------------------------------- ### Set Session Map Name Setting Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Sets a specific session setting, like the map name, using a predefined key. Custom settings can be defined and added as needed. ```cpp LastSessionSettings->Set(SETTING_MAPNAME, FString("Your Level Name"), EOnlineDataAdvertisementType::ViaOnlineService); ``` -------------------------------- ### Configure Session Search Presence Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Configures the session search to specifically look for Presence Sessions, which typically correspond to player-hosted sessions rather than dedicated server sessions. This is a crucial step for filtering search results. ```cpp LastSessionSearch->QuerySettings.Set(SEARCH_PRESENCE, true, EOnlineComparisonOp::Equals); ``` -------------------------------- ### Add Create Session Complete Delegate Handle Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/session-management/sessions-in-cpp Adds the previously bound delegate to the Session Interface's delegate list and saves the returned handle for later removal, preventing memory leaks. ```cpp CreateSessionCompleteDelegateHandle = sessionInterface->AddOnCreateSessionCompleteDelegate_Handle(CreateSessionCompleteDelegate); ``` -------------------------------- ### Unreal Engine C++ RPC Implementations and Validation Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/remote-procedure-calls Provides the implementation structure for Unreal Engine C++ RPCs. Server RPCs require both an '_Implementation' function and an optional '_Validate' function. Client and Multicast RPCs only require an '_Implementation' function. ```APIDOC // Server RPC Implementation void AMyCharacter::ServerRPCFunction_Implementation(ParameterType ParameterName) { // Server-side logic here. // This function is called when a client invokes ServerRPCFunction. } // Server RPC Validation (Optional, but required if 'WithValidation' is used) bool AMyCharacter::ServerRPCFunction_Validate(ParameterType ParameterName) { // Return true to allow the RPC to execute on the server. // Return false to disconnect the client that sent the RPC. // Example: Check parameter validity. if (ParameterName < 0) return false; return true; } // Client RPC Implementation void AMyCharacter::ClientRPCFunction_Implementation(ParameterType ParameterName) { // Client-side logic here. // This function is called on clients when the server invokes ClientRPCFunction. } // Multicast RPC Implementation void AMyCharacter::MulticastRPCFunction_Implementation(ParameterType ParameterName) { // Logic here runs on the server and all connected clients. // This function is called when the server invokes MulticastRPCFunction. } ``` -------------------------------- ### AGameMode Class Overview Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes Details the AGameMode class, noting its split into AGameModeBase and AGameMode in version 4.14. AGameModeBase offers a reduced feature set for games not requiring the full capabilities of the older AGameMode. ```APIDOC AGameMode: Description: Manages the game rules, player spawning, and overall game flow. In UE 4.14+, split into AGameModeBase (core features) and AGameMode (full features). Inheritance: AActor Notes: Primarily server-side logic. ``` -------------------------------- ### Unreal Engine C++ RPC Declarations Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/remote-procedure-calls Defines the syntax for declaring different types of Remote Procedure Calls (RPCs) in Unreal Engine C++. This includes Server, Client, and Multicast RPCs, with options for reliability (reliable/unreliable) and validation. ```APIDOC UFUNCTION(Server, unreliable, WithValidation) void ServerRPCFunction(ParameterType ParameterName); - Declares a function that runs on the server, called by a client. - 'unreliable': The RPC may be dropped. - 'WithValidation': Requires a corresponding '_Validate' function. UFUNCTION(Client, unreliable) void ClientRPCFunction(ParameterType ParameterName); - Declares a function that runs on clients, called by the server. - 'unreliable': The RPC may be dropped. UFUNCTION(NetMulticast, unreliable) void MulticastRPCFunction(ParameterType ParameterName); - Declares a function that runs on all clients and the server, called by the server. - 'unreliable': The RPC may be dropped. // Adding 'reliable' makes the RPC guaranteed to be delivered: UFUNCTION(Client, reliable) void ReliableClientRPCFunction(ParameterType ParameterName); UFUNCTION(NetMulticast, reliable) void ReliableMulticastRPCFunction(ParameterType ParameterName); UFUNCTION(Server, reliable, WithValidation) void ReliableServerRPCFunction(ParameterType ParameterName); // Note: RPCs cannot have return values. ``` -------------------------------- ### APlayerState Class Overview Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/common-classes Highlights APlayerState as a crucial class for shared player information. It is designed to hold current data about a specific player, with each player having their own instance of PlayerState. ```APIDOC APlayerState: Description: Stores persistent and replicated information about a player, such as name, score, ping, and team. Inheritance: AActor Notes: Replicated to all clients; essential for displaying player-specific data. ``` -------------------------------- ### Unreal Engine RPC Types and Behavior Source: https://cedric-neukirchen.net/docs/category/multiplayer-network-compendium/multiplayer-compendium/remote-procedure-calls Details the different types of Remote Procedure Calls (RPCs) in Unreal Engine, their intended execution targets, and the rules governing their behavior when invoked from clients or servers, considering actor ownership and replication status. ```APIDOC Unreal Engine RPCs (Remote Procedure Calls) Purpose: RPCs are used to call functions on other instances of an Actor or replicated Subobject. They facilitate communication between clients and servers for replication purposes. Key Characteristics: - RPCs cannot have a return value. To return a value, a second RPC must be called in the opposite direction. - RPCs must be called on Actors or replicated Subobjects (e.g., Components). - The Actor (and component) must be replicated for RPCs to function correctly. RPC Types: 1. **Run on Server**: - Purpose: Meant to be executed on the server instance of this Actor. - Invocation Rules: - Called from Server: Executes on the Server. - Called from Client (owning Actor): Executes on the Server. - Called from Client (non-owning Actor): Dropped. - Called on Unreplicated Actor: Executes on the Server. 2. **Run on owning Client**: - Purpose: Meant to be executed on the client that owns this Actor. - Invocation Rules: - Called from Server: Executes on the Actor's owning Client. - Called from Client (owning Actor): Executes on the Actor's owning Client. - Called from Client (non-owning Actor): Executes on the Actor's owning Client. - Called on Unreplicated Actor: Executes on the Actor's owning Client. 3. **NetMulticast**: - Purpose: Meant to be executed on all instances of this Actor. - Invocation Rules: - Called from Server: Executes locally on the Server AND on all currently relevant connected Clients. - Called from Client (owning Actor): Executes locally on the invoking Client ONLY. Does NOT execute on the Server or other Clients. - Called from Client (non-owning Actor): Executes locally on the invoking Client ONLY. Does NOT execute on the Server or other Clients. - Called on Unreplicated Actor: Executes locally on the invoking Client ONLY. Does NOT execute on the Server or other Clients. - Throttling: Multicast functions have a throttling mechanism, replicating at most twice per Actor's network update period. Summary Table (RPC invoked from Server): | Actor Ownership | Not Replicated | NetMulticast | Server (Run on Server) | Client (Run on owning Client) | |----------------------|----------------|------------------------------|------------------------|-------------------------------| | Client-owned Actor | Runs on Server | Runs on Server & all Clients | Runs on Server | Runs on Actor's owning Client | | Server-owned Actor | Runs on Server | Runs on Server & all Clients | Runs on Server | Runs on Server | | Unowned Actor | Runs on Server | Runs on Server & all Clients | Runs on Server | Runs on Server | Summary Table (RPC invoked from a Client): | Actor Ownership | Not Replicated | NetMulticast | Server (Run on Server) | Client (Run on owning Client) | |--------------------------|---------------------|------------------------------|------------------------|-------------------------------| | Owned by invoking Client | Runs on invoking Client | Runs on invoking Client | Dropped | Runs on invoking Client | | Owned by a different Client| Runs on invoking Client | Runs on invoking Client | Dropped | Runs on invoking Client | | Server-owned Actor | Runs on invoking Client | Runs on invoking Client | Dropped | Runs on Invoking Client | | Unowned Actor | Runs on invoking Client | Runs on invoking Client | Dropped | Runs on Invoking Client | ```