R-Type
Distributed multiplayer game engine in C++
Loading...
Searching...
No Matches
Replicator Class Reference

Client-server network replication manager with dedicated network thread. More...

#include <Replicator.hpp>

Collaboration diagram for Replicator:
Collaboration graph

Public Member Functions

 Replicator (EventBus &eventBus, bool isSpectator=false)
 Constructor with EventBus reference.
 
 ~Replicator ()
 Destructor.
 
bool connect (const std::string &host, uint16_t port)
 Connect to the game server.
 
void disconnect ()
 Disconnect from the server.
 
bool isConnected () const
 Check if connected to server.
 
bool isAuthenticated () const
 Check if authenticated with server.
 
uint32_t getMyPlayerId () const
 Get the player ID assigned by server.
 
void processMessages ()
 Process incoming network messages.
 
void startNetworkThread ()
 Start the dedicated network thread.
 
void stopNetworkThread ()
 Stop the dedicated network thread.
 
void sendPacket (NetworkMessageType type, const std::vector< uint8_t > &data)
 Send a packet to the server.
 
uint32_t getLatency () const
 Get current latency in milliseconds.
 
uint32_t getPacketLoss () const
 Get packet loss rate as percentage.
 
bool isSpectator () const
 Check if in spectator mode.
 
bool sendConnectRequest (const std::string &playerName, const std::string &username, const std::string &password)
 Send connect request to server with player name.
 
bool sendRegisterAccount (const std::string &username, const std::string &password)
 Send register account request to server.
 
bool sendLoginAccount (const std::string &username, const std::string &password)
 Send login request to server.
 
bool sendListRooms ()
 Send list rooms request to server.
 
bool sendCreateRoom (const std::string &roomName, uint32_t maxPlayers, bool isPrivate, float gameSpeedMultiplier=1.0f)
 Send create room request to server.
 
bool sendJoinRoom (const std::string &roomId)
 Send join room request to server.
 
bool sendAutoMatchmaking ()
 Send auto-matchmaking request to server.
 
bool updateAutoMatchmakingPreference (bool enabled)
 Update auto-matchmaking preference on server.
 
bool sendStartGame ()
 Send start game request to server.
 
bool sendRequestRoomList ()
 Request the list of available rooms from server.
 
bool sendLeaveRoom ()
 Send request to leave current room.
 
bool sendChatMessage (const std::string &message)
 Send chat message to server.
 
bool getAutoMatchmakingPreference () const
 Get the user's auto-matchmaking preference from server.
 

Private Member Functions

void networkThreadLoop (std::stop_token stopToken)
 Network thread main loop.
 
void onInputEvent (const InputEvent &event)
 Handle an incoming packet from the network.
 
void processIncomingPacket (const std::vector< uint8_t > &packet)
 

Private Attributes

EventBus_eventBus
 
std::atomic< bool > _connected {false}
 
std::atomic< bool > _authenticated {false}
 
std::atomic< uint32_t > _myPlayerId {0}
 
std::string _lastLoginUsername
 
std::atomic< bool > _autoMatchmakingPreference {false}
 
bool _isSpectator
 
std::string _serverHost
 
uint16_t _serverPort = 0
 
std::atomic< uint32_t > _latency {0}
 
uint32_t _packetLoss = 0
 
std::unique_ptr< IHost_host
 
IPeer_serverPeer = nullptr
 
std::jthread _networkThread
 Dedicated network thread.
 
ThreadSafeQueue< NetworkEvent_incomingMessages
 Queue for messages from network thread.
 
std::atomic< float > _smoothedLatency {0.0f}
 

Static Private Attributes

static constexpr float PING_SMOOTHING_FACTOR = 0.3f
 

Detailed Description

Client-server network replication manager with dedicated network thread.

The Replicator is responsible for:

  • UDP/TCP communication with the server (dedicated thread)
  • Sending player inputs to the server
  • Receiving world state from the server
  • Measuring latency and packet loss
  • Publishing network events on the EventBus

Multi-threading architecture:

NETWORK THREAD GAME THREAD (ECS)
┌──────────────────┐ ┌──────────────────┐
while(running) { │ │ GameLoop { │
│ service() │ │ processNetwork │
│ receive packet │──[Queue]────>│ update ECS │
│ push to queue │ │ render │
│ } │ │ } │
└──────────────────┘ └──────────────────┘
Main game loop orchestrating all subsystems.
Definition GameLoop.hpp:57

Communication flow:

CLIENT SERVER
| |
|---[InputEvent]--------------->| (player inputs)
| |
|<--[WorldState]----------------| (authoritative state)
| |
|---[PING]--------------------->|
|<--[PONG]----------------------| (latency measurement)
Event representing a player input action.
@ PONG
Latency measurement response.
@ PING
Latency measurement request.

EventBus integration:

Definition at line 70 of file Replicator.hpp.

Constructor & Destructor Documentation

◆ Replicator()

Replicator::Replicator ( EventBus eventBus,
bool  isSpectator = false 
)
explicit

Constructor with EventBus reference.

Initializes the Replicator and subscribes to necessary events.

Parameters
eventBusEvent bus for inter-component communication
isSpectatorWhether this client is in spectator mode (read-only)
Note
The Replicator automatically subscribes to InputEvent (unless spectator)

Definition at line 13 of file Replicator.cpp.

◆ ~Replicator()

Replicator::~Replicator ( )

Destructor.

Properly disconnects from server and frees network resources.

Definition at line 15 of file Replicator.cpp.

References disconnect().

Here is the call graph for this function:

Member Function Documentation

◆ connect()

bool Replicator::connect ( const std::string &  host,
uint16_t  port 
)

Connect to the game server.

Establishes a UDP/TCP connection with the specified server. Publishes a ConnectionEvent based on the result.

Parameters
hostServer IP address or hostname
portServer port (typically 4242)
Returns
true if connection is established, false otherwise
Note
Blocking until timeout (recommended: 5 seconds)
Publishes ConnectionEvent::CONNECTED or FAILED

Definition at line 19 of file Replicator.cpp.

References _connected, _host, _serverHost, _serverPeer, _serverPort, createAddress(), and startNetworkThread().

Here is the call graph for this function:

◆ disconnect()

void Replicator::disconnect ( )

Disconnect from the server.

Closes the connection cleanly and cleans up resources. Publishes a ConnectionEvent::DISCONNECTED.

Definition at line 45 of file Replicator.cpp.

References _authenticated, _connected, _serverPeer, CONNECTED, CONNECTING, CONNECTION_SUCCEEDED, IPeer::disconnectNow(), IPeer::getState(), and stopNetworkThread().

Referenced by ~Replicator().

Here is the call graph for this function:

◆ getAutoMatchmakingPreference()

bool Replicator::getAutoMatchmakingPreference ( ) const
inline

Get the user's auto-matchmaking preference from server.

Returns the auto-matchmaking preference loaded from the server after login. This preference is persisted in the user's account on the server.

Returns
true if auto-matchmaking is enabled for this user

Definition at line 326 of file Replicator.hpp.

References _autoMatchmakingPreference.

◆ getLatency()

uint32_t Replicator::getLatency ( ) const

Get current latency in milliseconds.

Calculates average RTT (Round-Trip Time) based on PING/PONG.

Returns
Latency in milliseconds
Note
Updated every 1 second via heartbeat
Rolling average over the last 10 pings

Definition at line 541 of file Replicator.cpp.

References _latency.

Referenced by GameLoop::update().

◆ getMyPlayerId()

uint32_t Replicator::getMyPlayerId ( ) const
inline

Get the player ID assigned by server.

Returns
Player ID (0 if not yet authenticated)

Definition at line 133 of file Replicator.hpp.

References _myPlayerId.

Referenced by GameLoop::run().

◆ getPacketLoss()

uint32_t Replicator::getPacketLoss ( ) const

Get packet loss rate as percentage.

Calculates the ratio of lost packets over the last 100 sent.

Returns
Loss percentage (0-100)
Note
Based on missing ACKs
Real-time update

Definition at line 545 of file Replicator.cpp.

References _packetLoss.

◆ isAuthenticated()

bool Replicator::isAuthenticated ( ) const

Check if authenticated with server.

Returns
true if authentication succeeded, false otherwise

Definition at line 67 of file Replicator.cpp.

References _authenticated.

◆ isConnected()

bool Replicator::isConnected ( ) const

Check if connected to server.

Returns
true if connection is active, false otherwise

Definition at line 63 of file Replicator.cpp.

References _connected.

◆ isSpectator()

bool Replicator::isSpectator ( ) const

Check if in spectator mode.

Returns
true if this client is a spectator (read-only)

Definition at line 549 of file Replicator.cpp.

References _isSpectator.

Referenced by GameLoop::processInput().

◆ networkThreadLoop()

◆ onInputEvent()

void Replicator::onInputEvent ( const InputEvent event)
private

Handle an incoming packet from the network.

Parameters
packetRaw packet data

Decodes the packet and creates a NetworkEvent.

Definition at line 610 of file Replicator.cpp.

◆ processIncomingPacket()

void Replicator::processIncomingPacket ( const std::vector< uint8_t > &  packet)
private

Definition at line 615 of file Replicator.cpp.

◆ processMessages()

void Replicator::processMessages ( )

Process incoming network messages.

Processes messages from the network thread queue and publishes them on the EventBus. Must be called every frame from the game thread.

Actions performed:

Note
Non-blocking, processes all available messages
Thread-safe: called from game thread, reads from network thread queue

Definition at line 250 of file Replicator.cpp.

References _eventBus, _incomingMessages, NetworkMessages::getMessageType(), NetworkMessages::getPayload(), LOG_DEBUG, LOG_ERROR, LOG_INFO, EventBus::publish(), NetworkMessages::S2C_GAME_START, NetworkMessages::S2C_GAME_STATE, NetworkMessages::S2C_ROOM_LIST, NetworkMessages::S2C_ROOM_STATE, and ThreadSafeQueue< T >::tryPop().

Referenced by GameLoop::run().

Here is the call graph for this function:

◆ sendAutoMatchmaking()

bool Replicator::sendAutoMatchmaking ( )

Send auto-matchmaking request to server.

Automatically joins the first available room or creates a new one.

Returns
true if the packet was sent successfully

Definition at line 472 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::C2S_AUTO_MATCHMAKING, NetworkMessages::createMessage(), createPacket(), LOG_ERROR, LOG_INFO, RELIABLE, IPeer::send(), and RType::Messages::C2S::AutoMatchmaking::serialize().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

◆ sendChatMessage()

bool Replicator::sendChatMessage ( const std::string &  message)

Send chat message to server.

Sends a chat message to be broadcast to other players in the room. Messages starting with "/" are treated as commands.

Parameters
messageThe message text to send
Returns
true if the packet was sent successfully

Definition at line 579 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::C2S_CHAT_MESSAGE, NetworkMessages::createMessage(), createPacket(), LOG_DEBUG, LOG_ERROR, LOG_INFO, RELIABLE, IPeer::send(), and RType::Messages::C2S::C2SChatMessage::serialize().

Referenced by GameLoop::run().

Here is the call graph for this function:

◆ sendConnectRequest()

bool Replicator::sendConnectRequest ( const std::string &  playerName,
const std::string &  username,
const std::string &  password 
)

◆ sendCreateRoom()

bool Replicator::sendCreateRoom ( const std::string &  roomName,
uint32_t  maxPlayers,
bool  isPrivate,
float  gameSpeedMultiplier = 1.0f 
)

Send create room request to server.

Parameters
roomNameName of the room to create
maxPlayersMaximum number of players
isPrivateWhether the room is private
gameSpeedMultiplierGame speed multiplier (0.25 to 1.0, default 1.0)
Returns
true if the packet was sent successfully

Definition at line 430 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::C2S_CREATE_ROOM, NetworkMessages::createMessage(), createPacket(), RELIABLE, IPeer::send(), and RType::Messages::C2S::CreateRoom::serialize().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

◆ sendJoinRoom()

bool Replicator::sendJoinRoom ( const std::string &  roomId)

Send join room request to server.

Parameters
roomIdID of the room to join
Returns
true if the packet was sent successfully

Definition at line 450 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::C2S_JOIN_ROOM, NetworkMessages::createMessage(), createPacket(), LOG_ERROR, LOG_INFO, RELIABLE, IPeer::send(), and RType::Messages::C2S::JoinRoom::serialize().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

◆ sendLeaveRoom()

bool Replicator::sendLeaveRoom ( )

Send request to leave current room.

Returns
true if the packet was sent successfully

Definition at line 558 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::C2S_LEAVE_ROOM, NetworkMessages::createMessage(), createPacket(), LOG_INFO, RELIABLE, IPeer::send(), and RType::Messages::C2S::LeaveRoom::serialize().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

◆ sendListRooms()

bool Replicator::sendListRooms ( )

Send list rooms request to server.

Returns
true if the packet was sent successfully

Definition at line 411 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::C2S_LIST_ROOMS, NetworkMessages::createMessage(), createPacket(), RELIABLE, IPeer::send(), and RType::Messages::C2S::ListRooms::serialize().

Referenced by sendRequestRoomList().

Here is the call graph for this function:

◆ sendLoginAccount()

bool Replicator::sendLoginAccount ( const std::string &  username,
const std::string &  password 
)

Send login request to server.

Parameters
usernameAccount username
passwordAccount password
Returns
true if the packet was sent successfully

Definition at line 388 of file Replicator.cpp.

References _connected, _lastLoginUsername, _serverPeer, NetworkMessages::createMessage(), createPacket(), LOG_ERROR, NetworkMessages::LOGIN_REQUEST, RELIABLE, IPeer::send(), and RType::Messages::C2S::LoginAccount::serialize().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

◆ sendPacket()

void Replicator::sendPacket ( NetworkMessageType  type,
const std::vector< uint8_t > &  data 
)

Send a packet to the server.

Serializes and sends a message to the server asynchronously.

Parameters
typeMessage type (PLAYER_INPUT, PING, etc.)
dataPacket data (serialized)
Note
Non-blocking
Automatically adds a timestamp for latency measurement

Definition at line 329 of file Replicator.cpp.

References _connected, _serverPeer, createPacket(), RELIABLE, and IPeer::send().

Referenced by GameLoop::processInput().

Here is the call graph for this function:

◆ sendRegisterAccount()

bool Replicator::sendRegisterAccount ( const std::string &  username,
const std::string &  password 
)

Send register account request to server.

Parameters
usernameUsername for new account
passwordPassword for new account
Returns
true if the packet was sent successfully

Definition at line 367 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::createMessage(), createPacket(), LOG_ERROR, NetworkMessages::REGISTER_REQUEST, RELIABLE, IPeer::send(), and RType::Messages::C2S::RegisterAccount::serialize().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

◆ sendRequestRoomList()

bool Replicator::sendRequestRoomList ( )

Request the list of available rooms from server.

Returns
true if the packet was sent successfully

Definition at line 553 of file Replicator.cpp.

References LOG_INFO, and sendListRooms().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

◆ sendStartGame()

bool Replicator::sendStartGame ( )

Send start game request to server.

Only the host of the room can start the game.

Returns
true if the packet was sent successfully

Definition at line 519 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::C2S_START_GAME, NetworkMessages::createMessage(), createPacket(), LOG_ERROR, LOG_INFO, RELIABLE, IPeer::send(), and RType::Messages::C2S::StartGame::serialize().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

◆ startNetworkThread()

void Replicator::startNetworkThread ( )

Start the dedicated network thread.

Launches a background thread that continuously polls the network for incoming packets and pushes them to the message queue.

Note
Automatically called by connect()
Thread runs until disconnect() is called

Definition at line 71 of file Replicator.cpp.

References _networkThread, and networkThreadLoop().

Referenced by connect().

Here is the call graph for this function:

◆ stopNetworkThread()

void Replicator::stopNetworkThread ( )

Stop the dedicated network thread.

Signals the network thread to stop and waits for it to join.

Note
Automatically called by disconnect()

Definition at line 81 of file Replicator.cpp.

References _networkThread.

Referenced by disconnect().

◆ updateAutoMatchmakingPreference()

bool Replicator::updateAutoMatchmakingPreference ( bool  enabled)

Update auto-matchmaking preference on server.

Sends the user's auto-matchmaking preference to be saved on the server. Does not trigger immediate matchmaking.

Parameters
enabledWhether auto-matchmaking should be enabled
Returns
true if the packet was sent successfully

Definition at line 495 of file Replicator.cpp.

References _connected, _serverPeer, NetworkMessages::C2S_UPDATE_AUTO_MM_PREF, NetworkMessages::createMessage(), createPacket(), LOG_ERROR, LOG_INFO, RELIABLE, IPeer::send(), and RType::Messages::C2S::AutoMatchmaking::serialize().

Referenced by GameLoop::handleUIEvent().

Here is the call graph for this function:

Member Data Documentation

◆ _authenticated

std::atomic<bool> Replicator::_authenticated {false}
private

Definition at line 350 of file Replicator.hpp.

Referenced by disconnect(), isAuthenticated(), and networkThreadLoop().

◆ _autoMatchmakingPreference

std::atomic<bool> Replicator::_autoMatchmakingPreference {false}
private

Definition at line 353 of file Replicator.hpp.

Referenced by getAutoMatchmakingPreference(), and networkThreadLoop().

◆ _connected

◆ _eventBus

EventBus& Replicator::_eventBus
private

Definition at line 348 of file Replicator.hpp.

Referenced by networkThreadLoop(), and processMessages().

◆ _host

std::unique_ptr<IHost> Replicator::_host
private

Definition at line 361 of file Replicator.hpp.

Referenced by connect(), and networkThreadLoop().

◆ _incomingMessages

ThreadSafeQueue<NetworkEvent> Replicator::_incomingMessages
private

Queue for messages from network thread.

Definition at line 366 of file Replicator.hpp.

Referenced by networkThreadLoop(), and processMessages().

◆ _isSpectator

bool Replicator::_isSpectator
private

Definition at line 354 of file Replicator.hpp.

Referenced by isSpectator().

◆ _lastLoginUsername

std::string Replicator::_lastLoginUsername
private

Definition at line 352 of file Replicator.hpp.

Referenced by networkThreadLoop(), and sendLoginAccount().

◆ _latency

std::atomic<uint32_t> Replicator::_latency {0}
private

Definition at line 358 of file Replicator.hpp.

Referenced by getLatency(), and networkThreadLoop().

◆ _myPlayerId

std::atomic<uint32_t> Replicator::_myPlayerId {0}
private

Definition at line 351 of file Replicator.hpp.

Referenced by getMyPlayerId(), and networkThreadLoop().

◆ _networkThread

std::jthread Replicator::_networkThread
private

Dedicated network thread.

Definition at line 365 of file Replicator.hpp.

Referenced by startNetworkThread(), and stopNetworkThread().

◆ _packetLoss

uint32_t Replicator::_packetLoss = 0
private

Definition at line 359 of file Replicator.hpp.

Referenced by getPacketLoss().

◆ _serverHost

std::string Replicator::_serverHost
private

Definition at line 355 of file Replicator.hpp.

Referenced by connect().

◆ _serverPeer

◆ _serverPort

uint16_t Replicator::_serverPort = 0
private

Definition at line 356 of file Replicator.hpp.

Referenced by connect().

◆ _smoothedLatency

std::atomic<float> Replicator::_smoothedLatency {0.0f}
private

Definition at line 370 of file Replicator.hpp.

Referenced by networkThreadLoop().

◆ PING_SMOOTHING_FACTOR

constexpr float Replicator::PING_SMOOTHING_FACTOR = 0.3f
staticconstexprprivate

Definition at line 369 of file Replicator.hpp.

Referenced by networkThreadLoop().


The documentation for this class was generated from the following files: