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