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