]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Modified Files:
[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
67   {200, "gear/gear[0]/compression-norm",           SGPropertyNode::FLOAT},
68   {201, "gear/gear[0]/position-norm",              SGPropertyNode::FLOAT},
69   {210, "gear/gear[1]/compression-norm",           SGPropertyNode::FLOAT},
70   {211, "gear/gear[1]/position-norm",              SGPropertyNode::FLOAT},
71   {220, "gear/gear[2]/compression-norm",           SGPropertyNode::FLOAT},
72   {221, "gear/gear[2]/position-norm",              SGPropertyNode::FLOAT},
73   {230, "gear/gear[3]/compression-norm",           SGPropertyNode::FLOAT},
74   {231, "gear/gear[3]/position-norm",              SGPropertyNode::FLOAT},
75   {240, "gear/gear[4]/compression-norm",           SGPropertyNode::FLOAT},
76   {241, "gear/gear[4]/position-norm",              SGPropertyNode::FLOAT},
77
78   {300, "engines/engine[0]/n1",  SGPropertyNode::FLOAT},
79   {301, "engines/engine[0]/n2",  SGPropertyNode::FLOAT},
80   {302, "engines/engine[0]/rpm", SGPropertyNode::FLOAT},
81   {310, "engines/engine[1]/n1",  SGPropertyNode::FLOAT},
82   {311, "engines/engine[1]/n2",  SGPropertyNode::FLOAT},
83   {312, "engines/engine[1]/rpm", SGPropertyNode::FLOAT},
84   {320, "engines/engine[2]/n1",  SGPropertyNode::FLOAT},
85   {321, "engines/engine[2]/n2",  SGPropertyNode::FLOAT},
86   {322, "engines/engine[2]/rpm", SGPropertyNode::FLOAT},
87   {330, "engines/engine[3]/n1",  SGPropertyNode::FLOAT},
88   {331, "engines/engine[3]/n2",  SGPropertyNode::FLOAT},
89   {332, "engines/engine[3]/rpm", SGPropertyNode::FLOAT},
90   {340, "engines/engine[4]/n1",  SGPropertyNode::FLOAT},
91   {341, "engines/engine[4]/n2",  SGPropertyNode::FLOAT},
92   {342, "engines/engine[4]/rpm", SGPropertyNode::FLOAT},
93   {350, "engines/engine[5]/n1",  SGPropertyNode::FLOAT},
94   {351, "engines/engine[5]/n2",  SGPropertyNode::FLOAT},
95   {352, "engines/engine[5]/rpm", SGPropertyNode::FLOAT},
96   {360, "engines/engine[6]/n1",  SGPropertyNode::FLOAT},
97   {361, "engines/engine[6]/n2",  SGPropertyNode::FLOAT},
98   {362, "engines/engine[6]/rpm", SGPropertyNode::FLOAT},
99   {370, "engines/engine[7]/n1",  SGPropertyNode::FLOAT},
100   {371, "engines/engine[7]/n2",  SGPropertyNode::FLOAT},
101   {372, "engines/engine[7]/rpm", SGPropertyNode::FLOAT},
102   {380, "engines/engine[8]/n1",  SGPropertyNode::FLOAT},
103   {381, "engines/engine[8]/n2",  SGPropertyNode::FLOAT},
104   {382, "engines/engine[8]/rpm", SGPropertyNode::FLOAT},
105   {390, "engines/engine[9]/n1",  SGPropertyNode::FLOAT},
106   {391, "engines/engine[9]/n2",  SGPropertyNode::FLOAT},
107   {392, "engines/engine[9]/rpm", SGPropertyNode::FLOAT},
108
109   {800, "rotors/main/rpm", SGPropertyNode::FLOAT},
110   {801, "rotors/tail/rpm", SGPropertyNode::FLOAT},
111   {810, "rotors/main/blade[0]/position-deg",  SGPropertyNode::FLOAT},
112   {811, "rotors/main/blade[1]/position-deg",  SGPropertyNode::FLOAT},
113   {812, "rotors/main/blade[2]/position-deg",  SGPropertyNode::FLOAT},
114   {813, "rotors/main/blade[3]/position-deg",  SGPropertyNode::FLOAT},
115   {820, "rotors/main/blade[0]/flap-deg",  SGPropertyNode::FLOAT},
116   {821, "rotors/main/blade[1]/flap-deg",  SGPropertyNode::FLOAT},
117   {822, "rotors/main/blade[2]/flap-deg",  SGPropertyNode::FLOAT},
118   {823, "rotors/main/blade[3]/flap-deg",  SGPropertyNode::FLOAT},
119   {830, "rotors/tail/blade[0]/position-deg",  SGPropertyNode::FLOAT},
120   {831, "rotors/tail/blade[1]/position-deg",  SGPropertyNode::FLOAT},
121
122   {1001, "controls/flight/slats",  SGPropertyNode::FLOAT},
123   {1002, "controls/flight/speedbrake",  SGPropertyNode::FLOAT},
124   {1003, "controls/flight/spoilers",  SGPropertyNode::FLOAT},
125   {1004, "controls/gear/gear-down",  SGPropertyNode::FLOAT},
126   {1005, "controls/lighting/nav-lights",  SGPropertyNode::FLOAT},
127   
128   {10001, "sim/multiplay/transmission-freq-hz",  SGPropertyNode::STRING},
129   {10002, "sim/multiplay/chat",  SGPropertyNode::STRING},
130
131   /// termination
132   {0, 0, SGPropertyNode::UNSPECIFIED}
133 };
134
135 //////////////////////////////////////////////////////////////////////
136 //
137 //  MultiplayMgr constructor
138 //
139 //////////////////////////////////////////////////////////////////////
140 FGMultiplayMgr::FGMultiplayMgr() 
141 {
142   mInitialised   = false;
143   mHaveServer    = false;
144 } // FGMultiplayMgr::FGMultiplayMgr()
145 //////////////////////////////////////////////////////////////////////
146
147 //////////////////////////////////////////////////////////////////////
148 //
149 //  MultiplayMgr destructor
150 //
151 //////////////////////////////////////////////////////////////////////
152 FGMultiplayMgr::~FGMultiplayMgr() 
153 {
154   Close();
155 } // FGMultiplayMgr::~FGMultiplayMgr()
156 //////////////////////////////////////////////////////////////////////
157
158 //////////////////////////////////////////////////////////////////////
159 //
160 //  Initialise object
161 //
162 //////////////////////////////////////////////////////////////////////
163 bool
164 FGMultiplayMgr::init (void) 
165 {
166   //////////////////////////////////////////////////
167   //  Initialise object if not already done
168   //////////////////////////////////////////////////
169   if (mInitialised) {
170     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
171     return false;
172   }
173   //////////////////////////////////////////////////
174   //  Set members from property values
175   //////////////////////////////////////////////////
176   short rxPort = fgGetInt("/sim/multiplay/rxport");
177   if (rxPort <= 0)
178     rxPort = 5000;
179   mCallsign = fgGetString("/sim/multiplay/callsign");
180   if (mCallsign.empty())
181     // FIXME: use getpwuid
182     mCallsign = "JohnDoe"; 
183   string rxAddress = fgGetString("/sim/multiplay/rxhost");
184   if (rxAddress.empty())
185     rxAddress = "127.0.0.1";
186   short txPort = fgGetInt("/sim/multiplay/txport");
187   string txAddress = fgGetString("/sim/multiplay/txhost");
188   if (txPort > 0 && !txAddress.empty()) {
189     mHaveServer = true;
190     mServer.set(txAddress.c_str(), txPort);
191   }
192   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
193   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
194   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
195   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
196   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
197   mSocket = new netSocket();
198   if (!mSocket->open(false)) {
199     SG_LOG( SG_NETWORK, SG_ALERT,
200             "FGMultiplayMgr::init - Failed to create data socket" );
201     return false;
202   }
203   mSocket->setBlocking(false);
204   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
205     perror("bind");
206     SG_LOG( SG_NETWORK, SG_ALERT,
207             "FGMultiplayMgr::Open - Failed to bind receive socket" );
208     return false;
209   }
210   mInitialised = true;
211   return true;
212 } // FGMultiplayMgr::init()
213 //////////////////////////////////////////////////////////////////////
214
215 //////////////////////////////////////////////////////////////////////
216 //
217 //  Closes and deletes the local player object. Closes
218 //  and deletes the tx socket. Resets the object state to unitialised.
219 //
220 //////////////////////////////////////////////////////////////////////
221 void
222 FGMultiplayMgr::Close (void) 
223 {
224   mMultiPlayerMap.clear();
225
226   if (mSocket) {
227     mSocket->close();
228     delete mSocket;
229     mSocket = 0;
230   }
231   mInitialised = false;
232 } // FGMultiplayMgr::Close(void)
233 //////////////////////////////////////////////////////////////////////
234
235 //////////////////////////////////////////////////////////////////////
236 //
237 //  Description: Sends the position data for the local position.
238 //
239 //////////////////////////////////////////////////////////////////////
240 void
241 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
242 {
243   if ((! mInitialised) || (! mHaveServer)) {
244     if (! mInitialised)
245       SG_LOG( SG_NETWORK, SG_ALERT,
246               "FGMultiplayMgr::SendMyPosition - not initialised" );
247     if (! mHaveServer)
248       SG_LOG( SG_NETWORK, SG_ALERT,
249               "FGMultiplayMgr::SendMyPosition - no server" );
250     return;
251   }
252
253   T_PositionMsg PosMsg;
254   strncpy(PosMsg.Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
255   PosMsg.Model[MAX_MODEL_NAME_LEN - 1] = '\0';
256   
257   PosMsg.time = XDR_encode_double (motionInfo.time);
258   PosMsg.lag = XDR_encode_double (motionInfo.lag);
259   for (unsigned i = 0 ; i < 3; ++i)
260     PosMsg.position[i] = XDR_encode_double (motionInfo.position(i));
261   SGVec3f angleAxis;
262   motionInfo.orientation.getAngleAxis(angleAxis);
263   for (unsigned i = 0 ; i < 3; ++i)
264     PosMsg.orientation[i] = XDR_encode_float (angleAxis(i));
265   for (unsigned i = 0 ; i < 3; ++i)
266     PosMsg.linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
267   for (unsigned i = 0 ; i < 3; ++i)
268     PosMsg.angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
269   for (unsigned i = 0 ; i < 3; ++i)
270     PosMsg.linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
271   for (unsigned i = 0 ; i < 3; ++i)
272     PosMsg.angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
273
274   char Msg[MAX_PACKET_SIZE];
275   memcpy(Msg + sizeof(T_MsgHdr), &PosMsg, sizeof(T_PositionMsg));
276   
277   char* ptr = Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg);
278   std::vector<FGPropertyData*>::const_iterator it;
279   it = motionInfo.properties.begin();
280   //cout << "OUTPUT PROPERTIES\n";
281   while (it != motionInfo.properties.end()
282          && ptr < (Msg + MAX_PACKET_SIZE - sizeof(xdr_data_t))) {
283              
284     // First elements is the ID
285     xdr_data_t xdr = XDR_encode_uint32((*it)->id);
286     memcpy(ptr, &xdr, sizeof(xdr_data_t));
287     ptr += sizeof(xdr_data_t);
288     
289     // The actual data representation depends on the type
290     switch ((*it)->type) {
291       case SGPropertyNode::INT:        
292       case SGPropertyNode::BOOL:        
293       case SGPropertyNode::LONG:        
294         xdr = XDR_encode_uint32((*it)->int_value);
295         memcpy(ptr, &xdr, sizeof(xdr_data_t));
296         ptr += sizeof(xdr_data_t);
297         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
298         break;
299       case SGPropertyNode::FLOAT:
300       case SGPropertyNode::DOUBLE:
301         xdr = XDR_encode_float((*it)->float_value);;
302         memcpy(ptr, &xdr, sizeof(xdr_data_t));
303         ptr += sizeof(xdr_data_t);
304         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
305         break;
306       case SGPropertyNode::STRING:
307       case SGPropertyNode::UNSPECIFIED:
308         {
309           // String is complicated. It consists of
310           // The length of the string
311           // The string itself
312           // Padding to the nearest 4-bytes.        
313           const char* lcharptr = (*it)->string_value;
314           
315           if (lcharptr != 0)
316           {
317             // Add the length         
318             ////cout << "String length: " << strlen(lcharptr) << "\n";
319             uint32_t len = strlen(lcharptr);
320             //cout << "String length unint32: " << len << "\n";
321             xdr = XDR_encode_uint32(len);
322             memcpy(ptr, &xdr, sizeof(xdr_data_t));
323             ptr += sizeof(xdr_data_t);
324             
325             if (len != 0)
326             {
327
328               // Now the text itself          
329               int lcount = 0;
330               while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
331               {
332                 xdr = XDR_encode_int8(*lcharptr);
333                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
334                 ptr += sizeof(xdr_data_t);
335                 lcharptr++;
336                 lcount++;          
337               }
338
339               //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
340
341               // Now pad if required
342               while ((lcount % 4) != 0)
343               {
344                 xdr = XDR_encode_int8(0);
345                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
346                 ptr += sizeof(xdr_data_t);
347                 lcount++;          
348                 //cout << "0";
349               }
350               
351               //cout << "\n";
352             }
353           }
354           else
355           {
356             // Nothing to encode
357             xdr = XDR_encode_uint32(0);
358             memcpy(ptr, &xdr, sizeof(xdr_data_t));
359             ptr += sizeof(xdr_data_t);
360             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
361           }
362            
363         }
364         break;
365         
366       default:
367         //cout << " Unknown Type: " << (*it)->type << "\n";
368         xdr = XDR_encode_float((*it)->float_value);;
369         memcpy(ptr, &xdr, sizeof(xdr_data_t));
370         ptr += sizeof(xdr_data_t);
371         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
372         break;
373     }
374         
375     ++it;
376   }
377
378   T_MsgHdr MsgHdr;
379   FillMsgHdr(&MsgHdr, POS_DATA_ID, ptr - Msg);
380   memcpy(Msg, &MsgHdr, sizeof(T_MsgHdr));
381
382   mSocket->sendto(Msg, ptr - Msg, 0, &mServer);
383   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
384 } // FGMultiplayMgr::SendMyPosition()
385 //////////////////////////////////////////////////////////////////////
386
387 //////////////////////////////////////////////////////////////////////
388 //
389 //  Name: SendTextMessage
390 //  Description: Sends a message to the player. The message must
391 //  contain a valid and correctly filled out header and optional
392 //  message body.
393 //
394 //////////////////////////////////////////////////////////////////////
395 void
396 FGMultiplayMgr::SendTextMessage(const string &MsgText)
397 {
398   if (!mInitialised || !mHaveServer)
399     return;
400
401   T_MsgHdr MsgHdr;
402   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
403   //////////////////////////////////////////////////
404   // Divide the text string into blocks that fit
405   // in the message and send the blocks.
406   //////////////////////////////////////////////////
407   unsigned iNextBlockPosition = 0;
408   T_ChatMsg ChatMsg;
409   
410   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
411   while (iNextBlockPosition < MsgText.length()) {
412     strncpy (ChatMsg.Text, 
413              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
414              MAX_CHAT_MSG_LEN);
415     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
416     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
417     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
418     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
419     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
420
421   }
422   
423   
424 } // FGMultiplayMgr::SendTextMessage ()
425 //////////////////////////////////////////////////////////////////////
426
427 //////////////////////////////////////////////////////////////////////
428 //
429 //  Name: ProcessData
430 //  Description: Processes data waiting at the receive socket. The
431 //  processing ends when there is no more data at the socket.
432 //  
433 //////////////////////////////////////////////////////////////////////
434 void
435 FGMultiplayMgr::Update(void) 
436 {
437   if (!mInitialised)
438     return;
439
440   /// Just for expiry
441   SGTimeStamp timestamper;
442   timestamper.stamp();
443   long stamp = timestamper.get_seconds();
444
445   //////////////////////////////////////////////////
446   //  Read the receive socket and process any data
447   //////////////////////////////////////////////////
448   int bytes;
449   do {
450     char Msg[MAX_PACKET_SIZE];
451     //////////////////////////////////////////////////
452     //  Although the recv call asks for 
453     //  MAX_PACKET_SIZE of data, the number of bytes
454     //  returned will only be that of the next
455     //  packet waiting to be processed.
456     //////////////////////////////////////////////////
457     netAddress SenderAddress;
458     bytes = mSocket->recvfrom(Msg, sizeof(Msg), 0, &SenderAddress);
459     //////////////////////////////////////////////////
460     //  no Data received
461     //////////////////////////////////////////////////
462     if (bytes <= 0) {
463       if (errno != EAGAIN && errno != 0) // MSVC output "NoError" otherwise
464         perror("FGMultiplayMgr::MP_ProcessData");
465       break;
466     }
467     if (bytes <= sizeof(T_MsgHdr)) {
468       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
469               << "received message with insufficient data" );
470       break;
471     }
472     //////////////////////////////////////////////////
473     //  Read header
474     //////////////////////////////////////////////////
475     T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
476     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
477     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
478     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
479     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
480     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
481     if (MsgHdr->Magic != MSG_MAGIC) {
482       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
483               << "message has invalid magic number!" );
484     }
485     if (MsgHdr->Version != PROTO_VER) {
486       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
487               << "message has invalid protocoll number!" );
488     }
489     if (MsgHdr->MsgLen != bytes) {
490       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
491               << "message has invalid length!" );
492     }
493     //////////////////////////////////////////////////
494     //  Process messages
495     //////////////////////////////////////////////////
496     switch (MsgHdr->MsgId) {
497     case CHAT_MSG_ID:
498       ProcessChatMsg(Msg, SenderAddress);
499       break;
500     case POS_DATA_ID:
501       ProcessPosMsg(Msg, SenderAddress, bytes, stamp);
502       break;
503     case UNUSABLE_POS_DATA_ID:
504     case OLD_OLD_POS_DATA_ID:
505     case OLD_PROP_MSG_ID:
506     case OLD_POS_DATA_ID:
507       break;
508     default:
509       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
510               << "Unknown message Id received: " << MsgHdr->MsgId );
511       break;
512     }
513   } while (bytes > 0);
514
515   // check for expiry
516   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
517   while (it != mMultiPlayerMap.end()) {
518     if (it->second->getLastTimestamp() + 10 < stamp) {
519       std::string name = it->first;
520       it->second->setDie(true);
521       mMultiPlayerMap.erase(it);
522       it = mMultiPlayerMap.upper_bound(name);
523     } else
524       ++it;
525   }
526 } // FGMultiplayMgr::ProcessData(void)
527 //////////////////////////////////////////////////////////////////////
528
529 //////////////////////////////////////////////////////////////////////
530 //
531 //  handle a position message
532 //
533 //////////////////////////////////////////////////////////////////////
534 void
535 FGMultiplayMgr::ProcessPosMsg(const char *Msg, netAddress & SenderAddress,
536                               unsigned len, long stamp)
537 {
538   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
539   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
540     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
541             << "Position message received with insufficient data" );
542     return;
543   }
544   T_PositionMsg* PosMsg = (T_PositionMsg *)(Msg + sizeof(T_MsgHdr));
545   FGExternalMotionData motionInfo;
546   motionInfo.time = XDR_decode_double(PosMsg->time);
547   motionInfo.lag = XDR_decode_double(PosMsg->lag);
548   for (unsigned i = 0; i < 3; ++i)
549     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
550   SGVec3f angleAxis;
551   for (unsigned i = 0; i < 3; ++i)
552     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
553   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
554   for (unsigned i = 0; i < 3; ++i)
555     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
556   for (unsigned i = 0; i < 3; ++i)
557     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
558   for (unsigned i = 0; i < 3; ++i)
559     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
560   for (unsigned i = 0; i < 3; ++i)
561     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
562
563
564   //cout << "INPUT MESSAGE\n";
565   xdr_data_t* xdr = (xdr_data_t*) 
566                    (Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg));
567   while ((char*)xdr < Msg + len) {
568     FGPropertyData* pData = new FGPropertyData;
569     SGPropertyNode::Type type = SGPropertyNode::UNSPECIFIED;
570     
571     // First element is always the ID
572     pData->id = XDR_decode_uint32(*xdr);
573     //cout << pData->id << " ";
574     xdr++;
575     
576     // Check the ID actually exists and get the type
577     unsigned i = 0;
578     bool found = false;
579     while (FGMultiplayMgr::sIdPropertyList[i].name) 
580     {
581       if (sIdPropertyList[i].id == pData->id)
582       {
583         found = true;
584         pData->type = sIdPropertyList[i].type;
585       } 
586       
587       i++;
588     }
589     
590     if (found == true)
591     {
592       // How we decode the remainder of the property depends on the type
593       switch (pData->type) {
594         case SGPropertyNode::INT:        
595         case SGPropertyNode::BOOL:
596         case SGPropertyNode::LONG:        
597           pData->int_value = XDR_decode_uint32(*xdr);
598           xdr++;
599           //cout << pData->int_value << "\n";
600           break;
601         case SGPropertyNode::FLOAT:
602         case SGPropertyNode::DOUBLE:
603           pData->float_value = XDR_decode_float(*xdr);
604           xdr++;
605           //cout << pData->float_value << "\n";
606           break;
607         case SGPropertyNode::STRING:
608         case SGPropertyNode::UNSPECIFIED:
609           {
610             // String is complicated. It consists of
611             // The length of the string
612             // The string itself
613             // Padding to the nearest 4-bytes.    
614             uint32_t length = XDR_decode_uint32(*xdr);
615             xdr++;
616             //cout << length << " ";
617
618             if ((length > 0) && (length < MAX_TEXT_SIZE))
619             {
620               pData->string_value = new char[length + 1];
621               //cout << " String: ";
622
623               for (int i = 0; i < length; i++)
624               {
625                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
626                 xdr++;
627                 //cout << pData->string_value[i];
628               }
629
630               pData->string_value[length] = '\0';
631
632               // Now handle the padding
633               while ((length % 4) != 0)
634               {
635                 xdr++;
636                 length++;
637                 //cout << "0";
638               }
639             }
640             else
641             {
642               pData->string_value = new char[1];
643               pData->string_value[0] = '\0';
644             }
645
646             //cout << "\n";
647           }
648           break;
649
650         default:
651           pData->float_value = XDR_decode_float(*xdr);
652           cerr << "Unknown Prop type " << pData->id << " " << pData->type << "\n";
653           xdr++;
654           break;
655       }            
656
657       motionInfo.properties.push_back(pData);
658     }
659     else
660     {
661       // We failed to find the property. We'll try the next packet immediately.
662       //cout << " Unknown\n";
663     }
664   }
665   
666   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
667   if (!mp)
668     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
669   mp->addMotionInfo(motionInfo, stamp);
670 } // FGMultiplayMgr::ProcessPosMsg()
671 //////////////////////////////////////////////////////////////////////
672
673 //////////////////////////////////////////////////////////////////////
674 //
675 //  handle a chat message
676 //  FIXME: display chat message withi flightgear
677 //
678 //////////////////////////////////////////////////////////////////////
679 void
680 FGMultiplayMgr::ProcessChatMsg(const char *Msg, netAddress& SenderAddress)
681 {
682   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
683   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
684     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
685             << "Chat message received with insufficient data" );
686     return;
687   }
688   
689   char *MsgBuf = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
690   strncpy(MsgBuf, ((T_ChatMsg *)(Msg + sizeof(T_MsgHdr)))->Text,
691           MsgHdr->MsgLen - sizeof(T_MsgHdr));
692   MsgBuf[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
693   
694   T_ChatMsg* ChatMsg = (T_ChatMsg *)(Msg + sizeof(T_MsgHdr));
695   SG_LOG ( SG_NETWORK, SG_ALERT, "Chat [" << MsgHdr->Callsign << "]"
696            << " " << MsgBuf << endl);
697
698   delete [] MsgBuf;
699 } // FGMultiplayMgr::ProcessChatMsg ()
700 //////////////////////////////////////////////////////////////////////
701
702 void
703 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
704 {
705   uint32_t len;
706   switch (MsgId) {
707   case CHAT_MSG_ID:
708     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
709     break;
710   case POS_DATA_ID:
711     len = _len;
712     break;
713   default:
714     len = sizeof(T_MsgHdr);
715     break;
716   }
717   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
718   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
719   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
720   MsgHdr->MsgLen          = XDR_encode_uint32(len);
721   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
722   MsgHdr->ReplyPort       = 0; // now
723   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
724   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
725 }
726
727 FGAIMultiplayer*
728 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
729                                const std::string& modelName)
730 {
731   if (0 < mMultiPlayerMap.count(callsign))
732     return mMultiPlayerMap[callsign];
733
734   FGAIMultiplayer* mp = new FGAIMultiplayer;
735   mp->setPath(modelName.c_str());
736   mp->setCallSign(callsign);
737   mMultiPlayerMap[callsign] = mp;
738
739   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
740   if (aiMgr) {
741     aiMgr->attach(mp);
742
743     /// FIXME: that must follow the attach ATM ...
744     unsigned i = 0;
745     while (sIdPropertyList[i].name) {
746       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
747       ++i;
748     }
749   }
750
751   return mp;
752 }
753
754 FGAIMultiplayer*
755 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
756 {
757   if (0 < mMultiPlayerMap.count(callsign))
758     return mMultiPlayerMap[callsign];
759   else
760     return 0;
761 }