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