]> git.mxchange.org Git - flightgear.git/blob - src/MultiPlayer/multiplaymgr.cxx
8983205a0ffc4bbb2aa33168737f2c870f5cb34a
[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
172   {10200, "sim/multiplay/generic/float[0]", SGPropertyNode::FLOAT},
173   {10201, "sim/multiplay/generic/float[1]", SGPropertyNode::FLOAT},
174   {10202, "sim/multiplay/generic/float[2]", SGPropertyNode::FLOAT},
175   {10203, "sim/multiplay/generic/float[3]", SGPropertyNode::FLOAT},
176   {10204, "sim/multiplay/generic/float[4]", SGPropertyNode::FLOAT},
177   {10205, "sim/multiplay/generic/float[5]", SGPropertyNode::FLOAT},
178   {10206, "sim/multiplay/generic/float[6]", SGPropertyNode::FLOAT},
179   {10207, "sim/multiplay/generic/float[7]", SGPropertyNode::FLOAT},
180   {10208, "sim/multiplay/generic/float[8]", SGPropertyNode::FLOAT},
181   {10209, "sim/multiplay/generic/float[9]", SGPropertyNode::FLOAT},
182
183   {10300, "sim/multiplay/generic/int[0]", SGPropertyNode::INT},
184   {10301, "sim/multiplay/generic/int[1]", SGPropertyNode::INT},
185   {10302, "sim/multiplay/generic/int[2]", SGPropertyNode::INT},
186   {10303, "sim/multiplay/generic/int[3]", SGPropertyNode::INT},
187   {10304, "sim/multiplay/generic/int[4]", SGPropertyNode::INT},
188   {10305, "sim/multiplay/generic/int[5]", SGPropertyNode::INT},
189   {10306, "sim/multiplay/generic/int[6]", SGPropertyNode::INT},
190   {10307, "sim/multiplay/generic/int[7]", SGPropertyNode::INT},
191   {10308, "sim/multiplay/generic/int[8]", SGPropertyNode::INT},
192   {10309, "sim/multiplay/generic/int[9]", SGPropertyNode::INT},
193
194   /// termination
195   {0, 0, SGPropertyNode::UNSPECIFIED}
196 };
197
198 //////////////////////////////////////////////////////////////////////
199 //
200 //  MultiplayMgr constructor
201 //
202 //////////////////////////////////////////////////////////////////////
203 FGMultiplayMgr::FGMultiplayMgr() 
204 {
205   mSocket        = 0;
206   mInitialised   = false;
207   mHaveServer    = false;
208 } // FGMultiplayMgr::FGMultiplayMgr()
209 //////////////////////////////////////////////////////////////////////
210
211 //////////////////////////////////////////////////////////////////////
212 //
213 //  MultiplayMgr destructor
214 //
215 //////////////////////////////////////////////////////////////////////
216 FGMultiplayMgr::~FGMultiplayMgr() 
217 {
218   Close();
219 } // FGMultiplayMgr::~FGMultiplayMgr()
220 //////////////////////////////////////////////////////////////////////
221
222 //////////////////////////////////////////////////////////////////////
223 //
224 //  Initialise object
225 //
226 //////////////////////////////////////////////////////////////////////
227 bool
228 FGMultiplayMgr::init (void) 
229 {
230   //////////////////////////////////////////////////
231   //  Initialise object if not already done
232   //////////////////////////////////////////////////
233   if (mInitialised) {
234     SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
235     return false;
236   }
237   //////////////////////////////////////////////////
238   //  Set members from property values
239   //////////////////////////////////////////////////
240   short rxPort = fgGetInt("/sim/multiplay/rxport");
241   string rxAddress = fgGetString("/sim/multiplay/rxhost");
242   short txPort = fgGetInt("/sim/multiplay/txport");
243   string txAddress = fgGetString("/sim/multiplay/txhost");
244   mCallsign = fgGetString("/sim/multiplay/callsign");
245   if (txPort > 0 && !txAddress.empty()) {
246     mServer.set(txAddress.c_str(), txPort);
247     if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
248       mHaveServer = false;
249       SG_LOG(SG_NETWORK, SG_ALERT,
250         "FGMultiplayMgr - could not resolve '"
251         << txAddress << "', Multiplayermode disabled");
252     } else {
253       mHaveServer = true;
254     }
255     if (rxPort <= 0)
256       rxPort = txPort;
257   }
258   if (rxPort <= 0) {
259     SG_LOG(SG_NETWORK, SG_ALERT,
260       "FGMultiplayMgr - No receiver port, Multiplayermode disabled");
261     return (false);
262   }
263   if (mCallsign.empty())
264     mCallsign = "JohnDoe"; // FIXME: use getpwuid
265   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
266   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
267   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
268   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
269   SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
270   Close(); // Should Init be called twice, close Socket first
271            // A memory leak was reported here by valgrind
272   mSocket = new netSocket();
273   if (!mSocket->open(false)) {
274     SG_LOG( SG_NETWORK, SG_ALERT,
275             "FGMultiplayMgr::init - Failed to create data socket" );
276     return false;
277   }
278   mSocket->setBlocking(false);
279   if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
280     perror("bind");
281     SG_LOG( SG_NETWORK, SG_ALERT,
282             "FGMultiplayMgr::Open - Failed to bind receive socket" );
283     return false;
284   }
285   mInitialised = true;
286   return true;
287 } // FGMultiplayMgr::init()
288 //////////////////////////////////////////////////////////////////////
289
290 //////////////////////////////////////////////////////////////////////
291 //
292 //  Closes and deletes the local player object. Closes
293 //  and deletes the tx socket. Resets the object state to unitialised.
294 //
295 //////////////////////////////////////////////////////////////////////
296 void
297 FGMultiplayMgr::Close (void) 
298 {
299   mMultiPlayerMap.clear();
300
301   if (mSocket) {
302     mSocket->close();
303     delete mSocket;
304     mSocket = 0;
305   }
306   mInitialised = false;
307 } // FGMultiplayMgr::Close(void)
308 //////////////////////////////////////////////////////////////////////
309
310 //////////////////////////////////////////////////////////////////////
311 //
312 //  Description: Sends the position data for the local position.
313 //
314 //////////////////////////////////////////////////////////////////////
315 void
316 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
317 {
318   if ((! mInitialised) || (! mHaveServer))
319         return;
320   if (! mHaveServer) {
321     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - no server");
322     return;
323   }
324
325   T_PositionMsg PosMsg;
326   strncpy(PosMsg.Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
327   PosMsg.Model[MAX_MODEL_NAME_LEN - 1] = '\0';
328   
329   PosMsg.time = XDR_encode_double (motionInfo.time);
330   PosMsg.lag = XDR_encode_double (motionInfo.lag);
331   for (unsigned i = 0 ; i < 3; ++i)
332     PosMsg.position[i] = XDR_encode_double (motionInfo.position(i));
333   SGVec3f angleAxis;
334   motionInfo.orientation.getAngleAxis(angleAxis);
335   for (unsigned i = 0 ; i < 3; ++i)
336     PosMsg.orientation[i] = XDR_encode_float (angleAxis(i));
337   for (unsigned i = 0 ; i < 3; ++i)
338     PosMsg.linearVel[i] = XDR_encode_float (motionInfo.linearVel(i));
339   for (unsigned i = 0 ; i < 3; ++i)
340     PosMsg.angularVel[i] = XDR_encode_float (motionInfo.angularVel(i));
341   for (unsigned i = 0 ; i < 3; ++i)
342     PosMsg.linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i));
343   for (unsigned i = 0 ; i < 3; ++i)
344     PosMsg.angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i));
345
346   char Msg[MAX_PACKET_SIZE];
347   memcpy(Msg + sizeof(T_MsgHdr), &PosMsg, sizeof(T_PositionMsg));
348   
349   char* ptr = Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg);
350   std::vector<FGPropertyData*>::const_iterator it;
351   it = motionInfo.properties.begin();
352   //cout << "OUTPUT PROPERTIES\n";
353   while (it != motionInfo.properties.end()
354          && ptr + 2 * sizeof(xdr_data_t) < (Msg + MAX_PACKET_SIZE)) {
355              
356     // First elements is the ID
357     xdr_data_t xdr = XDR_encode_uint32((*it)->id);
358     memcpy(ptr, &xdr, sizeof(xdr_data_t));
359     ptr += sizeof(xdr_data_t);
360     
361     // The actual data representation depends on the type
362     switch ((*it)->type) {
363       case SGPropertyNode::INT:        
364       case SGPropertyNode::BOOL:        
365       case SGPropertyNode::LONG:        
366         xdr = XDR_encode_uint32((*it)->int_value);
367         memcpy(ptr, &xdr, sizeof(xdr_data_t));
368         ptr += sizeof(xdr_data_t);
369         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
370         break;
371       case SGPropertyNode::FLOAT:
372       case SGPropertyNode::DOUBLE:
373         xdr = XDR_encode_float((*it)->float_value);;
374         memcpy(ptr, &xdr, sizeof(xdr_data_t));
375         ptr += sizeof(xdr_data_t);
376         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
377         break;
378       case SGPropertyNode::STRING:
379       case SGPropertyNode::UNSPECIFIED:
380         {
381           // String is complicated. It consists of
382           // The length of the string
383           // The string itself
384           // Padding to the nearest 4-bytes.        
385           const char* lcharptr = (*it)->string_value;
386           
387           if (lcharptr != 0)
388           {
389             // Add the length         
390             ////cout << "String length: " << strlen(lcharptr) << "\n";
391             uint32_t len = strlen(lcharptr);
392             // XXX This should not be using 4 bytes per character!
393             if (ptr + (1 + len + (4 - len % 4)) * sizeof (xdr_data_t)
394                 >= (Msg + MAX_PACKET_SIZE))
395                 goto escape;
396             //cout << "String length unint32: " << len << "\n";
397             xdr = XDR_encode_uint32(len);
398             memcpy(ptr, &xdr, sizeof(xdr_data_t));
399             ptr += sizeof(xdr_data_t);
400             
401             if (len != 0)
402             {
403
404               // Now the text itself
405               // XXX This should not be using 4 bytes per character!
406               int lcount = 0;
407               while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE)) 
408               {
409                 xdr = XDR_encode_int8(*lcharptr);
410                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
411                 ptr += sizeof(xdr_data_t);
412                 lcharptr++;
413                 lcount++;          
414               }
415
416               //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
417
418               // Now pad if required
419               while ((lcount % 4) != 0)
420               {
421                 xdr = XDR_encode_int8(0);
422                 memcpy(ptr, &xdr, sizeof(xdr_data_t));
423                 ptr += sizeof(xdr_data_t);
424                 lcount++;          
425                 //cout << "0";
426               }
427               
428               //cout << "\n";
429             }
430           }
431           else
432           {
433             // Nothing to encode
434             xdr = XDR_encode_uint32(0);
435             memcpy(ptr, &xdr, sizeof(xdr_data_t));
436             ptr += sizeof(xdr_data_t);
437             //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
438           }
439            
440         }
441         break;
442         
443       default:
444         //cout << " Unknown Type: " << (*it)->type << "\n";
445         xdr = XDR_encode_float((*it)->float_value);;
446         memcpy(ptr, &xdr, sizeof(xdr_data_t));
447         ptr += sizeof(xdr_data_t);
448         //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
449         break;
450     }
451         
452     ++it;
453   }
454 escape:
455   
456   T_MsgHdr MsgHdr;
457   FillMsgHdr(&MsgHdr, POS_DATA_ID, ptr - Msg);
458   memcpy(Msg, &MsgHdr, sizeof(T_MsgHdr));
459
460   mSocket->sendto(Msg, ptr - Msg, 0, &mServer);
461   SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
462 } // FGMultiplayMgr::SendMyPosition()
463 //////////////////////////////////////////////////////////////////////
464
465 //////////////////////////////////////////////////////////////////////
466 //
467 //  Name: SendTextMessage
468 //  Description: Sends a message to the player. The message must
469 //  contain a valid and correctly filled out header and optional
470 //  message body.
471 //
472 //////////////////////////////////////////////////////////////////////
473 void
474 FGMultiplayMgr::SendTextMessage(const string &MsgText)
475 {
476   if (!mInitialised || !mHaveServer)
477     return;
478
479   T_MsgHdr MsgHdr;
480   FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
481   //////////////////////////////////////////////////
482   // Divide the text string into blocks that fit
483   // in the message and send the blocks.
484   //////////////////////////////////////////////////
485   unsigned iNextBlockPosition = 0;
486   T_ChatMsg ChatMsg;
487   
488   char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
489   while (iNextBlockPosition < MsgText.length()) {
490     strncpy (ChatMsg.Text, 
491              MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
492              MAX_CHAT_MSG_LEN);
493     ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
494     memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
495     memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
496     mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
497     iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
498
499   }
500   
501   
502 } // FGMultiplayMgr::SendTextMessage ()
503 //////////////////////////////////////////////////////////////////////
504
505 //////////////////////////////////////////////////////////////////////
506 //
507 //  Name: ProcessData
508 //  Description: Processes data waiting at the receive socket. The
509 //  processing ends when there is no more data at the socket.
510 //  
511 //////////////////////////////////////////////////////////////////////
512 void
513 FGMultiplayMgr::Update(void) 
514 {
515   if (!mInitialised)
516     return;
517
518   /// Just for expiry
519   SGTimeStamp timestamper;
520   timestamper.stamp();
521   long stamp = timestamper.get_seconds();
522
523   //////////////////////////////////////////////////
524   //  Read the receive socket and process any data
525   //////////////////////////////////////////////////
526   int bytes;
527   do {
528     char Msg[MAX_PACKET_SIZE];
529     //////////////////////////////////////////////////
530     //  Although the recv call asks for 
531     //  MAX_PACKET_SIZE of data, the number of bytes
532     //  returned will only be that of the next
533     //  packet waiting to be processed.
534     //////////////////////////////////////////////////
535     netAddress SenderAddress;
536     bytes = mSocket->recvfrom(Msg, sizeof(Msg), 0, &SenderAddress);
537     //////////////////////////////////////////////////
538     //  no Data received
539     //////////////////////////////////////////////////
540     if (bytes <= 0) {
541       if (errno != EAGAIN && errno != 0) // MSVC output "NoError" otherwise
542         perror("FGMultiplayMgr::MP_ProcessData");
543       break;
544     }
545     if (bytes <= sizeof(T_MsgHdr)) {
546       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
547               << "received message with insufficient data" );
548       break;
549     }
550     //////////////////////////////////////////////////
551     //  Read header
552     //////////////////////////////////////////////////
553     T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
554     MsgHdr->Magic       = XDR_decode_uint32 (MsgHdr->Magic);
555     MsgHdr->Version     = XDR_decode_uint32 (MsgHdr->Version);
556     MsgHdr->MsgId       = XDR_decode_uint32 (MsgHdr->MsgId);
557     MsgHdr->MsgLen      = XDR_decode_uint32 (MsgHdr->MsgLen);
558     MsgHdr->ReplyPort   = XDR_decode_uint32 (MsgHdr->ReplyPort);
559     if (MsgHdr->Magic != MSG_MAGIC) {
560       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
561               << "message has invalid magic number!" );
562       break;
563     }
564     if (MsgHdr->Version != PROTO_VER) {
565       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
566               << "message has invalid protocoll number!" );
567       break;
568     }
569     if (MsgHdr->MsgLen != bytes) {
570       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
571               << "message has invalid length!" );
572       break;
573     }
574     //////////////////////////////////////////////////
575     //  Process messages
576     //////////////////////////////////////////////////
577     switch (MsgHdr->MsgId) {
578     case CHAT_MSG_ID:
579       ProcessChatMsg(Msg, SenderAddress);
580       break;
581     case POS_DATA_ID:
582       ProcessPosMsg(Msg, SenderAddress, bytes, stamp);
583       break;
584     case UNUSABLE_POS_DATA_ID:
585     case OLD_OLD_POS_DATA_ID:
586     case OLD_PROP_MSG_ID:
587     case OLD_POS_DATA_ID:
588       break;
589     default:
590       SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
591               << "Unknown message Id received: " << MsgHdr->MsgId );
592       break;
593     }
594   } while (bytes > 0);
595
596   // check for expiry
597   MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
598   while (it != mMultiPlayerMap.end()) {
599     if (it->second->getLastTimestamp() + 10 < stamp) {
600       std::string name = it->first;
601       it->second->setDie(true);
602       mMultiPlayerMap.erase(it);
603       it = mMultiPlayerMap.upper_bound(name);
604     } else
605       ++it;
606   }
607 } // FGMultiplayMgr::ProcessData(void)
608 //////////////////////////////////////////////////////////////////////
609
610 //////////////////////////////////////////////////////////////////////
611 //
612 //  handle a position message
613 //
614 //////////////////////////////////////////////////////////////////////
615 void
616 FGMultiplayMgr::ProcessPosMsg(const char *Msg, netAddress & SenderAddress,
617                               unsigned len, long stamp)
618 {
619   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
620   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
621     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
622             << "Position message received with insufficient data" );
623     return;
624   }
625   T_PositionMsg* PosMsg = (T_PositionMsg *)(Msg + sizeof(T_MsgHdr));
626   FGExternalMotionData motionInfo;
627   motionInfo.time = XDR_decode_double(PosMsg->time);
628   motionInfo.lag = XDR_decode_double(PosMsg->lag);
629   for (unsigned i = 0; i < 3; ++i)
630     motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
631   SGVec3f angleAxis;
632   for (unsigned i = 0; i < 3; ++i)
633     angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
634   motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
635   for (unsigned i = 0; i < 3; ++i)
636     motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
637   for (unsigned i = 0; i < 3; ++i)
638     motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
639   for (unsigned i = 0; i < 3; ++i)
640     motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
641   for (unsigned i = 0; i < 3; ++i)
642     motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
643
644
645   //cout << "INPUT MESSAGE\n";
646   xdr_data_t* xdr = (xdr_data_t*) 
647                    (Msg + sizeof(T_MsgHdr) + sizeof(T_PositionMsg));
648   while ((char*)xdr < Msg + len) {
649     FGPropertyData* pData = new FGPropertyData;
650     SGPropertyNode::Type type = SGPropertyNode::UNSPECIFIED;
651     
652     // First element is always the ID
653     pData->id = XDR_decode_uint32(*xdr);
654     //cout << pData->id << " ";
655     xdr++;
656     
657     // Check the ID actually exists and get the type
658     unsigned i = 0;
659     bool found = false;
660     while (FGMultiplayMgr::sIdPropertyList[i].name) 
661     {
662       if (sIdPropertyList[i].id == pData->id)
663       {
664         found = true;
665         pData->type = sIdPropertyList[i].type;
666       } 
667       
668       i++;
669     }
670     
671     if (found == true)
672     {
673       // How we decode the remainder of the property depends on the type
674       switch (pData->type) {
675         case SGPropertyNode::INT:        
676         case SGPropertyNode::BOOL:
677         case SGPropertyNode::LONG:        
678           pData->int_value = XDR_decode_uint32(*xdr);
679           xdr++;
680           //cout << pData->int_value << "\n";
681           break;
682         case SGPropertyNode::FLOAT:
683         case SGPropertyNode::DOUBLE:
684           pData->float_value = XDR_decode_float(*xdr);
685           xdr++;
686           //cout << pData->float_value << "\n";
687           break;
688         case SGPropertyNode::STRING:
689         case SGPropertyNode::UNSPECIFIED:
690           {
691             // String is complicated. It consists of
692             // The length of the string
693             // The string itself
694             // Padding to the nearest 4-bytes.    
695             uint32_t length = XDR_decode_uint32(*xdr);
696             xdr++;
697             //cout << length << " ";
698
699             if ((length > 0) && (length < MAX_TEXT_SIZE))
700             {
701               pData->string_value = new char[length + 1];
702               //cout << " String: ";
703
704               for (int i = 0; i < length; i++)
705               {
706                 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
707                 xdr++;
708                 //cout << pData->string_value[i];
709               }
710
711               pData->string_value[length] = '\0';
712
713               // Now handle the padding
714               while ((length % 4) != 0)
715               {
716                 xdr++;
717                 length++;
718                 //cout << "0";
719               }
720             }
721             else
722             {
723               pData->string_value = new char[1];
724               pData->string_value[0] = '\0';
725             }
726
727             //cout << "\n";
728           }
729           break;
730
731         default:
732           pData->float_value = XDR_decode_float(*xdr);
733           cerr << "Unknown Prop type " << pData->id << " " << pData->type << "\n";
734           xdr++;
735           break;
736       }            
737
738       motionInfo.properties.push_back(pData);
739     }
740     else
741     {
742       // We failed to find the property. We'll try the next packet immediately.
743       //cout << " Unknown\n";
744     }
745   }
746   
747   FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
748   if (!mp)
749     mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
750   mp->addMotionInfo(motionInfo, stamp);
751 } // FGMultiplayMgr::ProcessPosMsg()
752 //////////////////////////////////////////////////////////////////////
753
754 //////////////////////////////////////////////////////////////////////
755 //
756 //  handle a chat message
757 //  FIXME: display chat message withi flightgear
758 //
759 //////////////////////////////////////////////////////////////////////
760 void
761 FGMultiplayMgr::ProcessChatMsg(const char *Msg, netAddress& SenderAddress)
762 {
763   T_MsgHdr* MsgHdr = (T_MsgHdr *)Msg;
764   if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
765     SG_LOG( SG_NETWORK, SG_ALERT, "FGMultiplayMgr::MP_ProcessData - "
766             << "Chat message received with insufficient data" );
767     return;
768   }
769   
770   char *MsgBuf = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
771   strncpy(MsgBuf, ((T_ChatMsg *)(Msg + sizeof(T_MsgHdr)))->Text,
772           MsgHdr->MsgLen - sizeof(T_MsgHdr));
773   MsgBuf[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
774   
775   T_ChatMsg* ChatMsg = (T_ChatMsg *)(Msg + sizeof(T_MsgHdr));
776   SG_LOG (SG_NETWORK, SG_ALERT, "Chat [" << MsgHdr->Callsign << "]"
777            << " " << MsgBuf);
778
779   delete [] MsgBuf;
780 } // FGMultiplayMgr::ProcessChatMsg ()
781 //////////////////////////////////////////////////////////////////////
782
783 void
784 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
785 {
786   uint32_t len;
787   switch (MsgId) {
788   case CHAT_MSG_ID:
789     len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
790     break;
791   case POS_DATA_ID:
792     len = _len;
793     break;
794   default:
795     len = sizeof(T_MsgHdr);
796     break;
797   }
798   MsgHdr->Magic           = XDR_encode_uint32(MSG_MAGIC);
799   MsgHdr->Version         = XDR_encode_uint32(PROTO_VER);
800   MsgHdr->MsgId           = XDR_encode_uint32(MsgId);
801   MsgHdr->MsgLen          = XDR_encode_uint32(len);
802   MsgHdr->ReplyAddress    = 0; // Are obsolete, keep them for the server for
803   MsgHdr->ReplyPort       = 0; // now
804   strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
805   MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
806 }
807
808 FGAIMultiplayer*
809 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
810                                const std::string& modelName)
811 {
812   if (0 < mMultiPlayerMap.count(callsign))
813     return mMultiPlayerMap[callsign].get();
814
815   FGAIMultiplayer* mp = new FGAIMultiplayer;
816   mp->setPath(modelName.c_str());
817   mp->setCallSign(callsign);
818   mMultiPlayerMap[callsign] = mp;
819
820   FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai_model");
821   if (aiMgr) {
822     aiMgr->attach(mp);
823
824     /// FIXME: that must follow the attach ATM ...
825     unsigned i = 0;
826     while (sIdPropertyList[i].name) {
827       mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
828       ++i;
829     }
830   }
831
832   return mp;
833 }
834
835 FGAIMultiplayer*
836 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
837 {
838   if (0 < mMultiPlayerMap.count(callsign))
839     return mMultiPlayerMap[callsign].get();
840   else
841     return 0;
842 }