Plugins API Reference

Plugin Interface

class PluginInterface2

RakNet’s plugin system. Each plugin processes the following events: -Connection attempts -The result of connection attempts -Each incoming message -Updates over time, when RakPeer::Receive() is called

Subclassed by MafiaNet::CloudClient, MafiaNet::CloudServer, MafiaNet::ConnectionGraph2, MafiaNet::DirectoryDeltaTransfer, MafiaNet::FileListTransfer, MafiaNet::FullyConnectedMesh2, MafiaNet::HTTPConnection2, MafiaNet::MessageFilter, MafiaNet::NatPunchthroughClient, MafiaNet::NatPunchthroughServer, MafiaNet::NatTypeDetectionClient, MafiaNet::NatTypeDetectionServer, MafiaNet::PacketLogger, MafiaNet::RPC4, MafiaNet::RakNetTransport2, MafiaNet::ReadyEvent, MafiaNet::RelayPlugin, MafiaNet::ReplicaManager3, MafiaNet::Router2, MafiaNet::StatisticsHistoryPlugin, MafiaNet::TeamBalancer, MafiaNet::TeamManager, MafiaNet::TwoWayAuthentication, MafiaNet::UDPProxyClient, MafiaNet::UDPProxyCoordinator, MafiaNet::UDPProxyServer

Public Functions

PluginInterface2()
virtual ~PluginInterface2()
inline virtual void OnAttach(void)

Called when the interface is attached.

inline virtual void OnDetach(void)

Called when the interface is detached.

inline virtual void Update(void)

Update is called every time a packet is checked for .

inline virtual PluginReceiveResult OnReceive(Packet *packet)

OnReceive is called for every packet.

Parameters:

packet[in] the packet that is being returned to the user

Returns:

True to allow the game and other plugins to get this message, false to absorb it

inline virtual void OnRakPeerStartup(void)

Called when RakPeer is initialized.

inline virtual void OnRakPeerShutdown(void)

Called when RakPeer is shutdown.

inline virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason)

Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system

Parameters:
  • systemAddress[in] The system whose connection was closed

  • rakNetGuid[in] The guid of the specified system

  • lostConnectionReason[in] How the connection was closed: manually, connection lost, or notification of disconnection

inline virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)

Called when we got a new connection

Parameters:
  • systemAddress[in] Address of the new connection

  • rakNetGuid[in] The guid of the specified system

  • isIncoming[in] If true, this is ID_NEW_INCOMING_CONNECTION, or the equivalent

inline virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason)

Called when a connection attempt fails

Parameters:
  • packet[in] Packet to be returned to the user

  • failedConnectionReason[in] Why the connection failed

inline virtual bool UsesReliabilityLayer(void) const

Queried when attached to RakPeer Return true to call OnDirectSocketSend(), OnDirectSocketReceive(), OnReliabilityLayerNotification(), OnInternalPacket(), and OnAck() If true, then you cannot call RakPeer::AttachPlugin() or RakPeer::DetachPlugin() for this plugin, while RakPeer is active

inline virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress)

Called on a send to the socket, per datagram, that does not go through the reliability layer

Parameters:
  • data[in] The data being sent

  • bitsUsed[in] How many bits long data is

  • remoteSystemAddress[in] Which system this message is being sent to

Pre:

To be called, UsesReliabilityLayer() must return true

inline virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress)

Called on a receive from the socket, per datagram, that does not go through the reliability layer

Parameters:
  • data[in] The data being sent

  • bitsUsed[in] How many bits long data is

  • remoteSystemAddress[in] Which system this message is being sent to

Pre:

To be called, UsesReliabilityLayer() must return true

inline virtual void OnReliabilityLayerNotification(const char *errorMessage, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError)

Called when the reliability layer rejects a send or receive

Parameters:
  • bitsUsed[in] How many bits long data is

  • remoteSystemAddress[in] Which system this message is being sent to

Pre:

To be called, UsesReliabilityLayer() must return true

inline virtual void OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time, int isSend)

Called on a send or receive of a message within the reliability layer

Parameters:
  • internalPacket[in] The user message, along with all send data.

  • frameNumber[in] The number of frames sent or received so far for this player depending on isSend . Indicates the frame of this user message.

  • remoteSystemAddress[in] The player we sent or got this packet from

  • time[in] The current time as returned by MafiaNet::GetTimeMS()

  • isSend[in] Is this callback representing a send event or receive event?

Pre:

To be called, UsesReliabilityLayer() must return true

inline virtual void OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time)

Called when we get an ack for a message we reliably sent

Parameters:
  • messageNumber[in] The numerical identifier for which message this is

  • remoteSystemAddress[in] The player we sent or got this packet from

  • time[in] The current time as returned by MafiaNet::GetTimeMS()

Pre:

To be called, UsesReliabilityLayer() must return true

inline virtual void OnPushBackPacket(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress)

System called RakPeerInterface::PushBackPacket

Parameters:
  • data[in] The data being sent

  • bitsUsed[in] How many bits long data is

  • remoteSystemAddress[in] The player we sent or got this packet from

inline RakPeerInterface *GetRakPeerInterface(void) const
RakNetGUID GetMyGUIDUnified(void) const
void SetRakPeerInterface(RakPeerInterface *ptr)
void SetTCPInterface(TCPInterface *ptr)

Networking Plugins

FullyConnectedMesh2

class FullyConnectedMesh2 : public MafiaNet::PluginInterface2

Fully connected mesh plugin, revision 2.

This will connect RakPeer

to all connecting peers, and all peers the connecting peer knows about.

It will also calculate which system has been running longest, to find out who should be host, if you need one system to act as a host

Pre:

You must also install the ConnectionGraph2 plugin in order to use SetConnectOnNewRemoteConnection()

Public Types

enum JoinInProgressState

Values:

enumerator JIPS_PROCESSING
enumerator JIPS_FAILED
enumerator JIPS_CONNECTED
enumerator JIPS_UNNECESSARY

Public Functions

FullyConnectedMesh2()
virtual ~FullyConnectedMesh2()
void SetConnectOnNewRemoteConnection(bool attemptConnection, MafiaNet::RakString pw)

When the message ID_REMOTE_NEW_INCOMING_CONNECTION arrives, we try to connect to that system If attemptConnection is false, you can manually connect to all systems listed in ID_REMOTE_NEW_INCOMING_CONNECTION with ConnectToRemoteNewIncomingConnections()

Note

This will not work on any console. It will also not work if NAT punchthrough is needed. Generally, this should be false and you should connect manually. It is here for legacy reasons.

Parameters:
  • attemptConnection[in] If true, we try to connect to any systems we are notified about with ID_REMOTE_NEW_INCOMING_CONNECTION, which comes from the ConnectionGraph2 plugin. Defaults to true.

  • pw[in] The password to use to connect with. Only used if attemptConnection is true

RakNetGUID GetConnectedHost(void) const

The connected host is whichever system we are connected to that has been running the longest.

Will return UNASSIGNED_RAKNET_GUID if we are not connected to anyone, or if we are connected and are calculating the host If includeCalculating is true, will return the estimated calculated host as long as the calculation is nearly complete includeCalculating should be true if you are taking action based on another system becoming host, because not all host calculations may complete at the exact same time

See also

ConnectionGraph2::GetLowestAveragePingSystem() . If you need one system in the peer to peer group to relay data, have the host call this function after host migration, and use that system

Returns:

System address of whichever system is host.

SystemAddress GetConnectedHostAddr(void) const
RakNetGUID GetHostSystem(void) const
Returns:

System address of whichever system is host. Always returns something, even though it may be our own system.

bool IsHostSystem(void) const
Returns:

If our system is host

void GetHostOrder(DataStructures::List<RakNetGUID> &hostList)

Get the list of connected systems, from oldest connected to newest This is also the order that the hosts will be chosen in

bool IsConnectedHost(void) const
Parameters:

includeCalculating[in] If true, and we are currently calculating a new host, return the new host if the calculation is nearly complete

Returns:

If our system is host

void SetAutoparticipateConnections(bool b)

Automatically add new connections to the fully connected mesh. Each remote system that you want to check should be added as a participant, either through SetAutoparticipateConnections() or by calling this function.

Defaults to true.

Parameters:

b[in] As stated

void ResetHostCalculation(void)

Clear our own host order, and recalculate as if we had just reconnected Call this to reset the running time of the host just before joining/creating a game room for networking

void AddParticipant(RakNetGUID rakNetGuid)

if SetAutoparticipateConnections() is called with false, then you need to use AddParticipant before these systems will be added to the mesh FullyConnectedMesh2 will track who is the who host among a fully connected mesh of participants Each remote system that you want to check should be added as a participant, either through SetAutoparticipateConnections() or by calling this function

Parameters:
  • participant[in] The new participant

  • userContext[in] Static data to be passed around with each participant, which can be queried with GetParticipantData().

void GetParticipantList(DataStructures::List<RakNetGUID> &participantList)

Get the participants added with AddParticipant()

Parameters:

participantList[out] Participants added with AddParticipant();

bool HasParticipant(RakNetGUID participantGuid)

Returns if a participant is in the participant list.

Parameters:

RakNetGUID – of the participant to query

Returns:

True if in the list

void ConnectToRemoteNewIncomingConnections(Packet *packet)

Reads userData written with SetMyContext()

Parameters:
  • RakNetGUID – of the participant to query

  • userContext[out] Pointer to BitStream to be written to

  • userContext[in] Pointer to BitStream to be read from Connect to all systems from ID_REMOTE_NEW_INCOMING_CONNECTION You can call this if SetConnectOnNewRemoteConnection is false

  • packet[in] The packet containing ID_REMOTE_NEW_INCOMING_CONNECTION

  • connectionPassword[in] Password passed to RakPeerInterface::Connect()

  • connectionPasswordLength[in] Password length passed to RakPeerInterface::Connect()

Returns:

True if data was written Set data for other systems to read with GetParticipantContext

void Clear(void)

Clear all memory and reset everything.

unsigned int GetParticipantCount(void) const
void GetParticipantCount(unsigned int *participantListSize) const
virtual void StartVerifiedJoin(RakNetGUID client)

Notify the client of GetParticipantList() in order to connect to each of those systems until the mesh has been completed.

In the simple case of forming a peer to peer mesh:

  1. AddParticipant() is called on the host whenever you get a new connection

  2. The host sends all participants to the new client

  3. The client connects to the participant list

However, the above steps assumes connections to all systems in the mesh always complete. When there is a risk of failure, such as if relying on NATPunchthroughClient, you may not want to call AddParticipant() until are connections have completed to all other particpants StartVerifiedJoin() can manage the overhead of the negotiation involved so the programmer only has to deal with overall success or failure

Processing:

  1. Send the RakNetGUID and SystemAddress values of GetParticipantList() to the client with ID_FCM2_VERIFIED_JOIN_START

  2. The client, on ID_FCM2_VERIFIED_JOIN_START, can execute NatPunchthroughClient::OpenNAT() (optional), followed by RakPeerInterface::Connect() if punchthrough success, for each system returned from GetVerifiedJoinRequiredProcessingList()

  3. After all participants in step 2 have connected, failed to connect, or failed NatPunchthrough, the client automatically sends the results to the server.

  4. The server compares the results of the operations in step 2 with the values from GetParticpantList(). 4A. If the client failed to connect to a current participant, return ID_FCM2_VERIFIED_JOIN_FAILED to the client. CloseConnection() is automatically called on the client for the failed participants. 4B. If AddParticipant() was called between steps 1 and 4, go back to step 1, transmitting new participants. 4C. If the client successfully connected to all participants, the server gets ID_FCM2_VERIFIED_JOIN_CAPABLE. The server programmer, on the same frame, should execute RespondOnVerifiedJoinCapable() to either accept or reject the client.

  5. If the client got ID_FCM2_VERIFIED_JOIN_ACCEPTED, AddParticipant() is automatically called for each system in the mesh.

  6. If the client got ID_FCM2_VERIFIED_JOIN_REJECTED, CloseConnection() is automatically called for each system in the mesh. The connection is NOT automatically closed to the original host that sent StartVerifiedJoin().

  7. If the client’s connection to the server was lost before getting ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED, return to the programmer ID_FCM2_VERIFIED_JOIN_FAILED and call RakPeerInterface::CloseConnection()

Parameters:

client[in] The system to send ID_FCM2_VERIFIED_JOIN_START to

virtual void RespondOnVerifiedJoinCapable(Packet *packet, bool accept, BitStream *additionalData)

On ID_FCM2_VERIFIED_JOIN_CAPABLE , accept or reject the new connection.

fullyConnectedMesh->RespondOnVerifiedJoinCapable(packet, true, 0);

Parameters:
  • packet[in] The system that sent ID_FCM2_VERIFIED_JOIN_CAPABLE. Based on \accept, ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED will be sent in reply

  • accept[in] True to accept, and thereby automatically call AddParticipant() on all systems on the mesh. False to reject, and call CloseConnection() to all mesh systems on the target

  • additionalData[in] Any additional data you want to add to the ID_FCM2_VERIFIED_JOIN_ACCEPTED or ID_FCM2_VERIFIED_JOIN_REJECTED messages

virtual void GetVerifiedJoinRequiredProcessingList(RakNetGUID host, DataStructures::List<SystemAddress> &addresses, DataStructures::List<RakNetGUID> &guids, DataStructures::List<BitStream*> &userData)

On ID_FCM2_VERIFIED_JOIN_START, read the SystemAddress and RakNetGUID values of each system to connect to.

DataStructures::List<SystemAddress> addresses;
DataStructures::List<RakNetGUID> guids;
fullyConnectedMesh->GetVerifiedJoinRequiredProcessingList(packet->guid, addresses, guids);
for (unsigned int i=0; i < addresses.Size(); i++)
    rakPeer[i]->Connect(addresses[i].ToString(false), addresses[i].GetPort(), 0, 0);

Parameters:
  • host[in] Which system sent ID_FCM2_VERIFIED_JOIN_START

  • addresses[out] SystemAddress values of systems to connect to. List has the same number and order as guids

  • guids[out] RakNetGUID values of systems to connect to. List has the same number and order as guids

  • userData[out] What was written with WriteVJSUserData

virtual void GetVerifiedJoinAcceptedAdditionalData(Packet *packet, bool *thisSystemAccepted, DataStructures::List<RakNetGUID> &systemsAccepted, BitStream *additionalData)

On ID_FCM2_VERIFIED_JOIN_ACCEPTED, read additional data passed to RespondOnVerifiedJoinCapable()

bool thisSystemAccepted;
DataStructures::List<RakNetGUID> systemsAccepted;
MafiaNet::BitStream additionalData;
fullyConnectedMesh->GetVerifiedJoinAcceptedAdditionalData(packet, &thisSystemAccepted, systemsAccepted, &additionalData);

Parameters:
  • packet[in] Packet containing the ID_FCM2_VERIFIED_JOIN_ACCEPTED message

  • thisSystemAccepted[out] If true, it was this instance of RakPeerInterface that was accepted. If false, this is notification for another system

  • systemsAccepted[out] Which system(s) were added with AddParticipant(). If thisSystemAccepted is false, this list will only have length 1

  • additionalData[out] additionalData parameter passed to RespondOnVerifiedJoinCapable()

virtual void GetVerifiedJoinRejectedAdditionalData(Packet *packet, BitStream *additionalData)

On ID_FCM2_VERIFIED_JOIN_REJECTED, read additional data passed to RespondOnVerifiedJoinCapable()

This does not automatically close the connection. The following code will do so:

rakPeer[i]->CloseConnection(packet->guid, true);

Parameters:
inline virtual void WriteVJCUserData(MafiaNet::BitStream *bsOut)

Override to write data when ID_FCM2_VERIFIED_JOIN_CAPABLE is sent.

inline virtual void WriteVJSUserData(MafiaNet::BitStream *bsOut, RakNetGUID userGuid)

Write custom user data to be sent with ID_FCM2_VERIFIED_JOIN_START, per user

Parameters:
  • bsOut[out] Write your data here, if any. Has to match what is read by ReadVJSUserData

  • userGuid[in] The RakNetGuid of the user you are writing for

  • userContext[in] The data set with SetMyContext() for that system. May be empty. To properly write userContext, you will need to first write userContext->GetNumberOfBitsUsed(), followed by bsOut->Write(userContext);

MafiaNet::TimeUS GetElapsedRuntime(void)
virtual PluginReceiveResult OnReceive(Packet *packet)

OnReceive is called for every packet.

Parameters:

packet[in] the packet that is being returned to the user

Returns:

True to allow the game and other plugins to get this message, false to absorb it

virtual void OnRakPeerStartup(void)

Called when RakPeer is initialized.

virtual void OnAttach(void)

Called when the interface is attached.

virtual void OnRakPeerShutdown(void)

Called when RakPeer is shutdown.

virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason)

Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system

Parameters:
  • systemAddress[in] The system whose connection was closed

  • rakNetGuid[in] The guid of the specified system

  • lostConnectionReason[in] How the connection was closed: manually, connection lost, or notification of disconnection

virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)

Called when we got a new connection

Parameters:
  • systemAddress[in] Address of the new connection

  • rakNetGuid[in] The guid of the specified system

  • isIncoming[in] If true, this is ID_NEW_INCOMING_CONNECTION, or the equivalent

virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason)

Called when a connection attempt fails

Parameters:
  • packet[in] Packet to be returned to the user

  • failedConnectionReason[in] Why the connection failed

unsigned int GetTotalConnectionCount(void) const

Public Static Functions

static FullyConnectedMesh2 *GetInstance(void)
static void DestroyInstance(FullyConnectedMesh2 *i)
static void SkipToVJCUserData(MafiaNet::BitStream *bsIn)

Use to read data written from WriteVJCUserData()

MafiaNet::BitStream bsIn(packet->data,packet->length,false);
FullyConnectedMesh2::SkipToVJCUserData(&bsIn);
// Your code here

struct FCM2Participant

Public Functions

inline FCM2Participant()
inline FCM2Participant(const FCM2Guid &_fcm2Guid, const RakNetGUID &_rakNetGuid)

Public Members

FCM2Guid fcm2Guid
RakNetGUID rakNetGuid
struct VerifiedJoinInProgress

Public Members

RakNetGUID requester
DataStructures::List<VerifiedJoinInProgressMember> vjipMembers
struct VerifiedJoinInProgressMember

Public Members

SystemAddress systemAddress
RakNetGUID guid
JoinInProgressState joinInProgressState
BitStream *userData
bool workingFlag

NatPunchthroughClient

class NatPunchthroughClient : public MafiaNet::PluginInterface2

Client code for NATPunchthrough.

Maintain connection to NatPunchthroughServer to process incoming connection attempts through NatPunchthroughClient

Client will send datagrams to port to estimate next port

Will simultaneously connect with another client once ports are estimated.

Public Functions

NatPunchthroughClient()
~NatPunchthroughClient()
void FindRouterPortStride(const SystemAddress &facilitator)

If the instance of RakPeer running NATPunchthroughServer was bound to two IP addresses, then you can call FindRouterPortStride() This will determine the stride that your router uses when assigning ports, if your router is full-cone This function is also called automatically when you call OpenNAT - however, calling it earlier when you are connected to the facilitator will speed up the process

Parameters:

destination[in] The system to punch. Must already be connected to facilitator

bool OpenNAT(RakNetGUID destination, const SystemAddress &facilitator)

Punchthrough a NAT. Doesn’t connect, just tries to setup the routing table

See also

OpenNATGroup() You will get ID_NAT_PUNCHTHROUGH_SUCCEEDED on success You will get ID_NAT_TARGET_NOT_CONNECTED, ID_NAT_TARGET_UNRESPONSIVE, ID_NAT_CONNECTION_TO_TARGET_LOST, ID_NAT_ALREADY_IN_PROGRESS, or ID_NAT_PUNCHTHROUGH_FAILED on failures of various types However, if you lose connection to the facilitator, you may not necessarily get above

Parameters:
  • destination[in] The system to punch. Must already be connected to facilitator

  • facilitator[in] A system we are already connected to running the NatPunchthroughServer plugin

PunchthroughConfiguration *GetPunchthroughConfiguration(void)

Modify the system configuration if desired Don’t modify the variables in the structure while punchthrough is in progress

void SetDebugInterface(NatPunchthroughDebugInterface *i)

Sets a callback to be called with debug messages

Parameters:

i[in] Pointer to an interface. The pointer is stored, so don’t delete it while in progress. Pass 0 to clear.

void GetUPNPPortMappings(char *externalPort, char *internalPort, const SystemAddress &natPunchthroughServerAddress)

Get the port mappings you should pass to UPNP (for miniupnpc-1.6.20120410, for the function UPNP_AddPortMapping)

virtual void Update(void)

Update is called every time a packet is checked for .

virtual PluginReceiveResult OnReceive(Packet *packet)

OnReceive is called for every packet.

Parameters:

packet[in] the packet that is being returned to the user

Returns:

True to allow the game and other plugins to get this message, false to absorb it

virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)

Called when we got a new connection

Parameters:
  • systemAddress[in] Address of the new connection

  • rakNetGuid[in] The guid of the specified system

  • isIncoming[in] If true, this is ID_NEW_INCOMING_CONNECTION, or the equivalent

virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason)

Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system

Parameters:
  • systemAddress[in] The system whose connection was closed

  • rakNetGuid[in] The guid of the specified system

  • lostConnectionReason[in] How the connection was closed: manually, connection lost, or notification of disconnection

virtual void OnAttach(void)

Called when the interface is attached.

virtual void OnDetach(void)

Called when the interface is detached.

virtual void OnRakPeerShutdown(void)

Called when RakPeer is shutdown.

void Clear(void)

Public Members

struct MafiaNet::NatPunchthroughClient::SendPing sp

Public Static Functions

static NatPunchthroughClient *GetInstance(void)
static void DestroyInstance(NatPunchthroughClient *i)
struct SendPing

Public Types

enum TestMode

Values:

enumerator TESTING_INTERNAL_IPS
enumerator WAITING_FOR_INTERNAL_IPS_RESPONSE
enumerator TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_FACILITATOR_PORT
enumerator TESTING_EXTERNAL_IPS_1024_TO_FACILITATOR_PORT
enumerator TESTING_EXTERNAL_IPS_FACILITATOR_PORT_TO_1024
enumerator TESTING_EXTERNAL_IPS_1024_TO_1024
enumerator WAITING_AFTER_ALL_ATTEMPTS
enumerator PUNCHING_FIXED_PORT

Public Members

MafiaNet::Time nextActionTime
SystemAddress targetAddress
SystemAddress facilitator
SystemAddress internalIds[10]
RakNetGUID targetGuid
bool weAreSender
int attemptCount
int retryCount
int punchingFixedPortAttempts
uint16_t sessionId
bool sentTTL
enum MafiaNet::NatPunchthroughClient::SendPing::TestMode testMode

NatPunchthroughServer

class NatPunchthroughServer : public MafiaNet::PluginInterface2

Server code for NATPunchthrough.

Maintain connection to NatPunchthroughServer to process incoming connection attempts through NatPunchthroughClient

Server maintains two sockets clients can connect to so as to estimate the next port choice

Server tells other client about port estimate, current public port to the server, and a time to start connection attempts

Public Functions

NatPunchthroughServer()
virtual ~NatPunchthroughServer()
void SetDebugInterface(NatPunchthroughServerDebugInterface *i)

Sets a callback to be called with debug messages

Parameters:

i[in] Pointer to an interface. The pointer is stored, so don’t delete it while in progress. Pass 0 to clear.

virtual void Update(void)

Update is called every time a packet is checked for .

virtual PluginReceiveResult OnReceive(Packet *packet)

OnReceive is called for every packet.

Parameters:

packet[in] the packet that is being returned to the user

Returns:

True to allow the game and other plugins to get this message, false to absorb it

virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason)

Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system

Parameters:
  • systemAddress[in] The system whose connection was closed

  • rakNetGuid[in] The guid of the specified system

  • lostConnectionReason[in] How the connection was closed: manually, connection lost, or notification of disconnection

virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)

Called when we got a new connection

Parameters:
  • systemAddress[in] Address of the new connection

  • rakNetGuid[in] The guid of the specified system

  • isIncoming[in] If true, this is ID_NEW_INCOMING_CONNECTION, or the equivalent

Public Members

MafiaNet::Time lastUpdate

Public Static Functions

static NatPunchthroughServer *GetInstance(void)
static void DestroyInstance(NatPunchthroughServer *i)
static int NatPunchthroughUserComp(const RakNetGUID &key, User *const &data)
struct ConnectionAttempt

Public Types

Values:

enumerator NAT_ATTEMPT_PHASE_NOT_STARTED
enumerator NAT_ATTEMPT_PHASE_GETTING_RECENT_PORTS

Public Functions

inline ConnectionAttempt()

Public Members

User *sender
User *recipient
uint16_t sessionId
MafiaNet::Time startTime
enum MafiaNet::NatPunchthroughServer::ConnectionAttempt attemptPhase
struct User

Public Functions

bool HasConnectionAttemptToUser(User *user)
void DerefConnectionAttempt(ConnectionAttempt *ca)
void DeleteConnectionAttempt(ConnectionAttempt *ca)
void LogConnectionAttempts(MafiaNet::RakString &rs)

Public Members

RakNetGUID guid
SystemAddress systemAddress
unsigned short mostRecentPort
bool isReady
DataStructures::OrderedList<RakNetGUID, RakNetGUID> groupPunchthroughRequests
DataStructures::List<ConnectionAttempt*> connectionAttempts

Router2

class Router2 : public MafiaNet::PluginInterface2

Class interface for the Router2 system.

Public Types

enum Router2RequestStates

Values:

enumerator R2RS_REQUEST_STATE_QUERY_FORWARDING
enumerator REQUEST_STATE_REQUEST_FORWARDING

Public Functions

Router2()
virtual ~Router2()
void SetSocketFamily(unsigned short _socketFamily)

Sets the socket family to use, either IPV4 or IPV6

Parameters:

socketFamily[in] For IPV4, use AF_INET (default). For IPV6, use AF_INET6. To autoselect, use AF_UNSPEC.

void EstablishRouting(RakNetGUID endpointGuid)

Query all connected systems to connect through them to a third system. System will return ID_ROUTER_2_FORWARDING_NO_PATH if unable to connect. Else you will get ID_ROUTER_2_FORWARDING_ESTABLISHED.

On ID_ROUTER_2_FORWARDING_ESTABLISHED, EstablishRouting as follows:

MafiaNet::BitStream bs(packet->data, packet->length, false); bs.IgnoreBytes(sizeof(MessageID)); RakNetGUID endpointGuid; bs.Read(endpointGuid); unsigned short sourceToDestPort; bs.Read(sourceToDestPort); char ipAddressString[32]; packet->systemAddress.ToString(false, ipAddressString); rakPeerInterface->EstablishRouting(ipAddressString, sourceToDestPort, 0,0);

Note

The SystemAddress for a connection should not be used - always use RakNetGuid as the address can change at any time. When the address changes, you will get ID_ROUTER_2_REROUTED

void SetMaximumForwardingRequests(int max)

Set the maximum number of bidirectional connections this system will support Defaults to 0

void SetDebugInterface(Router2DebugInterface *_debugInterface)

For testing and debugging.

Router2DebugInterface *GetDebugInterface(void) const

Get the pointer passed to SetDebugInterface()

virtual PluginReceiveResult OnReceive(Packet *packet)

OnReceive is called for every packet.

Parameters:

packet[in] the packet that is being returned to the user

Returns:

True to allow the game and other plugins to get this message, false to absorb it

virtual void Update(void)

Update is called every time a packet is checked for .

virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason)

Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system

Parameters:
  • systemAddress[in] The system whose connection was closed

  • rakNetGuid[in] The guid of the specified system

  • lostConnectionReason[in] How the connection was closed: manually, connection lost, or notification of disconnection

virtual void OnFailedConnectionAttempt(Packet *packet, PI2_FailedConnectionAttemptReason failedConnectionAttemptReason)

Called when a connection attempt fails

Parameters:
  • packet[in] Packet to be returned to the user

  • failedConnectionReason[in] Why the connection failed

virtual void OnRakPeerShutdown(void)

Called when RakPeer is shutdown.

unsigned int GetConnectionRequestIndex(RakNetGUID endpointGuid)

Public Static Functions

static Router2 *GetInstance(void)
static void DestroyInstance(Router2 *i)
struct ConnectionRequestSystem

Public Members

RakNetGUID guid
int pingToEndpoint
unsigned short usedForwardingEntries
struct ConnnectRequest

Public Functions

ConnnectRequest()
~ConnnectRequest()
unsigned int GetGuidIndex(RakNetGUID guid)

Public Members

DataStructures::List<ConnectionRequestSystem> connectionRequestSystems
SimpleMutex connectionRequestSystemsMutex
Router2RequestStates requestState
MafiaNet::TimeMS pingTimeout
RakNetGUID endpointGuid
RakNetGUID lastRequestedForwardingSystem
bool returnConnectionLostOnFailure
struct ForwardedConnection

Public Members

RakNetGUID endpointGuid
RakNetGUID intermediaryGuid
SystemAddress intermediaryAddress
bool returnConnectionLostOnFailure
bool weInitiatedForwarding
struct MiniPunchRequest

Public Members

RakNetGUID endpointGuid
SystemAddress endpointAddress
bool gotReplyFromEndpoint
RakNetGUID sourceGuid
SystemAddress sourceAddress
bool gotReplyFromSource
MafiaNet::TimeMS timeout
MafiaNet::TimeMS nextAction
unsigned short forwardingPort
__UDPSOCKET__ forwardingSocket

Data Transfer Plugins

FileListTransfer

class FileListTransfer : public MafiaNet::PluginInterface2

A plugin to provide a simple way to compress and incrementally send the files in the FileList structure.

Similar to the DirectoryDeltaTransfer plugin, except that it doesn’t send deltas based on pre-existing files or actually write the files to disk.

Usage: Call SetupReceive to allow one file set to arrive. The value returned by FileListTransfer::SetupReceive()

is the setID that is allowed.

It’s up to you to transmit this value to the other system, along with information indicating what kind of files you want to get.

The other system should then prepare a FileList and call FileListTransfer::Send(), passing the return value of FileListTransfer::SetupReceive() as the setID parameter to FileListTransfer::Send()

Public Functions

FileListTransfer()
virtual ~FileListTransfer()
void StartIncrementalReadThreads(int numThreads, int threadPriority = -99999)

Optionally start worker threads when using _incrementalReadInterface for the Send() operation.

Parameters:
  • numThreads[in] how many worker threads to start

  • threadPriority[in] Passed to the thread creation routine. Use THREAD_PRIORITY_NORMAL for Windows. For Linux based systems, you MUST pass something reasonable based on the thread priorities for your application.

unsigned short SetupReceive(FileListTransferCBInterface *handler, bool deleteHandler, SystemAddress allowedSender)

Allows one corresponding Send() call from another system to arrive.

Parameters:
  • handler[in] The class to call on each file

  • deleteHandler[in] True to delete the handler when it is no longer needed. False to not do so.

  • allowedSender[in] Which system to allow files from.

Returns:

A set ID value, which should be passed as the setID value to the Send() call on the other system. This value will be returned in the callback and is unique per file set. Returns 65535 on failure (not connected to sender)

void Send(FileList *fileList, MafiaNet::RakPeerInterface *rakPeer, SystemAddress recipient, unsigned short setID, PacketPriority priority, char orderingChannel, IncrementalReadInterface *_incrementalReadInterface = 0, unsigned int _chunkSize = 262144 * 4 * 16)

Send the FileList structure to another system, which must have previously called SetupReceive().

Parameters:
  • fileList[in] A list of files. The data contained in FileList::data will be sent incrementally and compressed among all files in the set

  • rakPeer[in] The instance of RakNet to use to send the message. Pass 0 to use the instance the plugin is attached to

  • recipient[in] The address of the system to send to

  • setID[in] The return value of SetupReceive() which was previously called on recipient

  • priority[in] Passed to RakPeerInterface::Send()

  • orderingChannel[in] Passed to RakPeerInterface::Send()

  • _incrementalReadInterface[in] If a file in fileList has no data, _incrementalReadInterface will be used to read the file in chunks of size chunkSize

  • _chunkSize[in] How large of a block of a file to read/send at once. Large values use more memory but transfer slightly faster.

unsigned int GetPendingFilesToAddress(SystemAddress recipient)

Return number of files waiting to go out to a particular address.

void CancelReceive(unsigned short inSetId)

Stop a download.

void RemoveReceiver(SystemAddress systemAddress)

Remove all handlers associated with a particular system address.

bool IsHandlerActive(unsigned short inSetId)

Is a handler passed to SetupReceive still running?

void AddCallback(FileListProgress *cb)

Adds a callback to get progress reports about what the file list instances do.

Parameters:

cb[in] A pointer to an externally defined instance of FileListProgress. This pointer is held internally, so should remain valid as long as this class is valid.

void RemoveCallback(FileListProgress *cb)

Removes a callback.

Parameters:

cb[in] A pointer to an externally defined instance of FileListProgress that was previously added with AddCallback()

void ClearCallbacks(void)

Removes all callbacks.

void GetCallbacks(DataStructures::List<FileListProgress*> &callbacks)

Returns all callbacks added with AddCallback()

Parameters:

callbacks[out] The list is set to the list of callbacks

virtual PluginReceiveResult OnReceive(Packet *packet)

OnReceive is called for every packet.

Parameters:

packet[in] the packet that is being returned to the user

Returns:

True to allow the game and other plugins to get this message, false to absorb it

virtual void OnRakPeerShutdown(void)

Called when RakPeer is shutdown.

virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason)

Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system

Parameters:
  • systemAddress[in] The system whose connection was closed

  • rakNetGuid[in] The guid of the specified system

  • lostConnectionReason[in] How the connection was closed: manually, connection lost, or notification of disconnection

virtual void Update(void)

Update is called every time a packet is checked for .

Public Static Functions

static FileListTransfer *GetInstance(void)
static void DestroyInstance(FileListTransfer *i)

Game Plugins

ReplicaManager3

class ReplicaManager3 : public MafiaNet::PluginInterface2

System to help automate game object construction, destruction, and serialization.

ReplicaManager3

tracks your game objects and automates the networking for replicating them across the network

As objects are created, destroyed, or serialized differently, those changes are pushed out to other systems.

To use:
  1. Derive from Connection_RM3 and implement Connection_RM3::AllocReplica(). This is a factory function where given a user-supplied identifier for a class (such as name) return an instance of that class. Should be able to return any networked object in your game.

  2. Derive from ReplicaManager3 and implement AllocConnection() and DeallocConnection() to return the class you created in step 1.

  3. Derive your networked game objects from Replica3. All pure virtuals have to be implemented, however defaults are provided for Replica3::QueryConstruction(), Replica3::QueryRemoteConstruction(), and Replica3::QuerySerialization() depending on your network architecture.

  4. When a new game object is created on the local system, pass it to ReplicaManager3::Reference().

  5. When a game object is destroyed on the local system, and you want other systems to know about it, call Replica3::BroadcastDestruction()

At this point, all new connections will automatically download, get construction messages, get destruction messages, and update serialization automatically.

Public Functions

ReplicaManager3()
virtual ~ReplicaManager3()
virtual Connection_RM3 *AllocConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID) const = 0

Implement to return a game specific derivation of Connection_RM3.

The connection object represents a remote system connected to you that is using the ReplicaManager3

system.

It has functions to perform operations per-connection.

AllocConnection() and DeallocConnection()

are factory functions to create and destroy instances of the connection object.

It is used if autoCreate is true via

SetAutoManageConnections() (true by default). Otherwise, the function is not called, and you will have to call PushConnection() manually

Note

If you do not want a new network connection to immediately download game objects, SetAutoManageConnections() and PushConnection() are how you do this.

Parameters:
  • systemAddress[in] Address of the system you are adding

  • rakNetGUID[in] GUID of the system you are adding. See Packet::rakNetGUID or RakPeerInterface::GetGUIDFromSystemAddress()

Returns:

The new connection instance.

virtual void DeallocConnection(Connection_RM3 *connection) const = 0

Implement to destroy a class instanced returned by AllocConnection()

Most likely just implement as {delete connection;}

It is used if autoDestroy is true via

SetAutoManageConnections() (true by default). Otherwise, the function is not called and you would then be responsible for deleting your own connection objects.

Parameters:

connection[in] The pointer instance to delete

void SetAutoManageConnections(bool autoCreate, bool autoDestroy)

Enable or disable automatically assigning connections to new instances of Connection_RM3.

ReplicaManager3 can automatically create and/or destroy Connection_RM3 as systems connect or disconnect from RakPeerInterface

.

By default this is on, to make the system easier to learn and setup.

If you don’t want all connections to take part in the game, or you want to delay when a connection downloads the game, set autoCreate

to false.

If you want to delay deleting a connection that has dropped, set

autoDestroy to false. If you do this, then you must call PopConnection() to remove that connection from being internally tracked. You’ll also have to delete the connection instance on your own.

Parameters:
bool GetAutoCreateConnections(void) const
Returns:

What was passed to the autoCreate parameter of SetAutoManageConnections()

bool GetAutoDestroyConnections(void) const
Returns:

What was passed to the autoDestroy parameter of SetAutoManageConnections()

void AutoCreateConnectionList(DataStructures::List<RakNetGUID> &participantListIn, DataStructures::List<Connection_RM3*> &participantListOut, WorldId worldId = 0)

Call AllocConnection() and PushConnection() for each connection in participantList.

Parameters:
  • participantListIn[in] The list of connections to allocate

  • participantListOut[in] The connections allocated, if any

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

bool PushConnection(MafiaNet::Connection_RM3 *newConnection, WorldId worldId = 0)

Track a new Connection_RM3 instance.

If autoCreate is false for SetAutoManageConnections(), then you need this function to add new instances of Connection_RM3

yourself.

You don’t need to track this pointer yourself, you can get it with

GetConnectionAtIndex(), GetConnectionByGUID(), or GetConnectionBySystemAddress().

Parameters:
  • newConnection[in] The new connection instance to track.

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

MafiaNet::Connection_RM3 *PopConnection(RakNetGUID guid, WorldId worldId = 0)

Stop tracking a connection.

On call, for each replica returned by GetReplicasCreatedByGuid()

, QueryActionOnPopConnection() will be called. Depending on the return value, this may delete the corresponding replica.

If autoDestroy is true in the call to

SetAutoManageConnections() (true by default) then this is called automatically when the connection is lost. In that case, the returned connection instance is deleted.

Parameters:
void Reference(MafiaNet::Replica3 *replica3, WorldId worldId = 0)

Adds a replicated object to the system.

Anytime you create a new object that derives from Replica3, and you want ReplicaManager3 to use it, pass it to Reference()

.

Remote systems already connected will potentially download this object the next time

ReplicaManager3::Update() is called, which happens every time you call RakPeerInterface::Receive()

.

You can also call

ReplicaManager3::Update() manually to send referenced objects right away

Parameters:
  • replica3[in] The object to start tracking

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

void Dereference(MafiaNet::Replica3 *replica3, WorldId worldId = 0)

Removes a replicated object from the system.

The object is not deallocated, it is up to the caller to do so.

This is called automatically from the destructor of

Replica3, so you don’t need to call it manually unless you want to stop tracking an object before it is destroyed.

Parameters:
  • replica3[in] The object to stop tracking

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

void DereferenceList(DataStructures::List<Replica3*> &replicaListIn, WorldId worldId = 0)

Removes multiple replicated objects from the system.

Same as Dereference()

, but for a list of objects.

Useful with the lists returned by

GetReplicasCreatedByGuid(), GetReplicasCreatedByMe(), or GetReferencedReplicaList().

Parameters:
  • replicaListIn[in] List of objects

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

void GetReplicasCreatedByGuid(RakNetGUID guid, DataStructures::List<Replica3*> &replicaListOut, WorldId worldId = 0)

Returns all objects originally created by a particular system.

Originally created is defined as the value of Replica3::creatingSystemGUID, which is automatically assigned in ReplicaManager3::Reference()

.

You do not have to be directly connected to that system to get the objects originally created by that system.

Parameters:
  • guid[in] GUID of the system we are referring to. Originally passed as the guid parameter to ReplicaManager3::AllocConnection()

  • List[out] of Replica3 instances to be returned

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

void GetReplicasCreatedByMe(DataStructures::List<Replica3*> &replicaListOut, WorldId worldId = 0)

Returns all objects originally created by your system.

Calls GetReplicasCreatedByGuid() for your own system guid.

Parameters:
  • List[out] of Replica3 instances to be returned

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

void GetReferencedReplicaList(DataStructures::List<Replica3*> &replicaListOut, WorldId worldId = 0)

Returns the entire list of Replicas that we know about.

This is all Replica3 instances passed to Reference, as well as instances we downloaded and created via Connection_RM3::AllocReference()

Parameters:
  • List[out] of Replica3 instances to be returned

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

unsigned GetReplicaCount(WorldId worldId = 0) const

Returns the number of replicas known about.

Returns the size of the list that would be returned by GetReferencedReplicaList()

Parameters:

worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

Returns:

How many replica objects are in the list of replica objects

Replica3 *GetReplicaAtIndex(unsigned index, WorldId worldId = 0) const

Returns a replica by index.

Returns one of the items in the list that would be returned by GetReferencedReplicaList()

Parameters:
  • index[in] An index, from 0 to GetReplicaCount()-1.

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

Returns:

A Replica3 instance

unsigned int GetConnectionCount(WorldId worldId = 0) const

Returns the number of connections.

Returns the number of connections added with ReplicaManager3::PushConnection(), minus the number removed with ReplicaManager3::PopConnection()

Parameters:

worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

Returns:

The number of registered connections

Connection_RM3 *GetConnectionAtIndex(unsigned index, WorldId worldId = 0) const

Returns a connection pointer previously added with PushConnection()

Parameters:
  • index[in] An index, from 0 to GetConnectionCount()-1.

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

Returns:

A Connection_RM3 pointer

Connection_RM3 *GetConnectionBySystemAddress(const SystemAddress &sa, WorldId worldId = 0) const

Returns a connection pointer previously added with PushConnection()

Parameters:
  • sa[in] The system address of the connection to return

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

Returns:

A Connection_RM3 pointer, or 0 if not found

Connection_RM3 *GetConnectionByGUID(RakNetGUID guid, WorldId worldId = 0) const

Returns a connection pointer previously added with PushConnection.()

Parameters:
  • guid[in] The guid of the connection to return

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

Returns:

A Connection_RM3 pointer, or 0 if not found

void GetConnectionsInVirtualWorld(VirtualWorldId virtualWorld, DataStructures::List<Connection_RM3*> &connectionsOut, bool includeGlobal = true, WorldId worldId = 0) const

Return the connections (observers) currently in a given virtual world.

Recipient-filter helper for scoping non-replica traffic (chat, RPC4, raw Send) by virtual world. See VirtualWorld.h for the dimension model.

Parameters:
  • virtualWorld[in] The virtual world to match. See SetPlayerVirtualWorld() and Connection_RM3::SetVirtualWorld()

  • connectionsOut[out] Populated with the matching connections (cleared first)

  • includeGlobal[in] If true, also include observers in VIRTUAL_WORLD_GLOBAL

  • worldId[in] Which RM3 world to look in. World 0 by default. See AddWorld()

void GetGuidsInVirtualWorld(VirtualWorldId virtualWorld, DataStructures::List<RakNetGUID> &guidsOut, bool includeGlobal = true, WorldId worldId = 0) const

Return the guids of the connections (observers) currently in a given virtual world.

Same as GetConnectionsInVirtualWorld() but returns guids, convenient for addressing RakPeerInterface::Send().

Parameters:
  • virtualWorld[in] The virtual world to match

  • guidsOut[out] Populated with the matching guids (cleared first)

  • includeGlobal[in] If true, also include observers in VIRTUAL_WORLD_GLOBAL

  • worldId[in] Which RM3 world to look in. World 0 by default. See AddWorld()

void SetPlayerVirtualWorld(Connection_RM3 *connection, VirtualWorldReplica3 *avatar, VirtualWorldId virtualWorld)

Convenience to move a player to a virtual world: sets both the observer’s virtual world (what they see) and their avatar entity’s virtual world (how others see them).

RM3 spawns the new world in and the old world out automatically on the next Update() (in the default construction mode). avatar may be 0 if the player has no avatar entity yet.

Parameters:
  • connection[in] The player’s connection (observer side)

  • avatar[in] The player’s avatar entity, or 0

  • virtualWorld[in] The virtual world to move them to

void SetDefaultOrderingChannel(char def)
Parameters:

Default[in] ordering channel to use for object creation, destruction, and serializations

void SetDefaultPacketPriority(PacketPriority def)
Parameters:

Default[in] packet priority to use for object creation, destruction, and serializations

void SetDefaultPacketReliability(PacketReliability def)
Parameters:

Default[in] packet reliability to use for object creation, destruction, and serializations

void SetAutoSerializeInterval(MafiaNet::Time intervalMS)

Every intervalMS

milliseconds, Connection_RM3::OnAutoserializeInterval() will be called.

Defaults to 30.

Pass with <0 to disable. Pass 0 to Serialize() every time RakPeer::Recieve() is called

If you want to control the update interval with more granularity, use the return values from

Replica3::Serialize().

Parameters:

intervalMS[in] How frequently to autoserialize all objects. This controls the maximum number of game object updates per second.

void GetConnectionsThatHaveReplicaConstructed(Replica3 *replica, DataStructures::List<Connection_RM3*> &connectionsThatHaveConstructedThisReplica, WorldId worldId = 0)

Return the connections that we think have an instance of the specified Replica3 instance.

This can be wrong, for example if that system locally deleted the outside the scope of ReplicaManager3, if QueryRemoteConstruction() returned false, or if DeserializeConstruction() returned false.

Parameters:
  • replica[in] The replica to check against.

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

  • connectionsThatHaveConstructedThisReplica[out] Populated with connection instances that we believe have replica allocated

bool GetAllConnectionDownloadsCompleted(WorldId worldId = 0) const

Returns if GetDownloadWasCompleted() returns true for all connections.

Parameters:

worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

Returns:

True when all downloads have been completed

void AddWorld(WorldId worldId)

ReplicaManager3 can support multiple worlds, where each world has a separate NetworkIDManager, list of connections, replicas, etc A world with id 0 is created automatically. If you want multiple worlds, use this function, and ReplicaManager3::SetNetworkIDManager() to have a different NetworkIDManager instance per world.

Parameters:

worldId[in] A unique identifier for this world. User-defined

void RemoveWorld(WorldId worldId)

Deallocate a world added with AddWorld, or the default world with id 0 Deallocating a world will also stop tracking and updating all connections and replicas associated with that world.

Parameters:

worldId[in] A worldId value previously added with AddWorld()

WorldId GetWorldIdAtIndex(unsigned int index)

Get one of the WorldId values added with AddWorld()

WorldId 0 is created by default. Worlds will not necessarily be in the order added with AddWorld(). Edit RemoveWorld() changing RemoveAtIndexFast() to RemoveAtIndex() to preserve order.

Parameters:

index[in] A value between 0 and GetWorldCount()-1

Returns:

One of the WorldId values added with AddWorld()

unsigned int GetWorldCount(void) const

Returns the number of world id specifiers in memory, added with AddWorld() and removed with RemoveWorld()

Returns:

The number of worlds added

void SetNetworkIDManager(NetworkIDManager *_networkIDManager, WorldId worldId = 0)

Sets the networkIDManager instance that this plugin relys upon.

Uses whatever instance is attached to

RakPeerInterface

if unset.

To support multiple worlds, you should set it to a different manager for each instance of the plugin

Parameters:
  • _networkIDManager[in] The externally allocated NetworkIDManager instance for this plugin to use.

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

NetworkIDManager *GetNetworkIDManager(WorldId worldId = 0) const

Returns what was passed to SetNetworkIDManager(), or the instance on RakPeerInterface if unset.

Parameters:

worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

void BroadcastDestructionList(DataStructures::List<Replica3*> &replicaListSource, const SystemAddress &exclusionAddress, WorldId worldId = 0)

Send a network command to destroy one or more Replica3 instances Usually you won’t need this, but use Replica3::BroadcastDestruction() instead. The objects are unaffected locally

Parameters:
  • replicaList[in] List of Replica3 objects to tell other systems to destroy.

  • exclusionAddress[in] Which system to not send to. UNASSIGNED_SYSTEM_ADDRESS to send to all.

  • worldId[in] Used for multiple worlds. World 0 is created automatically by default. See AddWorld()

void BroadcastDestruction(Replica3 *replica, const SystemAddress &exclusionAddress)
void Clear(bool deleteWorlds = false)
PRO GetDefaultSendParameters(void) const
virtual void Update(void)

Call interfaces, send data.

struct RM3World

Public Functions

RM3World()
void Clear(ReplicaManager3 *replicaManager3)

Public Members

DataStructures::List<Connection_RM3*> connectionList
DataStructures::List<Replica3*> userReplicaList
WorldId worldId
NetworkIDManager *networkIDManager

Replica3

class Replica3 : public MafiaNet::NetworkIDObject

Base class for your replicated objects for the ReplicaManager3 system.

To use, derive your class, or a member of your class, from Replica3.

Subclassed by MafiaNet::Replica3Composite< parent_type >, MafiaNet::VirtualWorldReplica3

Public Functions

Replica3()
virtual ~Replica3()

Before deleting a local instance of Replica3, call Replica3::BroadcastDestruction() for the deletion notification to go out on the network. It is not necessary to call ReplicaManager3::Dereference(), as this happens automatically in the destructor

virtual void WriteAllocationID(MafiaNet::Connection_RM3 *destinationConnection, MafiaNet::BitStream *allocationIdBitstream) const = 0

Write a unique identifer that can be read on a remote system to create an object of this same class.

The value written to allocationIdBitstream will be passed to Connection_RM3::AllocReplica()

.

Sample implementation:

{allocationIdBitstream->Write(MafiaNet::RakString(“Soldier”);}

Parameters:

allocationIdBitstream[out] Bitstream for the user to write to, to identify this class

virtual RM3ConstructionState QueryConstruction(MafiaNet::Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3) = 0

Ask if this object, which does not exist on destinationConnection should (now) be sent to that system.

If ReplicaManager3::QueryConstructionMode() returns QUERY_CONNECTION_FOR_REPLICA_LIST or QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION (default), then QueyrConstruction() is called once per tick from ReplicaManager3::Update()

to determine if an object should exist on a given system.

Based on the return value, a network message may be sent to the other system to create the object.

If QueryConstructionMode() is overriden to return QUERY_CONNECTION_FOR_REPLICA_LIST, this function is unused.

Note

Defaults are provided: QueryConstruction_PeerToPeer(), QueryConstruction_ServerConstruction(), QueryConstruction_ClientConstruction(). Return one of these functions for a working default for the relevant topology.

Parameters:
  • destinationConnection[in] Which system we will send to

  • replicaManager3[in] Plugin instance for this Replica3

Returns:

What action to take

inline virtual RM3DestructionState QueryDestruction(MafiaNet::Connection_RM3 *destinationConnection, ReplicaManager3 *replicaManager3)

Ask if this object, which does exist on destinationConnection should be removed from the remote system.

If ReplicaManager3::QueryConstructionMode() returns QUERY_REPLICA_FOR_CONSTRUCTION_AND_DESTRUCTION (default), then QueryDestruction() is called once per tick from ReplicaManager3::Update()

to determine if an object that exists on a remote system should be destroyed for a given system.

Based on the return value, a network message may be sent to the other system to destroy the object.

Note that you can also destroy objects with BroadcastDestruction()

, so this function is not useful unless you plan to delete objects for only a particular connection.

If QueryConstructionMode() is overriden to return QUERY_CONNECTION_FOR_REPLICA_LIST, this function is unused.

Parameters:
  • destinationConnection[in] Which system we will send to

  • replicaManager3[in] Plugin instance for this Replica3

Returns:

What action to take. Only RM3CS_SEND_DESTRUCTION does anything at this time.

virtual bool QueryRemoteConstruction(MafiaNet::Connection_RM3 *sourceConnection) = 0

We’re about to call DeserializeConstruction() on this Replica3. If QueryRemoteConstruction() returns false, this object is deleted instead.

By default, QueryRemoteConstruction_ServerConstruction()

does not allow clients to create objects. The client will get Replica3::DeserializeConstructionRequestRejected().

If you want the client to be able to potentially create objects for client/server, override accordingly.

Other variants of QueryRemoteConstruction_* just return true.

Note

Defaults are provided: QueryRemoteConstruction_PeerToPeer(), QueryRemoteConstruction_ServerConstruction(), QueryRemoteConstruction_ClientConstruction(). Return one of these functions for a working default for the relevant topology.

Parameters:

sourceConnection[in] Which system sent us the object creation request message.

Returns:

True to allow the object to pass onto DeserializeConstruction() (where it may also be rejected), false to immediately reject the remote construction request

inline virtual bool QueryRelayDestruction(Connection_RM3 *sourceConnection) const

We got a message from a connection to destroy this replica Return true to automatically relay the destruction message to all our other connections For a client in client/server, it does not matter what this funtion returns For a server in client/server, this should normally return true For a peer in peer to peer, you can normally return false since the original destroying peer would have told all other peers about the destruction If a system gets a destruction command for an object that was already destroyed, the destruction message is ignored.

virtual void SerializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) = 0

Write data to be sent only when the object is constructed on a remote system.

SerializeConstruction is used to write out data that you need to create this object in the context of your game, such as health, score, name. Use it for data you only need to send when the object is created.

After

SerializeConstruction() is called, Serialize() will be called immediately thereafter. However, they are sent in different messages, so Serialize() may arrive a later frame than SerializeConstruction() For that reason, the object should be valid after a call to DeserializeConstruction() for at least a short time.

Note

The object’s NetworkID and allocation id are handled by the system automatically, you do not need to write these values to constructionBitstream

Parameters:
  • constructionBitstream[out] Destination bitstream to write your data to

  • destinationConnection[in] System that will receive this network message.

virtual bool DeserializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) = 0

Read data written by Replica3::SerializeConstruction()

Reads whatever data was written to constructionBitstream in Replica3::SerializeConstruction()

Parameters:
Returns:

true to accept construction of the object. false to reject, in which case the object will be deleted via Replica3::DeallocReplica()

inline virtual void SerializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection)

Same as SerializeConstruction(), but for an object that already exists on the remote system. Used if you return RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction

inline virtual void DeserializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection)

Same as DeserializeConstruction(), but for an object that already exists on the remote system. Used if you return RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction

virtual void SerializeDestruction(MafiaNet::BitStream *destructionBitstream, MafiaNet::Connection_RM3 *destinationConnection) = 0

Write extra data to send with the object deletion event, if desired.

Replica3::SerializeDestruction() will be called to write any object destruction specific data you want to send with this event. destructionBitstream can be read in DeserializeDestruction()

Parameters:
  • destructionBitstream[out] Bitstream for you to write to

  • destinationConnection[in] System that will receive this network message.

virtual bool DeserializeDestruction(MafiaNet::BitStream *destructionBitstream, MafiaNet::Connection_RM3 *sourceConnection) = 0

Read data written by Replica3::SerializeDestruction()

Return true to delete the object. BroadcastDestruction() will be called automatically, followed by ReplicaManager3::Dereference

.

Return false to not delete it. If you delete it at a later point, you are responsible for calling

BroadcastDestruction() yourself.

virtual MafiaNet::RM3ActionOnPopConnection QueryActionOnPopConnection(MafiaNet::Connection_RM3 *droppedConnection) const = 0

The system is asking what to do with this replica when the connection is dropped.

Return QueryActionOnPopConnection_Client, QueryActionOnPopConnection_Server, or QueryActionOnPopConnection_PeerToPeer

inline virtual void OnPoppedConnection(MafiaNet::Connection_RM3 *droppedConnection)

Notification called for each of our replicas when a connection is popped.

virtual void DeallocReplica(MafiaNet::Connection_RM3 *sourceConnection) = 0

Override with {delete this;}.

  1. Got a remote message to delete this object which passed DeserializeDestruction(), OR

  2. ReplicaManager3::SetAutoManageConnections()

    was called autoDestroy true (which is the default setting), and a remote system that owns this object disconnected) OR <\OL>

    Override with {delete this;} to actually delete the object (and any other processing you wish).

    If you don’t want to delete the object, just do nothing, however, the system will not know this. You may wish to call Dereference() if the object should no longer be networked, but remain in memory. You are responsible for deleting it yoruself later.

    destructionBitstream may be 0 if the object was deleted locally

virtual MafiaNet::RM3QuerySerializationResult QuerySerialization(MafiaNet::Connection_RM3 *destinationConnection) = 0

Implement with QuerySerialization_ClientSerializable(), QuerySerialization_ServerSerializable(), or QuerySerialization_PeerToPeer()

QuerySerialization()

is a first pass query to check if a given object should serializable to a given system. The intent is that the user implements with one of the defaults for client, server, or peer to peer.

Without this function, a careless implementation would serialize an object anytime it changed to all systems. This would give you feedback loops as the sender gets the same message back from the recipient it just sent to.

If more than one system can serialize the same object then you will need to override to return true, and control the serialization result from Replica3::Serialize(). Be careful not to send back the same data to the system that just sent to you!

Returns:

True to allow calling Replica3::Serialize() for this connection, false to not call.

inline virtual void OnUserReplicaPreSerializeTick(void)

Called for each replica owned by the user, once per Serialization tick, before Serialize() is called. If you want to do some kind of operation on the Replica objects that you own, just before Serialization(), then overload this function.

virtual RM3SerializationResult Serialize(MafiaNet::SerializeParameters *serializeParameters) = 0

Serialize our class to a bitstream.

User should implement this function to write the contents of this class to SerializationParamters::serializationBitstream.

If data only needs to be written once, you can write it to

SerializeConstruction()

instead for efficiency.

Transmitted over the network if it changed from the last time we called

Serialize()

.

Called every time the time interval to

ReplicaManager3::SetAutoSerializeInterval() elapses and ReplicaManager3::Update is subsequently called.

Parameters:

[in/out] – serializeParameters Parameters controlling the serialization, including destination bitstream to write to

Returns:

Whether to serialize, and if so, how to optimize the results

inline virtual void OnSerializeTransmission(MafiaNet::BitStream *bitStream, MafiaNet::Connection_RM3 *destinationConnection, BitSize_t bitsPerChannel[RM3_NUM_OUTPUT_BITSTREAM_CHANNELS], MafiaNet::Time curTime)

Called when the class is actually transmitted via Serialize()

Use to track how much bandwidth this class it taking

virtual void Deserialize(MafiaNet::DeserializeParameters *deserializeParameters) = 0

Read what was written in Serialize()

Reads the contents of the class from SerializationParamters::serializationBitstream.

Called whenever

Serialize() is called with different data from the last send.

Parameters:
  • serializationBitstream[in] Bitstream passed to Serialize()

  • timeStamp[in] 0 if unused, else contains the time the message originated on the remote system

  • sourceConnection[in] Which system sent to us

inline virtual void PostSerializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection)

Called after SerializeConstruction completes for all objects in a given update tick.

Writes to

PostDeserializeConstruction(), which is called after all objects are created for a given Construction tick(). Override to send data to PostDeserializeConstruction(), such as the NetworkID of other objects to resolve pointers to.

inline virtual void PostDeserializeConstruction(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection)

Called after DeserializeConstruction completes for all objects in a given update tick.

This is used to resolve dependency chains, where two objects would refer to each other in DeserializeConstruction, yet one had not been constructed yet In

PostDeserializeConstruction(), you know that all objects have already been created, so can resolve NetworkIDs to pointers safely. You can also use it to trigger some sort of event when you know the object has completed deserialization.

Parameters:
inline virtual void PostSerializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *destinationConnection)

Same as PostSerializeConstruction(), but for objects that returned RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction.

inline virtual void PostDeserializeConstructionExisting(MafiaNet::BitStream *constructionBitstream, MafiaNet::Connection_RM3 *sourceConnection)

Same as PostDeserializeConstruction(), but for objects that returned RM3CS_ALREADY_EXISTS_REMOTELY from QueryConstruction.

inline virtual void PreDestruction(MafiaNet::Connection_RM3 *sourceConnection)

Called after DeserializeDestruction completes for the object successfully, but obviously before the object is deleted.

Override to trigger some sort of event when you know the object has completed destruction.

Parameters:

sourceConnection[in] System that sent us this network message.

virtual RM3ConstructionState QueryConstruction_ClientConstruction(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer)

Default call for QueryConstruction().

Both the client and the server is allowed to create this object. The network topology is client/server

Parameters:
  • destinationConnection[in] destinationConnection parameter passed to QueryConstruction()

  • isThisTheServer[in] True if this system is the server, false if not.

virtual bool QueryRemoteConstruction_ClientConstruction(MafiaNet::Connection_RM3 *sourceConnection, bool isThisTheServer)

Default call for QueryRemoteConstruction().

Both the client and the server is allowed to create this object. The network topology is client/server The code means on the client or the server, allow creation of Replica3 instances

Parameters:
  • sourceConnection[in] destinationConnection parameter passed to QueryConstruction()

  • isThisTheServer[in] True if this system is the server, false if not.

virtual RM3ConstructionState QueryConstruction_ServerConstruction(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer)

Default call for QueryConstruction().

Only the server is allowed to create this object. The network topology is client/server

Parameters:
  • destinationConnection[in] destinationConnection parameter passed to QueryConstruction()

  • isThisTheServer[in] True if this system is the server, false if not.

virtual bool QueryRemoteConstruction_ServerConstruction(MafiaNet::Connection_RM3 *sourceConnection, bool isThisTheServer)

Default call for QueryRemoteConstruction(). Allow the server to create this object, but not the client.

Only the server is allowed to create this object. The network topology is client/server The code means if this is the server, and I got a command to create a Replica3 to ignore it. If this is the client, to allow it.

Parameters:
  • sourceConnection[in] destinationConnection parameter passed to QueryConstruction()

  • isThisTheServer[in] True if this system is the server, false if not.

virtual RM3ConstructionState QueryConstruction_PeerToPeer(MafiaNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode = R3P2PM_SINGLE_OWNER)

Default call for QueryConstruction().

All clients are allowed to create all objects. The object is not relayed when remotely created

Parameters:
  • destinationConnection[in] destinationConnection parameter passed to QueryConstruction()

  • p2pMode[in] If controlled only by this system ever, pass R3P2PM_SINGLE_OWNER. Otherwise pass R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE or R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE

virtual bool QueryRemoteConstruction_PeerToPeer(MafiaNet::Connection_RM3 *sourceConnection)

Default call for QueryRemoteConstruction().

All clients are allowed to create all objects. The object is not relayed when remotely created

Parameters:

sourceConnection[in] destinationConnection parameter passed to QueryConstruction()

virtual MafiaNet::RM3QuerySerializationResult QuerySerialization_ClientSerializable(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer)

Default call for QuerySerialization().

Use if the values you are serializing are generated by the client that owns the object. The serialization will be relayed through the server to the other clients.

Parameters:
  • destinationConnection[in] destinationConnection parameter passed to QueryConstruction()

  • isThisTheServer[in] True if this system is the server, false if not.

virtual MafiaNet::RM3QuerySerializationResult QuerySerialization_ServerSerializable(MafiaNet::Connection_RM3 *destinationConnection, bool isThisTheServer)

Default call for QuerySerialization().

Use if the values you are serializing are generated only by the server. The serialization will be sent to all clients, but the clients will not send back to the server.

Parameters:
  • destinationConnection[in] destinationConnection parameter passed to QueryConstruction()

  • isThisTheServer[in] True if this system is the server, false if not.

virtual MafiaNet::RM3QuerySerializationResult QuerySerialization_PeerToPeer(MafiaNet::Connection_RM3 *destinationConnection, Replica3P2PMode p2pMode = R3P2PM_SINGLE_OWNER)

Default call for QuerySerialization().

Use if the values you are serializing are on a peer to peer network. The peer that owns the object will send to all. Remote peers will not send.

Parameters:
  • destinationConnection[in] destinationConnection parameter passed to QueryConstruction()

  • p2pMode[in] If controlled only by this system ever, pass R3P2PM_SINGLE_OWNER. Otherwise pass R3P2PM_MULTI_OWNER_CURRENTLY_AUTHORITATIVE or R3P2PM_MULTI_OWNER_NOT_CURRENTLY_AUTHORITATIVE

virtual RM3ActionOnPopConnection QueryActionOnPopConnection_Client(MafiaNet::Connection_RM3 *droppedConnection) const

Default: If we are a client, and the connection is lost, delete the server’s objects.

virtual RM3ActionOnPopConnection QueryActionOnPopConnection_Server(MafiaNet::Connection_RM3 *droppedConnection) const

Default: If we are a server, and the connection is lost, delete the client’s objects and broadcast the destruction.

virtual RM3ActionOnPopConnection QueryActionOnPopConnection_PeerToPeer(MafiaNet::Connection_RM3 *droppedConnection) const

Default: If we are a peer, and the connection is lost, delete the peer’s objects.

virtual void BroadcastDestruction(void)

Call to send a network message to delete this object on other systems.

Call it before deleting the object

RakNetGUID GetCreatingSystemGUID(void) const

creatingSystemGUID is set the first time Reference() is called, or if we get the object from another system

Returns:

System that originally created this object

inline bool WasReferenced(void) const
Returns:

If ReplicaManager3::Reference() was called on this object.

Public Members

RakNetGUID creatingSystemGUID

GUID of the system that first called Reference() on this object. Transmitted automatically when the object is constructed

RakNetGUID deletingSystemGUID

GUID of the system that caused the item to send a deletion command over the network.

ReplicaManager3 *replicaManager
LastSerializationResultBS lastSentSerialization
bool forceSendUntilNextUpdate
LastSerializationResult *lsr
uint32_t referenceIndex

ReadyEvent

class ReadyEvent : public MafiaNet::PluginInterface2

Peer to peer synchronized ready and unready events.

For peer to peer networks in a fully connected mesh.

Solves the problem of how to tell if all peers, relative to all other peers, are in a certain ready state.

For example, if A is connected to B and C, A may see that B and C are ready, but does not know if B is ready to C, or vice-versa.

This plugin uses two stages to solve that problem, first, everyone I know about is ready. Second, everyone I know about is ready to everyone they know about.

The user will get ID_READY_EVENT_SET and ID_READY_EVENT_UNSET as the signal flag is set or unset

The user will get ID_READY_EVENT_ALL_SET when all systems are done waiting for all other systems, in which case the event is considered complete, and no longer tracked.

Public Functions

ReadyEvent()
virtual ~ReadyEvent()
bool SetEvent(int eventId, bool isReady)

Sets or updates the initial ready state for our local system. If eventId is an unknown event the event is created. If eventId was previously used and you want to reuse it, call DeleteEvent first, or else you will keep the same event signals from before Systems previously or later added through AddToWaitList() with the same eventId when isReady=true will get ID_READY_EVENT_SET Systems previously added through AddToWaitList with the same eventId will get ID_READY_EVENT_UNSET For both ID_READY_EVENT_SET and ID_READY_EVENT_UNSET, eventId is encoded in bytes 1 through 1+sizeof(int)

Parameters:
  • eventId[in] A user-defined identifier to wait on. This can be a sequence counter, an event identifier, or anything else you want.

  • isReady[in] True to signal we are ready to proceed with this event, false to unsignal

Returns:

False if event status is ID_READY_EVENT_FORCE_ALL_SET, or if we are setting to a status we are already in (no change). Otherwise true

void ForceCompletion(int eventId)

When systems can call SetEvent() with isReady==false, it is possible for one system to return true from IsEventCompleted() while the other systems return false This can occur if a system SetEvent() with isReady==false while the completion message is still being transmitted. If your game has the situation where some action should be taken on all systems when IsEventCompleted() is true for any system, then call ForceCompletion() when the action begins. This will force all systems to return true from IsEventCompleted().

Parameters:

eventId[in] A user-defined identifier to immediately set as completed

bool DeleteEvent(int eventId)

Deletes an event. We will no longer wait for this event, and any systems that we know have set the event will be forgotten. Call this to clear memory when events are completed and you know you will never need them again.

Parameters:

eventId[in] A user-defined identifier

Returns:

True on success. False (failure) on unknown eventId

bool IsEventSet(int eventId)

Returns what was passed to SetEvent()

Returns:

The value of isReady passed to SetEvent(). Also returns false on unknown event.

bool IsEventCompletionProcessing(int eventId) const

Returns if the event is about to be ready and we are negotiating the final packets. This will usually only be true for a very short time, after which IsEventCompleted should return true. While this is true you cannot add to the wait list, or SetEvent() isReady to false anymore.

Parameters:

eventId[in] A user-defined identifier

Returns:

True if any other system has completed processing. Will always be true if IsEventCompleted() is true

bool IsEventCompleted(int eventId) const

Returns if the wait list is a subset of the completion list. Call this after all systems you want to wait for have been added with AddToWaitList If you are waiting for a specific number of systems (such as players later connecting), also check GetRemoteWaitListSize(eventId) to be equal to 1 less than the total number of participants.

Parameters:

eventId[in] A user-defined identifier

Returns:

True on completion. False (failure) on unknown eventId, or the set is not completed.

bool HasEvent(int eventId)

Returns if this is a known event. Events may be known even if we never ourselves referenced them with SetEvent, because other systems created them via ID_READY_EVENT_SET.

Parameters:

eventId[in] A user-defined identifier

Returns:

true if we have this event, false otherwise

unsigned GetEventListSize(void) const

Returns the total number of events stored in the system.

Returns:

The total number of events stored in the system.

int GetEventAtIndex(unsigned index) const

Returns the event ID stored at a particular index. EventIDs are stored sorted from least to greatest.

Parameters:

index[in] Index into the array, from 0 to GetEventListSize()

Returns:

The event ID stored at a particular index

bool AddToWaitList(int eventId, RakNetGUID guid)

Adds a system to wait for to signal an event before considering the event complete and returning ID_READY_EVENT_ALL_SET. As we add systems, if this event was previously set to true with SetEvent, these systems will get ID_READY_EVENT_SET. As these systems disconnect (directly or indirectly through the router) they are removed.

Note

If the event completion process has already started, you cannot add more systems, as this would cause the completion process to fail

Parameters:
  • eventId[in] A user-defined number previously passed to SetEvent that has not yet completed

  • guid[in] An address to wait for event replies from. Pass UNASSIGNED_SYSTEM_ADDRESS for all currently connected systems. Until all systems in this list have called SetEvent with this ID and true, and have this system in the list, we won’t get ID_READY_EVENT_COMPLETE

Returns:

True on success, false on unknown eventId (this should be considered an error)

bool RemoveFromWaitList(int eventId, RakNetGUID guid)

Removes systems from the wait list, which should have been previously added with AddToWaitList

Note

Systems that directly or indirectly disconnect from us are automatically removed from the wait list

Parameters:

guid[in] The system to remove from the wait list. Pass UNASSIGNED_RAKNET_GUID for all currently connected systems.

Returns:

True on success, false on unknown eventId (this should be considered an error)

bool IsInWaitList(int eventId, RakNetGUID guid)

Returns if a particular system is waiting on a particular event.

Parameters:
  • eventId[in] A user-defined identifier

  • guid[in] The system we are checking up on

Returns:

True if this system is waiting on this event, false otherwise.

unsigned GetRemoteWaitListSize(int eventId) const

Returns the total number of systems we are waiting on for this event. Does not include yourself

Parameters:

eventId[in] A user-defined identifier

Returns:

The total number of systems we are waiting on for this event.

RakNetGUID GetFromWaitListAtIndex(int eventId, unsigned index) const

Returns the system address of a system at a particular index, for this event.

Parameters:
  • eventId[in] A user-defined identifier

  • index[in] Index into the array, from 0 to GetWaitListSize()

Returns:

The system address of a system at a particular index, for this event.

ReadyEventSystemStatus GetReadyStatus(int eventId, RakNetGUID guid)

For a remote system, find out what their ready status is (waiting, signaled, complete).

See also

ReadyEventSystemStatus

Parameters:
  • eventId[in] A user-defined identifier

  • guid[in] Which system we are checking up on

Returns:

The status of this system, for this particular event.

void SetSendChannel(unsigned char newChannel)

This channel will be used for all RakPeer::Send calls

Parameters:

newChannel[in] The channel to use for internal RakPeer::Send calls from this system. Defaults to 0.

Public Static Functions

static ReadyEvent *GetInstance(void)
static void DestroyInstance(ReadyEvent *i)
static int RemoteSystemCompByGuid(const RakNetGUID &key, const RemoteSystem &data)
static int ReadyEventNodeComp(const int &key, ReadyEvent::ReadyEventNode *const &data)
struct ReadyEventNode

Public Members

int eventId
MessageID eventStatus
DataStructures::OrderedList<RakNetGUID, RemoteSystem, ReadyEvent::RemoteSystemCompByGuid> systemList
struct RemoteSystem

Public Members

MessageID lastSentStatus
MessageID lastReceivedStatus
RakNetGUID rakNetGuid

TeamManager

class TeamManager : public MafiaNet::PluginInterface2

Automates networking and list management for teams.

TeamManager provides support for teams. A team is a list of team members. Teams contain properties including the number of team members per team, whether or not tagged teams must have equal numbers of members, and if a team is locked or not to certain entry conditions Team members contain properties including which teams they are on and which teams they want to join if a team is not immediately joinable Advanced functionality includes the ability for a team member to be on multiple teams simultaneously, the ability to swap teams with other members, and the ability to resize the number of members supported per team The architecture is designed for easy integration with ReplicaManager3

Usage:

  1. Define your game classes to represent teams and team members. Your game classes should hold game-specific information such as team name and color.

  2. Have those game classes contain a corresponding TM_Team or TM_TeamMember instance. Operations on teams will be performed by those instances. Use SetOwner() to refer to the parent object when using composition.

  3. Call TeamManager::SetTopology() for client/server or peer to peer.

  4. Call AddWorld() to instantiate a TM_World object which will contain references to your TM_TeamMember and TM_Team instances.

  5. When you instantiate a TM_TeamMember or TM_Team object, call ReferenceTeam() and ReferenceTeamMember() for each corresponding object

  6. When sending world state to a new connection, for example in ReplicaManager3::SerializeConstruction(), call TM_SerializeConstruction() on the corresponding TM_TeamMember and TM_Team objects. TM_Team instances on the new connection must be created before TM_TeamMember instances.

  7. Call TM_DeserializeConstruction() on your new corresponding TM_TeamMember and TM_Team instances.

  8. Execute team operations. ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED, and ID_TEAM_BALANCER_TEAM_ASSIGNED are returned to all systems when the corresponding event occurs for a team member.

  9. As the peer to peer session host changes, call SetHost() (Not necessary if using FullyConnectedMesh2). If using client/server, you must set the host

Note

This replaces TeamBalancer. You cannot use TeamBalancer and TeamManager at the same time.

Public Functions

TeamManager()
virtual ~TeamManager()
TM_World *AddWorld(WorldId worldId)

Allocate a world to hold a list of teams and players for that team. Use the returned TM_World object for actual team functionality.

Note

The world is tracked by TeamManager and deallocated by calling Clear()

Parameters:

worldId[in] Arbitrary user-defined id of the world to create. Each world instance must have a unique id.

void RemoveWorld(WorldId worldId)

Deallocate a world created with AddWorld()

Parameters:

worldId[in] The world to deallocate

unsigned int GetWorldCount(void) const
Returns:

Returns the number of worlds created with AddWorld()

TM_World *GetWorldAtIndex(unsigned int index) const
Parameters:

index[in] A value beteween 0 and GetWorldCount()-1 inclusive.

Returns:

Returns a world created with AddWorld()

TM_World *GetWorldWithId(WorldId worldId) const
Parameters:

worldId[in] worldId value passed to AddWorld()

Returns:

Returns a world created with AddWorld(), or 0 if no such worldId

void SetAutoManageConnections(bool autoAdd)

When auto managing connections, call TM_World::AddParticipant() on all worlds for all new connections automatically Defaults to true.

Note

You probably want this set to false if using multiple worlds

Parameters:

autoAdd[in] Automatically call TM_World::AddParticipant() all worlds each new connection. Defaults to true.

void SetTopology(TMTopology _topology)

If _topology is set to TM_CLIENT_SERVER, the host will relay messages to participants.

If topology is set to TM_PEER_TO_PEER, the host assumes the original message source was connected to all other participants and does not relay messages.

Note

If TM_PEER_TO_PEER, this plugin will listen for ID_FCM2_NEW_HOST and call SetHost() on all worlds automatically

Note

Defaults to TM_PEER_TO_PEER

Parameters:

_topology[in] Topology to use

void DecomposeTeamFull(Packet *packet, TM_World **world, TM_TeamMember **teamMember, TM_Team **team, uint16_t &currentMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions)

When you get ID_TEAM_BALANCER_REQUESTED_TEAM_FULL, pass the packet to this function to read out parameters.

Parameters:

A[in] packet where packet->data[0]==ID_TEAM_BALANCER_REQUESTED_TEAM_FULL

Returns:

true on success, false on read error

void DecomposeTeamLocked(Packet *packet, TM_World **world, TM_TeamMember **teamMember, TM_Team **team, uint16_t &currentMembers, uint16_t &memberLimitIncludingBalancing, bool &balancingIsActive, JoinPermissions &joinPermissions)

When you get ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED, pass the packet to this function to read out parameters.

Parameters:

A[in] packet where packet->data[0]==ID_TEAM_BALANCER_REQUESTED_TEAM_LOCKED

Returns:

true on success, false on read error

void Clear(void)

Clear all memory and reset everything.

Deallocates TM_World instances. It is up to the user to deallocate pointers passed to ReferenceTeamMember() or ReferenceTeam(), if so desired.

void DecodeTeamAssigned(Packet *packet, TM_World **world, TM_TeamMember **teamMember)

Reads out the world and teamMember from ID_TEAM_BALANCER_TEAM_ASSIGNED.

Note

You can get the current and prior team list from the teamMember itself

Parameters:
  • A[in] packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_ASSIGNED

  • world[out] Set to the world this teamMember is on. 0 on bad lookup.

  • teamMember[out] Set to the teamMember affected. 0 on bad lookup.

void DecodeTeamCancelled(Packet *packet, TM_World **world, TM_TeamMember **teamMember, TM_Team **teamCancelled)

Note

You can get the requested team list from the teamMember itself

Parameters:
  • A[in] packet where packet->data[0]==ID_TEAM_BALANCER_TEAM_REQUESTED_CANCELLED

  • world[out] Set to the world this teamMember is on. 0 on bad lookup.

  • teamMember[out] Set to the teamMember affected. 0 on bad lookup.

  • teamCancelled[out] Set to the team that was cancelled. 0 for all teams.

Public Static Functions

static TeamManager *GetInstance(void)
static void DestroyInstance(TeamManager *i)

Utility Plugins

RPC4Plugin

class RPC4 : public MafiaNet::PluginInterface2

The RPC4 plugin is just an association between a C function pointer and a string.

It is for users that want to use RPC, but do not want to use boost. You do not have the automatic serialization or other features of RPC3, and C++ member calls are not supported.

Note

You cannot use RPC4 at the same time as RPC3Plugin

Public Functions

RPC4()
virtual ~RPC4()
bool RegisterFunction(const char *uniqueID, void (*functionPointer)(MafiaNet::BitStream *userData, Packet *packet, void *context), void *context)

Register a function pointer to be callable from a remote system.

Deprecated:

Use RegisterSlot

The hash of the function name will be stored as an association with the function pointer When a call is made to call this function from the Call() or CallLoopback() function, the function pointer will be invoked with the passed bitStream to Call() and the actual Packet that RakNet got.

See also

RegisterPacketCallback()

Parameters:
  • uniqueID[in] Identifier to be associated with functionPointer. If this identifier is already in use, the call will return false.

  • functionPointer[in] C function pointer to be called

  • context[in] Opaque user pointer passed back to functionPointer on every invocation. Lets the handler recover its owning object instance without a file-static global. The pointer is not owned by RPC4; keep it valid until the function is unregistered.

Returns:

True if the hash of uniqueID is not in use, false otherwise.

void RegisterSlot(const char *sharedIdentifier, void (*functionPointer)(MafiaNet::BitStream *userData, Packet *packet, void *context), void *context, int callPriority)

Register a slot, which is a function pointer to one or more implementations that supports this function signature When a signal occurs, all slots with the same identifier are called.

Parameters:
  • sharedIdentifier[in] A string to identify the slot. Recommended to be the same as the name of the function.

  • functionPtr[in] Pointer to the function. For C, just pass the name of the function. For C++, use ARPC_REGISTER_CPP_FUNCTION

  • context[in] Opaque user pointer passed back to functionPointer on every invocation. Each registration carries its own context, so the same handler may be registered under one identifier for several object instances. Not owned by RPC4; keep it valid until the slot is unregistered.

  • callPriority[in] Slots are called by order of the highest callPriority first. For slots with the same priority, they are called in the order they are registered

bool RegisterBlockingFunction(const char *uniqueID, void (*functionPointer)(MafiaNet::BitStream *userData, MafiaNet::BitStream *returnData, Packet *packet, void *context), void *context)

Same as RegisterFunction, but is called with CallBlocking() instead of Call() and returns a value to the caller.

Parameters:

context[in] Opaque user pointer passed back to functionPointer on every invocation. Not owned by RPC4; keep it valid until the function is unregistered.

void RegisterLocalCallback(const char *uniqueID, MessageID messageId)

Deprecated:

Use RegisterSlot and invoke on self only when the packet you want arrives When a RakNet Packet with the specified identifier is returned, execute CallLoopback() on a function previously registered with RegisterFunction() For example, you could call “OnClosedConnection” whenever you get ID_DISCONNECTION_NOTIFICATION or ID_CONNECTION_LOST

Parameters:
  • uniqueID[in] Identifier passed to RegisterFunction()

  • messageId[in] What RakNet packet ID to call on, for example ID_DISCONNECTION_NOTIFICATION or ID_CONNECTION_LOST

bool UnregisterFunction(const char *uniqueID)

Unregister a function pointer previously registered with RegisterFunction()

Parameters:

Identifier[in] originally passed to RegisterFunction()

Returns:

True if the hash of uniqueID was in use, and hence removed. false otherwise.

bool UnregisterBlockingFunction(const char *uniqueID)

Same as UnregisterFunction, except for a blocking function.

bool UnregisterLocalCallback(const char *uniqueID, MessageID messageId)

Remove the association created with RegisterPacketCallback()

Parameters:
Returns:

True if the combination of uniqueID and messageId was in use, and hence removed

bool UnregisterSlot(const char *sharedIdentifier)

Remove the association created with RegisterSlot()

Parameters:

sharedIdentifier[in] Identifier passed as sharedIdentifier to RegisterSlot()

void CallLoopback(const char *uniqueID, MafiaNet::BitStream *bitStream)

Deprecated:

Use RegisterSlot() and Signal() with your own RakNetGUID as the send target Send to the attached instance of RakPeer. See RakPeerInterface::SendLoopback()

Parameters:
  • Identifier[in] originally passed to RegisterFunction() on the local system

  • bitStream[in] bitStream encoded data to send to the function callback

void Call(const char *uniqueID, MafiaNet::BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast)

Deprecated:

, use Signal() Send to the specified remote instance of RakPeer.

Parameters:
bool CallBlocking(const char *uniqueID, MafiaNet::BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, MafiaNet::BitStream *returnData)

Same as call, but don’t return until the remote system replies. Broadcasting parameter does not exist, this can only call one remote system.

Note

This function does not return until the remote system responds, disconnects, or was never connected to begin with

Parameters:
Returns:

true if successfully called. False on disconnect, function not registered, or not connected to begin with

void Signal(const char *sharedIdentifier, MafiaNet::BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, const AddressOrGUID systemIdentifier, bool broadcast, bool invokeLocal)

Calls zero or more functions identified by sharedIdentifier registered with RegisterSlot()

Parameters:
void InterruptSignal(void)

If called while processing a slot, no further slots for the currently executing signal will be executed.

Public Members

DataStructures::Hash<MafiaNet::RakString, LocalSlot*, 256, MafiaNet::RakString::ToInteger> localSlots

Public Static Functions

static RPC4 *GetInstance(void)
static void DestroyInstance(RPC4 *i)
static int LocalCallbackComp(const MessageID &key, LocalCallback *const &data)
static int LocalSlotObjectComp(const LocalSlotObject &key, const LocalSlotObject &data)
struct LocalCallback

Public Members

MessageID messageId
DataStructures::OrderedList<MafiaNet::RakString, MafiaNet::RakString> functions
struct LocalSlot

Public Members

DataStructures::OrderedList<LocalSlotObject, LocalSlotObject, LocalSlotObjectComp> slotObjects
struct LocalSlotObject

Public Functions

inline LocalSlotObject()
inline LocalSlotObject(unsigned int _registrationCount, int _callPriority, void (*_functionPointer)(MafiaNet::BitStream *userData, Packet *packet, void *context), void *_context)
inline ~LocalSlotObject()

Public Members

unsigned int registrationCount
int callPriority
void (*functionPointer)(MafiaNet::BitStream *userData, Packet *packet, void *context)
void *context

MessageFilter

class MessageFilter : public MafiaNet::PluginInterface2

Assigns systems to FilterSets. Each FilterSet limits what kinds of messages are allowed.

The MessageFilter

plugin is used for security where you limit what systems can send what kind of messages.

You implicitly define FilterSets, and add allowed message IDs to these FilterSets.

You then add systems to these filters, such that those systems are limited to sending what the filters allows.

You can automatically assign systems to a filter.

You can automatically kick and possibly ban users that stay in a filter too long, or send the wrong message.

Each system is a member of either zero or one filters.

Add this plugin before any plugin you wish to filter (most likely just add this plugin before any other).

Public Functions

MessageFilter()
virtual ~MessageFilter()
void SetAutoAddNewConnectionsToFilter(int filterSetID)

Automatically add all new systems to a particular filter Defaults to -1

Parameters:

filterSetID[in] Which filter to add new systems to. <0 for do not add.

void SetAllowMessageID(bool allow, int messageIDStart, int messageIDEnd, int filterSetID)

Allow a range of message IDs Always allowed by default: ID_CONNECTION_REQUEST_ACCEPTED through ID_DOWNLOAD_PROGRESS Usually you specify a range to make it easier to add new enumerations without having to constantly refer back to this function.

Parameters:
  • allow[in] True to allow this message ID, false to disallow. By default, all messageIDs except the noted types are disallowed. This includes messages from other plugins!

  • messageIDStart[in] The first ID_* message to allow in the range. Inclusive.

  • messageIDEnd[in] The last ID_* message to allow in the range. Inclusive.

  • filterSetID[in] A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings.

void SetAllowRPC4(bool allow, const char *uniqueID, int filterSetID)

Allow a specific RPC4 call

Parameters:
  • uniqueID[in] Identifier passed to RegisterFunction()

  • filterSetID[in] A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings.

Pre:

MessageFilter must be attached before RPC4

void SetActionOnDisallowedMessage(bool kickOnDisallowed, bool banOnDisallowed, MafiaNet::TimeMS banTimeMS, int filterSetID)

What action to take on a disallowed message. You can kick or not. You can add them to the ban list for some time By default no action is taken. The message is simply ignored. param[in] 0 for permanent ban, >0 for ban time in milliseconds.

Parameters:
  • kickOnDisallowed[in] kick the system that sent a disallowed message.

  • banOnDisallowed[in] ban the system that sent a disallowed message. See banTimeMS for the ban duration

  • banTimeMS[in] Passed to the milliseconds parameter of RakPeer::AddToBanList.

  • filterSetID[in] A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings.

void SetDisallowedMessageCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID addressOrGUID, int filterSetID, void *userData, unsigned char messageID))

Set a user callback to be called on an invalid message for a particular filterSet

Parameters:
  • filterSetID[in] A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings.

  • userData[in] A pointer passed with the callback

  • invalidMessageCallback[in] A pointer to a C function to be called back with the specified parameters.

void SetTimeoutCallback(int filterSetID, void *userData, void (*invalidMessageCallback)(RakPeerInterface *peer, AddressOrGUID addressOrGUID, int filterSetID, void *userData))

Set a user callback to be called when a user is disconnected due to SetFilterMaxTime

Parameters:
  • filterSetID[in] A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings.

  • userData[in] A pointer passed with the callback

  • invalidMessageCallback[in] A pointer to a C function to be called back with the specified parameters.

void SetFilterMaxTime(int allowedTimeMS, bool banOnExceed, MafiaNet::TimeMS banTimeMS, int filterSetID)

Limit how long a connection can stay in a particular filterSetID. After this time, the connection is kicked and possibly banned. By default there is no limit to how long a connection can stay in a particular filter set.

Parameters:
  • allowedTimeMS[in] How many milliseconds to allow a connection to stay in this filter set.

  • banOnExceed[in] True or false to ban the system, or not, when allowedTimeMS is exceeded

  • banTimeMS[in] Passed to the milliseconds parameter of RakPeer::AddToBanList.

  • filterSetID[in] A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings.

int GetSystemFilterSet(AddressOrGUID addressOrGUID)

Get the filterSetID a system is using. Returns -1 for none.

Parameters:

addressOrGUID[in] The system we are referring to

void SetSystemFilterSet(AddressOrGUID addressOrGUID, int filterSetID)

Assign a system to a filter set. Systems are automatically added to filter sets (or not) based on SetAutoAddNewConnectionsToFilter() This function is used to change the filter set a system is using, to add it to a new filter set, or to remove it from all existin filter sets.

Parameters:
  • addressOrGUID[in] The system we are referring to

  • filterSetID[in] A user defined ID to represent a filter set. If no filter with this ID exists, one will be created with default settings. If -1, the system will be removed from all filter sets.

unsigned GetSystemCount(int filterSetID) const

Returns the number of systems subscribed to a particular filter set Using anything other than -1 for filterSetID is slow, so you should store the returned value.

Parameters:

filterSetID[in] The filter set to limit to. Use -1 for none (just returns the total number of filter systems in that case).

unsigned GetFilterSetCount(void) const

Returns the total number of filter sets.

Returns:

The total number of filter sets.

int GetFilterSetIDByIndex(unsigned index)

Returns the ID of a filter set, by index

Parameters:

An[in] index between 0 and GetFilterSetCount()-1 inclusive

void DeleteFilterSet(int filterSetID)

Delete a FilterSet. All systems formerly subscribed to this filter are now unrestricted.

Parameters:

filterSetID[in] The ID of the filter set to delete.

virtual void Update(void)

Update is called every time a packet is checked for .

virtual PluginReceiveResult OnReceive(Packet *packet)

OnReceive is called for every packet.

Parameters:

packet[in] the packet that is being returned to the user

Returns:

True to allow the game and other plugins to get this message, false to absorb it

virtual void OnNewConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, bool isIncoming)

Called when we got a new connection

Parameters:
  • systemAddress[in] Address of the new connection

  • rakNetGuid[in] The guid of the specified system

  • isIncoming[in] If true, this is ID_NEW_INCOMING_CONNECTION, or the equivalent

virtual void OnClosedConnection(const SystemAddress &systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason)

Called when a connection is dropped because the user called RakPeer::CloseConnection() for a particular system

Parameters:
  • systemAddress[in] The system whose connection was closed

  • rakNetGuid[in] The guid of the specified system

  • lostConnectionReason[in] How the connection was closed: manually, connection lost, or notification of disconnection

Public Static Functions

static MessageFilter *GetInstance(void)
static void DestroyInstance(MessageFilter *i)

PacketLogger

class PacketLogger : public MafiaNet::PluginInterface2

Writes incoming and outgoing messages to the screen. This will write all incoming and outgoing messages to the console window, or to a file if you override it and give it this functionality.

Subclassed by MafiaNet::PacketConsoleLogger, MafiaNet::PacketFileLogger, MafiaNet::PacketOutputWindowLogger, MafiaNet::ThreadsafePacketLogger

Public Functions

PacketLogger()
virtual ~PacketLogger()
virtual void FormatLine(char *into, size_t intoLength, const char *dir, const char *type, unsigned int reliableMessageNumber, unsigned int frame, unsigned char id, const BitSize_t bitLen, unsigned long long time, const SystemAddress &local, const SystemAddress &remote, unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex)
virtual void FormatLine(char *into, const char *dir, const char *type, unsigned int reliableMessageNumber, unsigned int frame, unsigned char id, const BitSize_t bitLen, unsigned long long time, const SystemAddress &local, const SystemAddress &remote, unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex)
virtual void FormatLine(char *into, size_t intoLength, const char *dir, const char *type, unsigned int reliableMessageNumber, unsigned int frame, const char *idToPrint, const BitSize_t bitLen, unsigned long long time, const SystemAddress &local, const SystemAddress &remote, unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex)
virtual void FormatLine(char *into, const char *dir, const char *type, unsigned int reliableMessageNumber, unsigned int frame, const char *idToPrint, const BitSize_t bitLen, unsigned long long time, const SystemAddress &local, const SystemAddress &remote, unsigned int splitPacketId, unsigned int splitPacketIndex, unsigned int splitPacketCount, unsigned int orderingIndex)
virtual void OnDirectSocketSend(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress)

Events on low level sends and receives. These functions may be called from different threads at the same time.

virtual void OnDirectSocketReceive(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress)

Called on a receive from the socket, per datagram, that does not go through the reliability layer

Parameters:
  • data[in] The data being sent

  • bitsUsed[in] How many bits long data is

  • remoteSystemAddress[in] Which system this message is being sent to

Pre:

To be called, UsesReliabilityLayer() must return true

virtual void OnReliabilityLayerNotification(const char *errorMessage, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress, bool isError)

Called when the reliability layer rejects a send or receive

Parameters:
  • bitsUsed[in] How many bits long data is

  • remoteSystemAddress[in] Which system this message is being sent to

Pre:

To be called, UsesReliabilityLayer() must return true

virtual void OnInternalPacket(InternalPacket *internalPacket, unsigned frameNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time, int isSend)

Called on a send or receive of a message within the reliability layer

Parameters:
  • internalPacket[in] The user message, along with all send data.

  • frameNumber[in] The number of frames sent or received so far for this player depending on isSend . Indicates the frame of this user message.

  • remoteSystemAddress[in] The player we sent or got this packet from

  • time[in] The current time as returned by MafiaNet::GetTimeMS()

  • isSend[in] Is this callback representing a send event or receive event?

Pre:

To be called, UsesReliabilityLayer() must return true

virtual void OnAck(unsigned int messageNumber, SystemAddress remoteSystemAddress, MafiaNet::TimeMS time)

Called when we get an ack for a message we reliably sent

Parameters:
  • messageNumber[in] The numerical identifier for which message this is

  • remoteSystemAddress[in] The player we sent or got this packet from

  • time[in] The current time as returned by MafiaNet::GetTimeMS()

Pre:

To be called, UsesReliabilityLayer() must return true

virtual void OnPushBackPacket(const char *data, const BitSize_t bitsUsed, SystemAddress remoteSystemAddress)

System called RakPeerInterface::PushBackPacket

Parameters:
  • data[in] The data being sent

  • bitsUsed[in] How many bits long data is

  • remoteSystemAddress[in] The player we sent or got this packet from

virtual void LogHeader(void)

Logs out a header for all the data.

virtual void WriteLog(const char *str)

Override this to log strings to wherever. Log should be threadsafe.

virtual void WriteMiscellaneous(const char *type, const char *msg)
virtual void SetPrintID(bool print)
virtual void SetPrintAcks(bool print)
virtual void SetPrefix(const char *_prefix)

Prepend this string to output logs.

virtual void SetSuffix(const char *_suffix)

Append this string to output logs. (newline is useful here)

void SetLogDirectMessages(bool send)

Log the direct sends and receives or not. Default true.

Public Static Functions

static PacketLogger *GetInstance(void)
static void DestroyInstance(PacketLogger *i)
static const char *BaseIDTOString(unsigned char Id)