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