]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Report bad command-line args via message box.
[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   fgGetNode("/sim/multiplay/callsign", true)->setAttribute(SGPropertyNode::PRESERVE, true);
432     
433   if ((!txAddress.empty()) && (txAddress!="0")) {
434     mServer.set(txAddress.c_str(), txPort);
435     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
436       mHaveServer = false;
437       SG_LOG(SG_NETWORK, SG_ALERT,
438         "Cannot enable multiplayer mode: resolving MP server address '"
439         << txAddress << "' failed.");
440       return;
441     } else {
442       SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - have server");
443       mHaveServer = true;
444     }
445     if (rxPort <= 0)
446       rxPort = txPort;
447   } else {
448     SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - multiplayer mode disabled (no MP server specificed).");
449     return;
450   }
451
452   if (rxPort <= 0) {
453     SG_LOG(SG_NETWORK, SG_ALERT,
454       "Cannot enable multiplayer mode: No receiver port specified.");
455     return;
456   }
457   if (mCallsign.empty())
458     mCallsign = "JohnDoe"; // FIXME: use getpwuid
459   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
460   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
461   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
462   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
463   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
464   
465   mSocket.reset(new simgear::Socket());
466   if (!mSocket->open(false)) {
467     SG_LOG( SG_NETWORK, SG_ALERT,
468             "Cannot enable multiplayer mode: creating data socket failed." );
469     return;
470   }
471   mSocket->setBlocking(false);
472   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
473     SG_LOG( SG_NETWORK, SG_ALERT,
474             "Cannot enable multiplayer mode: binding receive socket failed. "
475             << strerror(errno) << "(errno " << errno << ")");
476     return;
477   }
478   
479   mPropertiesChanged = true;
480   mListener = new MPPropertyListener(this);
481   globals->get_props()->addChangeListener(mListener, false);
482   
483   fgSetBool("/sim/multiplay/online", true);
484   mInitialised = true;
485
486   SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer mode active!");
487
488   if (!fgGetBool("/sim/ai/enabled"))
489   {
490       // multiplayer depends on AI module
491       fgSetBool("/sim/ai/enabled", true);
492   }
493 } // FGMultiplayMgr::init()
494 //////////////////////////////////////////////////////////////////////
495
496 //////////////////////////////////////////////////////////////////////
497 //
498 //  Closes and deletes the local player object. Closes
499 //  and deletes the tx socket. Resets the object state to unitialised.
500 //
501 //////////////////////////////////////////////////////////////////////
502 void
503 FGMultiplayMgr::shutdown (void) 
504 {
505   fgSetBool("/sim/multiplay/online", false);
506   
507   if (mSocket.get()) {
508     mSocket->close();
509     mSocket.reset(); 
510   }
511   
512   MultiPlayerMap::iterator it = mMultiPlayerMap.begin(),
513     end = mMultiPlayerMap.end();
514   for (; it != end; ++it) {
515     it->second->setDie(true);
516   }
517   mMultiPlayerMap.clear();
518   
519   if (mListener) {
520     globals->get_props()->removeChangeListener(mListener);
521     delete mListener;
522     mListener = NULL;
523   }
524   
525   mInitialised = false;
526 } // FGMultiplayMgr::Close(void)
527 //////////////////////////////////////////////////////////////////////
528
529 void
530 FGMultiplayMgr::reinit()
531 {
532   shutdown();
533   init();
534 }
535
536 //////////////////////////////////////////////////////////////////////
537 //
538 //  Description: Sends the position data for the local position.
539 //
540 //////////////////////////////////////////////////////////////////////
541
542 /**
543  * The buffer that holds a multi-player message, suitably aligned.
544  */
545 union FGMultiplayMgr::MsgBuf
546 {
547     MsgBuf()
548     {
549         memset(&Msg, 0, sizeof(Msg));
550     }
551
552     T_MsgHdr* msgHdr()
553     {
554         return &Header;
555     }
556
557     const T_MsgHdr* msgHdr() const
558     {
559         return reinterpret_cast<const T_MsgHdr*>(&Header);
560     }
561
562     T_PositionMsg* posMsg()
563     {
564         return reinterpret_cast<T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
565     }
566
567     const T_PositionMsg* posMsg() const
568     {
569         return reinterpret_cast<const T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
570     }
571
572     xdr_data_t* properties()
573     {
574         return reinterpret_cast<xdr_data_t*>(Msg + sizeof(T_MsgHdr)
575                                              + sizeof(T_PositionMsg));
576     }
577
578     const xdr_data_t* properties() const
579     {
580         return reinterpret_cast<const xdr_data_t*>(Msg + sizeof(T_MsgHdr)
581                                                    + sizeof(T_PositionMsg));
582     }
583     /**
584      * The end of the properties buffer.
585      */
586     xdr_data_t* propsEnd()
587     {
588         return reinterpret_cast<xdr_data_t*>(Msg + MAX_PACKET_SIZE);
589     };
590
591     const xdr_data_t* propsEnd() const
592     {
593         return reinterpret_cast<const xdr_data_t*>(Msg + MAX_PACKET_SIZE);
594     };
595     /**
596      * The end of properties actually in the buffer. This assumes that
597      * the message header is valid.
598      */
599     xdr_data_t* propsRecvdEnd()
600     {
601         return reinterpret_cast<xdr_data_t*>(Msg + Header.MsgLen);
602     }
603
604     const xdr_data_t* propsRecvdEnd() const
605     {
606         return reinterpret_cast<const xdr_data_t*>(Msg + Header.MsgLen);
607     }
608     
609     xdr_data2_t double_val;
610     char Msg[MAX_PACKET_SIZE];
611     T_MsgHdr Header;
612 };
613
614 bool
615 FGMultiplayMgr::isSane(const FGExternalMotionData& motionInfo)
616 {
617     // check for corrupted data (NaNs)
618     bool isCorrupted = false;
619     isCorrupted |= ((SGMisc<double>::isNaN(motionInfo.time           )) ||
620                     (SGMisc<double>::isNaN(motionInfo.lag            )) ||
621                     (osg::isNaN(motionInfo.orientation(3) )));
622     for (unsigned i = 0; (i < 3)&&(!isCorrupted); ++i)
623     {
624         isCorrupted |= ((osg::isNaN(motionInfo.position(i)      ))||
625                         (osg::isNaN(motionInfo.orientation(i)   ))||
626                         (osg::isNaN(motionInfo.linearVel(i))    )||
627                         (osg::isNaN(motionInfo.angularVel(i))   )||
628                         (osg::isNaN(motionInfo.linearAccel(i))  )||
629                         (osg::isNaN(motionInfo.angularAccel(i)) ));
630     }
631     return !isCorrupted;
632 }
633
634 void
635 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
636 {
637   if ((! mInitialised) || (! mHaveServer))
638         return;
639
640   if (! mHaveServer) {
641       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition - no server");
642       return;
643   }
644
645   if (!isSane(motionInfo))
646   {
647       // Current local data is invalid (NaN), so stop MP transmission.
648       // => Be nice to older FG versions (no NaN checks) and don't waste bandwidth.
649       SG_LOG(SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - "
650               << "Local data is invalid (NaN). Data not transmitted.");
651       return;
652   }
653
654   static MsgBuf msgBuf;
655   static unsigned msgLen = 0;
656   T_PositionMsg* PosMsg = msgBuf.posMsg();
657
658   strncpy(PosMsg->Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
659   PosMsg->Model[MAX_MODEL_NAME_LEN - 1] = '\0';
660   if (fgGetBool("/sim/freeze/replay-state", true)&&
661       fgGetBool("/sim/multiplay/freeze-on-replay",true))
662   {
663       // do not send position updates during replay
664       for (unsigned i = 0 ; i < 3; ++i)
665       {
666           // no movement during replay
667           PosMsg->linearVel[i] = XDR_encode_float (0.0);
668           PosMsg->angularVel[i] = XDR_encode_float (0.0);
669           PosMsg->linearAccel[i] = XDR_encode_float (0.0);
670           PosMsg->angularAccel[i] = XDR_encode_float (0.0);
671       }
672       // all other data remains unchanged (resend last state) 
673   }
674   else
675   {
676       PosMsg->time = XDR_encode_double (motionInfo.time);
677       PosMsg->lag = XDR_encode_double (motionInfo.lag);
678       for (unsigned i = 0 ; i < 3; ++i)
679         PosMsg->position[i] = XDR_encode_double (motionInfo.position(i));
680       SGVec3f angleAxis;
681       motionInfo.orientation.getAngleAxis(angleAxis);
682       for (unsigned i = 0 ; i < 3; ++i)
683         PosMsg->orientation[i] = XDR_encode_float (angleAxis(i));
684       for (unsigned i = 0 ; i < 3; ++i)
685         PosMsg->linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
686       for (unsigned i = 0 ; i < 3; ++i)
687         PosMsg->angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
688       for (unsigned i = 0 ; i < 3; ++i)
689         PosMsg->linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
690       for (unsigned i = 0 ; i < 3; ++i)
691         PosMsg->angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
692
693       xdr_data_t* ptr = msgBuf.properties();
694       std::vector<FGPropertyData*>::const_iterator it;
695       it = motionInfo.properties.begin();
696       //cout << "OUTPUT PROPERTIES\n";
697       xdr_data_t* msgEnd = msgBuf.propsEnd();
698       while (it != motionInfo.properties.end() && ptr + 2 < msgEnd) {
699         
700         // First element is the ID. Write it out when we know we have room for
701         // the whole property.
702         xdr_data_t id =  XDR_encode_uint32((*it)->id);
703         // The actual data representation depends on the type
704         switch ((*it)->type) {
705           case simgear::props::INT:
706           case simgear::props::BOOL:
707           case simgear::props::LONG:
708             *ptr++ = id;
709             *ptr++ = XDR_encode_uint32((*it)->int_value);
710             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
711             break;
712           case simgear::props::FLOAT:
713           case simgear::props::DOUBLE:
714             *ptr++ = id;
715             *ptr++ = XDR_encode_float((*it)->float_value);
716             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
717             break;
718           case simgear::props::STRING:
719           case simgear::props::UNSPECIFIED:
720             {
721               // String is complicated. It consists of
722               // The length of the string
723               // The string itself
724               // Padding to the nearest 4-bytes.        
725               const char* lcharptr = (*it)->string_value;
726               
727               if (lcharptr != 0)
728               {
729                 // Add the length         
730                 ////cout << "String length: " << strlen(lcharptr) << "\n";
731                 uint32_t len = strlen(lcharptr);
732                 if (len > MAX_TEXT_SIZE)
733                   len = MAX_TEXT_SIZE;
734                 // XXX This should not be using 4 bytes per character!
735                 // If there's not enough room for this property, drop it
736                 // on the floor.
737                 if (ptr + 2 + ((len + 3) & ~3) > msgEnd)
738                     goto escape;
739                 //cout << "String length unint32: " << len << "\n";
740                 *ptr++ = id;
741                 *ptr++ = XDR_encode_uint32(len);
742                 if (len != 0)
743                 {
744                   // Now the text itself
745                   // XXX This should not be using 4 bytes per character!
746                   int lcount = 0;
747                   while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
748                   {
749                     *ptr++ = XDR_encode_int8(*lcharptr);
750                     lcharptr++;
751                     lcount++;          
752                   }
753     
754                   //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
755     
756                   // Now pad if required
757                   while ((lcount % 4) != 0)
758                   {
759                     *ptr++ = XDR_encode_int8(0);
760                     lcount++;          
761                     //cout << "0";
762                   }
763                   
764                   //cout << "\n";
765                 }
766               }
767               else
768               {
769                 // Nothing to encode
770                 *ptr++ = id;
771                 *ptr++ = XDR_encode_uint32(0);
772                 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
773               }
774             }
775             break;
776             
777           default:
778             //cout << " Unknown Type: " << (*it)->type << "\n";
779             *ptr++ = id;
780             *ptr++ = XDR_encode_float((*it)->float_value);;
781             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
782             break;
783         }
784             
785         ++it;
786       }
787   escape:
788       msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
789       FillMsgHdr(msgBuf.msgHdr(), POS_DATA_ID, msgLen);
790   }
791   if (msgLen>0)
792       mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
793   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
794 } // FGMultiplayMgr::SendMyPosition()
795
796 //////////////////////////////////////////////////////////////////////
797
798 //////////////////////////////////////////////////////////////////////
799 //
800 //  Name: SendTextMessage
801 //  Description: Sends a message to the player. The message must
802 //  contain a valid and correctly filled out header and optional
803 //  message body.
804 //
805 //////////////////////////////////////////////////////////////////////
806 void
807 FGMultiplayMgr::SendTextMessage(const string &MsgText)
808 {
809   if (!mInitialised || !mHaveServer)
810     return;
811
812   T_MsgHdr MsgHdr;
813   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
814   //////////////////////////////////////////////////
815   // Divide the text string into blocks that fit
816   // in the message and send the blocks.
817   //////////////////////////////////////////////////
818   unsigned iNextBlockPosition = 0;
819   T_ChatMsg ChatMsg;
820   
821   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
822   while (iNextBlockPosition < MsgText.length()) {
823     strncpy (ChatMsg.Text, 
824              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
825              MAX_CHAT_MSG_LEN);
826     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
827     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
828     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
829     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
830     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
831
832   }
833   
834   
835 } // FGMultiplayMgr::SendTextMessage ()
836 //////////////////////////////////////////////////////////////////////
837
838 //////////////////////////////////////////////////////////////////////
839 //
840 //  Name: ProcessData
841 //  Description: Processes data waiting at the receive socket. The
842 //  processing ends when there is no more data at the socket.
843 //  
844 //////////////////////////////////////////////////////////////////////
845 void
846 FGMultiplayMgr::update(double dt) 
847 {
848   if (!mInitialised)
849     return;
850
851   /// Just for expiry
852   long stamp = SGTimeStamp::now().getSeconds();
853
854   //////////////////////////////////////////////////
855   //  Send if required
856   //////////////////////////////////////////////////
857   mTimeUntilSend -= dt;
858   if (mTimeUntilSend <= 0.0) {
859     Send();
860   }
861
862   //////////////////////////////////////////////////
863   //  Read the receive socket and process any data
864   //////////////////////////////////////////////////
865   ssize_t bytes;
866   do {
867     MsgBuf msgBuf;
868     //////////////////////////////////////////////////
869     //  Although the recv call asks for 
870     //  MAX_PACKET_SIZE of data, the number of bytes
871     //  returned will only be that of the next
872     //  packet waiting to be processed.
873     //////////////////////////////////////////////////
874     simgear::IPAddress SenderAddress;
875     int RecvStatus = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
876                               &SenderAddress);
877     //////////////////////////////////////////////////
878     //  no Data received
879     //////////////////////////////////////////////////
880     if (RecvStatus == 0)
881         break;
882
883     // socket error reported?
884     // errno isn't thread-safe - so only check its value when
885     // socket return status < 0 really indicates a failure.
886     if ((RecvStatus < 0)&&
887         ((errno == EAGAIN) || (errno == 0))) // MSVC output "NoError" otherwise
888     {
889         // ignore "normal" errors
890         break;
891     }
892
893     if (RecvStatus<0)
894     {
895         SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - Unable to receive data. "
896                << strerror(errno) << "(errno " << errno << ")");
897         break;
898     }
899
900     // status is positive: bytes received
901     bytes = (ssize_t) RecvStatus;
902     if (bytes <= static_cast<ssize_t>(sizeof(T_MsgHdr))) {
903       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
904               << "received message with insufficient data" );
905       break;
906     }
907     //////////////////////////////////////////////////
908     //  Read header
909     //////////////////////////////////////////////////
910     T_MsgHdr* MsgHdr = msgBuf.msgHdr();
911     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
912     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
913     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
914     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
915     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
916     MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
917     if (MsgHdr->Magic != MSG_MAGIC) {
918       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
919               << "message has invalid magic number!" );
920       break;
921     }
922     if (MsgHdr->Version != PROTO_VER) {
923       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
924               << "message has invalid protocol number!" );
925       break;
926     }
927     if (static_cast<ssize_t>(MsgHdr->MsgLen) != bytes) {
928       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
929              << "message from " << MsgHdr->Callsign << " has invalid length!");
930       break;
931     }
932     //////////////////////////////////////////////////
933     //  Process messages
934     //////////////////////////////////////////////////
935     switch (MsgHdr->MsgId) {
936     case CHAT_MSG_ID:
937       ProcessChatMsg(msgBuf, SenderAddress);
938       break;
939     case POS_DATA_ID:
940       ProcessPosMsg(msgBuf, SenderAddress, stamp);
941       break;
942     case UNUSABLE_POS_DATA_ID:
943     case OLD_OLD_POS_DATA_ID:
944     case OLD_PROP_MSG_ID:
945     case OLD_POS_DATA_ID:
946       break;
947     default:
948       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
949               << "Unknown message Id received: " << MsgHdr->MsgId );
950       break;
951     }
952   } while (bytes > 0);
953
954   // check for expiry
955   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
956   while (it != mMultiPlayerMap.end()) {
957     if (it->second->getLastTimestamp() + 10 < stamp) {
958       std::string name = it->first;
959       it->second->setDie(true);
960       mMultiPlayerMap.erase(it);
961       it = mMultiPlayerMap.upper_bound(name);
962     } else
963       ++it;
964   }
965 } // FGMultiplayMgr::ProcessData(void)
966 //////////////////////////////////////////////////////////////////////
967
968 void
969 FGMultiplayMgr::Send()
970 {
971   using namespace simgear;
972   
973   findProperties();
974     
975   // smooth the send rate, by adjusting based on the 'remainder' time, which
976   // is how -ve mTimeUntilSend is. Watch for large values and ignore them,
977   // however.
978     if ((mTimeUntilSend < 0.0) && (fabs(mTimeUntilSend) < mDt)) {
979       mTimeUntilSend = mDt + mTimeUntilSend;
980     } else {
981       mTimeUntilSend = mDt;
982     }
983
984     double sim_time = globals->get_sim_time_sec();
985 //    static double lastTime = 0.0;
986     
987    // SG_LOG(SG_GENERAL, SG_INFO, "actual dt=" << sim_time - lastTime);
988 //    lastTime = sim_time;
989     
990     FlightProperties ifce;
991
992     // put together a motion info struct, you will get that later
993     // from FGInterface directly ...
994     FGExternalMotionData motionInfo;
995
996     // The current simulation time we need to update for,
997     // note that the simulation time is updated before calling all the
998     // update methods. Thus it contains the time intervals *end* time.
999     // The FDM is already run, so the states belong to that time.
1000     motionInfo.time = sim_time;
1001     motionInfo.lag = mDt;
1002
1003     // These are for now converted from lat/lon/alt and euler angles.
1004     // But this should change in FGInterface ...
1005     double lon = ifce.get_Longitude();
1006     double lat = ifce.get_Latitude();
1007     // first the aprioriate structure for the geodetic one
1008     SGGeod geod = SGGeod::fromRadFt(lon, lat, ifce.get_Altitude());
1009     // Convert to cartesion coordinate
1010     motionInfo.position = SGVec3d::fromGeod(geod);
1011     
1012     // The quaternion rotating from the earth centered frame to the
1013     // horizontal local frame
1014     SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)lon, (float)lat);
1015     // The orientation wrt the horizontal local frame
1016     float heading = ifce.get_Psi();
1017     float pitch = ifce.get_Theta();
1018     float roll = ifce.get_Phi();
1019     SGQuatf hlOr = SGQuatf::fromYawPitchRoll(heading, pitch, roll);
1020     // The orientation of the vehicle wrt the earth centered frame
1021     motionInfo.orientation = qEc2Hl*hlOr;
1022
1023     if (!globals->get_subsystem("flight")->is_suspended()) {
1024       // velocities
1025       motionInfo.linearVel = SG_FEET_TO_METER*SGVec3f(ifce.get_uBody(),
1026                                                       ifce.get_vBody(),
1027                                                       ifce.get_wBody());
1028       motionInfo.angularVel = SGVec3f(ifce.get_P_body(),
1029                                       ifce.get_Q_body(),
1030                                       ifce.get_R_body());
1031       
1032       // accels, set that to zero for now.
1033       // Angular accelerations are missing from the interface anyway,
1034       // linear accelerations are screwed up at least for JSBSim.
1035 //  motionInfo.linearAccel = SG_FEET_TO_METER*SGVec3f(ifce.get_U_dot_body(),
1036 //                                                    ifce.get_V_dot_body(),
1037 //                                                    ifce.get_W_dot_body());
1038       motionInfo.linearAccel = SGVec3f::zeros();
1039       motionInfo.angularAccel = SGVec3f::zeros();
1040     } else {
1041       // if the interface is suspendend, prevent the client from
1042       // wild extrapolations
1043       motionInfo.linearVel = SGVec3f::zeros();
1044       motionInfo.angularVel = SGVec3f::zeros();
1045       motionInfo.linearAccel = SGVec3f::zeros();
1046       motionInfo.angularAccel = SGVec3f::zeros();
1047     }
1048
1049     // now send the properties
1050     PropertyMap::iterator it;
1051     for (it = mPropertyMap.begin(); it != mPropertyMap.end(); ++it) {
1052       FGPropertyData* pData = new FGPropertyData;
1053       pData->id = it->first;
1054       pData->type = it->second->getType();
1055       
1056       switch (pData->type) {
1057         case props::INT:
1058         case props::LONG:
1059         case props::BOOL:
1060           pData->int_value = it->second->getIntValue();
1061           break;
1062         case props::FLOAT:
1063         case props::DOUBLE:
1064           pData->float_value = it->second->getFloatValue();
1065           break;
1066         case props::STRING:
1067         case props::UNSPECIFIED:
1068           {
1069             // FIXME: We assume unspecified are strings for the moment.
1070
1071             const char* cstr = it->second->getStringValue();
1072             int len = strlen(cstr);
1073             
1074             if (len > 0)
1075             {            
1076               pData->string_value = new char[len + 1];
1077               strcpy(pData->string_value, cstr);
1078             }
1079             else
1080             {
1081               // Size 0 - ignore
1082               pData->string_value = 0;            
1083             }
1084
1085             //cout << " Sending property " << pData->id << " " << pData->type << " " <<  pData->string_value << "\n";
1086             break;        
1087           }
1088         default:
1089           // FIXME Currently default to a float. 
1090           //cout << "Unknown type when iterating through props: " << pData->type << "\n";
1091           pData->float_value = it->second->getFloatValue();
1092           break;
1093       }
1094       
1095       motionInfo.properties.push_back(pData);
1096     }
1097
1098     SendMyPosition(motionInfo);
1099 }
1100
1101
1102 //////////////////////////////////////////////////////////////////////
1103 //
1104 //  handle a position message
1105 //
1106 //////////////////////////////////////////////////////////////////////
1107 void
1108 FGMultiplayMgr::ProcessPosMsg(const FGMultiplayMgr::MsgBuf& Msg,
1109                               const simgear::IPAddress& SenderAddress, long stamp)
1110 {
1111   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1112   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
1113     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1114             << "Position message received with insufficient data" );
1115     return;
1116   }
1117   const T_PositionMsg* PosMsg = Msg.posMsg();
1118   FGExternalMotionData motionInfo;
1119   motionInfo.time = XDR_decode_double(PosMsg->time);
1120   motionInfo.lag = XDR_decode_double(PosMsg->lag);
1121   for (unsigned i = 0; i < 3; ++i)
1122     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
1123   SGVec3f angleAxis;
1124   for (unsigned i = 0; i < 3; ++i)
1125     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
1126   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
1127   for (unsigned i = 0; i < 3; ++i)
1128     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
1129   for (unsigned i = 0; i < 3; ++i)
1130     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
1131   for (unsigned i = 0; i < 3; ++i)
1132     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
1133   for (unsigned i = 0; i < 3; ++i)
1134     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
1135
1136   // sanity check: do not allow injection of corrupted data (NaNs)
1137   if (!isSane(motionInfo))
1138   {
1139       // drop this message, keep old position until receiving valid data
1140       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1141               << "Position message with invalid data (NaN) received from "
1142               << MsgHdr->Callsign);
1143       return;
1144   }
1145
1146   //cout << "INPUT MESSAGE\n";
1147
1148   // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
1149   // on 32 bit architectures and 200 bytes on 64 bit, and this
1150   // structure is put directly on the wire. By looking at the padding,
1151   // we can sort through the mess, mostly:
1152   // If padding is 0 (which is not a valid property type), then the
1153   // message was produced by a new client or an old 64 bit client that
1154   // happened to have 0 on the stack;
1155   // Else if the property list starting with the padding word is
1156   // well-formed, then the client is probably an old 32 bit client and
1157   // we'll go with that;
1158   // Else it is an old 64-bit client and properties start after the
1159   // padding.
1160   // There is a chance that we could be fooled by garbage in the
1161   // padding looking like a valid property, so verifyProperties() is
1162   // strict about the validity of the property values.
1163   const xdr_data_t* xdr = Msg.properties();
1164   if (PosMsg->pad != 0) {
1165     if (verifyProperties(&PosMsg->pad, Msg.propsRecvdEnd()))
1166       xdr = &PosMsg->pad;
1167     else if (!verifyProperties(xdr, Msg.propsRecvdEnd()))
1168       goto noprops;
1169   }
1170   while (xdr < Msg.propsRecvdEnd()) {
1171     // simgear::props::Type type = simgear::props::UNSPECIFIED;
1172     
1173     // First element is always the ID
1174     unsigned id = XDR_decode_uint32(*xdr);
1175     //cout << pData->id << " ";
1176     xdr++;
1177     
1178     // Check the ID actually exists and get the type
1179     const IdPropertyList* plist = findProperty(id);
1180     
1181     if (plist)
1182     {
1183       FGPropertyData* pData = new FGPropertyData;
1184       pData->id = id;
1185       pData->type = plist->type;
1186       // How we decode the remainder of the property depends on the type
1187       switch (pData->type) {
1188         case simgear::props::INT:
1189         case simgear::props::BOOL:
1190         case simgear::props::LONG:
1191           pData->int_value = XDR_decode_uint32(*xdr);
1192           xdr++;
1193           //cout << pData->int_value << "\n";
1194           break;
1195         case simgear::props::FLOAT:
1196         case simgear::props::DOUBLE:
1197           pData->float_value = XDR_decode_float(*xdr);
1198           xdr++;
1199           //cout << pData->float_value << "\n";
1200           break;
1201         case simgear::props::STRING:
1202         case simgear::props::UNSPECIFIED:
1203           {
1204             // String is complicated. It consists of
1205             // The length of the string
1206             // The string itself
1207             // Padding to the nearest 4-bytes.    
1208             uint32_t length = XDR_decode_uint32(*xdr);
1209             xdr++;
1210             //cout << length << " ";
1211             // Old versions truncated the string but left the length unadjusted.
1212             if (length > MAX_TEXT_SIZE)
1213               length = MAX_TEXT_SIZE;
1214             pData->string_value = new char[length + 1];
1215             //cout << " String: ";
1216             for (unsigned i = 0; i < length; i++)
1217               {
1218                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
1219                 xdr++;
1220                 //cout << pData->string_value[i];
1221               }
1222
1223             pData->string_value[length] = '\0';
1224
1225             // Now handle the padding
1226             while ((length % 4) != 0)
1227               {
1228                 xdr++;
1229                 length++;
1230                 //cout << "0";
1231               }
1232             //cout << "\n";
1233           }
1234           break;
1235
1236         default:
1237           pData->float_value = XDR_decode_float(*xdr);
1238           SG_LOG(SG_NETWORK, SG_DEBUG, "Unknown Prop type " << pData->id << " " << pData->type);
1239           xdr++;
1240           break;
1241       }
1242
1243       motionInfo.properties.push_back(pData);
1244     }
1245     else
1246     {
1247       // We failed to find the property. We'll try the next packet immediately.
1248       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1249              "message from " << MsgHdr->Callsign << " has unknown property id "
1250              << id); 
1251     }
1252   }
1253  noprops:
1254   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
1255   if (!mp)
1256     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
1257   mp->addMotionInfo(motionInfo, stamp);
1258 } // FGMultiplayMgr::ProcessPosMsg()
1259 //////////////////////////////////////////////////////////////////////
1260
1261 //////////////////////////////////////////////////////////////////////
1262 //
1263 //  handle a chat message
1264 //  FIXME: display chat message within flightgear
1265 //
1266 //////////////////////////////////////////////////////////////////////
1267 void
1268 FGMultiplayMgr::ProcessChatMsg(const MsgBuf& Msg,
1269                                const simgear::IPAddress& SenderAddress)
1270 {
1271   const T_MsgHdr* MsgHdr = Msg.msgHdr();
1272   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
1273     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1274             << "Chat message received with insufficient data" );
1275     return;
1276   }
1277   
1278   char *chatStr = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
1279   const T_ChatMsg* ChatMsg
1280       = reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr));
1281   strncpy(chatStr, ChatMsg->Text,
1282           MsgHdr->MsgLen - sizeof(T_MsgHdr));
1283   chatStr[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
1284   
1285   SG_LOG (SG_NETWORK, SG_WARN, "Chat [" << MsgHdr->Callsign << "]"
1286            << " " << chatStr);
1287
1288   delete [] chatStr;
1289 } // FGMultiplayMgr::ProcessChatMsg ()
1290 //////////////////////////////////////////////////////////////////////
1291
1292 void
1293 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
1294 {
1295   uint32_t len;
1296   switch (MsgId) {
1297   case CHAT_MSG_ID:
1298     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
1299     break;
1300   case POS_DATA_ID:
1301     len = _len;
1302     break;
1303   default:
1304     len = sizeof(T_MsgHdr);
1305     break;
1306   }
1307   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
1308   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
1309   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
1310   MsgHdr->MsgLen          = XDR_encode_uint32(len);
1311   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
1312   MsgHdr->ReplyPort       = 0; // now
1313   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
1314   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
1315 }
1316
1317 FGAIMultiplayer*
1318 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
1319                                const std::string& modelName)
1320 {
1321   if (0 < mMultiPlayerMap.count(callsign))
1322     return mMultiPlayerMap[callsign].get();
1323
1324   FGAIMultiplayer* mp = new FGAIMultiplayer;
1325   mp->setPath(modelName.c_str());
1326   mp->setCallSign(callsign);
1327   mMultiPlayerMap[callsign] = mp;
1328
1329   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai-model");
1330   if (aiMgr) {
1331     aiMgr->attach(mp);
1332
1333     /// FIXME: that must follow the attach ATM ...
1334     for (unsigned i = 0; i < numProperties; ++i)
1335       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
1336   }
1337
1338   return mp;
1339 }
1340
1341 FGAIMultiplayer*
1342 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
1343 {
1344   if (0 < mMultiPlayerMap.count(callsign))
1345     return mMultiPlayerMap[callsign].get();
1346   else
1347     return 0;
1348 }
1349
1350 void
1351 FGMultiplayMgr::findProperties()
1352 {
1353   if (!mPropertiesChanged) {
1354     return;
1355   }
1356   
1357   mPropertiesChanged = false;
1358   
1359   for (unsigned i = 0; i < numProperties; ++i) {
1360       const char* name = sIdPropertyList[i].name;
1361       SGPropertyNode* pNode = globals->get_props()->getNode(name);
1362       if (!pNode) {
1363         continue;
1364       }
1365       
1366       int id = sIdPropertyList[i].id;
1367       if (mPropertyMap.find(id) != mPropertyMap.end()) {
1368         continue; // already activated
1369       }
1370       
1371       mPropertyMap[id] = pNode;
1372       SG_LOG(SG_NETWORK, SG_DEBUG, "activating MP property:" << pNode->getPath());
1373     }
1374 }