]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Fix various mp bugs.
[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 <iostream>
35 #include <algorithm>
36 #include <osg/Math>             // isNaN
37 #include <plib/netSocket.h>
38
39 #include <simgear/misc/stdint.hxx>
40 #include <simgear/timing/timestamp.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/props/props.hxx>
43
44 #include <AIModel/AIManager.hxx>
45 #include <Main/fg_props.hxx>
46 #include "multiplaymgr.hxx"
47 #include "mpmessages.hxx"
48
49 using std::cerr;
50
51 #define MAX_PACKET_SIZE 1200
52 #define MAX_TEXT_SIZE 128
53
54 // These constants are provided so that the ident 
55 // command can list file versions
56 const char sMULTIPLAYMGR_BID[] = "$Id$";
57 const char sMULTIPLAYMGR_HID[] = MULTIPLAYTXMGR_HID;
58
59 // A static map of protocol property id values to property paths,
60 // This should be extendable dynamically for every specific aircraft ...
61 // For now only that static list
62 FGMultiplayMgr::IdPropertyList
63 const FGMultiplayMgr::sIdPropertyList[] = {
64   {100, "surface-positions/left-aileron-pos-norm",  SGPropertyNode::FLOAT},
65   {101, "surface-positions/right-aileron-pos-norm", SGPropertyNode::FLOAT},
66   {102, "surface-positions/elevator-pos-norm",      SGPropertyNode::FLOAT},
67   {103, "surface-positions/rudder-pos-norm",        SGPropertyNode::FLOAT},
68   {104, "surface-positions/flap-pos-norm",          SGPropertyNode::FLOAT},
69   {105, "surface-positions/speedbrake-pos-norm",    SGPropertyNode::FLOAT},
70   {106, "gear/tailhook/position-norm",              SGPropertyNode::FLOAT},
71   {107, "gear/launchbar/position-norm",             SGPropertyNode::FLOAT},
72   {108, "gear/launchbar/state",                     SGPropertyNode::STRING},
73   {109, "gear/launchbar/holdback-position-norm",    SGPropertyNode::FLOAT},
74   {110, "canopy/position-norm",                     SGPropertyNode::FLOAT},
75   {111, "surface-positions/wing-pos-norm",          SGPropertyNode::FLOAT},
76   {112, "surface-positions/wing-fold-pos-norm",     SGPropertyNode::FLOAT},
77
78   {200, "gear/gear[0]/compression-norm",           SGPropertyNode::FLOAT},
79   {201, "gear/gear[0]/position-norm",              SGPropertyNode::FLOAT},
80   {210, "gear/gear[1]/compression-norm",           SGPropertyNode::FLOAT},
81   {211, "gear/gear[1]/position-norm",              SGPropertyNode::FLOAT},
82   {220, "gear/gear[2]/compression-norm",           SGPropertyNode::FLOAT},
83   {221, "gear/gear[2]/position-norm",              SGPropertyNode::FLOAT},
84   {230, "gear/gear[3]/compression-norm",           SGPropertyNode::FLOAT},
85   {231, "gear/gear[3]/position-norm",              SGPropertyNode::FLOAT},
86   {240, "gear/gear[4]/compression-norm",           SGPropertyNode::FLOAT},
87   {241, "gear/gear[4]/position-norm",              SGPropertyNode::FLOAT},
88
89   {300, "engines/engine[0]/n1",  SGPropertyNode::FLOAT},
90   {301, "engines/engine[0]/n2",  SGPropertyNode::FLOAT},
91   {302, "engines/engine[0]/rpm", SGPropertyNode::FLOAT},
92   {310, "engines/engine[1]/n1",  SGPropertyNode::FLOAT},
93   {311, "engines/engine[1]/n2",  SGPropertyNode::FLOAT},
94   {312, "engines/engine[1]/rpm", SGPropertyNode::FLOAT},
95   {320, "engines/engine[2]/n1",  SGPropertyNode::FLOAT},
96   {321, "engines/engine[2]/n2",  SGPropertyNode::FLOAT},
97   {322, "engines/engine[2]/rpm", SGPropertyNode::FLOAT},
98   {330, "engines/engine[3]/n1",  SGPropertyNode::FLOAT},
99   {331, "engines/engine[3]/n2",  SGPropertyNode::FLOAT},
100   {332, "engines/engine[3]/rpm", SGPropertyNode::FLOAT},
101   {340, "engines/engine[4]/n1",  SGPropertyNode::FLOAT},
102   {341, "engines/engine[4]/n2",  SGPropertyNode::FLOAT},
103   {342, "engines/engine[4]/rpm", SGPropertyNode::FLOAT},
104   {350, "engines/engine[5]/n1",  SGPropertyNode::FLOAT},
105   {351, "engines/engine[5]/n2",  SGPropertyNode::FLOAT},
106   {352, "engines/engine[5]/rpm", SGPropertyNode::FLOAT},
107   {360, "engines/engine[6]/n1",  SGPropertyNode::FLOAT},
108   {361, "engines/engine[6]/n2",  SGPropertyNode::FLOAT},
109   {362, "engines/engine[6]/rpm", SGPropertyNode::FLOAT},
110   {370, "engines/engine[7]/n1",  SGPropertyNode::FLOAT},
111   {371, "engines/engine[7]/n2",  SGPropertyNode::FLOAT},
112   {372, "engines/engine[7]/rpm", SGPropertyNode::FLOAT},
113   {380, "engines/engine[8]/n1",  SGPropertyNode::FLOAT},
114   {381, "engines/engine[8]/n2",  SGPropertyNode::FLOAT},
115   {382, "engines/engine[8]/rpm", SGPropertyNode::FLOAT},
116   {390, "engines/engine[9]/n1",  SGPropertyNode::FLOAT},
117   {391, "engines/engine[9]/n2",  SGPropertyNode::FLOAT},
118   {392, "engines/engine[9]/rpm", SGPropertyNode::FLOAT},
119
120   {800, "rotors/main/rpm", SGPropertyNode::FLOAT},
121   {801, "rotors/tail/rpm", SGPropertyNode::FLOAT},
122   {810, "rotors/main/blade[0]/position-deg",  SGPropertyNode::FLOAT},
123   {811, "rotors/main/blade[1]/position-deg",  SGPropertyNode::FLOAT},
124   {812, "rotors/main/blade[2]/position-deg",  SGPropertyNode::FLOAT},
125   {813, "rotors/main/blade[3]/position-deg",  SGPropertyNode::FLOAT},
126   {820, "rotors/main/blade[0]/flap-deg",  SGPropertyNode::FLOAT},
127   {821, "rotors/main/blade[1]/flap-deg",  SGPropertyNode::FLOAT},
128   {822, "rotors/main/blade[2]/flap-deg",  SGPropertyNode::FLOAT},
129   {823, "rotors/main/blade[3]/flap-deg",  SGPropertyNode::FLOAT},
130   {830, "rotors/tail/blade[0]/position-deg",  SGPropertyNode::FLOAT},
131   {831, "rotors/tail/blade[1]/position-deg",  SGPropertyNode::FLOAT},
132
133   {900, "sim/hitches/aerotow/tow/length",                       SGPropertyNode::FLOAT},
134   {901, "sim/hitches/aerotow/tow/elastic-constant",             SGPropertyNode::FLOAT},
135   {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m",            SGPropertyNode::FLOAT},
136   {903, "sim/hitches/aerotow/tow/dist",                         SGPropertyNode::FLOAT},
137   {904, "sim/hitches/aerotow/tow/connected-to-property-node",   SGPropertyNode::BOOL},
138   {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign",   SGPropertyNode::STRING},
139   {906, "sim/hitches/aerotow/tow/brake-force",                  SGPropertyNode::FLOAT},
140   {907, "sim/hitches/aerotow/tow/end-force-x",                  SGPropertyNode::FLOAT},
141   {908, "sim/hitches/aerotow/tow/end-force-y",                  SGPropertyNode::FLOAT},
142   {909, "sim/hitches/aerotow/tow/end-force-z",                  SGPropertyNode::FLOAT},
143   {930, "sim/hitches/aerotow/is-slave",                         SGPropertyNode::BOOL},
144   {931, "sim/hitches/aerotow/speed-in-tow-direction",           SGPropertyNode::FLOAT},
145   {932, "sim/hitches/aerotow/open",                             SGPropertyNode::BOOL},
146   {933, "sim/hitches/aerotow/local-pos-x",                      SGPropertyNode::FLOAT},
147   {934, "sim/hitches/aerotow/local-pos-y",                      SGPropertyNode::FLOAT},
148   {935, "sim/hitches/aerotow/local-pos-z",                      SGPropertyNode::FLOAT},
149
150   {1001, "controls/flight/slats",  SGPropertyNode::FLOAT},
151   {1002, "controls/flight/speedbrake",  SGPropertyNode::FLOAT},
152   {1003, "controls/flight/spoilers",  SGPropertyNode::FLOAT},
153   {1004, "controls/gear/gear-down",  SGPropertyNode::FLOAT},
154   {1005, "controls/lighting/nav-lights",  SGPropertyNode::FLOAT},
155   {1006, "controls/armament/station[0]/jettison-all",  SGPropertyNode::BOOL},
156
157   {1100, "sim/model/variant", SGPropertyNode::INT},
158   {1101, "sim/model/livery/file", SGPropertyNode::STRING},
159
160   {10001, "sim/multiplay/transmission-freq-hz",  SGPropertyNode::STRING},
161   {10002, "sim/multiplay/chat",  SGPropertyNode::STRING},
162
163   {10100, "sim/multiplay/generic/string[0]", SGPropertyNode::STRING},
164   {10101, "sim/multiplay/generic/string[1]", SGPropertyNode::STRING},
165   {10102, "sim/multiplay/generic/string[2]", SGPropertyNode::STRING},
166   {10103, "sim/multiplay/generic/string[3]", SGPropertyNode::STRING},
167   {10104, "sim/multiplay/generic/string[4]", SGPropertyNode::STRING},
168   {10105, "sim/multiplay/generic/string[5]", SGPropertyNode::STRING},
169   {10106, "sim/multiplay/generic/string[6]", SGPropertyNode::STRING},
170   {10107, "sim/multiplay/generic/string[7]", SGPropertyNode::STRING},
171   {10108, "sim/multiplay/generic/string[8]", SGPropertyNode::STRING},
172   {10109, "sim/multiplay/generic/string[9]", SGPropertyNode::STRING},
173   {10110, "sim/multiplay/generic/string[10]", SGPropertyNode::STRING},
174   {10111, "sim/multiplay/generic/string[11]", SGPropertyNode::STRING},
175   {10112, "sim/multiplay/generic/string[12]", SGPropertyNode::STRING},
176   {10113, "sim/multiplay/generic/string[13]", SGPropertyNode::STRING},
177   {10114, "sim/multiplay/generic/string[14]", SGPropertyNode::STRING},
178   {10115, "sim/multiplay/generic/string[15]", SGPropertyNode::STRING},
179   {10116, "sim/multiplay/generic/string[16]", SGPropertyNode::STRING},
180   {10117, "sim/multiplay/generic/string[17]", SGPropertyNode::STRING},
181   {10118, "sim/multiplay/generic/string[18]", SGPropertyNode::STRING},
182   {10119, "sim/multiplay/generic/string[19]", SGPropertyNode::STRING},
183
184   {10200, "sim/multiplay/generic/float[0]", SGPropertyNode::FLOAT},
185   {10201, "sim/multiplay/generic/float[1]", SGPropertyNode::FLOAT},
186   {10202, "sim/multiplay/generic/float[2]", SGPropertyNode::FLOAT},
187   {10203, "sim/multiplay/generic/float[3]", SGPropertyNode::FLOAT},
188   {10204, "sim/multiplay/generic/float[4]", SGPropertyNode::FLOAT},
189   {10205, "sim/multiplay/generic/float[5]", SGPropertyNode::FLOAT},
190   {10206, "sim/multiplay/generic/float[6]", SGPropertyNode::FLOAT},
191   {10207, "sim/multiplay/generic/float[7]", SGPropertyNode::FLOAT},
192   {10208, "sim/multiplay/generic/float[8]", SGPropertyNode::FLOAT},
193   {10209, "sim/multiplay/generic/float[9]", SGPropertyNode::FLOAT},
194   {10210, "sim/multiplay/generic/float[10]", SGPropertyNode::FLOAT},
195   {10211, "sim/multiplay/generic/float[11]", SGPropertyNode::FLOAT},
196   {10212, "sim/multiplay/generic/float[12]", SGPropertyNode::FLOAT},
197   {10213, "sim/multiplay/generic/float[13]", SGPropertyNode::FLOAT},
198   {10214, "sim/multiplay/generic/float[14]", SGPropertyNode::FLOAT},
199   {10215, "sim/multiplay/generic/float[15]", SGPropertyNode::FLOAT},
200   {10216, "sim/multiplay/generic/float[16]", SGPropertyNode::FLOAT},
201   {10217, "sim/multiplay/generic/float[17]", SGPropertyNode::FLOAT},
202   {10218, "sim/multiplay/generic/float[18]", SGPropertyNode::FLOAT},
203   {10219, "sim/multiplay/generic/float[19]", SGPropertyNode::FLOAT},
204
205   {10300, "sim/multiplay/generic/int[0]", SGPropertyNode::INT},
206   {10301, "sim/multiplay/generic/int[1]", SGPropertyNode::INT},
207   {10302, "sim/multiplay/generic/int[2]", SGPropertyNode::INT},
208   {10303, "sim/multiplay/generic/int[3]", SGPropertyNode::INT},
209   {10304, "sim/multiplay/generic/int[4]", SGPropertyNode::INT},
210   {10305, "sim/multiplay/generic/int[5]", SGPropertyNode::INT},
211   {10306, "sim/multiplay/generic/int[6]", SGPropertyNode::INT},
212   {10307, "sim/multiplay/generic/int[7]", SGPropertyNode::INT},
213   {10308, "sim/multiplay/generic/int[8]", SGPropertyNode::INT},
214   {10309, "sim/multiplay/generic/int[9]", SGPropertyNode::INT},
215   {10310, "sim/multiplay/generic/int[10]", SGPropertyNode::INT},
216   {10311, "sim/multiplay/generic/int[11]", SGPropertyNode::INT},
217   {10312, "sim/multiplay/generic/int[12]", SGPropertyNode::INT},
218   {10313, "sim/multiplay/generic/int[13]", SGPropertyNode::INT},
219   {10314, "sim/multiplay/generic/int[14]", SGPropertyNode::INT},
220   {10315, "sim/multiplay/generic/int[15]", SGPropertyNode::INT},
221   {10316, "sim/multiplay/generic/int[16]", SGPropertyNode::INT},
222   {10317, "sim/multiplay/generic/int[17]", SGPropertyNode::INT},
223   {10318, "sim/multiplay/generic/int[18]", SGPropertyNode::INT},
224   {10319, "sim/multiplay/generic/int[19]", SGPropertyNode::INT},
225 };
226
227 const unsigned
228 FGMultiplayMgr::numProperties = (sizeof(FGMultiplayMgr::sIdPropertyList)
229                                  / sizeof(FGMultiplayMgr::sIdPropertyList[0]));
230
231 // Look up a property ID using binary search.
232 namespace
233 {
234   struct ComparePropertyId
235   {
236     bool operator()(const FGMultiplayMgr::IdPropertyList& lhs,
237                     const FGMultiplayMgr::IdPropertyList& rhs)
238     {
239       return lhs.id < rhs.id;
240     }
241     bool operator()(const FGMultiplayMgr::IdPropertyList& lhs,
242                     unsigned id)
243     {
244       return lhs.id < id;
245     }
246     bool operator()(unsigned id,
247                     const FGMultiplayMgr::IdPropertyList& rhs)
248     {
249       return id < rhs.id;
250     }
251   };
252     
253 }
254 const FGMultiplayMgr::IdPropertyList* FGMultiplayMgr::findProperty(unsigned id)
255 {
256   std::pair<const IdPropertyList*, const IdPropertyList*> result
257     = std::equal_range(sIdPropertyList, sIdPropertyList + numProperties, id,
258                        ComparePropertyId());
259   if (result.first == result.second) {
260     return 0;
261   } else {
262     return result.first;
263   }
264 }
265
266 namespace
267 {
268   bool verifyProperties(const xdr_data_t* data, const xdr_data_t* end)
269   {
270     const xdr_data_t* xdr = data;
271     while (xdr < end) {
272       unsigned id = XDR_decode_uint32(*xdr);
273       const FGMultiplayMgr::IdPropertyList* plist
274         = FGMultiplayMgr::findProperty(id);
275     
276       if (plist) {
277         xdr++;
278         // How we decode the remainder of the property depends on the type
279         switch (plist->type) {
280         case SGPropertyNode::INT:        
281         case SGPropertyNode::BOOL:
282         case SGPropertyNode::LONG:
283           xdr++;
284           break;
285         case SGPropertyNode::FLOAT:
286         case SGPropertyNode::DOUBLE:
287           {
288             float val = XDR_decode_float(*xdr);
289             if (osg::isNaN(val))
290               return false;
291             xdr++;
292             break;
293           }
294         case SGPropertyNode::STRING:
295         case SGPropertyNode::UNSPECIFIED:
296           {
297             // String is complicated. It consists of
298             // The length of the string
299             // The string itself
300             // Padding to the nearest 4-bytes.
301             // XXX Yes, each byte is padded out to a word! Too late
302             // to change...
303             uint32_t length = XDR_decode_uint32(*xdr);
304             xdr++;
305             // Old versions truncated the string but left the length
306             // unadjusted.
307             if (length > MAX_TEXT_SIZE)
308               length = MAX_TEXT_SIZE;
309             xdr += length;
310             // Now handle the padding
311             while ((length % 4) != 0)
312               {
313                 xdr++;
314                 length++;
315                 //cout << "0";
316               }
317           }
318           break;
319         default:
320           // cerr << "Unknown Prop type " << id << " " << type << "\n";
321           xdr++;
322           break;
323         }            
324       }
325       else {
326         // give up; this is a malformed property list.
327         return false;
328       }
329     }
330     return true;
331   }
332 }
333 //////////////////////////////////////////////////////////////////////
334 //
335 //  MultiplayMgr constructor
336 //
337 //////////////////////////////////////////////////////////////////////
338 FGMultiplayMgr::FGMultiplayMgr() 
339 {
340   mSocket        = 0;
341   mInitialised   = false;
342   mHaveServer    = false;
343 } // FGMultiplayMgr::FGMultiplayMgr()
344 //////////////////////////////////////////////////////////////////////
345
346 //////////////////////////////////////////////////////////////////////
347 //
348 //  MultiplayMgr destructor
349 //
350 //////////////////////////////////////////////////////////////////////
351 FGMultiplayMgr::~FGMultiplayMgr() 
352 {
353   Close();
354 } // FGMultiplayMgr::~FGMultiplayMgr()
355 //////////////////////////////////////////////////////////////////////
356
357 //////////////////////////////////////////////////////////////////////
358 //
359 //  Initialise object
360 //
361 //////////////////////////////////////////////////////////////////////
362 bool
363 FGMultiplayMgr::init (void) 
364 {
365   //////////////////////////////////////////////////
366   //  Initialise object if not already done
367   //////////////////////////////////////////////////
368   if (mInitialised) {
369     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
370     return false;
371   }
372   //////////////////////////////////////////////////
373   //  Set members from property values
374   //////////////////////////////////////////////////
375   short rxPort = fgGetInt("/sim/multiplay/rxport");
376   string rxAddress = fgGetString("/sim/multiplay/rxhost");
377   short txPort = fgGetInt("/sim/multiplay/txport");
378   string txAddress = fgGetString("/sim/multiplay/txhost");
379   mCallsign = fgGetString("/sim/multiplay/callsign");
380   if (txPort > 0 && !txAddress.empty()) {
381     mServer.set(txAddress.c_str(), txPort);
382     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
383       mHaveServer = false;
384       SG_LOG(SG_NETWORK, SG_ALERT,
385         "FGMultiplayMgr - could not resolve '"
386         << txAddress << "', Multiplayermode disabled");
387     } else {
388       mHaveServer = true;
389     }
390     if (rxPort <= 0)
391       rxPort = txPort;
392   }
393   if (rxPort <= 0) {
394     SG_LOG(SG_NETWORK, SG_ALERT,
395       "FGMultiplayMgr - No receiver port, Multiplayermode disabled");
396     return (false);
397   }
398   if (mCallsign.empty())
399     mCallsign = "JohnDoe"; // FIXME: use getpwuid
400   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
401   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
402   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
403   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
404   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
405   Close(); // Should Init be called twice, close Socket first
406            // A memory leak was reported here by valgrind
407   mSocket = new netSocket();
408   if (!mSocket->open(false)) {
409     SG_LOG( SG_NETWORK, SG_ALERT,
410             "FGMultiplayMgr::init - Failed to create data socket" );
411     return false;
412   }
413   mSocket->setBlocking(false);
414   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
415     perror("bind");
416     SG_LOG( SG_NETWORK, SG_ALERT,
417             "FGMultiplayMgr::Open - Failed to bind receive socket" );
418     return false;
419   }
420   mInitialised = true;
421   return true;
422 } // FGMultiplayMgr::init()
423 //////////////////////////////////////////////////////////////////////
424
425 //////////////////////////////////////////////////////////////////////
426 //
427 //  Closes and deletes the local player object. Closes
428 //  and deletes the tx socket. Resets the object state to unitialised.
429 //
430 //////////////////////////////////////////////////////////////////////
431 void
432 FGMultiplayMgr::Close (void) 
433 {
434   mMultiPlayerMap.clear();
435
436   if (mSocket) {
437     mSocket->close();
438     delete mSocket;
439     mSocket = 0;
440   }
441   mInitialised = false;
442 } // FGMultiplayMgr::Close(void)
443 //////////////////////////////////////////////////////////////////////
444
445 //////////////////////////////////////////////////////////////////////
446 //
447 //  Description: Sends the position data for the local position.
448 //
449 //////////////////////////////////////////////////////////////////////
450 void
451 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
452 {
453   if ((! mInitialised) || (! mHaveServer))
454         return;
455   if (! mHaveServer) {
456     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - no server");
457     return;
458   }
459
460   T_PositionMsg PosMsg;
461
462   memset(&PosMsg, 0, sizeof(PosMsg));
463   strncpy(PosMsg.Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
464   PosMsg.Model[MAX_MODEL_NAME_LEN - 1] = '\0';
465   
466   PosMsg.time = XDR_encode_double (motionInfo.time);
467   PosMsg.lag = XDR_encode_double (motionInfo.lag);
468   for (unsigned i = 0 ; i < 3; ++i)
469     PosMsg.position[i] = XDR_encode_double (motionInfo.position(i));
470   SGVec3f angleAxis;
471   motionInfo.orientation.getAngleAxis(angleAxis);
472   for (unsigned i = 0 ; i < 3; ++i)
473     PosMsg.orientation[i] = XDR_encode_float (angleAxis(i));
474   for (unsigned i = 0 ; i < 3; ++i)
475     PosMsg.linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
476   for (unsigned i = 0 ; i < 3; ++i)
477     PosMsg.angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
478   for (unsigned i = 0 ; i < 3; ++i)
479     PosMsg.linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
480   for (unsigned i = 0 ; i < 3; ++i)
481     PosMsg.angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
482   // ensure alignment of message buffer
483   union {
484     xdr_data2_t double_val;
485     char Msg[MAX_PACKET_SIZE];
486   } msgBuf;
487   memcpy(msgBuf.Msg + sizeof(T_MsgHdr), &PosMsg, sizeof(T_PositionMsg));
488   
489   xdr_data_t* ptr = reinterpret_cast<xdr_data_t*>(msgBuf.Msg + sizeof(T_MsgHdr)
490                                                   + sizeof(T_PositionMsg));
491   std::vector<FGPropertyData*>::const_iterator it;
492   it = motionInfo.properties.begin();
493   //cout << "OUTPUT PROPERTIES\n";
494   xdr_data_t* msgEnd = reinterpret_cast<xdr_data_t*>(msgBuf.Msg
495                                                      + MAX_PACKET_SIZE);
496   while (it != motionInfo.properties.end() && ptr + 2 < msgEnd) {
497     
498     // First element is the ID. Write it out when we know we have room for
499     // the whole property.
500     xdr_data_t id =  XDR_encode_uint32((*it)->id);
501     // The actual data representation depends on the type
502     switch ((*it)->type) {
503       case SGPropertyNode::INT:        
504       case SGPropertyNode::BOOL:        
505       case SGPropertyNode::LONG:
506         *ptr++ = id;
507         *ptr++ = XDR_encode_uint32((*it)->int_value);
508         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
509         break;
510       case SGPropertyNode::FLOAT:
511       case SGPropertyNode::DOUBLE:
512         *ptr++ = id;
513         *ptr++ = XDR_encode_float((*it)->float_value);
514         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
515         break;
516       case SGPropertyNode::STRING:
517       case SGPropertyNode::UNSPECIFIED:
518         {
519           // String is complicated. It consists of
520           // The length of the string
521           // The string itself
522           // Padding to the nearest 4-bytes.        
523           const char* lcharptr = (*it)->string_value;
524           
525           if (lcharptr != 0)
526           {
527             // Add the length         
528             ////cout << "String length: " << strlen(lcharptr) << "\n";
529             uint32_t len = strlen(lcharptr);
530             if (len > MAX_TEXT_SIZE)
531               len = MAX_TEXT_SIZE;
532             // XXX This should not be using 4 bytes per character!
533             // If there's not enough room for this property, drop it
534             // on the floor.
535             if (ptr + 2 + ((len + 3) & ~3) > msgEnd)
536                 goto escape;
537             //cout << "String length unint32: " << len << "\n";
538             *ptr++ = id;
539             *ptr++ = XDR_encode_uint32(len);
540             if (len != 0)
541             {
542               // Now the text itself
543               // XXX This should not be using 4 bytes per character!
544               int lcount = 0;
545               while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
546               {
547                 *ptr++ = XDR_encode_int8(*lcharptr);
548                 lcharptr++;
549                 lcount++;          
550               }
551
552               //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
553
554               // Now pad if required
555               while ((lcount % 4) != 0)
556               {
557                 *ptr++ = XDR_encode_int8(0);
558                 lcount++;          
559                 //cout << "0";
560               }
561               
562               //cout << "\n";
563             }
564           }
565           else
566           {
567             // Nothing to encode
568             *ptr++ = id;
569             *ptr++ = XDR_encode_uint32(0);
570             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
571           }
572         }
573         break;
574         
575       default:
576         //cout << " Unknown Type: " << (*it)->type << "\n";
577         *ptr++ = id;
578         *ptr++ = XDR_encode_float((*it)->float_value);;
579         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
580         break;
581     }
582         
583     ++it;
584   }
585 escape:
586   
587   T_MsgHdr MsgHdr;
588   unsigned msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
589   FillMsgHdr(&MsgHdr, POS_DATA_ID, msgLen);
590   memcpy(msgBuf.Msg, &MsgHdr, sizeof(T_MsgHdr));
591
592   mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
593   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
594 } // FGMultiplayMgr::SendMyPosition()
595 //////////////////////////////////////////////////////////////////////
596
597 //////////////////////////////////////////////////////////////////////
598 //
599 //  Name: SendTextMessage
600 //  Description: Sends a message to the player. The message must
601 //  contain a valid and correctly filled out header and optional
602 //  message body.
603 //
604 //////////////////////////////////////////////////////////////////////
605 void
606 FGMultiplayMgr::SendTextMessage(const string &MsgText)
607 {
608   if (!mInitialised || !mHaveServer)
609     return;
610
611   T_MsgHdr MsgHdr;
612   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
613   //////////////////////////////////////////////////
614   // Divide the text string into blocks that fit
615   // in the message and send the blocks.
616   //////////////////////////////////////////////////
617   unsigned iNextBlockPosition = 0;
618   T_ChatMsg ChatMsg;
619   
620   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
621   while (iNextBlockPosition < MsgText.length()) {
622     strncpy (ChatMsg.Text, 
623              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
624              MAX_CHAT_MSG_LEN);
625     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
626     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
627     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
628     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
629     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
630
631   }
632   
633   
634 } // FGMultiplayMgr::SendTextMessage ()
635 //////////////////////////////////////////////////////////////////////
636
637 //////////////////////////////////////////////////////////////////////
638 //
639 //  Name: ProcessData
640 //  Description: Processes data waiting at the receive socket. The
641 //  processing ends when there is no more data at the socket.
642 //  
643 //////////////////////////////////////////////////////////////////////
644 void
645 FGMultiplayMgr::Update(void) 
646 {
647   if (!mInitialised)
648     return;
649
650   /// Just for expiry
651   SGTimeStamp timestamper;
652   timestamper.stamp();
653   long stamp = timestamper.get_seconds();
654
655   //////////////////////////////////////////////////
656   //  Read the receive socket and process any data
657   //////////////////////////////////////////////////
658   int bytes;
659   do {
660     // ensure alignment
661     union {
662       xdr_data2_t doubleVal;
663       char Msg[MAX_PACKET_SIZE];
664     } msgBuf;
665     //////////////////////////////////////////////////
666     //  Although the recv call asks for 
667     //  MAX_PACKET_SIZE of data, the number of bytes
668     //  returned will only be that of the next
669     //  packet waiting to be processed.
670     //////////////////////////////////////////////////
671     netAddress SenderAddress;
672     bytes = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
673                               &SenderAddress);
674     //////////////////////////////////////////////////
675     //  no Data received
676     //////////////////////////////////////////////////
677     if (bytes <= 0) {
678       if (errno != EAGAIN && errno != 0) // MSVC output "NoError" otherwise
679         perror("FGMultiplayMgr::MP_ProcessData");
680       break;
681     }
682     if (bytes <= sizeof(T_MsgHdr)) {
683       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
684               << "received message with insufficient data" );
685       break;
686     }
687     //////////////////////////////////////////////////
688     //  Read header
689     //////////////////////////////////////////////////
690     T_MsgHdr* MsgHdr = reinterpret_cast<T_MsgHdr *>(msgBuf.Msg);
691     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
692     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
693     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
694     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
695     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
696     MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
697     if (MsgHdr->Magic != MSG_MAGIC) {
698       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
699               << "message has invalid magic number!" );
700       break;
701     }
702     if (MsgHdr->Version != PROTO_VER) {
703       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
704               << "message has invalid protocoll number!" );
705       break;
706     }
707     if (MsgHdr->MsgLen != bytes) {
708       SG_LOG(SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
709              << "message from " << MsgHdr->Callsign << " has invalid length!");
710       break;
711     }
712     //////////////////////////////////////////////////
713     //  Process messages
714     //////////////////////////////////////////////////
715     switch (MsgHdr->MsgId) {
716     case CHAT_MSG_ID:
717       ProcessChatMsg(msgBuf.Msg, SenderAddress);
718       break;
719     case POS_DATA_ID:
720       ProcessPosMsg(msgBuf.Msg, SenderAddress, bytes, stamp);
721       break;
722     case UNUSABLE_POS_DATA_ID:
723     case OLD_OLD_POS_DATA_ID:
724     case OLD_PROP_MSG_ID:
725     case OLD_POS_DATA_ID:
726       break;
727     default:
728       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
729               << "Unknown message Id received: " << MsgHdr->MsgId );
730       break;
731     }
732   } while (bytes > 0);
733
734   // check for expiry
735   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
736   while (it != mMultiPlayerMap.end()) {
737     if (it->second->getLastTimestamp() + 10 < stamp) {
738       std::string name = it->first;
739       it->second->setDie(true);
740       mMultiPlayerMap.erase(it);
741       it = mMultiPlayerMap.upper_bound(name);
742     } else
743       ++it;
744   }
745 } // FGMultiplayMgr::ProcessData(void)
746 //////////////////////////////////////////////////////////////////////
747
748 //////////////////////////////////////////////////////////////////////
749 //
750 //  handle a position message
751 //
752 //////////////////////////////////////////////////////////////////////
753 void
754 FGMultiplayMgr::ProcessPosMsg(const char *Msg, netAddress & SenderAddress,
755                               unsigned len, long stamp)
756 {
757   const T_MsgHdr* MsgHdr = reinterpret_cast<const T_MsgHdr *>(Msg);
758   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
759     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
760             << "Position message received with insufficient data" );
761     return;
762   }
763   const T_PositionMsg* PosMsg
764     = reinterpret_cast<const T_PositionMsg *>(Msg + sizeof(T_MsgHdr));
765   FGExternalMotionData motionInfo;
766   motionInfo.time = XDR_decode_double(PosMsg->time);
767   motionInfo.lag = XDR_decode_double(PosMsg->lag);
768   for (unsigned i = 0; i < 3; ++i)
769     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
770   SGVec3f angleAxis;
771   for (unsigned i = 0; i < 3; ++i)
772     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
773   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
774   for (unsigned i = 0; i < 3; ++i)
775     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
776   for (unsigned i = 0; i < 3; ++i)
777     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
778   for (unsigned i = 0; i < 3; ++i)
779     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
780   for (unsigned i = 0; i < 3; ++i)
781     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
782
783
784   //cout << "INPUT MESSAGE\n";
785   const xdr_data_t* xdr = (xdr_data_t*)(Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg));
786   // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
787   // on 32 bit architectures and 200 bytes on 64 bit, and this
788   // structure is put directly on the wire. By looking at the padding,
789   // we can sort through the mess, mostly:
790   // If padding is 0 (which is not a valid property type), then the
791   // message was produced by a new client or an old 64 bit client that
792   // happened to have 0 on the stack;
793   // Else if the property list starting with the padding word is
794   // well-formed, then the client is probably an old 32 bit client and
795   // we'll go with that;
796   // Else it is an old 64-bit client and properties start after the
797   // padding.
798   // There is a chance that we could be fooled by garbage in the
799   // padding looking like a valid property, so verifyProperties() is
800   // strict about the validity of the property values.
801   if (PosMsg->pad != 0) {
802     if (verifyProperties(&PosMsg->pad,
803                          reinterpret_cast<const xdr_data_t*>(Msg + len)))
804       xdr = &PosMsg->pad;
805     else if (!verifyProperties(xdr,
806                                reinterpret_cast<const xdr_data_t*>(Msg + len)))
807       goto noprops;
808   }
809   while ((char*)xdr < Msg + len) {
810     FGPropertyData* pData = new FGPropertyData;
811     SGPropertyNode::Type type = SGPropertyNode::UNSPECIFIED;
812     
813     // First element is always the ID
814     pData->id = XDR_decode_uint32(*xdr);
815     //cout << pData->id << " ";
816     xdr++;
817     
818     // Check the ID actually exists and get the type
819     const IdPropertyList* plist = findProperty(pData->id);
820     
821     if (plist)
822     {
823       pData->type = plist->type;
824       // How we decode the remainder of the property depends on the type
825       switch (pData->type) {
826         case SGPropertyNode::INT:        
827         case SGPropertyNode::BOOL:
828         case SGPropertyNode::LONG:        
829           pData->int_value = XDR_decode_uint32(*xdr);
830           xdr++;
831           //cout << pData->int_value << "\n";
832           break;
833         case SGPropertyNode::FLOAT:
834         case SGPropertyNode::DOUBLE:
835           pData->float_value = XDR_decode_float(*xdr);
836           xdr++;
837           //cout << pData->float_value << "\n";
838           break;
839         case SGPropertyNode::STRING:
840         case SGPropertyNode::UNSPECIFIED:
841           {
842             // String is complicated. It consists of
843             // The length of the string
844             // The string itself
845             // Padding to the nearest 4-bytes.    
846             uint32_t length = XDR_decode_uint32(*xdr);
847             xdr++;
848             //cout << length << " ";
849             // Old versions truncated the string but left the length unadjusted.
850             if (length > MAX_TEXT_SIZE)
851               length = MAX_TEXT_SIZE;
852             pData->string_value = new char[length + 1];
853             //cout << " String: ";
854             for (int i = 0; i < length; i++)
855               {
856                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
857                 xdr++;
858                 //cout << pData->string_value[i];
859               }
860
861             pData->string_value[length] = '\0';
862
863             // Now handle the padding
864             while ((length % 4) != 0)
865               {
866                 xdr++;
867                 length++;
868                 //cout << "0";
869               }
870             //cout << "\n";
871           }
872           break;
873
874         default:
875           pData->float_value = XDR_decode_float(*xdr);
876           cerr << "Unknown Prop type " << pData->id << " " << pData->type << "\n";
877           xdr++;
878           break;
879       }            
880
881       motionInfo.properties.push_back(pData);
882     }
883     else
884     {
885       // We failed to find the property. We'll try the next packet immediately.
886       SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr::ProcessPosMsg - "
887              "message from " << MsgHdr->Callsign << " has unknown property id "
888              << pData->id); 
889     }
890   }
891  noprops:
892   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
893   if (!mp)
894     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
895   mp->addMotionInfo(motionInfo, stamp);
896 } // FGMultiplayMgr::ProcessPosMsg()
897 //////////////////////////////////////////////////////////////////////
898
899 //////////////////////////////////////////////////////////////////////
900 //
901 //  handle a chat message
902 //  FIXME: display chat message withi flightgear
903 //
904 //////////////////////////////////////////////////////////////////////
905 void
906 FGMultiplayMgr::ProcessChatMsg(const char *Msg, netAddress& SenderAddress)
907 {
908   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
909   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
910     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
911             << "Chat message received with insufficient data" );
912     return;
913   }
914   
915   char *MsgBuf = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
916   strncpy(MsgBuf, ((T_ChatMsg *)(Msg + sizeof(T_MsgHdr)))->Text,
917           MsgHdr->MsgLen - sizeof(T_MsgHdr));
918   MsgBuf[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
919   
920   T_ChatMsg* ChatMsg = (T_ChatMsg *)(Msg + sizeof(T_MsgHdr));
921   SG_LOG (SG_NETWORK, SG_ALERT, "Chat [" << MsgHdr->Callsign << "]"
922            << " " << MsgBuf);
923
924   delete [] MsgBuf;
925 } // FGMultiplayMgr::ProcessChatMsg ()
926 //////////////////////////////////////////////////////////////////////
927
928 void
929 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
930 {
931   uint32_t len;
932   switch (MsgId) {
933   case CHAT_MSG_ID:
934     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
935     break;
936   case POS_DATA_ID:
937     len = _len;
938     break;
939   default:
940     len = sizeof(T_MsgHdr);
941     break;
942   }
943   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
944   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
945   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
946   MsgHdr->MsgLen          = XDR_encode_uint32(len);
947   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
948   MsgHdr->ReplyPort       = 0; // now
949   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
950   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
951 }
952
953 FGAIMultiplayer*
954 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
955                                const std::string& modelName)
956 {
957   if (0 < mMultiPlayerMap.count(callsign))
958     return mMultiPlayerMap[callsign].get();
959
960   FGAIMultiplayer* mp = new FGAIMultiplayer;
961   mp->setPath(modelName.c_str());
962   mp->setCallSign(callsign);
963   mMultiPlayerMap[callsign] = mp;
964
965   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
966   if (aiMgr) {
967     aiMgr->attach(mp);
968
969     /// FIXME: that must follow the attach ATM ...
970     for (unsigned i = 0; i < numProperties; ++i)
971       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
972   }
973
974   return mp;
975 }
976
977 FGAIMultiplayer*
978 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
979 {
980   if (0 < mMultiPlayerMap.count(callsign))
981     return mMultiPlayerMap[callsign].get();
982   else
983     return 0;
984 }