]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
Merge commit 'refs/merge-requests/1551' of git://gitorious.org/fg/flightgear into...
[flightgear.git] / src / MultiPlayer / multiplaymgr.cxx
1 //////////////////////////////////////////////////////////////////////
2 //
3 // multiplaymgr.hpp
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 <osg/Math>             // isNaN
38 #include <plib/netSocket.h>
39
40 #include <simgear/misc/stdint.hxx>
41 #include <simgear/timing/timestamp.hxx>
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/props/props.hxx>
44
45 #include <AIModel/AIManager.hxx>
46 #include <Main/fg_props.hxx>
47 #include "multiplaymgr.hxx"
48 #include "mpmessages.hxx"
49
50 using namespace std;
51
52 #define MAX_PACKET_SIZE 1200
53 #define MAX_TEXT_SIZE 128
54
55 // These constants are provided so that the ident 
56 // command can list file versions
57 const char sMULTIPLAYMGR_BID[] = "$Id$";
58 const char sMULTIPLAYMGR_HID[] = MULTIPLAYTXMGR_HID;
59
60 // A static map of protocol property id values to property paths,
61 // This should be extendable dynamically for every specific aircraft ...
62 // For now only that static list
63 const FGMultiplayMgr::IdPropertyList
64 FGMultiplayMgr::sIdPropertyList[] = {
65   {100, "surface-positions/left-aileron-pos-norm",  simgear::props::FLOAT},
66   {101, "surface-positions/right-aileron-pos-norm", simgear::props::FLOAT},
67   {102, "surface-positions/elevator-pos-norm",      simgear::props::FLOAT},
68   {103, "surface-positions/rudder-pos-norm",        simgear::props::FLOAT},
69   {104, "surface-positions/flap-pos-norm",          simgear::props::FLOAT},
70   {105, "surface-positions/speedbrake-pos-norm",    simgear::props::FLOAT},
71   {106, "gear/tailhook/position-norm",              simgear::props::FLOAT},
72   {107, "gear/launchbar/position-norm",             simgear::props::FLOAT},
73   {108, "gear/launchbar/state",                     simgear::props::STRING},
74   {109, "gear/launchbar/holdback-position-norm",    simgear::props::FLOAT},
75   {110, "canopy/position-norm",                     simgear::props::FLOAT},
76   {111, "surface-positions/wing-pos-norm",          simgear::props::FLOAT},
77   {112, "surface-positions/wing-fold-pos-norm",     simgear::props::FLOAT},
78
79   {200, "gear/gear[0]/compression-norm",           simgear::props::FLOAT},
80   {201, "gear/gear[0]/position-norm",              simgear::props::FLOAT},
81   {210, "gear/gear[1]/compression-norm",           simgear::props::FLOAT},
82   {211, "gear/gear[1]/position-norm",              simgear::props::FLOAT},
83   {220, "gear/gear[2]/compression-norm",           simgear::props::FLOAT},
84   {221, "gear/gear[2]/position-norm",              simgear::props::FLOAT},
85   {230, "gear/gear[3]/compression-norm",           simgear::props::FLOAT},
86   {231, "gear/gear[3]/position-norm",              simgear::props::FLOAT},
87   {240, "gear/gear[4]/compression-norm",           simgear::props::FLOAT},
88   {241, "gear/gear[4]/position-norm",              simgear::props::FLOAT},
89
90   {300, "engines/engine[0]/n1",  simgear::props::FLOAT},
91   {301, "engines/engine[0]/n2",  simgear::props::FLOAT},
92   {302, "engines/engine[0]/rpm", simgear::props::FLOAT},
93   {310, "engines/engine[1]/n1",  simgear::props::FLOAT},
94   {311, "engines/engine[1]/n2",  simgear::props::FLOAT},
95   {312, "engines/engine[1]/rpm", simgear::props::FLOAT},
96   {320, "engines/engine[2]/n1",  simgear::props::FLOAT},
97   {321, "engines/engine[2]/n2",  simgear::props::FLOAT},
98   {322, "engines/engine[2]/rpm", simgear::props::FLOAT},
99   {330, "engines/engine[3]/n1",  simgear::props::FLOAT},
100   {331, "engines/engine[3]/n2",  simgear::props::FLOAT},
101   {332, "engines/engine[3]/rpm", simgear::props::FLOAT},
102   {340, "engines/engine[4]/n1",  simgear::props::FLOAT},
103   {341, "engines/engine[4]/n2",  simgear::props::FLOAT},
104   {342, "engines/engine[4]/rpm", simgear::props::FLOAT},
105   {350, "engines/engine[5]/n1",  simgear::props::FLOAT},
106   {351, "engines/engine[5]/n2",  simgear::props::FLOAT},
107   {352, "engines/engine[5]/rpm", simgear::props::FLOAT},
108   {360, "engines/engine[6]/n1",  simgear::props::FLOAT},
109   {361, "engines/engine[6]/n2",  simgear::props::FLOAT},
110   {362, "engines/engine[6]/rpm", simgear::props::FLOAT},
111   {370, "engines/engine[7]/n1",  simgear::props::FLOAT},
112   {371, "engines/engine[7]/n2",  simgear::props::FLOAT},
113   {372, "engines/engine[7]/rpm", simgear::props::FLOAT},
114   {380, "engines/engine[8]/n1",  simgear::props::FLOAT},
115   {381, "engines/engine[8]/n2",  simgear::props::FLOAT},
116   {382, "engines/engine[8]/rpm", simgear::props::FLOAT},
117   {390, "engines/engine[9]/n1",  simgear::props::FLOAT},
118   {391, "engines/engine[9]/n2",  simgear::props::FLOAT},
119   {392, "engines/engine[9]/rpm", simgear::props::FLOAT},
120
121   {800, "rotors/main/rpm", simgear::props::FLOAT},
122   {801, "rotors/tail/rpm", simgear::props::FLOAT},
123   {810, "rotors/main/blade[0]/position-deg",  simgear::props::FLOAT},
124   {811, "rotors/main/blade[1]/position-deg",  simgear::props::FLOAT},
125   {812, "rotors/main/blade[2]/position-deg",  simgear::props::FLOAT},
126   {813, "rotors/main/blade[3]/position-deg",  simgear::props::FLOAT},
127   {820, "rotors/main/blade[0]/flap-deg",  simgear::props::FLOAT},
128   {821, "rotors/main/blade[1]/flap-deg",  simgear::props::FLOAT},
129   {822, "rotors/main/blade[2]/flap-deg",  simgear::props::FLOAT},
130   {823, "rotors/main/blade[3]/flap-deg",  simgear::props::FLOAT},
131   {830, "rotors/tail/blade[0]/position-deg",  simgear::props::FLOAT},
132   {831, "rotors/tail/blade[1]/position-deg",  simgear::props::FLOAT},
133
134   {900, "sim/hitches/aerotow/tow/length",                       simgear::props::FLOAT},
135   {901, "sim/hitches/aerotow/tow/elastic-constant",             simgear::props::FLOAT},
136   {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m",            simgear::props::FLOAT},
137   {903, "sim/hitches/aerotow/tow/dist",                         simgear::props::FLOAT},
138   {904, "sim/hitches/aerotow/tow/connected-to-property-node",   simgear::props::BOOL},
139   {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign",   simgear::props::STRING},
140   {906, "sim/hitches/aerotow/tow/brake-force",                  simgear::props::FLOAT},
141   {907, "sim/hitches/aerotow/tow/end-force-x",                  simgear::props::FLOAT},
142   {908, "sim/hitches/aerotow/tow/end-force-y",                  simgear::props::FLOAT},
143   {909, "sim/hitches/aerotow/tow/end-force-z",                  simgear::props::FLOAT},
144   {930, "sim/hitches/aerotow/is-slave",                         simgear::props::BOOL},
145   {931, "sim/hitches/aerotow/speed-in-tow-direction",           simgear::props::FLOAT},
146   {932, "sim/hitches/aerotow/open",                             simgear::props::BOOL},
147   {933, "sim/hitches/aerotow/local-pos-x",                      simgear::props::FLOAT},
148   {934, "sim/hitches/aerotow/local-pos-y",                      simgear::props::FLOAT},
149   {935, "sim/hitches/aerotow/local-pos-z",                      simgear::props::FLOAT},
150
151   {1001, "controls/flight/slats",  simgear::props::FLOAT},
152   {1002, "controls/flight/speedbrake",  simgear::props::FLOAT},
153   {1003, "controls/flight/spoilers",  simgear::props::FLOAT},
154   {1004, "controls/gear/gear-down",  simgear::props::FLOAT},
155   {1005, "controls/lighting/nav-lights",  simgear::props::FLOAT},
156   {1006, "controls/armament/station[0]/jettison-all",  simgear::props::BOOL},
157
158   {1100, "sim/model/variant", simgear::props::INT},
159   {1101, "sim/model/livery/file", simgear::props::STRING},
160
161   {1200, "environment/wildfire/data", simgear::props::STRING},
162   
163   {10001, "sim/multiplay/transmission-freq-hz",  simgear::props::STRING},
164   {10002, "sim/multiplay/chat",  simgear::props::STRING},
165
166   {10100, "sim/multiplay/generic/string[0]", simgear::props::STRING},
167   {10101, "sim/multiplay/generic/string[1]", simgear::props::STRING},
168   {10102, "sim/multiplay/generic/string[2]", simgear::props::STRING},
169   {10103, "sim/multiplay/generic/string[3]", simgear::props::STRING},
170   {10104, "sim/multiplay/generic/string[4]", simgear::props::STRING},
171   {10105, "sim/multiplay/generic/string[5]", simgear::props::STRING},
172   {10106, "sim/multiplay/generic/string[6]", simgear::props::STRING},
173   {10107, "sim/multiplay/generic/string[7]", simgear::props::STRING},
174   {10108, "sim/multiplay/generic/string[8]", simgear::props::STRING},
175   {10109, "sim/multiplay/generic/string[9]", simgear::props::STRING},
176   {10110, "sim/multiplay/generic/string[10]", simgear::props::STRING},
177   {10111, "sim/multiplay/generic/string[11]", simgear::props::STRING},
178   {10112, "sim/multiplay/generic/string[12]", simgear::props::STRING},
179   {10113, "sim/multiplay/generic/string[13]", simgear::props::STRING},
180   {10114, "sim/multiplay/generic/string[14]", simgear::props::STRING},
181   {10115, "sim/multiplay/generic/string[15]", simgear::props::STRING},
182   {10116, "sim/multiplay/generic/string[16]", simgear::props::STRING},
183   {10117, "sim/multiplay/generic/string[17]", simgear::props::STRING},
184   {10118, "sim/multiplay/generic/string[18]", simgear::props::STRING},
185   {10119, "sim/multiplay/generic/string[19]", simgear::props::STRING},
186
187   {10200, "sim/multiplay/generic/float[0]", simgear::props::FLOAT},
188   {10201, "sim/multiplay/generic/float[1]", simgear::props::FLOAT},
189   {10202, "sim/multiplay/generic/float[2]", simgear::props::FLOAT},
190   {10203, "sim/multiplay/generic/float[3]", simgear::props::FLOAT},
191   {10204, "sim/multiplay/generic/float[4]", simgear::props::FLOAT},
192   {10205, "sim/multiplay/generic/float[5]", simgear::props::FLOAT},
193   {10206, "sim/multiplay/generic/float[6]", simgear::props::FLOAT},
194   {10207, "sim/multiplay/generic/float[7]", simgear::props::FLOAT},
195   {10208, "sim/multiplay/generic/float[8]", simgear::props::FLOAT},
196   {10209, "sim/multiplay/generic/float[9]", simgear::props::FLOAT},
197   {10210, "sim/multiplay/generic/float[10]", simgear::props::FLOAT},
198   {10211, "sim/multiplay/generic/float[11]", simgear::props::FLOAT},
199   {10212, "sim/multiplay/generic/float[12]", simgear::props::FLOAT},
200   {10213, "sim/multiplay/generic/float[13]", simgear::props::FLOAT},
201   {10214, "sim/multiplay/generic/float[14]", simgear::props::FLOAT},
202   {10215, "sim/multiplay/generic/float[15]", simgear::props::FLOAT},
203   {10216, "sim/multiplay/generic/float[16]", simgear::props::FLOAT},
204   {10217, "sim/multiplay/generic/float[17]", simgear::props::FLOAT},
205   {10218, "sim/multiplay/generic/float[18]", simgear::props::FLOAT},
206   {10219, "sim/multiplay/generic/float[19]", simgear::props::FLOAT},
207
208   {10300, "sim/multiplay/generic/int[0]", simgear::props::INT},
209   {10301, "sim/multiplay/generic/int[1]", simgear::props::INT},
210   {10302, "sim/multiplay/generic/int[2]", simgear::props::INT},
211   {10303, "sim/multiplay/generic/int[3]", simgear::props::INT},
212   {10304, "sim/multiplay/generic/int[4]", simgear::props::INT},
213   {10305, "sim/multiplay/generic/int[5]", simgear::props::INT},
214   {10306, "sim/multiplay/generic/int[6]", simgear::props::INT},
215   {10307, "sim/multiplay/generic/int[7]", simgear::props::INT},
216   {10308, "sim/multiplay/generic/int[8]", simgear::props::INT},
217   {10309, "sim/multiplay/generic/int[9]", simgear::props::INT},
218   {10310, "sim/multiplay/generic/int[10]", simgear::props::INT},
219   {10311, "sim/multiplay/generic/int[11]", simgear::props::INT},
220   {10312, "sim/multiplay/generic/int[12]", simgear::props::INT},
221   {10313, "sim/multiplay/generic/int[13]", simgear::props::INT},
222   {10314, "sim/multiplay/generic/int[14]", simgear::props::INT},
223   {10315, "sim/multiplay/generic/int[15]", simgear::props::INT},
224   {10316, "sim/multiplay/generic/int[16]", simgear::props::INT},
225   {10317, "sim/multiplay/generic/int[17]", simgear::props::INT},
226   {10318, "sim/multiplay/generic/int[18]", simgear::props::INT},
227   {10319, "sim/multiplay/generic/int[19]", simgear::props::INT}
228 };
229
230 const unsigned
231 FGMultiplayMgr::numProperties = (sizeof(FGMultiplayMgr::sIdPropertyList)
232                                  / sizeof(FGMultiplayMgr::sIdPropertyList[0]));
233
234 // Look up a property ID using binary search.
235 namespace
236 {
237   struct ComparePropertyId
238   {
239     bool operator()(const FGMultiplayMgr::IdPropertyList& lhs,
240                     const FGMultiplayMgr::IdPropertyList& rhs)
241     {
242       return lhs.id < rhs.id;
243     }
244     bool operator()(const FGMultiplayMgr::IdPropertyList& lhs,
245                     unsigned id)
246     {
247       return lhs.id < id;
248     }
249     bool operator()(unsigned id,
250                     const FGMultiplayMgr::IdPropertyList& rhs)
251     {
252       return id < rhs.id;
253     }
254   };
255     
256 }
257 const FGMultiplayMgr::IdPropertyList* FGMultiplayMgr::findProperty(unsigned id)
258 {
259   std::pair<const IdPropertyList*, const IdPropertyList*> result
260     = std::equal_range(sIdPropertyList, sIdPropertyList + numProperties, id,
261                        ComparePropertyId());
262   if (result.first == result.second) {
263     return 0;
264   } else {
265     return result.first;
266   }
267 }
268
269 namespace
270 {
271   bool verifyProperties(const xdr_data_t* data, const xdr_data_t* end)
272   {
273     using namespace simgear;
274     const xdr_data_t* xdr = data;
275     while (xdr < end) {
276       unsigned id = XDR_decode_uint32(*xdr);
277       const FGMultiplayMgr::IdPropertyList* plist
278         = FGMultiplayMgr::findProperty(id);
279     
280       if (plist) {
281         xdr++;
282         // How we decode the remainder of the property depends on the type
283         switch (plist->type) {
284         case props::INT:
285         case props::BOOL:
286         case props::LONG:
287           xdr++;
288           break;
289         case props::FLOAT:
290         case props::DOUBLE:
291           {
292             float val = XDR_decode_float(*xdr);
293             if (osg::isNaN(val))
294               return false;
295             xdr++;
296             break;
297           }
298         case props::STRING:
299         case props::UNSPECIFIED:
300           {
301             // String is complicated. It consists of
302             // The length of the string
303             // The string itself
304             // Padding to the nearest 4-bytes.
305             // XXX Yes, each byte is padded out to a word! Too late
306             // to change...
307             uint32_t length = XDR_decode_uint32(*xdr);
308             xdr++;
309             // Old versions truncated the string but left the length
310             // unadjusted.
311             if (length > MAX_TEXT_SIZE)
312               length = MAX_TEXT_SIZE;
313             xdr += length;
314             // Now handle the padding
315             while ((length % 4) != 0)
316               {
317                 xdr++;
318                 length++;
319                 //cout << "0";
320               }
321           }
322           break;
323         default:
324           // cerr << "Unknown Prop type " << id << " " << type << "\n";
325           xdr++;
326           break;
327         }            
328       }
329       else {
330         // give up; this is a malformed property list.
331         return false;
332       }
333     }
334     return true;
335   }
336 }
337 //////////////////////////////////////////////////////////////////////
338 //
339 //  MultiplayMgr constructor
340 //
341 //////////////////////////////////////////////////////////////////////
342 FGMultiplayMgr::FGMultiplayMgr() 
343 {
344   mSocket        = 0;
345   mInitialised   = false;
346   mHaveServer    = false;
347 } // FGMultiplayMgr::FGMultiplayMgr()
348 //////////////////////////////////////////////////////////////////////
349
350 //////////////////////////////////////////////////////////////////////
351 //
352 //  MultiplayMgr destructor
353 //
354 //////////////////////////////////////////////////////////////////////
355 FGMultiplayMgr::~FGMultiplayMgr() 
356 {
357   Close();
358 } // FGMultiplayMgr::~FGMultiplayMgr()
359 //////////////////////////////////////////////////////////////////////
360
361 //////////////////////////////////////////////////////////////////////
362 //
363 //  Initialise object
364 //
365 //////////////////////////////////////////////////////////////////////
366 bool
367 FGMultiplayMgr::init (void) 
368 {
369   //////////////////////////////////////////////////
370   //  Initialise object if not already done
371   //////////////////////////////////////////////////
372   if (mInitialised) {
373     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
374     return false;
375   }
376   //////////////////////////////////////////////////
377   //  Set members from property values
378   //////////////////////////////////////////////////
379   short rxPort = fgGetInt("/sim/multiplay/rxport");
380   string rxAddress = fgGetString("/sim/multiplay/rxhost");
381   short txPort = fgGetInt("/sim/multiplay/txport");
382   string txAddress = fgGetString("/sim/multiplay/txhost");
383   mCallsign = fgGetString("/sim/multiplay/callsign");
384   if (txPort > 0 && !txAddress.empty()) {
385     mServer.set(txAddress.c_str(), txPort);
386     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
387       mHaveServer = false;
388       SG_LOG(SG_NETWORK, SG_DEBUG,
389         "FGMultiplayMgr - could not resolve '"
390         << txAddress << "', Multiplayermode disabled");
391     } else {
392       mHaveServer = true;
393     }
394     if (rxPort <= 0)
395       rxPort = txPort;
396   }
397   if (rxPort <= 0) {
398     SG_LOG(SG_NETWORK, SG_DEBUG,
399       "FGMultiplayMgr - No receiver port, Multiplayermode disabled");
400     return (false);
401   }
402   if (mCallsign.empty())
403     mCallsign = "JohnDoe"; // FIXME: use getpwuid
404   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
405   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
406   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
407   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
408   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
409   Close(); // Should Init be called twice, close Socket first
410            // A memory leak was reported here by valgrind
411   mSocket = new netSocket();
412   if (!mSocket->open(false)) {
413     SG_LOG( SG_NETWORK, SG_DEBUG,
414             "FGMultiplayMgr::init - Failed to create data socket" );
415     return false;
416   }
417   mSocket->setBlocking(false);
418   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
419     perror("bind");
420     SG_LOG( SG_NETWORK, SG_DEBUG,
421             "FGMultiplayMgr::Open - Failed to bind receive socket" );
422     return false;
423   }
424   mInitialised = true;
425   return true;
426 } // FGMultiplayMgr::init()
427 //////////////////////////////////////////////////////////////////////
428
429 //////////////////////////////////////////////////////////////////////
430 //
431 //  Closes and deletes the local player object. Closes
432 //  and deletes the tx socket. Resets the object state to unitialised.
433 //
434 //////////////////////////////////////////////////////////////////////
435 void
436 FGMultiplayMgr::Close (void) 
437 {
438   mMultiPlayerMap.clear();
439
440   if (mSocket) {
441     mSocket->close();
442     delete mSocket;
443     mSocket = 0;
444   }
445   mInitialised = false;
446 } // FGMultiplayMgr::Close(void)
447 //////////////////////////////////////////////////////////////////////
448
449 //////////////////////////////////////////////////////////////////////
450 //
451 //  Description: Sends the position data for the local position.
452 //
453 //////////////////////////////////////////////////////////////////////
454
455 /**
456  * The buffer that holds a multi-player message, suitably aligned.
457  */
458 union FGMultiplayMgr::MsgBuf
459 {
460     MsgBuf()
461     {
462         memset(&Msg, 0, sizeof(Msg));
463     }
464
465     T_MsgHdr* msgHdr()
466     {
467         return reinterpret_cast<T_MsgHdr*>(Msg);
468     }
469
470     const T_MsgHdr* msgHdr() const
471     {
472         return reinterpret_cast<const T_MsgHdr*>(Msg);
473     }
474
475     T_PositionMsg* posMsg()
476     {
477         return reinterpret_cast<T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
478     }
479
480     const T_PositionMsg* posMsg() const
481     {
482         return reinterpret_cast<const T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
483     }
484
485     xdr_data_t* properties()
486     {
487         return reinterpret_cast<xdr_data_t*>(Msg + sizeof(T_MsgHdr)
488                                              + sizeof(T_PositionMsg));
489     }
490
491     const xdr_data_t* properties() const
492     {
493         return reinterpret_cast<const xdr_data_t*>(Msg + sizeof(T_MsgHdr)
494                                                    + sizeof(T_PositionMsg));
495     }
496     /**
497      * The end of the properties buffer.
498      */
499     xdr_data_t* propsEnd()
500     {
501         return reinterpret_cast<xdr_data_t*>(Msg + MAX_PACKET_SIZE);
502     };
503
504     const xdr_data_t* propsEnd() const
505     {
506         return reinterpret_cast<const xdr_data_t*>(Msg + MAX_PACKET_SIZE);
507     };
508     /**
509      * The end of properties actually in the buffer. This assumes that
510      * the message header is valid.
511      */
512     xdr_data_t* propsRecvdEnd()
513     {
514         return reinterpret_cast<xdr_data_t*>(Msg + msgHdr()->MsgLen);
515     }
516
517     const xdr_data_t* propsRecvdEnd() const
518     {
519         return reinterpret_cast<const xdr_data_t*>(Msg + msgHdr()->MsgLen);
520     }
521     
522     xdr_data2_t double_val;
523     char Msg[MAX_PACKET_SIZE];
524 };
525
526 void
527 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
528 {
529   if ((! mInitialised) || (! mHaveServer))
530         return;
531   if (! mHaveServer) {
532     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition - no server");
533     return;
534   }
535
536   MsgBuf msgBuf;
537   T_PositionMsg* PosMsg = msgBuf.posMsg();
538
539   strncpy(PosMsg->Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
540   PosMsg->Model[MAX_MODEL_NAME_LEN - 1] = '\0';
541   
542   PosMsg->time = XDR_encode_double (motionInfo.time);
543   PosMsg->lag = XDR_encode_double (motionInfo.lag);
544   for (unsigned i = 0 ; i < 3; ++i)
545     PosMsg->position[i] = XDR_encode_double (motionInfo.position(i));
546   SGVec3f angleAxis;
547   motionInfo.orientation.getAngleAxis(angleAxis);
548   for (unsigned i = 0 ; i < 3; ++i)
549     PosMsg->orientation[i] = XDR_encode_float (angleAxis(i));
550   for (unsigned i = 0 ; i < 3; ++i)
551     PosMsg->linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
552   for (unsigned i = 0 ; i < 3; ++i)
553     PosMsg->angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
554   for (unsigned i = 0 ; i < 3; ++i)
555     PosMsg->linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
556   for (unsigned i = 0 ; i < 3; ++i)
557     PosMsg->angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
558   
559   xdr_data_t* ptr = msgBuf.properties();
560   std::vector<FGPropertyData*>::const_iterator it;
561   it = motionInfo.properties.begin();
562   //cout << "OUTPUT PROPERTIES\n";
563   xdr_data_t* msgEnd = msgBuf.propsEnd();
564   while (it != motionInfo.properties.end() && ptr + 2 < msgEnd) {
565     
566     // First element is the ID. Write it out when we know we have room for
567     // the whole property.
568     xdr_data_t id =  XDR_encode_uint32((*it)->id);
569     // The actual data representation depends on the type
570     switch ((*it)->type) {
571       case simgear::props::INT:
572       case simgear::props::BOOL:
573       case simgear::props::LONG:
574         *ptr++ = id;
575         *ptr++ = XDR_encode_uint32((*it)->int_value);
576         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
577         break;
578       case simgear::props::FLOAT:
579       case simgear::props::DOUBLE:
580         *ptr++ = id;
581         *ptr++ = XDR_encode_float((*it)->float_value);
582         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
583         break;
584       case simgear::props::STRING:
585       case simgear::props::UNSPECIFIED:
586         {
587           // String is complicated. It consists of
588           // The length of the string
589           // The string itself
590           // Padding to the nearest 4-bytes.        
591           const char* lcharptr = (*it)->string_value;
592           
593           if (lcharptr != 0)
594           {
595             // Add the length         
596             ////cout << "String length: " << strlen(lcharptr) << "\n";
597             uint32_t len = strlen(lcharptr);
598             if (len > MAX_TEXT_SIZE)
599               len = MAX_TEXT_SIZE;
600             // XXX This should not be using 4 bytes per character!
601             // If there's not enough room for this property, drop it
602             // on the floor.
603             if (ptr + 2 + ((len + 3) & ~3) > msgEnd)
604                 goto escape;
605             //cout << "String length unint32: " << len << "\n";
606             *ptr++ = id;
607             *ptr++ = XDR_encode_uint32(len);
608             if (len != 0)
609             {
610               // Now the text itself
611               // XXX This should not be using 4 bytes per character!
612               int lcount = 0;
613               while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
614               {
615                 *ptr++ = XDR_encode_int8(*lcharptr);
616                 lcharptr++;
617                 lcount++;          
618               }
619
620               //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
621
622               // Now pad if required
623               while ((lcount % 4) != 0)
624               {
625                 *ptr++ = XDR_encode_int8(0);
626                 lcount++;          
627                 //cout << "0";
628               }
629               
630               //cout << "\n";
631             }
632           }
633           else
634           {
635             // Nothing to encode
636             *ptr++ = id;
637             *ptr++ = XDR_encode_uint32(0);
638             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
639           }
640         }
641         break;
642         
643       default:
644         //cout << " Unknown Type: " << (*it)->type << "\n";
645         *ptr++ = id;
646         *ptr++ = XDR_encode_float((*it)->float_value);;
647         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
648         break;
649     }
650         
651     ++it;
652   }
653 escape:
654   unsigned msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
655   FillMsgHdr(msgBuf.msgHdr(), POS_DATA_ID, msgLen);
656   mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
657   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
658 } // FGMultiplayMgr::SendMyPosition()
659
660 //////////////////////////////////////////////////////////////////////
661
662 //////////////////////////////////////////////////////////////////////
663 //
664 //  Name: SendTextMessage
665 //  Description: Sends a message to the player. The message must
666 //  contain a valid and correctly filled out header and optional
667 //  message body.
668 //
669 //////////////////////////////////////////////////////////////////////
670 void
671 FGMultiplayMgr::SendTextMessage(const string &MsgText)
672 {
673   if (!mInitialised || !mHaveServer)
674     return;
675
676   T_MsgHdr MsgHdr;
677   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
678   //////////////////////////////////////////////////
679   // Divide the text string into blocks that fit
680   // in the message and send the blocks.
681   //////////////////////////////////////////////////
682   unsigned iNextBlockPosition = 0;
683   T_ChatMsg ChatMsg;
684   
685   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
686   while (iNextBlockPosition < MsgText.length()) {
687     strncpy (ChatMsg.Text, 
688              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
689              MAX_CHAT_MSG_LEN);
690     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
691     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
692     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
693     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
694     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
695
696   }
697   
698   
699 } // FGMultiplayMgr::SendTextMessage ()
700 //////////////////////////////////////////////////////////////////////
701
702 //////////////////////////////////////////////////////////////////////
703 //
704 //  Name: ProcessData
705 //  Description: Processes data waiting at the receive socket. The
706 //  processing ends when there is no more data at the socket.
707 //  
708 //////////////////////////////////////////////////////////////////////
709 void
710 FGMultiplayMgr::Update(void) 
711 {
712   if (!mInitialised)
713     return;
714
715   /// Just for expiry
716   long stamp = SGTimeStamp::now().getSeconds();
717
718   //////////////////////////////////////////////////
719   //  Read the receive socket and process any data
720   //////////////////////////////////////////////////
721   ssize_t bytes;
722   do {
723     MsgBuf msgBuf;
724     //////////////////////////////////////////////////
725     //  Although the recv call asks for 
726     //  MAX_PACKET_SIZE of data, the number of bytes
727     //  returned will only be that of the next
728     //  packet waiting to be processed.
729     //////////////////////////////////////////////////
730     netAddress SenderAddress;
731     bytes = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
732                               &SenderAddress);
733     //////////////////////////////////////////////////
734     //  no Data received
735     //////////////////////////////////////////////////
736     if (bytes <= 0) {
737       if (errno != EAGAIN && errno != 0) // MSVC output "NoError" otherwise
738         perror("FGMultiplayMgr::MP_ProcessData");
739       break;
740     }
741     if (bytes <= static_cast<ssize_t>(sizeof(T_MsgHdr))) {
742       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
743               << "received message with insufficient data" );
744       break;
745     }
746     //////////////////////////////////////////////////
747     //  Read header
748     //////////////////////////////////////////////////
749     T_MsgHdr* MsgHdr = msgBuf.msgHdr();
750     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
751     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
752     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
753     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
754     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
755     MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
756     if (MsgHdr->Magic != MSG_MAGIC) {
757       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
758               << "message has invalid magic number!" );
759       break;
760     }
761     if (MsgHdr->Version != PROTO_VER) {
762       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
763               << "message has invalid protocoll number!" );
764       break;
765     }
766     if (MsgHdr->MsgLen != bytes) {
767       SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
768              << "message from " << MsgHdr->Callsign << " has invalid length!");
769       break;
770     }
771     //////////////////////////////////////////////////
772     //  Process messages
773     //////////////////////////////////////////////////
774     switch (MsgHdr->MsgId) {
775     case CHAT_MSG_ID:
776       ProcessChatMsg(msgBuf, SenderAddress);
777       break;
778     case POS_DATA_ID:
779       ProcessPosMsg(msgBuf, SenderAddress, stamp);
780       break;
781     case UNUSABLE_POS_DATA_ID:
782     case OLD_OLD_POS_DATA_ID:
783     case OLD_PROP_MSG_ID:
784     case OLD_POS_DATA_ID:
785       break;
786     default:
787       SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
788               << "Unknown message Id received: " << MsgHdr->MsgId );
789       break;
790     }
791   } while (bytes > 0);
792
793   // check for expiry
794   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
795   while (it != mMultiPlayerMap.end()) {
796     if (it->second->getLastTimestamp() + 10 < stamp) {
797       std::string name = it->first;
798       it->second->setDie(true);
799       mMultiPlayerMap.erase(it);
800       it = mMultiPlayerMap.upper_bound(name);
801     } else
802       ++it;
803   }
804 } // FGMultiplayMgr::ProcessData(void)
805 //////////////////////////////////////////////////////////////////////
806
807 //////////////////////////////////////////////////////////////////////
808 //
809 //  handle a position message
810 //
811 //////////////////////////////////////////////////////////////////////
812 void
813 FGMultiplayMgr::ProcessPosMsg(const FGMultiplayMgr::MsgBuf& Msg,
814                               const netAddress& SenderAddress, long stamp)
815 {
816   const T_MsgHdr* MsgHdr = Msg.msgHdr();
817   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
818     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
819             << "Position message received with insufficient data" );
820     return;
821   }
822   const T_PositionMsg* PosMsg = Msg.posMsg();
823   FGExternalMotionData motionInfo;
824   motionInfo.time = XDR_decode_double(PosMsg->time);
825   motionInfo.lag = XDR_decode_double(PosMsg->lag);
826   for (unsigned i = 0; i < 3; ++i)
827     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
828   SGVec3f angleAxis;
829   for (unsigned i = 0; i < 3; ++i)
830     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
831   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
832   for (unsigned i = 0; i < 3; ++i)
833     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
834   for (unsigned i = 0; i < 3; ++i)
835     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
836   for (unsigned i = 0; i < 3; ++i)
837     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
838   for (unsigned i = 0; i < 3; ++i)
839     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
840
841
842   //cout << "INPUT MESSAGE\n";
843
844   // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
845   // on 32 bit architectures and 200 bytes on 64 bit, and this
846   // structure is put directly on the wire. By looking at the padding,
847   // we can sort through the mess, mostly:
848   // If padding is 0 (which is not a valid property type), then the
849   // message was produced by a new client or an old 64 bit client that
850   // happened to have 0 on the stack;
851   // Else if the property list starting with the padding word is
852   // well-formed, then the client is probably an old 32 bit client and
853   // we'll go with that;
854   // Else it is an old 64-bit client and properties start after the
855   // padding.
856   // There is a chance that we could be fooled by garbage in the
857   // padding looking like a valid property, so verifyProperties() is
858   // strict about the validity of the property values.
859   const xdr_data_t* xdr = Msg.properties();
860   if (PosMsg->pad != 0) {
861     if (verifyProperties(&PosMsg->pad, Msg.propsRecvdEnd()))
862       xdr = &PosMsg->pad;
863     else if (!verifyProperties(xdr, Msg.propsRecvdEnd()))
864       goto noprops;
865   }
866   while (xdr < Msg.propsRecvdEnd()) {
867     FGPropertyData* pData = new FGPropertyData;
868     // simgear::props::Type type = simgear::props::UNSPECIFIED;
869     
870     // First element is always the ID
871     pData->id = XDR_decode_uint32(*xdr);
872     //cout << pData->id << " ";
873     xdr++;
874     
875     // Check the ID actually exists and get the type
876     const IdPropertyList* plist = findProperty(pData->id);
877     
878     if (plist)
879     {
880       pData->type = plist->type;
881       // How we decode the remainder of the property depends on the type
882       switch (pData->type) {
883         case simgear::props::INT:
884         case simgear::props::BOOL:
885         case simgear::props::LONG:
886           pData->int_value = XDR_decode_uint32(*xdr);
887           xdr++;
888           //cout << pData->int_value << "\n";
889           break;
890         case simgear::props::FLOAT:
891         case simgear::props::DOUBLE:
892           pData->float_value = XDR_decode_float(*xdr);
893           xdr++;
894           //cout << pData->float_value << "\n";
895           break;
896         case simgear::props::STRING:
897         case simgear::props::UNSPECIFIED:
898           {
899             // String is complicated. It consists of
900             // The length of the string
901             // The string itself
902             // Padding to the nearest 4-bytes.    
903             uint32_t length = XDR_decode_uint32(*xdr);
904             xdr++;
905             //cout << length << " ";
906             // Old versions truncated the string but left the length unadjusted.
907             if (length > MAX_TEXT_SIZE)
908               length = MAX_TEXT_SIZE;
909             pData->string_value = new char[length + 1];
910             //cout << " String: ";
911             for (unsigned i = 0; i < length; i++)
912               {
913                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
914                 xdr++;
915                 //cout << pData->string_value[i];
916               }
917
918             pData->string_value[length] = '\0';
919
920             // Now handle the padding
921             while ((length % 4) != 0)
922               {
923                 xdr++;
924                 length++;
925                 //cout << "0";
926               }
927             //cout << "\n";
928           }
929           break;
930
931         default:
932           pData->float_value = XDR_decode_float(*xdr);
933           SG_LOG(SG_NETWORK, SG_DEBUG, "Unknown Prop type " << pData->id << " " << pData->type);
934           xdr++;
935           break;
936       }            
937
938       motionInfo.properties.push_back(pData);
939     }
940     else
941     {
942       // We failed to find the property. We'll try the next packet immediately.
943       SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr::ProcessPosMsg - "
944              "message from " << MsgHdr->Callsign << " has unknown property id "
945              << pData->id); 
946     }
947   }
948  noprops:
949   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
950   if (!mp)
951     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
952   mp->addMotionInfo(motionInfo, stamp);
953 } // FGMultiplayMgr::ProcessPosMsg()
954 //////////////////////////////////////////////////////////////////////
955
956 //////////////////////////////////////////////////////////////////////
957 //
958 //  handle a chat message
959 //  FIXME: display chat message withi flightgear
960 //
961 //////////////////////////////////////////////////////////////////////
962 void
963 FGMultiplayMgr::ProcessChatMsg(const MsgBuf& Msg,
964                                const netAddress& SenderAddress)
965 {
966   const T_MsgHdr* MsgHdr = Msg.msgHdr();
967   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
968     SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
969             << "Chat message received with insufficient data" );
970     return;
971   }
972   
973   char *chatStr = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
974   const T_ChatMsg* ChatMsg
975       = reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr));
976   strncpy(chatStr, ChatMsg->Text,
977           MsgHdr->MsgLen - sizeof(T_MsgHdr));
978   chatStr[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
979   
980   SG_LOG (SG_NETWORK, SG_WARN, "Chat [" << MsgHdr->Callsign << "]"
981            << " " << chatStr);
982
983   delete [] chatStr;
984 } // FGMultiplayMgr::ProcessChatMsg ()
985 //////////////////////////////////////////////////////////////////////
986
987 void
988 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
989 {
990   uint32_t len;
991   switch (MsgId) {
992   case CHAT_MSG_ID:
993     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
994     break;
995   case POS_DATA_ID:
996     len = _len;
997     break;
998   default:
999     len = sizeof(T_MsgHdr);
1000     break;
1001   }
1002   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
1003   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
1004   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
1005   MsgHdr->MsgLen          = XDR_encode_uint32(len);
1006   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
1007   MsgHdr->ReplyPort       = 0; // now
1008   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
1009   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
1010 }
1011
1012 FGAIMultiplayer*
1013 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
1014                                const std::string& modelName)
1015 {
1016   if (0 < mMultiPlayerMap.count(callsign))
1017     return mMultiPlayerMap[callsign].get();
1018
1019   FGAIMultiplayer* mp = new FGAIMultiplayer;
1020   mp->setPath(modelName.c_str());
1021   mp->setCallSign(callsign);
1022   mMultiPlayerMap[callsign] = mp;
1023
1024   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
1025   if (aiMgr) {
1026     aiMgr->attach(mp);
1027
1028     /// FIXME: that must follow the attach ATM ...
1029     for (unsigned i = 0; i < numProperties; ++i)
1030       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
1031   }
1032
1033   return mp;
1034 }
1035
1036 FGAIMultiplayer*
1037 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
1038 {
1039   if (0 < mMultiPlayerMap.count(callsign))
1040     return mMultiPlayerMap[callsign].get();
1041   else
1042     return 0;
1043 }