]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Improve transponder instrumentation: new version
[flightgear.git] / src / MultiPlayer / multiplaymgr.cxx
1 //////////////////////////////////////////////////////////////////////
2 //
3 // multiplaymgr.cxx
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 <cstring>
37 #include <errno.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 <AIModel/AIMultiplayer.hxx>
46 #include <Main/fg_props.hxx>
47 #include "multiplaymgr.hxx"
48 #include "mpmessages.hxx"
49 #include <FDM/flightProperties.hxx>
50
51 using namespace std;
52
53 #define MAX_PACKET_SIZE 1200
54 #define MAX_TEXT_SIZE 128
55
56 // These constants are provided so that the ident 
57 // command can list file versions
58 const char sMULTIPLAYMGR_BID[] = "$Id$";
59 const char sMULTIPLAYMGR_HID[] = MULTIPLAYTXMGR_HID;
60
61 struct IdPropertyList {
62   unsigned id;
63   const char* name;
64   simgear::props::Type type;
65 };
66  
67 static const IdPropertyList* findProperty(unsigned id);
68   
69 // A static map of protocol property id values to property paths,
70 // This should be extendable dynamically for every specific aircraft ...
71 // For now only that static list
72 static const IdPropertyList sIdPropertyList[] = {
73   {100, "surface-positions/left-aileron-pos-norm",  simgear::props::FLOAT},
74   {101, "surface-positions/right-aileron-pos-norm", simgear::props::FLOAT},
75   {102, "surface-positions/elevator-pos-norm",      simgear::props::FLOAT},
76   {103, "surface-positions/rudder-pos-norm",        simgear::props::FLOAT},
77   {104, "surface-positions/flap-pos-norm",          simgear::props::FLOAT},
78   {105, "surface-positions/speedbrake-pos-norm",    simgear::props::FLOAT},
79   {106, "gear/tailhook/position-norm",              simgear::props::FLOAT},
80   {107, "gear/launchbar/position-norm",             simgear::props::FLOAT},
81   {108, "gear/launchbar/state",                     simgear::props::STRING},
82   {109, "gear/launchbar/holdback-position-norm",    simgear::props::FLOAT},
83   {110, "canopy/position-norm",                     simgear::props::FLOAT},
84   {111, "surface-positions/wing-pos-norm",          simgear::props::FLOAT},
85   {112, "surface-positions/wing-fold-pos-norm",     simgear::props::FLOAT},
86
87   {200, "gear/gear[0]/compression-norm",           simgear::props::FLOAT},
88   {201, "gear/gear[0]/position-norm",              simgear::props::FLOAT},
89   {210, "gear/gear[1]/compression-norm",           simgear::props::FLOAT},
90   {211, "gear/gear[1]/position-norm",              simgear::props::FLOAT},
91   {220, "gear/gear[2]/compression-norm",           simgear::props::FLOAT},
92   {221, "gear/gear[2]/position-norm",              simgear::props::FLOAT},
93   {230, "gear/gear[3]/compression-norm",           simgear::props::FLOAT},
94   {231, "gear/gear[3]/position-norm",              simgear::props::FLOAT},
95   {240, "gear/gear[4]/compression-norm",           simgear::props::FLOAT},
96   {241, "gear/gear[4]/position-norm",              simgear::props::FLOAT},
97
98   {300, "engines/engine[0]/n1",  simgear::props::FLOAT},
99   {301, "engines/engine[0]/n2",  simgear::props::FLOAT},
100   {302, "engines/engine[0]/rpm", simgear::props::FLOAT},
101   {310, "engines/engine[1]/n1",  simgear::props::FLOAT},
102   {311, "engines/engine[1]/n2",  simgear::props::FLOAT},
103   {312, "engines/engine[1]/rpm", simgear::props::FLOAT},
104   {320, "engines/engine[2]/n1",  simgear::props::FLOAT},
105   {321, "engines/engine[2]/n2",  simgear::props::FLOAT},
106   {322, "engines/engine[2]/rpm", simgear::props::FLOAT},
107   {330, "engines/engine[3]/n1",  simgear::props::FLOAT},
108   {331, "engines/engine[3]/n2",  simgear::props::FLOAT},
109   {332, "engines/engine[3]/rpm", simgear::props::FLOAT},
110   {340, "engines/engine[4]/n1",  simgear::props::FLOAT},
111   {341, "engines/engine[4]/n2",  simgear::props::FLOAT},
112   {342, "engines/engine[4]/rpm", simgear::props::FLOAT},
113   {350, "engines/engine[5]/n1",  simgear::props::FLOAT},
114   {351, "engines/engine[5]/n2",  simgear::props::FLOAT},
115   {352, "engines/engine[5]/rpm", simgear::props::FLOAT},
116   {360, "engines/engine[6]/n1",  simgear::props::FLOAT},
117   {361, "engines/engine[6]/n2",  simgear::props::FLOAT},
118   {362, "engines/engine[6]/rpm", simgear::props::FLOAT},
119   {370, "engines/engine[7]/n1",  simgear::props::FLOAT},
120   {371, "engines/engine[7]/n2",  simgear::props::FLOAT},
121   {372, "engines/engine[7]/rpm", simgear::props::FLOAT},
122   {380, "engines/engine[8]/n1",  simgear::props::FLOAT},
123   {381, "engines/engine[8]/n2",  simgear::props::FLOAT},
124   {382, "engines/engine[8]/rpm", simgear::props::FLOAT},
125   {390, "engines/engine[9]/n1",  simgear::props::FLOAT},
126   {391, "engines/engine[9]/n2",  simgear::props::FLOAT},
127   {392, "engines/engine[9]/rpm", simgear::props::FLOAT},
128
129   {800, "rotors/main/rpm", simgear::props::FLOAT},
130   {801, "rotors/tail/rpm", simgear::props::FLOAT},
131   {810, "rotors/main/blade[0]/position-deg",  simgear::props::FLOAT},
132   {811, "rotors/main/blade[1]/position-deg",  simgear::props::FLOAT},
133   {812, "rotors/main/blade[2]/position-deg",  simgear::props::FLOAT},
134   {813, "rotors/main/blade[3]/position-deg",  simgear::props::FLOAT},
135   {820, "rotors/main/blade[0]/flap-deg",  simgear::props::FLOAT},
136   {821, "rotors/main/blade[1]/flap-deg",  simgear::props::FLOAT},
137   {822, "rotors/main/blade[2]/flap-deg",  simgear::props::FLOAT},
138   {823, "rotors/main/blade[3]/flap-deg",  simgear::props::FLOAT},
139   {830, "rotors/tail/blade[0]/position-deg",  simgear::props::FLOAT},
140   {831, "rotors/tail/blade[1]/position-deg",  simgear::props::FLOAT},
141
142   {900, "sim/hitches/aerotow/tow/length",                       simgear::props::FLOAT},
143   {901, "sim/hitches/aerotow/tow/elastic-constant",             simgear::props::FLOAT},
144   {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m",            simgear::props::FLOAT},
145   {903, "sim/hitches/aerotow/tow/dist",                         simgear::props::FLOAT},
146   {904, "sim/hitches/aerotow/tow/connected-to-property-node",   simgear::props::BOOL},
147   {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign",   simgear::props::STRING},
148   {906, "sim/hitches/aerotow/tow/brake-force",                  simgear::props::FLOAT},
149   {907, "sim/hitches/aerotow/tow/end-force-x",                  simgear::props::FLOAT},
150   {908, "sim/hitches/aerotow/tow/end-force-y",                  simgear::props::FLOAT},
151   {909, "sim/hitches/aerotow/tow/end-force-z",                  simgear::props::FLOAT},
152   {930, "sim/hitches/aerotow/is-slave",                         simgear::props::BOOL},
153   {931, "sim/hitches/aerotow/speed-in-tow-direction",           simgear::props::FLOAT},
154   {932, "sim/hitches/aerotow/open",                             simgear::props::BOOL},
155   {933, "sim/hitches/aerotow/local-pos-x",                      simgear::props::FLOAT},
156   {934, "sim/hitches/aerotow/local-pos-y",                      simgear::props::FLOAT},
157   {935, "sim/hitches/aerotow/local-pos-z",                      simgear::props::FLOAT},
158
159   {1001, "controls/flight/slats",  simgear::props::FLOAT},
160   {1002, "controls/flight/speedbrake",  simgear::props::FLOAT},
161   {1003, "controls/flight/spoilers",  simgear::props::FLOAT},
162   {1004, "controls/gear/gear-down",  simgear::props::FLOAT},
163   {1005, "controls/lighting/nav-lights",  simgear::props::FLOAT},
164   {1006, "controls/armament/station[0]/jettison-all",  simgear::props::BOOL},
165
166   {1100, "sim/model/variant", simgear::props::INT},
167   {1101, "sim/model/livery/file", simgear::props::STRING},
168
169   {1200, "environment/wildfire/data", simgear::props::STRING},
170   {1201, "environment/contrail", simgear::props::INT},
171
172   {1300, "tanker", simgear::props::INT},
173
174   {1400, "scenery/events", simgear::props::STRING},
175
176   {1500, "instrumentation/transponder/transmitted-id", simgear::props::INT},
177   {1501, "instrumentation/transponder/altitude", simgear::props::INT},
178   {1502, "instrumentation/transponder/ident", simgear::props::BOOL},
179
180   {10001, "sim/multiplay/transmission-freq-hz",  simgear::props::STRING},
181   {10002, "sim/multiplay/chat",  simgear::props::STRING},
182
183   {10100, "sim/multiplay/generic/string[0]", simgear::props::STRING},
184   {10101, "sim/multiplay/generic/string[1]", simgear::props::STRING},
185   {10102, "sim/multiplay/generic/string[2]", simgear::props::STRING},
186   {10103, "sim/multiplay/generic/string[3]", simgear::props::STRING},
187   {10104, "sim/multiplay/generic/string[4]", simgear::props::STRING},
188   {10105, "sim/multiplay/generic/string[5]", simgear::props::STRING},
189   {10106, "sim/multiplay/generic/string[6]", simgear::props::STRING},
190   {10107, "sim/multiplay/generic/string[7]", simgear::props::STRING},
191   {10108, "sim/multiplay/generic/string[8]", simgear::props::STRING},
192   {10109, "sim/multiplay/generic/string[9]", simgear::props::STRING},
193   {10110, "sim/multiplay/generic/string[10]", simgear::props::STRING},
194   {10111, "sim/multiplay/generic/string[11]", simgear::props::STRING},
195   {10112, "sim/multiplay/generic/string[12]", simgear::props::STRING},
196   {10113, "sim/multiplay/generic/string[13]", simgear::props::STRING},
197   {10114, "sim/multiplay/generic/string[14]", simgear::props::STRING},
198   {10115, "sim/multiplay/generic/string[15]", simgear::props::STRING},
199   {10116, "sim/multiplay/generic/string[16]", simgear::props::STRING},
200   {10117, "sim/multiplay/generic/string[17]", simgear::props::STRING},
201   {10118, "sim/multiplay/generic/string[18]", simgear::props::STRING},
202   {10119, "sim/multiplay/generic/string[19]", simgear::props::STRING},
203
204   {10200, "sim/multiplay/generic/float[0]", simgear::props::FLOAT},
205   {10201, "sim/multiplay/generic/float[1]", simgear::props::FLOAT},
206   {10202, "sim/multiplay/generic/float[2]", simgear::props::FLOAT},
207   {10203, "sim/multiplay/generic/float[3]", simgear::props::FLOAT},
208   {10204, "sim/multiplay/generic/float[4]", simgear::props::FLOAT},
209   {10205, "sim/multiplay/generic/float[5]", simgear::props::FLOAT},
210   {10206, "sim/multiplay/generic/float[6]", simgear::props::FLOAT},
211   {10207, "sim/multiplay/generic/float[7]", simgear::props::FLOAT},
212   {10208, "sim/multiplay/generic/float[8]", simgear::props::FLOAT},
213   {10209, "sim/multiplay/generic/float[9]", simgear::props::FLOAT},
214   {10210, "sim/multiplay/generic/float[10]", simgear::props::FLOAT},
215   {10211, "sim/multiplay/generic/float[11]", simgear::props::FLOAT},
216   {10212, "sim/multiplay/generic/float[12]", simgear::props::FLOAT},
217   {10213, "sim/multiplay/generic/float[13]", simgear::props::FLOAT},
218   {10214, "sim/multiplay/generic/float[14]", simgear::props::FLOAT},
219   {10215, "sim/multiplay/generic/float[15]", simgear::props::FLOAT},
220   {10216, "sim/multiplay/generic/float[16]", simgear::props::FLOAT},
221   {10217, "sim/multiplay/generic/float[17]", simgear::props::FLOAT},
222   {10218, "sim/multiplay/generic/float[18]", simgear::props::FLOAT},
223   {10219, "sim/multiplay/generic/float[19]", simgear::props::FLOAT},
224
225   {10300, "sim/multiplay/generic/int[0]", simgear::props::INT},
226   {10301, "sim/multiplay/generic/int[1]", simgear::props::INT},
227   {10302, "sim/multiplay/generic/int[2]", simgear::props::INT},
228   {10303, "sim/multiplay/generic/int[3]", simgear::props::INT},
229   {10304, "sim/multiplay/generic/int[4]", simgear::props::INT},
230   {10305, "sim/multiplay/generic/int[5]", simgear::props::INT},
231   {10306, "sim/multiplay/generic/int[6]", simgear::props::INT},
232   {10307, "sim/multiplay/generic/int[7]", simgear::props::INT},
233   {10308, "sim/multiplay/generic/int[8]", simgear::props::INT},
234   {10309, "sim/multiplay/generic/int[9]", simgear::props::INT},
235   {10310, "sim/multiplay/generic/int[10]", simgear::props::INT},
236   {10311, "sim/multiplay/generic/int[11]", simgear::props::INT},
237   {10312, "sim/multiplay/generic/int[12]", simgear::props::INT},
238   {10313, "sim/multiplay/generic/int[13]", simgear::props::INT},
239   {10314, "sim/multiplay/generic/int[14]", simgear::props::INT},
240   {10315, "sim/multiplay/generic/int[15]", simgear::props::INT},
241   {10316, "sim/multiplay/generic/int[16]", simgear::props::INT},
242   {10317, "sim/multiplay/generic/int[17]", simgear::props::INT},
243   {10318, "sim/multiplay/generic/int[18]", simgear::props::INT},
244   {10319, "sim/multiplay/generic/int[19]", simgear::props::INT}
245 };
246
247 const unsigned int numProperties = (sizeof(sIdPropertyList)
248                                  / sizeof(sIdPropertyList[0]));
249
250 // Look up a property ID using binary search.
251 namespace
252 {
253   struct ComparePropertyId
254   {
255     bool operator()(const IdPropertyList& lhs,
256                     const IdPropertyList& rhs)
257     {
258       return lhs.id < rhs.id;
259     }
260     bool operator()(const IdPropertyList& lhs,
261                     unsigned id)
262     {
263       return lhs.id < id;
264     }
265     bool operator()(unsigned id,
266                     const IdPropertyList& rhs)
267     {
268       return id < rhs.id;
269     }
270   };    
271 }
272
273 const IdPropertyList* findProperty(unsigned id)
274 {
275   std::pair<const IdPropertyList*, const IdPropertyList*> result
276     = std::equal_range(sIdPropertyList, sIdPropertyList + numProperties, id,
277                        ComparePropertyId());
278   if (result.first == result.second) {
279     return 0;
280   } else {
281     return result.first;
282   }
283 }
284
285 namespace
286 {
287   bool verifyProperties(const xdr_data_t* data, const xdr_data_t* end)
288   {
289     using namespace simgear;
290     const xdr_data_t* xdr = data;
291     while (xdr < end) {
292       unsigned id = XDR_decode_uint32(*xdr);
293       const IdPropertyList* plist = findProperty(id);
294     
295       if (plist) {
296         xdr++;
297         // How we decode the remainder of the property depends on the type
298         switch (plist->type) {
299         case props::INT:
300         case props::BOOL:
301         case props::LONG:
302           xdr++;
303           break;
304         case props::FLOAT:
305         case props::DOUBLE:
306           {
307             float val = XDR_decode_float(*xdr);
308             if (SGMisc<float>::isNaN(val))
309               return false;
310             xdr++;
311             break;
312           }
313         case props::STRING:
314         case props::UNSPECIFIED:
315           {
316             // String is complicated. It consists of
317             // The length of the string
318             // The string itself
319             // Padding to the nearest 4-bytes.
320             // XXX Yes, each byte is padded out to a word! Too late
321             // to change...
322             uint32_t length = XDR_decode_uint32(*xdr);
323             xdr++;
324             // Old versions truncated the string but left the length
325             // unadjusted.
326             if (length > MAX_TEXT_SIZE)
327               length = MAX_TEXT_SIZE;
328             xdr += length;
329             // Now handle the padding
330             while ((length % 4) != 0)
331               {
332                 xdr++;
333                 length++;
334                 //cout << "0";
335               }
336           }
337           break;
338         default:
339           // cerr << "Unknown Prop type " << id << " " << type << "\n";
340           xdr++;
341           break;
342         }            
343       }
344       else {
345         // give up; this is a malformed property list.
346         return false;
347       }
348     }
349     return true;
350   }
351 }
352
353 class MPPropertyListener : public SGPropertyChangeListener
354 {
355 public:
356   MPPropertyListener(FGMultiplayMgr* mp) :
357     _multiplay(mp)
358   {
359   }
360
361   virtual void childAdded(SGPropertyNode*, SGPropertyNode*)
362   {
363     _multiplay->setPropertiesChanged();
364   }
365
366 private:
367   FGMultiplayMgr* _multiplay;
368 };
369
370 //////////////////////////////////////////////////////////////////////
371 //
372 //  MultiplayMgr constructor
373 //
374 //////////////////////////////////////////////////////////////////////
375 FGMultiplayMgr::FGMultiplayMgr() 
376 {
377   mInitialised   = false;
378   mHaveServer    = false;
379   mListener = NULL;
380 } // FGMultiplayMgr::FGMultiplayMgr()
381 //////////////////////////////////////////////////////////////////////
382
383 //////////////////////////////////////////////////////////////////////
384 //
385 //  MultiplayMgr destructor
386 //
387 //////////////////////////////////////////////////////////////////////
388 FGMultiplayMgr::~FGMultiplayMgr() 
389 {
390   
391 } // FGMultiplayMgr::~FGMultiplayMgr()
392 //////////////////////////////////////////////////////////////////////
393
394 //////////////////////////////////////////////////////////////////////
395 //
396 //  Initialise object
397 //
398 //////////////////////////////////////////////////////////////////////
399 void
400 FGMultiplayMgr::init (void) 
401 {
402   //////////////////////////////////////////////////
403   //  Initialise object if not already done
404   //////////////////////////////////////////////////
405   if (mInitialised) {
406     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
407     return;
408   }
409
410   SGPropertyNode* propOnline = fgGetNode("/sim/multiplay/online", true);
411   propOnline->setBoolValue(false);
412   propOnline->setAttribute(SGPropertyNode::PRESERVE, true);
413
414   //////////////////////////////////////////////////
415   //  Set members from property values
416   //////////////////////////////////////////////////
417   short rxPort = fgGetInt("/sim/multiplay/rxport");
418   string rxAddress = fgGetString("/sim/multiplay/rxhost");
419   short txPort = fgGetInt("/sim/multiplay/txport", 5000);
420   string txAddress = fgGetString("/sim/multiplay/txhost");
421   
422   int hz = fgGetInt("/sim/multiplay/tx-rate-hz", 10);
423   if (hz < 1) {
424     hz = 10;
425   }
426   
427   mDt = 1.0 / hz;
428   mTimeUntilSend = 0.0;
429   
430   mCallsign = fgGetString("/sim/multiplay/callsign");
431   if ((!txAddress.empty()) && (txAddress!="0")) {
432     mServer.set(txAddress.c_str(), txPort);
433     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
434       mHaveServer = false;
435       SG_LOG(SG_NETWORK, SG_ALERT,
436         "Cannot enable multiplayer mode: resolving MP server address '"
437         << txAddress << "' failed.");
438       return;
439     } else {
440       SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - have server");
441       mHaveServer = true;
442     }
443     if (rxPort <= 0)
444       rxPort = txPort;
445   } else {
446     SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - multiplayer mode disabled (no MP server specificed).");
447     return;
448   }
449
450   if (rxPort <= 0) {
451     SG_LOG(SG_NETWORK, SG_ALERT,
452       "Cannot enable multiplayer mode: No receiver port specified.");
453     return;
454   }
455   if (mCallsign.empty())
456     mCallsign = "JohnDoe"; // FIXME: use getpwuid
457   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
458   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
459   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
460   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
461   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
462   
463   mSocket.reset(new simgear::Socket());
464   if (!mSocket->open(false)) {
465     SG_LOG( SG_NETWORK, SG_ALERT,
466             "Cannot enable multiplayer mode: creating data socket failed." );
467     return;
468   }
469   mSocket->setBlocking(false);
470   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
471     SG_LOG( SG_NETWORK, SG_ALERT,
472             "Cannot enable multiplayer mode: binding receive socket failed. "
473             << strerror(errno) << "(errno " << errno << ")");
474     return;
475   }
476   
477   mPropertiesChanged = true;
478   mListener = new MPPropertyListener(this);
479   globals->get_props()->addChangeListener(mListener, false);
480   
481   fgSetBool("/sim/multiplay/online", true);
482   mInitialised = true;
483
484   SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer mode active!");
485
486   if (!fgGetBool("/sim/ai/enabled"))
487   {
488       // multiplayer depends on AI module
489       fgSetBool("/sim/ai/enabled", true);
490   }
491 } // FGMultiplayMgr::init()
492 //////////////////////////////////////////////////////////////////////
493
494 //////////////////////////////////////////////////////////////////////
495 //
496 //  Closes and deletes the local player object. Closes
497 //  and deletes the tx socket. Resets the object state to unitialised.
498 //
499 //////////////////////////////////////////////////////////////////////
500 void
501 FGMultiplayMgr::shutdown (void) 
502 {
503   fgSetBool("/sim/multiplay/online", false);
504   
505   if (mSocket.get()) {
506     mSocket->close();
507     mSocket.reset(); 
508   }
509   
510   MultiPlayerMap::iterator it = mMultiPlayerMap.begin(),
511     end = mMultiPlayerMap.end();
512   for (; it != end; ++it) {
513     it->second->setDie(true);
514   }
515   mMultiPlayerMap.clear();
516   
517   if (mListener) {
518     globals->get_props()->removeChangeListener(mListener);
519     delete mListener;
520     mListener = NULL;
521   }
522   
523   mInitialised = false;
524 } // FGMultiplayMgr::Close(void)
525 //////////////////////////////////////////////////////////////////////
526
527 void
528 FGMultiplayMgr::reinit()
529 {
530   shutdown();
531   init();
532 }
533
534 //////////////////////////////////////////////////////////////////////
535 //
536 //  Description: Sends the position data for the local position.
537 //
538 //////////////////////////////////////////////////////////////////////
539
540 /**
541  * The buffer that holds a multi-player message, suitably aligned.
542  */
543 union FGMultiplayMgr::MsgBuf
544 {
545     MsgBuf()
546     {
547         memset(&Msg, 0, sizeof(Msg));
548     }
549
550     T_MsgHdr* msgHdr()
551     {
552         return &Header;
553     }
554
555     const T_MsgHdr* msgHdr() const
556     {
557         return reinterpret_cast<const T_MsgHdr*>(&Header);
558     }
559
560     T_PositionMsg* posMsg()
561     {
562         return reinterpret_cast<T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
563     }
564
565     const T_PositionMsg* posMsg() const
566     {
567         return reinterpret_cast<const T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
568     }
569
570     xdr_data_t* properties()
571     {
572         return reinterpret_cast<xdr_data_t*>(Msg + sizeof(T_MsgHdr)
573                                              + sizeof(T_PositionMsg));
574     }
575
576     const xdr_data_t* properties() const
577     {
578         return reinterpret_cast<const xdr_data_t*>(Msg + sizeof(T_MsgHdr)
579                                                    + sizeof(T_PositionMsg));
580     }
581     /**
582      * The end of the properties buffer.
583      */
584     xdr_data_t* propsEnd()
585     {
586         return reinterpret_cast<xdr_data_t*>(Msg + MAX_PACKET_SIZE);
587     };
588
589     const xdr_data_t* propsEnd() const
590     {
591         return reinterpret_cast<const xdr_data_t*>(Msg + MAX_PACKET_SIZE);
592     };
593     /**
594      * The end of properties actually in the buffer. This assumes that
595      * the message header is valid.
596      */
597     xdr_data_t* propsRecvdEnd()
598     {
599         return reinterpret_cast<xdr_data_t*>(Msg + Header.MsgLen);
600     }
601
602     const xdr_data_t* propsRecvdEnd() const
603     {
604         return reinterpret_cast<const xdr_data_t*>(Msg + Header.MsgLen);
605     }
606     
607     xdr_data2_t double_val;
608     char Msg[MAX_PACKET_SIZE];
609     T_MsgHdr Header;
610 };
611
612 bool
613 FGMultiplayMgr::isSane(const FGExternalMotionData& motionInfo)
614 {
615     // check for corrupted data (NaNs)
616     bool isCorrupted = false;
617     isCorrupted |= ((SGMisc<double>::isNaN(motionInfo.time           )) ||
618                     (SGMisc<double>::isNaN(motionInfo.lag            )) ||
619                     (osg::isNaN(motionInfo.orientation(3) )));
620     for (unsigned i = 0; (i < 3)&&(!isCorrupted); ++i)
621     {
622         isCorrupted |= ((osg::isNaN(motionInfo.position(i)      ))||
623                         (osg::isNaN(motionInfo.orientation(i)   ))||
624                         (osg::isNaN(motionInfo.linearVel(i))    )||
625                         (osg::isNaN(motionInfo.angularVel(i))   )||
626                         (osg::isNaN(motionInfo.linearAccel(i))  )||
627                         (osg::isNaN(motionInfo.angularAccel(i)) ));
628     }
629     return !isCorrupted;
630 }
631
632 void
633 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
634 {
635   if ((! mInitialised) || (! mHaveServer))
636         return;
637
638   if (! mHaveServer) {
639       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition - no server");
640       return;
641   }
642
643   if (!isSane(motionInfo))
644   {
645       // Current local data is invalid (NaN), so stop MP transmission.
646       // => Be nice to older FG versions (no NaN checks) and don't waste bandwidth.
647       SG_LOG(SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - "
648               << "Local data is invalid (NaN). Data not transmitted.");
649       return;
650   }
651
652   static MsgBuf msgBuf;
653   static unsigned msgLen = 0;
654   T_PositionMsg* PosMsg = msgBuf.posMsg();
655
656   strncpy(PosMsg->Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
657   PosMsg->Model[MAX_MODEL_NAME_LEN - 1] = '\0';
658   if (fgGetBool("/sim/freeze/replay-state", true)&&
659       fgGetBool("/sim/multiplay/freeze-on-replay",true))
660   {
661       // do not send position updates during replay
662       for (unsigned i = 0 ; i < 3; ++i)
663       {
664           // no movement during replay
665           PosMsg->linearVel[i] = XDR_encode_float (0.0);
666           PosMsg->angularVel[i] = XDR_encode_float (0.0);
667           PosMsg->linearAccel[i] = XDR_encode_float (0.0);
668           PosMsg->angularAccel[i] = XDR_encode_float (0.0);
669       }
670       // all other data remains unchanged (resend last state) 
671   }
672   else
673   {
674       PosMsg->time = XDR_encode_double (motionInfo.time);
675       PosMsg->lag = XDR_encode_double (motionInfo.lag);
676       for (unsigned i = 0 ; i < 3; ++i)
677         PosMsg->position[i] = XDR_encode_double (motionInfo.position(i));
678       SGVec3f angleAxis;
679       motionInfo.orientation.getAngleAxis(angleAxis);
680       for (unsigned i = 0 ; i < 3; ++i)
681         PosMsg->orientation[i] = XDR_encode_float (angleAxis(i));
682       for (unsigned i = 0 ; i < 3; ++i)
683         PosMsg->linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
684       for (unsigned i = 0 ; i < 3; ++i)
685         PosMsg->angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
686       for (unsigned i = 0 ; i < 3; ++i)
687         PosMsg->linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
688       for (unsigned i = 0 ; i < 3; ++i)
689         PosMsg->angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
690
691       xdr_data_t* ptr = msgBuf.properties();
692       std::vector<FGPropertyData*>::const_iterator it;
693       it = motionInfo.properties.begin();
694       //cout << "OUTPUT PROPERTIES\n";
695       xdr_data_t* msgEnd = msgBuf.propsEnd();
696       while (it != motionInfo.properties.end() && ptr + 2 < msgEnd) {
697         
698         // First element is the ID. Write it out when we know we have room for
699         // the whole property.
700         xdr_data_t id =  XDR_encode_uint32((*it)->id);
701         // The actual data representation depends on the type
702         switch ((*it)->type) {
703           case simgear::props::INT:
704           case simgear::props::BOOL:
705           case simgear::props::LONG:
706             *ptr++ = id;
707             *ptr++ = XDR_encode_uint32((*it)->int_value);
708             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
709             break;
710           case simgear::props::FLOAT:
711           case simgear::props::DOUBLE:
712             *ptr++ = id;
713             *ptr++ = XDR_encode_float((*it)->float_value);
714             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
715             break;
716           case simgear::props::STRING:
717           case simgear::props::UNSPECIFIED:
718             {
719               // String is complicated. It consists of
720               // The length of the string
721               // The string itself
722               // Padding to the nearest 4-bytes.        
723               const char* lcharptr = (*it)->string_value;
724               
725               if (lcharptr != 0)
726               {
727                 // Add the length         
728                 ////cout << "String length: " << strlen(lcharptr) << "\n";
729                 uint32_t len = strlen(lcharptr);
730                 if (len > MAX_TEXT_SIZE)
731                   len = MAX_TEXT_SIZE;
732                 // XXX This should not be using 4 bytes per character!
733                 // If there's not enough room for this property, drop it
734                 // on the floor.
735                 if (ptr + 2 + ((len + 3) & ~3) > msgEnd)
736                     goto escape;
737                 //cout << "String length unint32: " << len << "\n";
738                 *ptr++ = id;
739                 *ptr++ = XDR_encode_uint32(len);
740                 if (len != 0)
741                 {
742                   // Now the text itself
743                   // XXX This should not be using 4 bytes per character!
744                   int lcount = 0;
745                   while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
746                   {
747                     *ptr++ = XDR_encode_int8(*lcharptr);
748                     lcharptr++;
749                     lcount++;          
750                   }
751     
752                   //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
753     
754                   // Now pad if required
755                   while ((lcount % 4) != 0)
756                   {
757                     *ptr++ = XDR_encode_int8(0);
758                     lcount++;          
759                     //cout << "0";
760                   }
761                   
762                   //cout << "\n";
763                 }
764               }
765               else
766               {
767                 // Nothing to encode
768                 *ptr++ = id;
769                 *ptr++ = XDR_encode_uint32(0);
770                 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
771               }
772             }
773             break;
774             
775           default:
776             //cout << " Unknown Type: " << (*it)->type << "\n";
777             *ptr++ = id;
778             *ptr++ = XDR_encode_float((*it)->float_value);;
779             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
780             break;
781         }
782             
783         ++it;
784       }
785   escape:
786       msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
787       FillMsgHdr(msgBuf.msgHdr(), POS_DATA_ID, msgLen);
788   }
789   if (msgLen>0)
790       mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
791   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
792 } // FGMultiplayMgr::SendMyPosition()
793
794 //////////////////////////////////////////////////////////////////////
795
796 //////////////////////////////////////////////////////////////////////
797 //
798 //  Name: SendTextMessage
799 //  Description: Sends a message to the player. The message must
800 //  contain a valid and correctly filled out header and optional
801 //  message body.
802 //
803 //////////////////////////////////////////////////////////////////////
804 void
805 FGMultiplayMgr::SendTextMessage(const string &MsgText)
806 {
807   if (!mInitialised || !mHaveServer)
808     return;
809
810   T_MsgHdr MsgHdr;
811   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
812   //////////////////////////////////////////////////
813   // Divide the text string into blocks that fit
814   // in the message and send the blocks.
815   //////////////////////////////////////////////////
816   unsigned iNextBlockPosition = 0;
817   T_ChatMsg ChatMsg;
818   
819   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
820   while (iNextBlockPosition < MsgText.length()) {
821     strncpy (ChatMsg.Text, 
822              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
823              MAX_CHAT_MSG_LEN);
824     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
825     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
826     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
827     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
828     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
829
830   }
831   
832   
833 } // FGMultiplayMgr::SendTextMessage ()
834 //////////////////////////////////////////////////////////////////////
835
836 //////////////////////////////////////////////////////////////////////
837 //
838 //  Name: ProcessData
839 //  Description: Processes data waiting at the receive socket. The
840 //  processing ends when there is no more data at the socket.
841 //  
842 //////////////////////////////////////////////////////////////////////
843 void
844 FGMultiplayMgr::update(double dt) 
845 {
846   if (!mInitialised)
847     return;
848
849   /// Just for expiry
850   long stamp = SGTimeStamp::now().getSeconds();
851
852   //////////////////////////////////////////////////
853   //  Send if required
854   //////////////////////////////////////////////////
855   mTimeUntilSend -= dt;
856   if (mTimeUntilSend <= 0.0) {
857     Send();
858   }
859
860   //////////////////////////////////////////////////
861   //  Read the receive socket and process any data
862   //////////////////////////////////////////////////
863   ssize_t bytes;
864   do {
865     MsgBuf msgBuf;
866     //////////////////////////////////////////////////
867     //  Although the recv call asks for 
868     //  MAX_PACKET_SIZE of data, the number of bytes
869     //  returned will only be that of the next
870     //  packet waiting to be processed.
871     //////////////////////////////////////////////////
872     simgear::IPAddress SenderAddress;
873     int RecvStatus = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
874                               &SenderAddress);
875     //////////////////////////////////////////////////
876     //  no Data received
877     //////////////////////////////////////////////////
878     if (RecvStatus == 0)
879         break;
880
881     // socket error reported?
882     // errno isn't thread-safe - so only check its value when
883     // socket return status < 0 really indicates a failure.
884     if ((RecvStatus < 0)&&
885         ((errno == EAGAIN) || (errno == 0))) // MSVC output "NoError" otherwise
886     {
887         // ignore "normal" errors
888         break;
889     }
890
891     if (RecvStatus<0)
892     {
893         SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - Unable to receive data. "
894                << strerror(errno) << "(errno " << errno << ")");
895         break;
896     }
897
898     // status is positive: bytes received
899     bytes = (ssize_t) RecvStatus;
900     if (bytes <= static_cast<ssize_t>(sizeof(T_MsgHdr))) {
901       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
902               << "received message with insufficient data" );
903       break;
904     }
905     //////////////////////////////////////////////////
906     //  Read header
907     //////////////////////////////////////////////////
908     T_MsgHdr* MsgHdr = msgBuf.msgHdr();
909     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
910     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
911     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
912     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
913     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
914     MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
915     if (MsgHdr->Magic != MSG_MAGIC) {
916       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
917               << "message has invalid magic number!" );
918       break;
919     }
920     if (MsgHdr->Version != PROTO_VER) {
921       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
922               << "message has invalid protocol number!" );
923       break;
924     }
925     if (static_cast<ssize_t>(MsgHdr->MsgLen) != bytes) {
926       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
927              << "message from " << MsgHdr->Callsign << " has invalid length!");
928       break;
929     }
930     //////////////////////////////////////////////////
931     //  Process messages
932     //////////////////////////////////////////////////
933     switch (MsgHdr->MsgId) {
934     case CHAT_MSG_ID:
935       ProcessChatMsg(msgBuf, SenderAddress);
936       break;
937     case POS_DATA_ID:
938       ProcessPosMsg(msgBuf, SenderAddress, stamp);
939       break;
940     case UNUSABLE_POS_DATA_ID:
941     case OLD_OLD_POS_DATA_ID:
942     case OLD_PROP_MSG_ID:
943     case OLD_POS_DATA_ID:
944       break;
945     default:
946       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
947               << "Unknown message Id received: " << MsgHdr->MsgId );
948       break;
949     }
950   } while (bytes > 0);
951
952   // check for expiry
953   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
954   while (it != mMultiPlayerMap.end()) {
955     if (it->second->getLastTimestamp() + 10 < stamp) {
956       std::string name = it->first;
957       it->second->setDie(true);
958       mMultiPlayerMap.erase(it);
959       it = mMultiPlayerMap.upper_bound(name);
960     } else
961       ++it;
962   }
963 } // FGMultiplayMgr::ProcessData(void)
964 //////////////////////////////////////////////////////////////////////
965
966 void
967 FGMultiplayMgr::Send()
968 {
969   using namespace simgear;
970   
971   findProperties();
972     
973   // smooth the send rate, by adjusting based on the 'remainder' time, which
974   // is how -ve mTimeUntilSend is. Watch for large values and ignore them,
975   // however.
976     if ((mTimeUntilSend < 0.0) && (fabs(mTimeUntilSend) < mDt)) {
977       mTimeUntilSend = mDt + mTimeUntilSend;
978     } else {
979       mTimeUntilSend = mDt;
980     }
981
982     double sim_time = globals->get_sim_time_sec();
983 //    static double lastTime = 0.0;
984     
985    // SG_LOG(SG_GENERAL, SG_INFO, "actual dt=" << sim_time - lastTime);
986 //    lastTime = sim_time;
987     
988     FlightProperties ifce;
989
990     // put together a motion info struct, you will get that later
991     // from FGInterface directly ...
992     FGExternalMotionData motionInfo;
993
994     // The current simulation time we need to update for,
995     // note that the simulation time is updated before calling all the
996     // update methods. Thus it contains the time intervals *end* time.
997     // The FDM is already run, so the states belong to that time.
998     motionInfo.time = sim_time;
999     motionInfo.lag = mDt;
1000
1001     // These are for now converted from lat/lon/alt and euler angles.
1002     // But this should change in FGInterface ...
1003     double lon = ifce.get_Longitude();
1004     double lat = ifce.get_Latitude();
1005     // first the aprioriate structure for the geodetic one
1006     SGGeod geod = SGGeod::fromRadFt(lon, lat, ifce.get_Altitude());
1007     // Convert to cartesion coordinate
1008     motionInfo.position = SGVec3d::fromGeod(geod);
1009     
1010     // The quaternion rotating from the earth centered frame to the
1011     // horizontal local frame
1012     SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)lon, (float)lat);
1013     // The orientation wrt the horizontal local frame
1014     float heading = ifce.get_Psi();
1015     float pitch = ifce.get_Theta();
1016     float roll = ifce.get_Phi();
1017     SGQuatf hlOr = SGQuatf::fromYawPitchRoll(heading, pitch, roll);
1018     // The orientation of the vehicle wrt the earth centered frame
1019     motionInfo.orientation = qEc2Hl*hlOr;
1020
1021     if (!globals->get_subsystem("flight")->is_suspended()) {
1022       // velocities
1023       motionInfo.linearVel = SG_FEET_TO_METER*SGVec3f(ifce.get_uBody(),
1024                                                       ifce.get_vBody(),
1025                                                       ifce.get_wBody());
1026       motionInfo.angularVel = SGVec3f(ifce.get_P_body(),
1027                                       ifce.get_Q_body(),
1028                                       ifce.get_R_body());
1029       
1030       // accels, set that to zero for now.
1031       // Angular accelerations are missing from the interface anyway,
1032       // linear accelerations are screwed up at least for JSBSim.
1033 //  motionInfo.linearAccel = SG_FEET_TO_METER*SGVec3f(ifce.get_U_dot_body(),
1034 //                                                    ifce.get_V_dot_body(),
1035 //                                                    ifce.get_W_dot_body());
1036       motionInfo.linearAccel = SGVec3f::zeros();
1037       motionInfo.angularAccel = SGVec3f::zeros();
1038     } else {
1039       // if the interface is suspendend, prevent the client from
1040       // wild extrapolations
1041       motionInfo.linearVel = SGVec3f::zeros();
1042       motionInfo.angularVel = SGVec3f::zeros();
1043       motionInfo.linearAccel = SGVec3f::zeros();
1044       motionInfo.angularAccel = SGVec3f::zeros();
1045     }
1046
1047     // now send the properties
1048     PropertyMap::iterator it;
1049     for (it = mPropertyMap.begin(); it != mPropertyMap.end(); ++it) {
1050       FGPropertyData* pData = new FGPropertyData;
1051       pData->id = it->first;
1052       pData->type = it->second->getType();
1053       
1054       switch (pData->type) {
1055         case props::INT:
1056         case props::LONG:
1057         case props::BOOL:
1058           pData->int_value = it->second->getIntValue();
1059           break;
1060         case props::FLOAT:
1061         case props::DOUBLE:
1062           pData->float_value = it->second->getFloatValue();
1063           break;
1064         case props::STRING:
1065         case props::UNSPECIFIED:
1066           {
1067             // FIXME: We assume unspecified are strings for the moment.
1068
1069             const char* cstr = it->second->getStringValue();
1070             int len = strlen(cstr);
1071             
1072             if (len > 0)
1073             {            
1074               pData->string_value = new char[len + 1];
1075               strcpy(pData->string_value, cstr);
1076             }
1077             else
1078             {
1079               // Size 0 - ignore
1080               pData->string_value = 0;            
1081             }
1082
1083             //cout << " Sending property " << pData->id << " " << pData->type << " " <<  pData->string_value << "\n";
1084             break;        
1085           }
1086         default:
1087           // FIXME Currently default to a float. 
1088           //cout << "Unknown type when iterating through props: " << pData->type << "\n";
1089           pData->float_value = it->second->getFloatValue();
1090           break;
1091       }
1092       
1093       motionInfo.properties.push_back(pData);
1094     }
1095
1096     SendMyPosition(motionInfo);
1097 }
1098
1099
1100 //////////////////////////////////////////////////////////////////////
1101 //
1102 //  handle a position message
1103 //
1104 //////////////////////////////////////////////////////////////////////
1105 void
1106 FGMultiplayMgr::ProcessPosMsg(const FGMultiplayMgr::MsgBuf& Msg,
1107                               const simgear::IPAddress& SenderAddress, long stamp)
1108 {
1109   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1110   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
1111     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1112             << "Position message received with insufficient data" );
1113     return;
1114   }
1115   const T_PositionMsg* PosMsg = Msg.posMsg();
1116   FGExternalMotionData motionInfo;
1117   motionInfo.time = XDR_decode_double(PosMsg->time);
1118   motionInfo.lag = XDR_decode_double(PosMsg->lag);
1119   for (unsigned i = 0; i < 3; ++i)
1120     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
1121   SGVec3f angleAxis;
1122   for (unsigned i = 0; i < 3; ++i)
1123     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
1124   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
1125   for (unsigned i = 0; i < 3; ++i)
1126     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
1127   for (unsigned i = 0; i < 3; ++i)
1128     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
1129   for (unsigned i = 0; i < 3; ++i)
1130     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
1131   for (unsigned i = 0; i < 3; ++i)
1132     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
1133
1134   // sanity check: do not allow injection of corrupted data (NaNs)
1135   if (!isSane(motionInfo))
1136   {
1137       // drop this message, keep old position until receiving valid data
1138       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1139               << "Position message with invalid data (NaN) received from "
1140               << MsgHdr->Callsign);
1141       return;
1142   }
1143
1144   //cout << "INPUT MESSAGE\n";
1145
1146   // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
1147   // on 32 bit architectures and 200 bytes on 64 bit, and this
1148   // structure is put directly on the wire. By looking at the padding,
1149   // we can sort through the mess, mostly:
1150   // If padding is 0 (which is not a valid property type), then the
1151   // message was produced by a new client or an old 64 bit client that
1152   // happened to have 0 on the stack;
1153   // Else if the property list starting with the padding word is
1154   // well-formed, then the client is probably an old 32 bit client and
1155   // we'll go with that;
1156   // Else it is an old 64-bit client and properties start after the
1157   // padding.
1158   // There is a chance that we could be fooled by garbage in the
1159   // padding looking like a valid property, so verifyProperties() is
1160   // strict about the validity of the property values.
1161   const xdr_data_t* xdr = Msg.properties();
1162   if (PosMsg->pad != 0) {
1163     if (verifyProperties(&PosMsg->pad, Msg.propsRecvdEnd()))
1164       xdr = &PosMsg->pad;
1165     else if (!verifyProperties(xdr, Msg.propsRecvdEnd()))
1166       goto noprops;
1167   }
1168   while (xdr < Msg.propsRecvdEnd()) {
1169     // simgear::props::Type type = simgear::props::UNSPECIFIED;
1170     
1171     // First element is always the ID
1172     unsigned id = XDR_decode_uint32(*xdr);
1173     //cout << pData->id << " ";
1174     xdr++;
1175     
1176     // Check the ID actually exists and get the type
1177     const IdPropertyList* plist = findProperty(id);
1178     
1179     if (plist)
1180     {
1181       FGPropertyData* pData = new FGPropertyData;
1182       pData->id = id;
1183       pData->type = plist->type;
1184       // How we decode the remainder of the property depends on the type
1185       switch (pData->type) {
1186         case simgear::props::INT:
1187         case simgear::props::BOOL:
1188         case simgear::props::LONG:
1189           pData->int_value = XDR_decode_uint32(*xdr);
1190           xdr++;
1191           //cout << pData->int_value << "\n";
1192           break;
1193         case simgear::props::FLOAT:
1194         case simgear::props::DOUBLE:
1195           pData->float_value = XDR_decode_float(*xdr);
1196           xdr++;
1197           //cout << pData->float_value << "\n";
1198           break;
1199         case simgear::props::STRING:
1200         case simgear::props::UNSPECIFIED:
1201           {
1202             // String is complicated. It consists of
1203             // The length of the string
1204             // The string itself
1205             // Padding to the nearest 4-bytes.    
1206             uint32_t length = XDR_decode_uint32(*xdr);
1207             xdr++;
1208             //cout << length << " ";
1209             // Old versions truncated the string but left the length unadjusted.
1210             if (length > MAX_TEXT_SIZE)
1211               length = MAX_TEXT_SIZE;
1212             pData->string_value = new char[length + 1];
1213             //cout << " String: ";
1214             for (unsigned i = 0; i < length; i++)
1215               {
1216                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
1217                 xdr++;
1218                 //cout << pData->string_value[i];
1219               }
1220
1221             pData->string_value[length] = '\0';
1222
1223             // Now handle the padding
1224             while ((length % 4) != 0)
1225               {
1226                 xdr++;
1227                 length++;
1228                 //cout << "0";
1229               }
1230             //cout << "\n";
1231           }
1232           break;
1233
1234         default:
1235           pData->float_value = XDR_decode_float(*xdr);
1236           SG_LOG(SG_NETWORK, SG_DEBUG, "Unknown Prop type " << pData->id << " " << pData->type);
1237           xdr++;
1238           break;
1239       }
1240
1241       motionInfo.properties.push_back(pData);
1242     }
1243     else
1244     {
1245       // We failed to find the property. We'll try the next packet immediately.
1246       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1247              "message from " << MsgHdr->Callsign << " has unknown property id "
1248              << id); 
1249     }
1250   }
1251  noprops:
1252   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
1253   if (!mp)
1254     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
1255   mp->addMotionInfo(motionInfo, stamp);
1256 } // FGMultiplayMgr::ProcessPosMsg()
1257 //////////////////////////////////////////////////////////////////////
1258
1259 //////////////////////////////////////////////////////////////////////
1260 //
1261 //  handle a chat message
1262 //  FIXME: display chat message within flightgear
1263 //
1264 //////////////////////////////////////////////////////////////////////
1265 void
1266 FGMultiplayMgr::ProcessChatMsg(const MsgBuf& Msg,
1267                                const simgear::IPAddress& SenderAddress)
1268 {
1269   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1270   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
1271     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1272             << "Chat message received with insufficient data" );
1273     return;
1274   }
1275   
1276   char *chatStr = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
1277   const T_ChatMsg* ChatMsg
1278       = reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr));
1279   strncpy(chatStr, ChatMsg->Text,
1280           MsgHdr->MsgLen - sizeof(T_MsgHdr));
1281   chatStr[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
1282   
1283   SG_LOG (SG_NETWORK, SG_WARN, "Chat [" << MsgHdr->Callsign << "]"
1284            << " " << chatStr);
1285
1286   delete [] chatStr;
1287 } // FGMultiplayMgr::ProcessChatMsg ()
1288 //////////////////////////////////////////////////////////////////////
1289
1290 void
1291 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
1292 {
1293   uint32_t len;
1294   switch (MsgId) {
1295   case CHAT_MSG_ID:
1296     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
1297     break;
1298   case POS_DATA_ID:
1299     len = _len;
1300     break;
1301   default:
1302     len = sizeof(T_MsgHdr);
1303     break;
1304   }
1305   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
1306   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
1307   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
1308   MsgHdr->MsgLen          = XDR_encode_uint32(len);
1309   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
1310   MsgHdr->ReplyPort       = 0; // now
1311   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
1312   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
1313 }
1314
1315 FGAIMultiplayer*
1316 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
1317                                const std::string& modelName)
1318 {
1319   if (0 < mMultiPlayerMap.count(callsign))
1320     return mMultiPlayerMap[callsign].get();
1321
1322   FGAIMultiplayer* mp = new FGAIMultiplayer;
1323   mp->setPath(modelName.c_str());
1324   mp->setCallSign(callsign);
1325   mMultiPlayerMap[callsign] = mp;
1326
1327   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai-model");
1328   if (aiMgr) {
1329     aiMgr->attach(mp);
1330
1331     /// FIXME: that must follow the attach ATM ...
1332     for (unsigned i = 0; i < numProperties; ++i)
1333       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
1334   }
1335
1336   return mp;
1337 }
1338
1339 FGAIMultiplayer*
1340 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
1341 {
1342   if (0 < mMultiPlayerMap.count(callsign))
1343     return mMultiPlayerMap[callsign].get();
1344   else
1345     return 0;
1346 }
1347
1348 void
1349 FGMultiplayMgr::findProperties()
1350 {
1351   if (!mPropertiesChanged) {
1352     return;
1353   }
1354   
1355   mPropertiesChanged = false;
1356   
1357   for (unsigned i = 0; i < numProperties; ++i) {
1358       const char* name = sIdPropertyList[i].name;
1359       SGPropertyNode* pNode = globals->get_props()->getNode(name);
1360       if (!pNode) {
1361         continue;
1362       }
1363       
1364       int id = sIdPropertyList[i].id;
1365       if (mPropertyMap.find(id) != mPropertyMap.end()) {
1366         continue; // already activated
1367       }
1368       
1369       mPropertyMap[id] = pNode;
1370       SG_LOG(SG_NETWORK, SG_DEBUG, "activating MP property:" << pNode->getPath());
1371     }
1372 }