]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Fix tiny memory leak, as reported by Valgrind.
[flightgear.git] / src / MultiPlayer / multiplaymgr.cxx
1 //////////////////////////////////////////////////////////////////////
2 //
3 // multiplaymgr.hpp
4 //
5 // Written by Duncan McCreanor, started February 2003.
6 // duncan.mccreanor@airservicesaustralia.com
7 //
8 // Copyright (C) 2003  Airservices Australia
9 // Copyright (C) 2005  Oliver Schroeder
10 // Copyright (C) 2006  Mathias Froehlich
11 //
12 // This program is free software; you can redistribute it and/or
13 // modify it under the terms of the GNU General Public License as
14 // published by the Free Software Foundation; either version 2 of the
15 // License, or (at your option) any later version.
16 //
17 // This program is distributed in the hope that it will be useful, but
18 // WITHOUT ANY WARRANTY; without even the implied warranty of
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 // General Public License for more details.
21 //
22 // You should have received a copy of the GNU General Public License
23 // along with this program; if not, write to the Free Software
24 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
25 //
26 // $Id$
27 //  
28 //////////////////////////////////////////////////////////////////////
29
30 #ifdef HAVE_CONFIG_H
31 #include <config.h>
32 #endif
33
34 #include <plib/netSocket.h>
35
36 #include <simgear/misc/stdint.hxx>
37 #include <simgear/timing/timestamp.hxx>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/props/props.hxx>
40
41 #include <AIModel/AIManager.hxx>
42 #include <Main/fg_props.hxx>
43 #include "multiplaymgr.hxx"
44 #include "mpmessages.hxx"
45
46 #define MAX_PACKET_SIZE 1200
47 #define MAX_TEXT_SIZE 128
48
49 // These constants are provided so that the ident 
50 // command can list file versions
51 const char sMULTIPLAYMGR_BID[] = "$Id$";
52 const char sMULTIPLAYMGR_HID[] = MULTIPLAYTXMGR_HID;
53
54 // A static map of protocol property id values to property paths,
55 // This should be extendable dynamically for every specific aircraft ...
56 // For now only that static list
57 FGMultiplayMgr::IdPropertyList
58 FGMultiplayMgr::sIdPropertyList[] = {
59   {100, "surface-positions/left-aileron-pos-norm",  SGPropertyNode::FLOAT},
60   {101, "surface-positions/right-aileron-pos-norm", SGPropertyNode::FLOAT},
61   {102, "surface-positions/elevator-pos-norm",      SGPropertyNode::FLOAT},
62   {103, "surface-positions/rudder-pos-norm",        SGPropertyNode::FLOAT},
63   {104, "surface-positions/flap-pos-norm",          SGPropertyNode::FLOAT},
64   {105, "surface-positions/speedbrake-pos-norm",    SGPropertyNode::FLOAT},
65   {106, "gear/tailhook/position-norm",              SGPropertyNode::FLOAT},
66   {107, "gear/launchbar/position-norm",             SGPropertyNode::FLOAT},
67   {108, "gear/launchbar/state",                     SGPropertyNode::STRING},
68   {109, "gear/launchbar/holdback-position-norm",    SGPropertyNode::FLOAT},
69   {110, "canopy/position-norm",                     SGPropertyNode::FLOAT},
70
71   {200, "gear/gear[0]/compression-norm",           SGPropertyNode::FLOAT},
72   {201, "gear/gear[0]/position-norm",              SGPropertyNode::FLOAT},
73   {210, "gear/gear[1]/compression-norm",           SGPropertyNode::FLOAT},
74   {211, "gear/gear[1]/position-norm",              SGPropertyNode::FLOAT},
75   {220, "gear/gear[2]/compression-norm",           SGPropertyNode::FLOAT},
76   {221, "gear/gear[2]/position-norm",              SGPropertyNode::FLOAT},
77   {230, "gear/gear[3]/compression-norm",           SGPropertyNode::FLOAT},
78   {231, "gear/gear[3]/position-norm",              SGPropertyNode::FLOAT},
79   {240, "gear/gear[4]/compression-norm",           SGPropertyNode::FLOAT},
80   {241, "gear/gear[4]/position-norm",              SGPropertyNode::FLOAT},
81
82   {300, "engines/engine[0]/n1",  SGPropertyNode::FLOAT},
83   {301, "engines/engine[0]/n2",  SGPropertyNode::FLOAT},
84   {302, "engines/engine[0]/rpm", SGPropertyNode::FLOAT},
85   {310, "engines/engine[1]/n1",  SGPropertyNode::FLOAT},
86   {311, "engines/engine[1]/n2",  SGPropertyNode::FLOAT},
87   {312, "engines/engine[1]/rpm", SGPropertyNode::FLOAT},
88   {320, "engines/engine[2]/n1",  SGPropertyNode::FLOAT},
89   {321, "engines/engine[2]/n2",  SGPropertyNode::FLOAT},
90   {322, "engines/engine[2]/rpm", SGPropertyNode::FLOAT},
91   {330, "engines/engine[3]/n1",  SGPropertyNode::FLOAT},
92   {331, "engines/engine[3]/n2",  SGPropertyNode::FLOAT},
93   {332, "engines/engine[3]/rpm", SGPropertyNode::FLOAT},
94   {340, "engines/engine[4]/n1",  SGPropertyNode::FLOAT},
95   {341, "engines/engine[4]/n2",  SGPropertyNode::FLOAT},
96   {342, "engines/engine[4]/rpm", SGPropertyNode::FLOAT},
97   {350, "engines/engine[5]/n1",  SGPropertyNode::FLOAT},
98   {351, "engines/engine[5]/n2",  SGPropertyNode::FLOAT},
99   {352, "engines/engine[5]/rpm", SGPropertyNode::FLOAT},
100   {360, "engines/engine[6]/n1",  SGPropertyNode::FLOAT},
101   {361, "engines/engine[6]/n2",  SGPropertyNode::FLOAT},
102   {362, "engines/engine[6]/rpm", SGPropertyNode::FLOAT},
103   {370, "engines/engine[7]/n1",  SGPropertyNode::FLOAT},
104   {371, "engines/engine[7]/n2",  SGPropertyNode::FLOAT},
105   {372, "engines/engine[7]/rpm", SGPropertyNode::FLOAT},
106   {380, "engines/engine[8]/n1",  SGPropertyNode::FLOAT},
107   {381, "engines/engine[8]/n2",  SGPropertyNode::FLOAT},
108   {382, "engines/engine[8]/rpm", SGPropertyNode::FLOAT},
109   {390, "engines/engine[9]/n1",  SGPropertyNode::FLOAT},
110   {391, "engines/engine[9]/n2",  SGPropertyNode::FLOAT},
111   {392, "engines/engine[9]/rpm", SGPropertyNode::FLOAT},
112
113   {800, "rotors/main/rpm", SGPropertyNode::FLOAT},
114   {801, "rotors/tail/rpm", SGPropertyNode::FLOAT},
115   {810, "rotors/main/blade[0]/position-deg",  SGPropertyNode::FLOAT},
116   {811, "rotors/main/blade[1]/position-deg",  SGPropertyNode::FLOAT},
117   {812, "rotors/main/blade[2]/position-deg",  SGPropertyNode::FLOAT},
118   {813, "rotors/main/blade[3]/position-deg",  SGPropertyNode::FLOAT},
119   {820, "rotors/main/blade[0]/flap-deg",  SGPropertyNode::FLOAT},
120   {821, "rotors/main/blade[1]/flap-deg",  SGPropertyNode::FLOAT},
121   {822, "rotors/main/blade[2]/flap-deg",  SGPropertyNode::FLOAT},
122   {823, "rotors/main/blade[3]/flap-deg",  SGPropertyNode::FLOAT},
123   {830, "rotors/tail/blade[0]/position-deg",  SGPropertyNode::FLOAT},
124   {831, "rotors/tail/blade[1]/position-deg",  SGPropertyNode::FLOAT},
125
126   {900, "sim/hitches/aerotow/tow/length",                       SGPropertyNode::FLOAT},
127   {901, "sim/hitches/aerotow/tow/elastic-constant",             SGPropertyNode::FLOAT},
128   {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m",            SGPropertyNode::FLOAT},
129   {903, "sim/hitches/aerotow/tow/dist",                         SGPropertyNode::FLOAT},
130   {904, "sim/hitches/aerotow/tow/connected-to-property-node",   SGPropertyNode::BOOL},
131   {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign",   SGPropertyNode::STRING},
132   {906, "sim/hitches/aerotow/tow/brake-force",                  SGPropertyNode::FLOAT},
133   {907, "sim/hitches/aerotow/tow/end-force-x",                  SGPropertyNode::FLOAT},
134   {908, "sim/hitches/aerotow/tow/end-force-y",                  SGPropertyNode::FLOAT},
135   {909, "sim/hitches/aerotow/tow/end-force-z",                  SGPropertyNode::FLOAT},
136   {930, "sim/hitches/aerotow/is-slave",                         SGPropertyNode::BOOL},
137   {931, "sim/hitches/aerotow/speed-in-tow-direction",           SGPropertyNode::FLOAT},
138   {932, "sim/hitches/aerotow/open",                             SGPropertyNode::BOOL},
139   {933, "sim/hitches/aerotow/local-pos-x",                      SGPropertyNode::FLOAT},
140   {934, "sim/hitches/aerotow/local-pos-y",                      SGPropertyNode::FLOAT},
141   {935, "sim/hitches/aerotow/local-pos-z",                      SGPropertyNode::FLOAT},
142
143   {1001, "controls/flight/slats",  SGPropertyNode::FLOAT},
144   {1002, "controls/flight/speedbrake",  SGPropertyNode::FLOAT},
145   {1003, "controls/flight/spoilers",  SGPropertyNode::FLOAT},
146   {1004, "controls/gear/gear-down",  SGPropertyNode::FLOAT},
147   {1005, "controls/lighting/nav-lights",  SGPropertyNode::FLOAT},
148   {1006, "controls/armament/station[0]/jettison-all",  SGPropertyNode::BOOL},
149
150   {1100, "sim/model/variant", SGPropertyNode::INT},
151
152   {10001, "sim/multiplay/transmission-freq-hz",  SGPropertyNode::STRING},
153   {10002, "sim/multiplay/chat",  SGPropertyNode::STRING},
154
155   /// termination
156   {0, 0, SGPropertyNode::UNSPECIFIED}
157 };
158
159 //////////////////////////////////////////////////////////////////////
160 //
161 //  MultiplayMgr constructor
162 //
163 //////////////////////////////////////////////////////////////////////
164 FGMultiplayMgr::FGMultiplayMgr() 
165 {
166   mSocket        = 0;
167   mInitialised   = false;
168   mHaveServer    = false;
169 } // FGMultiplayMgr::FGMultiplayMgr()
170 //////////////////////////////////////////////////////////////////////
171
172 //////////////////////////////////////////////////////////////////////
173 //
174 //  MultiplayMgr destructor
175 //
176 //////////////////////////////////////////////////////////////////////
177 FGMultiplayMgr::~FGMultiplayMgr() 
178 {
179   Close();
180 } // FGMultiplayMgr::~FGMultiplayMgr()
181 //////////////////////////////////////////////////////////////////////
182
183 //////////////////////////////////////////////////////////////////////
184 //
185 //  Initialise object
186 //
187 //////////////////////////////////////////////////////////////////////
188 bool
189 FGMultiplayMgr::init (void) 
190 {
191   //////////////////////////////////////////////////
192   //  Initialise object if not already done
193   //////////////////////////////////////////////////
194   if (mInitialised) {
195     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
196     return false;
197   }
198   //////////////////////////////////////////////////
199   //  Set members from property values
200   //////////////////////////////////////////////////
201   short rxPort = fgGetInt("/sim/multiplay/rxport");
202   if (rxPort <= 0)
203     rxPort = 5000;
204   mCallsign = fgGetString("/sim/multiplay/callsign");
205   if (mCallsign.empty())
206     // FIXME: use getpwuid
207     mCallsign = "JohnDoe"; 
208   string rxAddress = fgGetString("/sim/multiplay/rxhost");
209   if (rxAddress.empty())
210     rxAddress = "127.0.0.1";
211   short txPort = fgGetInt("/sim/multiplay/txport");
212   string txAddress = fgGetString("/sim/multiplay/txhost");
213   if (txPort > 0 && !txAddress.empty()) {
214     mHaveServer = true;
215     mServer.set(txAddress.c_str(), txPort);
216   }
217   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
218   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
219   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
220   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
221   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
222   Close(); // Should Init be called twice, close Socket first
223            // A memory leak was reported here by valgrind
224   mSocket = new netSocket();
225   if (!mSocket->open(false)) {
226     SG_LOG( SG_NETWORK, SG_ALERT,
227             "FGMultiplayMgr::init - Failed to create data socket" );
228     return false;
229   }
230   mSocket->setBlocking(false);
231   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
232     perror("bind");
233     SG_LOG( SG_NETWORK, SG_ALERT,
234             "FGMultiplayMgr::Open - Failed to bind receive socket" );
235     return false;
236   }
237   mInitialised = true;
238   return true;
239 } // FGMultiplayMgr::init()
240 //////////////////////////////////////////////////////////////////////
241
242 //////////////////////////////////////////////////////////////////////
243 //
244 //  Closes and deletes the local player object. Closes
245 //  and deletes the tx socket. Resets the object state to unitialised.
246 //
247 //////////////////////////////////////////////////////////////////////
248 void
249 FGMultiplayMgr::Close (void) 
250 {
251   mMultiPlayerMap.clear();
252
253   if (mSocket) {
254     mSocket->close();
255     delete mSocket;
256     mSocket = 0;
257   }
258   mInitialised = false;
259 } // FGMultiplayMgr::Close(void)
260 //////////////////////////////////////////////////////////////////////
261
262 //////////////////////////////////////////////////////////////////////
263 //
264 //  Description: Sends the position data for the local position.
265 //
266 //////////////////////////////////////////////////////////////////////
267 void
268 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
269 {
270   if ((! mInitialised) || (! mHaveServer)) {
271     if (! mInitialised)
272       SG_LOG( SG_NETWORK, SG_ALERT,
273               "FGMultiplayMgr::SendMyPosition - not initialised" );
274     if (! mHaveServer)
275       SG_LOG( SG_NETWORK, SG_ALERT,
276               "FGMultiplayMgr::SendMyPosition - no server" );
277     return;
278   }
279
280   T_PositionMsg PosMsg;
281   strncpy(PosMsg.Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
282   PosMsg.Model[MAX_MODEL_NAME_LEN - 1] = '\0';
283   
284   PosMsg.time = XDR_encode_double (motionInfo.time);
285   PosMsg.lag = XDR_encode_double (motionInfo.lag);
286   for (unsigned i = 0 ; i < 3; ++i)
287     PosMsg.position[i] = XDR_encode_double (motionInfo.position(i));
288   SGVec3f angleAxis;
289   motionInfo.orientation.getAngleAxis(angleAxis);
290   for (unsigned i = 0 ; i < 3; ++i)
291     PosMsg.orientation[i] = XDR_encode_float (angleAxis(i));
292   for (unsigned i = 0 ; i < 3; ++i)
293     PosMsg.linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
294   for (unsigned i = 0 ; i < 3; ++i)
295     PosMsg.angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
296   for (unsigned i = 0 ; i < 3; ++i)
297     PosMsg.linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
298   for (unsigned i = 0 ; i < 3; ++i)
299     PosMsg.angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
300
301   char Msg[MAX_PACKET_SIZE];
302   memcpy(Msg + sizeof(T_MsgHdr), &PosMsg, sizeof(T_PositionMsg));
303   
304   char* ptr = Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg);
305   std::vector<FGPropertyData*>::const_iterator it;
306   it = motionInfo.properties.begin();
307   //cout << "OUTPUT PROPERTIES\n";
308   while (it != motionInfo.properties.end()
309          && ptr < (Msg + MAX_PACKET_SIZE - sizeof(xdr_data_t))) {
310              
311     // First elements is the ID
312     xdr_data_t xdr = XDR_encode_uint32((*it)->id);
313     memcpy(ptr, &xdr, sizeof(xdr_data_t));
314     ptr += sizeof(xdr_data_t);
315     
316     // The actual data representation depends on the type
317     switch ((*it)->type) {
318       case SGPropertyNode::INT:        
319       case SGPropertyNode::BOOL:        
320       case SGPropertyNode::LONG:        
321         xdr = XDR_encode_uint32((*it)->int_value);
322         memcpy(ptr, &xdr, sizeof(xdr_data_t));
323         ptr += sizeof(xdr_data_t);
324         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
325         break;
326       case SGPropertyNode::FLOAT:
327       case SGPropertyNode::DOUBLE:
328         xdr = XDR_encode_float((*it)->float_value);;
329         memcpy(ptr, &xdr, sizeof(xdr_data_t));
330         ptr += sizeof(xdr_data_t);
331         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
332         break;
333       case SGPropertyNode::STRING:
334       case SGPropertyNode::UNSPECIFIED:
335         {
336           // String is complicated. It consists of
337           // The length of the string
338           // The string itself
339           // Padding to the nearest 4-bytes.        
340           const char* lcharptr = (*it)->string_value;
341           
342           if (lcharptr != 0)
343           {
344             // Add the length         
345             ////cout << "String length: " << strlen(lcharptr) << "\n";
346             uint32_t len = strlen(lcharptr);
347             //cout << "String length unint32: " << len << "\n";
348             xdr = XDR_encode_uint32(len);
349             memcpy(ptr, &xdr, sizeof(xdr_data_t));
350             ptr += sizeof(xdr_data_t);
351             
352             if (len != 0)
353             {
354
355               // Now the text itself          
356               int lcount = 0;
357               while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
358               {
359                 xdr = XDR_encode_int8(*lcharptr);
360                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
361                 ptr += sizeof(xdr_data_t);
362                 lcharptr++;
363                 lcount++;          
364               }
365
366               //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
367
368               // Now pad if required
369               while ((lcount % 4) != 0)
370               {
371                 xdr = XDR_encode_int8(0);
372                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
373                 ptr += sizeof(xdr_data_t);
374                 lcount++;          
375                 //cout << "0";
376               }
377               
378               //cout << "\n";
379             }
380           }
381           else
382           {
383             // Nothing to encode
384             xdr = XDR_encode_uint32(0);
385             memcpy(ptr, &xdr, sizeof(xdr_data_t));
386             ptr += sizeof(xdr_data_t);
387             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
388           }
389            
390         }
391         break;
392         
393       default:
394         //cout << " Unknown Type: " << (*it)->type << "\n";
395         xdr = XDR_encode_float((*it)->float_value);;
396         memcpy(ptr, &xdr, sizeof(xdr_data_t));
397         ptr += sizeof(xdr_data_t);
398         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
399         break;
400     }
401         
402     ++it;
403   }
404
405   T_MsgHdr MsgHdr;
406   FillMsgHdr(&MsgHdr, POS_DATA_ID, ptr - Msg);
407   memcpy(Msg, &MsgHdr, sizeof(T_MsgHdr));
408
409   mSocket->sendto(Msg, ptr - Msg, 0, &mServer);
410   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
411 } // FGMultiplayMgr::SendMyPosition()
412 //////////////////////////////////////////////////////////////////////
413
414 //////////////////////////////////////////////////////////////////////
415 //
416 //  Name: SendTextMessage
417 //  Description: Sends a message to the player. The message must
418 //  contain a valid and correctly filled out header and optional
419 //  message body.
420 //
421 //////////////////////////////////////////////////////////////////////
422 void
423 FGMultiplayMgr::SendTextMessage(const string &MsgText)
424 {
425   if (!mInitialised || !mHaveServer)
426     return;
427
428   T_MsgHdr MsgHdr;
429   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
430   //////////////////////////////////////////////////
431   // Divide the text string into blocks that fit
432   // in the message and send the blocks.
433   //////////////////////////////////////////////////
434   unsigned iNextBlockPosition = 0;
435   T_ChatMsg ChatMsg;
436   
437   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
438   while (iNextBlockPosition < MsgText.length()) {
439     strncpy (ChatMsg.Text, 
440              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
441              MAX_CHAT_MSG_LEN);
442     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
443     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
444     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
445     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
446     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
447
448   }
449   
450   
451 } // FGMultiplayMgr::SendTextMessage ()
452 //////////////////////////////////////////////////////////////////////
453
454 //////////////////////////////////////////////////////////////////////
455 //
456 //  Name: ProcessData
457 //  Description: Processes data waiting at the receive socket. The
458 //  processing ends when there is no more data at the socket.
459 //  
460 //////////////////////////////////////////////////////////////////////
461 void
462 FGMultiplayMgr::Update(void) 
463 {
464   if (!mInitialised)
465     return;
466
467   /// Just for expiry
468   SGTimeStamp timestamper;
469   timestamper.stamp();
470   long stamp = timestamper.get_seconds();
471
472   //////////////////////////////////////////////////
473   //  Read the receive socket and process any data
474   //////////////////////////////////////////////////
475   int bytes;
476   do {
477     char Msg[MAX_PACKET_SIZE];
478     //////////////////////////////////////////////////
479     //  Although the recv call asks for 
480     //  MAX_PACKET_SIZE of data, the number of bytes
481     //  returned will only be that of the next
482     //  packet waiting to be processed.
483     //////////////////////////////////////////////////
484     netAddress SenderAddress;
485     bytes = mSocket->recvfrom(Msg, sizeof(Msg), 0, &SenderAddress);
486     //////////////////////////////////////////////////
487     //  no Data received
488     //////////////////////////////////////////////////
489     if (bytes <= 0) {
490       if (errno != EAGAIN && errno != 0) // MSVC output "NoError" otherwise
491         perror("FGMultiplayMgr::MP_ProcessData");
492       break;
493     }
494     if (bytes <= sizeof(T_MsgHdr)) {
495       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
496               << "received message with insufficient data" );
497       break;
498     }
499     //////////////////////////////////////////////////
500     //  Read header
501     //////////////////////////////////////////////////
502     T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
503     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
504     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
505     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
506     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
507     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
508     if (MsgHdr->Magic != MSG_MAGIC) {
509       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
510               << "message has invalid magic number!" );
511     }
512     if (MsgHdr->Version != PROTO_VER) {
513       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
514               << "message has invalid protocoll number!" );
515     }
516     if (MsgHdr->MsgLen != bytes) {
517       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
518               << "message has invalid length!" );
519     }
520     //////////////////////////////////////////////////
521     //  Process messages
522     //////////////////////////////////////////////////
523     switch (MsgHdr->MsgId) {
524     case CHAT_MSG_ID:
525       ProcessChatMsg(Msg, SenderAddress);
526       break;
527     case POS_DATA_ID:
528       ProcessPosMsg(Msg, SenderAddress, bytes, stamp);
529       break;
530     case UNUSABLE_POS_DATA_ID:
531     case OLD_OLD_POS_DATA_ID:
532     case OLD_PROP_MSG_ID:
533     case OLD_POS_DATA_ID:
534       break;
535     default:
536       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
537               << "Unknown message Id received: " << MsgHdr->MsgId );
538       break;
539     }
540   } while (bytes > 0);
541
542   // check for expiry
543   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
544   while (it != mMultiPlayerMap.end()) {
545     if (it->second->getLastTimestamp() + 10 < stamp) {
546       std::string name = it->first;
547       it->second->setDie(true);
548       mMultiPlayerMap.erase(it);
549       it = mMultiPlayerMap.upper_bound(name);
550     } else
551       ++it;
552   }
553 } // FGMultiplayMgr::ProcessData(void)
554 //////////////////////////////////////////////////////////////////////
555
556 //////////////////////////////////////////////////////////////////////
557 //
558 //  handle a position message
559 //
560 //////////////////////////////////////////////////////////////////////
561 void
562 FGMultiplayMgr::ProcessPosMsg(const char *Msg, netAddress & SenderAddress,
563                               unsigned len, long stamp)
564 {
565   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
566   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
567     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
568             << "Position message received with insufficient data" );
569     return;
570   }
571   T_PositionMsg* PosMsg = (T_PositionMsg *)(Msg + sizeof(T_MsgHdr));
572   FGExternalMotionData motionInfo;
573   motionInfo.time = XDR_decode_double(PosMsg->time);
574   motionInfo.lag = XDR_decode_double(PosMsg->lag);
575   for (unsigned i = 0; i < 3; ++i)
576     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
577   SGVec3f angleAxis;
578   for (unsigned i = 0; i < 3; ++i)
579     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
580   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
581   for (unsigned i = 0; i < 3; ++i)
582     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
583   for (unsigned i = 0; i < 3; ++i)
584     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
585   for (unsigned i = 0; i < 3; ++i)
586     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
587   for (unsigned i = 0; i < 3; ++i)
588     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
589
590
591   //cout << "INPUT MESSAGE\n";
592   xdr_data_t* xdr = (xdr_data_t*) 
593                    (Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg));
594   while ((char*)xdr < Msg + len) {
595     FGPropertyData* pData = new FGPropertyData;
596     SGPropertyNode::Type type = SGPropertyNode::UNSPECIFIED;
597     
598     // First element is always the ID
599     pData->id = XDR_decode_uint32(*xdr);
600     //cout << pData->id << " ";
601     xdr++;
602     
603     // Check the ID actually exists and get the type
604     unsigned i = 0;
605     bool found = false;
606     while (FGMultiplayMgr::sIdPropertyList[i].name) 
607     {
608       if (sIdPropertyList[i].id == pData->id)
609       {
610         found = true;
611         pData->type = sIdPropertyList[i].type;
612       } 
613       
614       i++;
615     }
616     
617     if (found == true)
618     {
619       // How we decode the remainder of the property depends on the type
620       switch (pData->type) {
621         case SGPropertyNode::INT:        
622         case SGPropertyNode::BOOL:
623         case SGPropertyNode::LONG:        
624           pData->int_value = XDR_decode_uint32(*xdr);
625           xdr++;
626           //cout << pData->int_value << "\n";
627           break;
628         case SGPropertyNode::FLOAT:
629         case SGPropertyNode::DOUBLE:
630           pData->float_value = XDR_decode_float(*xdr);
631           xdr++;
632           //cout << pData->float_value << "\n";
633           break;
634         case SGPropertyNode::STRING:
635         case SGPropertyNode::UNSPECIFIED:
636           {
637             // String is complicated. It consists of
638             // The length of the string
639             // The string itself
640             // Padding to the nearest 4-bytes.    
641             uint32_t length = XDR_decode_uint32(*xdr);
642             xdr++;
643             //cout << length << " ";
644
645             if ((length > 0) && (length < MAX_TEXT_SIZE))
646             {
647               pData->string_value = new char[length + 1];
648               //cout << " String: ";
649
650               for (int i = 0; i < length; i++)
651               {
652                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
653                 xdr++;
654                 //cout << pData->string_value[i];
655               }
656
657               pData->string_value[length] = '\0';
658
659               // Now handle the padding
660               while ((length % 4) != 0)
661               {
662                 xdr++;
663                 length++;
664                 //cout << "0";
665               }
666             }
667             else
668             {
669               pData->string_value = new char[1];
670               pData->string_value[0] = '\0';
671             }
672
673             //cout << "\n";
674           }
675           break;
676
677         default:
678           pData->float_value = XDR_decode_float(*xdr);
679           cerr << "Unknown Prop type " << pData->id << " " << pData->type << "\n";
680           xdr++;
681           break;
682       }            
683
684       motionInfo.properties.push_back(pData);
685     }
686     else
687     {
688       // We failed to find the property. We'll try the next packet immediately.
689       //cout << " Unknown\n";
690     }
691   }
692   
693   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
694   if (!mp)
695     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
696   mp->addMotionInfo(motionInfo, stamp);
697 } // FGMultiplayMgr::ProcessPosMsg()
698 //////////////////////////////////////////////////////////////////////
699
700 //////////////////////////////////////////////////////////////////////
701 //
702 //  handle a chat message
703 //  FIXME: display chat message withi flightgear
704 //
705 //////////////////////////////////////////////////////////////////////
706 void
707 FGMultiplayMgr::ProcessChatMsg(const char *Msg, netAddress& SenderAddress)
708 {
709   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
710   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
711     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
712             << "Chat message received with insufficient data" );
713     return;
714   }
715   
716   char *MsgBuf = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
717   strncpy(MsgBuf, ((T_ChatMsg *)(Msg + sizeof(T_MsgHdr)))->Text,
718           MsgHdr->MsgLen - sizeof(T_MsgHdr));
719   MsgBuf[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
720   
721   T_ChatMsg* ChatMsg = (T_ChatMsg *)(Msg + sizeof(T_MsgHdr));
722   SG_LOG ( SG_NETWORK, SG_ALERT, "Chat [" << MsgHdr->Callsign << "]"
723            << " " << MsgBuf << endl);
724
725   delete [] MsgBuf;
726 } // FGMultiplayMgr::ProcessChatMsg ()
727 //////////////////////////////////////////////////////////////////////
728
729 void
730 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
731 {
732   uint32_t len;
733   switch (MsgId) {
734   case CHAT_MSG_ID:
735     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
736     break;
737   case POS_DATA_ID:
738     len = _len;
739     break;
740   default:
741     len = sizeof(T_MsgHdr);
742     break;
743   }
744   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
745   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
746   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
747   MsgHdr->MsgLen          = XDR_encode_uint32(len);
748   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
749   MsgHdr->ReplyPort       = 0; // now
750   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
751   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
752 }
753
754 FGAIMultiplayer*
755 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
756                                const std::string& modelName)
757 {
758   if (0 < mMultiPlayerMap.count(callsign))
759     return mMultiPlayerMap[callsign];
760
761   FGAIMultiplayer* mp = new FGAIMultiplayer;
762   mp->setPath(modelName.c_str());
763   mp->setCallSign(callsign);
764   mMultiPlayerMap[callsign] = mp;
765
766   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
767   if (aiMgr) {
768     aiMgr->attach(mp);
769
770     /// FIXME: that must follow the attach ATM ...
771     unsigned i = 0;
772     while (sIdPropertyList[i].name) {
773       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
774       ++i;
775     }
776   }
777
778   return mp;
779 }
780
781 FGAIMultiplayer*
782 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
783 {
784   if (0 < mMultiPlayerMap.count(callsign))
785     return mMultiPlayerMap[callsign];
786   else
787     return 0;
788 }