]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplayrxmgr.cxx
Melchior FRANZ:
[flightgear.git] / src / MultiPlayer / multiplayrxmgr.cxx
1 // multiplayrxmgr.cxx -- routines for receiving multiplayer data
2 //                       for Flightgear
3 //
4 // Written by Duncan McCreanor, started February 2003.
5 // duncan.mccreanor@airservicesaustralia.com
6 //
7 // Copyright (C) 2003  Airservices Australia
8 //
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 // General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 //
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #ifdef FG_MPLAYER_AS
29
30 /******************************************************************
31 * $Id$
32 *
33 * Description: The multiplayer rx manager provides control over
34 * multiplayer data reception and processing for an interactive
35 * multiplayer FlightGear simulation.
36 *
37 * The objects that hold player information are accessed via
38 * a fixed size array. A fixed array is used since it provides
39 * speed benefits over working with linked lists and is easier
40 * to code. Also, there is no point allowing for an unlimited
41 * number of players as too many players will slow the game
42 * down to the point where it is unplayable.
43 *
44 * When player position data is received, the callsign of
45 * the player is checked against existing players. If the
46 * player does not exist, a new player is created in the
47 * next free slot of the player array. If the player does
48 * exist, the player's positional matrix is updated.
49 *
50 * The Update method is used to move the players on the
51 * scene. The return value from calling MPPlayer::Draw
52 * indicates the state of the player. If data for a player
53 * has not been received data for some time, the player object
54 * is deleted and the array element freed.
55 *
56 ******************************************************************/
57
58 #include <sys/types.h>
59 #if !(defined(_MSC_VER) || defined(__MINGW32__))
60 # include <sys/socket.h>
61 # include <netinet/in.h>
62 # include <arpa/inet.h>
63 #endif
64 #include <plib/netSocket.h>
65 #include <stdlib.h>
66
67 #include <simgear/debug/logstream.hxx>
68 #include <Main/fg_props.hxx>
69
70 #include "multiplayrxmgr.hxx"
71 #include "mpmessages.hxx"
72 #include "mpplayer.hxx"
73
74 #define MAX_PACKET_SIZE 1024
75
76 // These constants are provided so that the ident command can list file versions.
77 const char sMULTIPLAYTXMGR_BID[] = "$Id$";
78 const char sMULTIPLAYRXMGR_HID[] = MULTIPLAYRXMGR_HID;
79
80
81
82 /******************************************************************
83 * Name: FGMultiplayRxMgr
84 * Description: Constructor.
85 ******************************************************************/
86 FGMultiplayRxMgr::FGMultiplayRxMgr() {
87
88     int iPlayerCnt;         // Count of players in player array
89
90     // Initialise private members
91     m_sRxAddress = "0";
92     m_iRxPort = 0;
93     m_bInitialised = false;
94
95     // Clear the player array
96     for (iPlayerCnt = 0; iPlayerCnt < MAX_PLAYERS; iPlayerCnt++) {
97         m_Player[iPlayerCnt] = NULL;
98     }
99
100 }
101
102
103 /******************************************************************
104 * Name: ~FGMultiplayRxMgr
105 * Description: Destructor. Closes and deletes objects owned by
106 * this object.
107 ******************************************************************/
108 FGMultiplayRxMgr::~FGMultiplayRxMgr() {
109
110     Close();
111
112 }
113
114
115 /******************************************************************
116 * Name: init
117 * Description: Initialises multiplayer receive.
118 ******************************************************************/
119 bool FGMultiplayRxMgr::init(void) {
120
121     bool bSuccess = true;                       // Result of initialisation
122
123     // Initialise object if not already done
124     if (!m_bInitialised) {
125
126         // Set members from property values
127         m_sCallsign = fgGetString("/sim/multiplay/callsign");
128         m_sRxAddress = fgGetString("/sim/multiplay/rxhost");
129         m_iRxPort = fgGetInt("/sim/multiplay/rxport");
130
131         SG_LOG( SG_NETWORK, SG_INFO, "FGMultiplayRxMgr::init - rxaddress= "
132                                      << m_sRxAddress );
133         SG_LOG( SG_NETWORK, SG_INFO, "FGMultiplayRxMgr::init - rxport= "
134                                      << m_iRxPort);
135         SG_LOG( SG_NETWORK, SG_INFO, "FGMultiplayRxMgr::init - callsign= "
136                                      << m_sCallsign );
137
138
139         // Create and open rx socket
140         mDataRxSocket = new netSocket();
141         if (!mDataRxSocket->open(false)) {
142             // Failed to open rx socket
143             SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayRxMgr::Open - Failed to create data receive socket" );
144             bSuccess = false;
145         } else {
146
147             // Configure the socket
148             mDataRxSocket->setBlocking(false);
149             mDataRxSocket->setBroadcast(true);
150             if (mDataRxSocket->bind(m_sRxAddress.c_str(), m_iRxPort) != 0) {
151                 perror("bind");
152                 // Failed to bind
153                 SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayRxMgr::Open - Failed to bind receive socket" );
154                 bSuccess = false;
155             }
156
157         }
158
159         // Save manager state
160         m_bInitialised = bSuccess;
161
162     } else {
163         SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayRxMgr::OpenRx - Receiver open requested when receiver is already open" );
164         bSuccess = false;
165     }
166
167     /* Return true if open succeeds */
168     return bSuccess;
169
170 }
171
172
173 /******************************************************************
174 * Name: Close
175 * Description: Closes and deletes and player connections. Closes
176 * and deletes the rx socket. Resets the object state
177 * to unitialised.
178 ******************************************************************/
179 void FGMultiplayRxMgr::Close(void) {
180
181     int iPlayerCnt;         // Count of players in player array
182
183     // Delete any existing players
184     for (iPlayerCnt = 0; iPlayerCnt < MAX_PLAYERS; iPlayerCnt++) {
185         if (m_Player[iPlayerCnt] != NULL) {
186             delete m_Player[iPlayerCnt];
187             m_Player[iPlayerCnt] = NULL;
188         }
189     }
190
191     // Delete socket
192     if (mDataRxSocket) {
193         mDataRxSocket->close();
194         delete mDataRxSocket;
195         mDataRxSocket = NULL;
196     }
197
198     m_bInitialised = false;
199
200 }
201
202
203 /******************************************************************
204 * Name: ProcessData
205 * Description: Processes data waiting at the receive socket. The
206 * processing ends when there is no more data at the socket.
207 ******************************************************************/
208 void FGMultiplayRxMgr::ProcessData(void) {
209
210     char sMsg[MAX_PACKET_SIZE];         // Buffer for received message
211     int iBytes;                         // Bytes received
212     T_MsgHdr *MsgHdr;                   // Pointer to header in received data
213     T_ChatMsg *ChatMsg;                 // Pointer to chat message in received data
214     T_PositionMsg *PosMsg;              // Pointer to position message in received data
215     char *sIpAddress;                   // Address information from header
216     char *sModelName;                   // Model that the remote player is using
217     char *sCallsign;                    // Callsign of the remote player
218     struct in_addr PlayerAddress;       // Used for converting the player's address into dot notation
219     int iPlayerCnt;                     // Count of players in player array
220     bool bActivePlayer = false;         // The state of the player that sent the data
221     int iPort;                          // Port that the remote player receives on
222
223
224     if (m_bInitialised) {
225
226         // Read the receive socket and process any data
227         do {
228
229             // Although the recv call asks for MAX_PACKET_SIZE of data,
230             // the number of bytes returned will only be that of the next
231             // packet waiting to be processed.
232             iBytes = mDataRxSocket->recv(sMsg, MAX_PACKET_SIZE, 0);
233
234             // Data received
235             if (iBytes > 0) {
236                 if (iBytes >= (int)sizeof(MsgHdr)) {
237
238                     // Read header
239                     MsgHdr = (T_MsgHdr *)sMsg;
240                     PlayerAddress.s_addr = MsgHdr->lReplyAddress;
241                     sIpAddress = inet_ntoa(PlayerAddress);
242                     iPort = MsgHdr->iReplyPort;
243                     sCallsign = MsgHdr->sCallsign;
244
245                     // Process the player data unless we generated it
246                     if (m_sCallsign != MsgHdr->sCallsign) {
247
248
249                         // Process messages
250                         switch(MsgHdr->MsgId) {
251                             case CHAT_MSG_ID:
252                                 if (MsgHdr->iMsgLen == sizeof(T_MsgHdr) + sizeof(T_ChatMsg)) {
253                                     ChatMsg = (T_ChatMsg *)(sMsg + sizeof(T_MsgHdr));
254                                     SG_LOG( SG_NETWORK, SG_BULK, "Chat [" << MsgHdr->sCallsign << "]" << " " << ChatMsg->sText );
255                                 } else {
256                                     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayRxMgr::MP_ProcessData - Chat message received with insufficient data" );
257                                 }
258                                 break;
259
260                             case POS_DATA_ID:
261                                 if (MsgHdr->iMsgLen == sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
262                                     PosMsg = (T_PositionMsg *)(sMsg + sizeof(T_MsgHdr));
263                                     sModelName = PosMsg->sModel;
264
265                                     // Check if the player is already in the game by using the Callsign.
266                                     bActivePlayer = false;
267                                     for (iPlayerCnt = 0; iPlayerCnt < MAX_PLAYERS; iPlayerCnt++) {
268                                         if (m_Player[iPlayerCnt] != NULL) {
269                                             if (m_Player[iPlayerCnt]->CompareCallsign(MsgHdr->sCallsign)) {
270
271                                                 // Player found. Update the data for the player.
272                                                 m_Player[iPlayerCnt]->SetPosition(PosMsg->PlayerPos);
273                                                 bActivePlayer = true;
274
275                                             }
276                                         }
277                                     }
278
279                                     // Player not active, so add as new player
280                                     if (!bActivePlayer) {
281                                         iPlayerCnt = 0;
282                                         do {
283                                             if (m_Player[iPlayerCnt] == NULL) {
284                                                 SG_LOG( SG_NETWORK, SG_INFO, "FGMultiplayRxMgr::ProcessRxData - Add new player. IP: " << sIpAddress << ", Call: " <<  sCallsign << ", model: " << sModelName );
285                                                 m_Player[iPlayerCnt] = new MPPlayer;
286                                                 m_Player[iPlayerCnt]->Open(sIpAddress, iPort, sCallsign, sModelName, false);
287                                                 m_Player[iPlayerCnt]->SetPosition(PosMsg->PlayerPos);
288                                                 bActivePlayer = true;
289                                             }
290                                             iPlayerCnt++;
291                                         } while (iPlayerCnt < MAX_PLAYERS && !bActivePlayer);
292
293                                         // Check if the player was added
294                                         if (!bActivePlayer) {
295                                             if (iPlayerCnt == MAX_PLAYERS) {
296                                                 SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayRxMgr::MP_ProcessData - Unable to add new player (" << sCallsign << "). Too many players." );
297                                             }
298                                         }
299                                     }
300
301                                 } else {
302                                     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayRxMgr::MP_ProcessData - Position message received with insufficient data" );
303                                 }
304                                 break;
305
306                             default:
307                                 SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayRxMgr::MP_ProcessData - Unknown message Id received: " << MsgHdr->MsgId );
308                                 break;
309
310
311                         }
312                     }
313                 }
314
315
316             // Error or no data
317             } else if (iBytes == -1) {
318                 if (errno != EAGAIN) {
319                     perror("FGMultiplayRxMgr::MP_ProcessData");
320                 }
321             }
322
323         } while (iBytes > 0);
324
325     }
326
327
328 }
329
330
331 /******************************************************************
332 * Name: Update
333 * Description: For each active player, tell the player object
334 * to update its position on the scene. If a player object
335 * returns status information indicating that it has not
336 * had an update for some time then the player is deleted.
337 ******************************************************************/
338 void FGMultiplayRxMgr::Update(void) {
339
340     MPPlayer::TPlayerDataState ePlayerDataState;
341     int iPlayerId;
342
343     for (iPlayerId = 0; iPlayerId < MAX_PLAYERS; iPlayerId++) {
344         if (m_Player[iPlayerId] != NULL) {
345             ePlayerDataState = m_Player[iPlayerId]->Draw();
346
347             // If the player has not received an update for some
348             // time then assume that the player has quit.
349             if (ePlayerDataState == MPPlayer::PLAYER_DATA_EXPIRED) {
350                 SG_LOG( SG_NETWORK, SG_BULK, "FGMultiplayRxMgr::Update - Deleting player from game. Callsign: "
351                         << m_Player[iPlayerId]->Callsign() );
352                 delete m_Player[iPlayerId];
353                 m_Player[iPlayerId] = NULL;
354             }
355
356         }
357     }
358
359 }
360
361 #endif // FG_MPLAYER_AS
362