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