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