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