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