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