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