1 //////////////////////////////////////////////////////////////////////
5 // Written by Duncan McCreanor, started February 2003.
6 // duncan.mccreanor@airservicesaustralia.com
8 // Copyright (C) 2003 Airservices Australia
9 // Copyright (C) 2005 Oliver Schroeder
10 // Copyright (C) 2006 Mathias Froehlich
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.
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.
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.
28 //////////////////////////////////////////////////////////////////////
39 #include <simgear/misc/stdint.hxx>
40 #include <simgear/timing/timestamp.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/props/props.hxx>
43 #include <simgear/structure/commands.hxx>
45 #include <AIModel/AIManager.hxx>
46 #include <AIModel/AIMultiplayer.hxx>
47 #include <Main/fg_props.hxx>
48 #include <Network/RemoteXMLRequest.hxx>
49 #include <Network/HTTPClient.hxx>
50 #include "multiplaymgr.hxx"
51 #include "mpmessages.hxx"
52 #include <FDM/flightProperties.hxx>
56 #define MAX_PACKET_SIZE 1200
57 #define MAX_TEXT_SIZE 128
59 struct IdPropertyList {
62 simgear::props::Type type;
65 static const IdPropertyList* findProperty(unsigned id);
67 // A static map of protocol property id values to property paths,
68 // This should be extendable dynamically for every specific aircraft ...
69 // For now only that static list
70 static const IdPropertyList sIdPropertyList[] = {
71 {100, "surface-positions/left-aileron-pos-norm", simgear::props::FLOAT},
72 {101, "surface-positions/right-aileron-pos-norm", simgear::props::FLOAT},
73 {102, "surface-positions/elevator-pos-norm", simgear::props::FLOAT},
74 {103, "surface-positions/rudder-pos-norm", simgear::props::FLOAT},
75 {104, "surface-positions/flap-pos-norm", simgear::props::FLOAT},
76 {105, "surface-positions/speedbrake-pos-norm", simgear::props::FLOAT},
77 {106, "gear/tailhook/position-norm", simgear::props::FLOAT},
78 {107, "gear/launchbar/position-norm", simgear::props::FLOAT},
79 {108, "gear/launchbar/state", simgear::props::STRING},
80 {109, "gear/launchbar/holdback-position-norm", simgear::props::FLOAT},
81 {110, "canopy/position-norm", simgear::props::FLOAT},
82 {111, "surface-positions/wing-pos-norm", simgear::props::FLOAT},
83 {112, "surface-positions/wing-fold-pos-norm", simgear::props::FLOAT},
85 {200, "gear/gear[0]/compression-norm", simgear::props::FLOAT},
86 {201, "gear/gear[0]/position-norm", simgear::props::FLOAT},
87 {210, "gear/gear[1]/compression-norm", simgear::props::FLOAT},
88 {211, "gear/gear[1]/position-norm", simgear::props::FLOAT},
89 {220, "gear/gear[2]/compression-norm", simgear::props::FLOAT},
90 {221, "gear/gear[2]/position-norm", simgear::props::FLOAT},
91 {230, "gear/gear[3]/compression-norm", simgear::props::FLOAT},
92 {231, "gear/gear[3]/position-norm", simgear::props::FLOAT},
93 {240, "gear/gear[4]/compression-norm", simgear::props::FLOAT},
94 {241, "gear/gear[4]/position-norm", simgear::props::FLOAT},
96 {300, "engines/engine[0]/n1", simgear::props::FLOAT},
97 {301, "engines/engine[0]/n2", simgear::props::FLOAT},
98 {302, "engines/engine[0]/rpm", simgear::props::FLOAT},
99 {310, "engines/engine[1]/n1", simgear::props::FLOAT},
100 {311, "engines/engine[1]/n2", simgear::props::FLOAT},
101 {312, "engines/engine[1]/rpm", simgear::props::FLOAT},
102 {320, "engines/engine[2]/n1", simgear::props::FLOAT},
103 {321, "engines/engine[2]/n2", simgear::props::FLOAT},
104 {322, "engines/engine[2]/rpm", simgear::props::FLOAT},
105 {330, "engines/engine[3]/n1", simgear::props::FLOAT},
106 {331, "engines/engine[3]/n2", simgear::props::FLOAT},
107 {332, "engines/engine[3]/rpm", simgear::props::FLOAT},
108 {340, "engines/engine[4]/n1", simgear::props::FLOAT},
109 {341, "engines/engine[4]/n2", simgear::props::FLOAT},
110 {342, "engines/engine[4]/rpm", simgear::props::FLOAT},
111 {350, "engines/engine[5]/n1", simgear::props::FLOAT},
112 {351, "engines/engine[5]/n2", simgear::props::FLOAT},
113 {352, "engines/engine[5]/rpm", simgear::props::FLOAT},
114 {360, "engines/engine[6]/n1", simgear::props::FLOAT},
115 {361, "engines/engine[6]/n2", simgear::props::FLOAT},
116 {362, "engines/engine[6]/rpm", simgear::props::FLOAT},
117 {370, "engines/engine[7]/n1", simgear::props::FLOAT},
118 {371, "engines/engine[7]/n2", simgear::props::FLOAT},
119 {372, "engines/engine[7]/rpm", simgear::props::FLOAT},
120 {380, "engines/engine[8]/n1", simgear::props::FLOAT},
121 {381, "engines/engine[8]/n2", simgear::props::FLOAT},
122 {382, "engines/engine[8]/rpm", simgear::props::FLOAT},
123 {390, "engines/engine[9]/n1", simgear::props::FLOAT},
124 {391, "engines/engine[9]/n2", simgear::props::FLOAT},
125 {392, "engines/engine[9]/rpm", simgear::props::FLOAT},
127 {800, "rotors/main/rpm", simgear::props::FLOAT},
128 {801, "rotors/tail/rpm", simgear::props::FLOAT},
129 {810, "rotors/main/blade[0]/position-deg", simgear::props::FLOAT},
130 {811, "rotors/main/blade[1]/position-deg", simgear::props::FLOAT},
131 {812, "rotors/main/blade[2]/position-deg", simgear::props::FLOAT},
132 {813, "rotors/main/blade[3]/position-deg", simgear::props::FLOAT},
133 {820, "rotors/main/blade[0]/flap-deg", simgear::props::FLOAT},
134 {821, "rotors/main/blade[1]/flap-deg", simgear::props::FLOAT},
135 {822, "rotors/main/blade[2]/flap-deg", simgear::props::FLOAT},
136 {823, "rotors/main/blade[3]/flap-deg", simgear::props::FLOAT},
137 {830, "rotors/tail/blade[0]/position-deg", simgear::props::FLOAT},
138 {831, "rotors/tail/blade[1]/position-deg", simgear::props::FLOAT},
140 {900, "sim/hitches/aerotow/tow/length", simgear::props::FLOAT},
141 {901, "sim/hitches/aerotow/tow/elastic-constant", simgear::props::FLOAT},
142 {902, "sim/hitches/aerotow/tow/weight-per-m-kg-m", simgear::props::FLOAT},
143 {903, "sim/hitches/aerotow/tow/dist", simgear::props::FLOAT},
144 {904, "sim/hitches/aerotow/tow/connected-to-property-node", simgear::props::BOOL},
145 {905, "sim/hitches/aerotow/tow/connected-to-ai-or-mp-callsign", simgear::props::STRING},
146 {906, "sim/hitches/aerotow/tow/brake-force", simgear::props::FLOAT},
147 {907, "sim/hitches/aerotow/tow/end-force-x", simgear::props::FLOAT},
148 {908, "sim/hitches/aerotow/tow/end-force-y", simgear::props::FLOAT},
149 {909, "sim/hitches/aerotow/tow/end-force-z", simgear::props::FLOAT},
150 {930, "sim/hitches/aerotow/is-slave", simgear::props::BOOL},
151 {931, "sim/hitches/aerotow/speed-in-tow-direction", simgear::props::FLOAT},
152 {932, "sim/hitches/aerotow/open", simgear::props::BOOL},
153 {933, "sim/hitches/aerotow/local-pos-x", simgear::props::FLOAT},
154 {934, "sim/hitches/aerotow/local-pos-y", simgear::props::FLOAT},
155 {935, "sim/hitches/aerotow/local-pos-z", simgear::props::FLOAT},
157 {1001, "controls/flight/slats", simgear::props::FLOAT},
158 {1002, "controls/flight/speedbrake", simgear::props::FLOAT},
159 {1003, "controls/flight/spoilers", simgear::props::FLOAT},
160 {1004, "controls/gear/gear-down", simgear::props::FLOAT},
161 {1005, "controls/lighting/nav-lights", simgear::props::FLOAT},
162 {1006, "controls/armament/station[0]/jettison-all", simgear::props::BOOL},
164 {1100, "sim/model/variant", simgear::props::INT},
165 {1101, "sim/model/livery/file", simgear::props::STRING},
167 {1200, "environment/wildfire/data", simgear::props::STRING},
168 {1201, "environment/contrail", simgear::props::INT},
170 {1300, "tanker", simgear::props::INT},
172 {1400, "scenery/events", simgear::props::STRING},
174 {1500, "instrumentation/transponder/transmitted-id", simgear::props::INT},
175 {1501, "instrumentation/transponder/altitude", simgear::props::INT},
176 {1502, "instrumentation/transponder/ident", simgear::props::BOOL},
177 {1503, "instrumentation/transponder/inputs/mode", simgear::props::INT},
179 {10001, "sim/multiplay/transmission-freq-hz", simgear::props::STRING},
180 {10002, "sim/multiplay/chat", simgear::props::STRING},
182 {10100, "sim/multiplay/generic/string[0]", simgear::props::STRING},
183 {10101, "sim/multiplay/generic/string[1]", simgear::props::STRING},
184 {10102, "sim/multiplay/generic/string[2]", simgear::props::STRING},
185 {10103, "sim/multiplay/generic/string[3]", simgear::props::STRING},
186 {10104, "sim/multiplay/generic/string[4]", simgear::props::STRING},
187 {10105, "sim/multiplay/generic/string[5]", simgear::props::STRING},
188 {10106, "sim/multiplay/generic/string[6]", simgear::props::STRING},
189 {10107, "sim/multiplay/generic/string[7]", simgear::props::STRING},
190 {10108, "sim/multiplay/generic/string[8]", simgear::props::STRING},
191 {10109, "sim/multiplay/generic/string[9]", simgear::props::STRING},
192 {10110, "sim/multiplay/generic/string[10]", simgear::props::STRING},
193 {10111, "sim/multiplay/generic/string[11]", simgear::props::STRING},
194 {10112, "sim/multiplay/generic/string[12]", simgear::props::STRING},
195 {10113, "sim/multiplay/generic/string[13]", simgear::props::STRING},
196 {10114, "sim/multiplay/generic/string[14]", simgear::props::STRING},
197 {10115, "sim/multiplay/generic/string[15]", simgear::props::STRING},
198 {10116, "sim/multiplay/generic/string[16]", simgear::props::STRING},
199 {10117, "sim/multiplay/generic/string[17]", simgear::props::STRING},
200 {10118, "sim/multiplay/generic/string[18]", simgear::props::STRING},
201 {10119, "sim/multiplay/generic/string[19]", simgear::props::STRING},
203 {10200, "sim/multiplay/generic/float[0]", simgear::props::FLOAT},
204 {10201, "sim/multiplay/generic/float[1]", simgear::props::FLOAT},
205 {10202, "sim/multiplay/generic/float[2]", simgear::props::FLOAT},
206 {10203, "sim/multiplay/generic/float[3]", simgear::props::FLOAT},
207 {10204, "sim/multiplay/generic/float[4]", simgear::props::FLOAT},
208 {10205, "sim/multiplay/generic/float[5]", simgear::props::FLOAT},
209 {10206, "sim/multiplay/generic/float[6]", simgear::props::FLOAT},
210 {10207, "sim/multiplay/generic/float[7]", simgear::props::FLOAT},
211 {10208, "sim/multiplay/generic/float[8]", simgear::props::FLOAT},
212 {10209, "sim/multiplay/generic/float[9]", simgear::props::FLOAT},
213 {10210, "sim/multiplay/generic/float[10]", simgear::props::FLOAT},
214 {10211, "sim/multiplay/generic/float[11]", simgear::props::FLOAT},
215 {10212, "sim/multiplay/generic/float[12]", simgear::props::FLOAT},
216 {10213, "sim/multiplay/generic/float[13]", simgear::props::FLOAT},
217 {10214, "sim/multiplay/generic/float[14]", simgear::props::FLOAT},
218 {10215, "sim/multiplay/generic/float[15]", simgear::props::FLOAT},
219 {10216, "sim/multiplay/generic/float[16]", simgear::props::FLOAT},
220 {10217, "sim/multiplay/generic/float[17]", simgear::props::FLOAT},
221 {10218, "sim/multiplay/generic/float[18]", simgear::props::FLOAT},
222 {10219, "sim/multiplay/generic/float[19]", simgear::props::FLOAT},
224 {10300, "sim/multiplay/generic/int[0]", simgear::props::INT},
225 {10301, "sim/multiplay/generic/int[1]", simgear::props::INT},
226 {10302, "sim/multiplay/generic/int[2]", simgear::props::INT},
227 {10303, "sim/multiplay/generic/int[3]", simgear::props::INT},
228 {10304, "sim/multiplay/generic/int[4]", simgear::props::INT},
229 {10305, "sim/multiplay/generic/int[5]", simgear::props::INT},
230 {10306, "sim/multiplay/generic/int[6]", simgear::props::INT},
231 {10307, "sim/multiplay/generic/int[7]", simgear::props::INT},
232 {10308, "sim/multiplay/generic/int[8]", simgear::props::INT},
233 {10309, "sim/multiplay/generic/int[9]", simgear::props::INT},
234 {10310, "sim/multiplay/generic/int[10]", simgear::props::INT},
235 {10311, "sim/multiplay/generic/int[11]", simgear::props::INT},
236 {10312, "sim/multiplay/generic/int[12]", simgear::props::INT},
237 {10313, "sim/multiplay/generic/int[13]", simgear::props::INT},
238 {10314, "sim/multiplay/generic/int[14]", simgear::props::INT},
239 {10315, "sim/multiplay/generic/int[15]", simgear::props::INT},
240 {10316, "sim/multiplay/generic/int[16]", simgear::props::INT},
241 {10317, "sim/multiplay/generic/int[17]", simgear::props::INT},
242 {10318, "sim/multiplay/generic/int[18]", simgear::props::INT},
243 {10319, "sim/multiplay/generic/int[19]", simgear::props::INT}
246 const unsigned int numProperties = (sizeof(sIdPropertyList)
247 / sizeof(sIdPropertyList[0]));
249 // Look up a property ID using binary search.
252 struct ComparePropertyId
254 bool operator()(const IdPropertyList& lhs,
255 const IdPropertyList& rhs)
257 return lhs.id < rhs.id;
259 bool operator()(const IdPropertyList& lhs,
264 bool operator()(unsigned id,
265 const IdPropertyList& rhs)
272 const IdPropertyList* findProperty(unsigned id)
274 std::pair<const IdPropertyList*, const IdPropertyList*> result
275 = std::equal_range(sIdPropertyList, sIdPropertyList + numProperties, id,
276 ComparePropertyId());
277 if (result.first == result.second) {
286 bool verifyProperties(const xdr_data_t* data, const xdr_data_t* end)
288 using namespace simgear;
289 const xdr_data_t* xdr = data;
291 unsigned id = XDR_decode_uint32(*xdr);
292 const IdPropertyList* plist = findProperty(id);
296 // How we decode the remainder of the property depends on the type
297 switch (plist->type) {
306 float val = XDR_decode_float(*xdr);
307 if (SGMisc<float>::isNaN(val))
313 case props::UNSPECIFIED:
315 // String is complicated. It consists of
316 // The length of the string
318 // Padding to the nearest 4-bytes.
319 // XXX Yes, each byte is padded out to a word! Too late
321 uint32_t length = XDR_decode_uint32(*xdr);
323 // Old versions truncated the string but left the length
325 if (length > MAX_TEXT_SIZE)
326 length = MAX_TEXT_SIZE;
328 // Now handle the padding
329 while ((length % 4) != 0)
338 // cerr << "Unknown Prop type " << id << " " << type << "\n";
344 // give up; this is a malformed property list.
352 class MPPropertyListener : public SGPropertyChangeListener
355 MPPropertyListener(FGMultiplayMgr* mp) :
360 virtual void childAdded(SGPropertyNode*, SGPropertyNode*)
362 _multiplay->setPropertiesChanged();
366 FGMultiplayMgr* _multiplay;
369 //////////////////////////////////////////////////////////////////////
371 // handle command "multiplayer-connect"
373 // server: servername to connect (mandatory)
374 // txport: outgoing port number (default: 5000)
375 // rxport: incoming port number (default: 5000)
376 //////////////////////////////////////////////////////////////////////
377 static bool do_multiplayer_connect(const SGPropertyNode * arg) {
378 FGMultiplayMgr * self = (FGMultiplayMgr*) globals->get_subsystem("mp");
380 SG_LOG(SG_NETWORK, SG_WARN, "Multiplayer subsystem not available.");
384 string servername = arg->getStringValue("servername", "");
385 if (servername.empty()) {
386 SG_LOG(SG_NETWORK, SG_WARN,
387 "do_multiplayer.connect: no server name given, command ignored.");
390 int port = arg->getIntValue("rxport", -1);
391 if (port > 0 && port <= 0xffff) {
392 fgSetInt("/sim/multiplay/rxport", port);
395 port = arg->getIntValue("txport", -1);
396 if (port > 0 && port <= 0xffff) {
397 fgSetInt("/sim/multiplay/txport", port);
400 servername = servername.substr(0, servername.find_first_of(' '));
401 fgSetString("/sim/multiplay/txhost", servername);
406 //////////////////////////////////////////////////////////////////////
408 // handle command "multiplayer-disconnect"
411 //////////////////////////////////////////////////////////////////////
412 static bool do_multiplayer_disconnect(const SGPropertyNode * arg) {
413 FGMultiplayMgr * self = (FGMultiplayMgr*) globals->get_subsystem("mp");
415 SG_LOG(SG_NETWORK, SG_WARN, "Multiplayer subsystem not available.");
419 fgSetString("/sim/multiplay/txhost", "");
424 //////////////////////////////////////////////////////////////////////
426 // handle command "multiplayer-refreshserverlist"
427 // refreshserverlist args:
430 //////////////////////////////////////////////////////////////////////
431 static bool do_multiplayer_refreshserverlist(const SGPropertyNode * arg) {
432 FGMultiplayMgr * self = (FGMultiplayMgr*) globals->get_subsystem("mp");
434 SG_LOG(SG_NETWORK, SG_WARN, "Multiplayer subsystem not available.");
438 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
440 SG_LOG(SG_IO, SG_ALERT,
441 "do_multiplayer.refreshserverlist: HTTP client not running");
446 fgGetString("/sim/multiplay/serverlist-url",
447 "http://liveries.flightgear.org/mpstatus/mpservers.xml"));
450 SG_LOG(SG_IO, SG_ALERT,
451 "do_multiplayer.refreshserverlist: no URL given");
455 SGPropertyNode *targetnode = fgGetNode("/sim/multiplay/server-list", true);
456 SGPropertyNode *completeNode = fgGetNode("/sim/multiplay/got-servers", true);
457 SGPropertyNode *failureNode = fgGetNode("/sim/multiplay/get-servers-failure", true);
458 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
459 req->setCompletionProp(completeNode);
460 req->setFailedProp(failureNode);
461 completeNode->setBoolValue(false);
462 failureNode->setBoolValue(false);
463 http->makeRequest(req);
467 //////////////////////////////////////////////////////////////////////
469 // MultiplayMgr constructor
471 //////////////////////////////////////////////////////////////////////
472 FGMultiplayMgr::FGMultiplayMgr()
474 mInitialised = false;
477 globals->get_commands()->addCommand("multiplayer-connect", do_multiplayer_connect);
478 globals->get_commands()->addCommand("multiplayer-disconnect", do_multiplayer_disconnect);
479 globals->get_commands()->addCommand("multiplayer-refreshserverlist", do_multiplayer_refreshserverlist);
480 } // FGMultiplayMgr::FGMultiplayMgr()
481 //////////////////////////////////////////////////////////////////////
483 //////////////////////////////////////////////////////////////////////
485 // MultiplayMgr destructor
487 //////////////////////////////////////////////////////////////////////
488 FGMultiplayMgr::~FGMultiplayMgr()
490 globals->get_commands()->removeCommand("multiplayer-connect");
491 globals->get_commands()->removeCommand("multiplayer-disconnect");
492 globals->get_commands()->removeCommand("multiplayer-refreshserverlist");
493 } // FGMultiplayMgr::~FGMultiplayMgr()
494 //////////////////////////////////////////////////////////////////////
496 //////////////////////////////////////////////////////////////////////
500 //////////////////////////////////////////////////////////////////////
502 FGMultiplayMgr::init (void)
504 //////////////////////////////////////////////////
505 // Initialise object if not already done
506 //////////////////////////////////////////////////
508 SG_LOG(SG_NETWORK, SG_WARN, "FGMultiplayMgr::init - already initialised");
512 SGPropertyNode* propOnline = fgGetNode("/sim/multiplay/online", true);
513 propOnline->setBoolValue(false);
514 propOnline->setAttribute(SGPropertyNode::PRESERVE, true);
516 //////////////////////////////////////////////////
517 // Set members from property values
518 //////////////////////////////////////////////////
519 short rxPort = fgGetInt("/sim/multiplay/rxport");
520 string rxAddress = fgGetString("/sim/multiplay/rxhost");
521 short txPort = fgGetInt("/sim/multiplay/txport", 5000);
522 string txAddress = fgGetString("/sim/multiplay/txhost");
524 int hz = fgGetInt("/sim/multiplay/tx-rate-hz", 10);
530 mTimeUntilSend = 0.0;
532 mCallsign = fgGetString("/sim/multiplay/callsign");
533 fgGetNode("/sim/multiplay/callsign", true)->setAttribute(SGPropertyNode::PRESERVE, true);
535 if ((!txAddress.empty()) && (txAddress!="0")) {
536 mServer.set(txAddress.c_str(), txPort);
537 if (strncmp (mServer.getHost(), "0.0.0.0", 8) == 0) {
539 SG_LOG(SG_NETWORK, SG_ALERT,
540 "Cannot enable multiplayer mode: resolving MP server address '"
541 << txAddress << "' failed.");
544 SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - have server");
550 SG_LOG(SG_NETWORK, SG_INFO, "FGMultiplayMgr - multiplayer mode disabled (no MP server specificed).");
555 SG_LOG(SG_NETWORK, SG_ALERT,
556 "Cannot enable multiplayer mode: No receiver port specified.");
559 if (mCallsign.empty())
560 mCallsign = "JohnDoe"; // FIXME: use getpwuid
561 SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txaddress= "<<txAddress);
562 SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-txport= "<<txPort );
563 SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxaddress="<<rxAddress );
564 SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-rxport= "<<rxPort);
565 SG_LOG(SG_NETWORK,SG_INFO,"FGMultiplayMgr::init-callsign= "<<mCallsign);
567 mSocket.reset(new simgear::Socket());
568 if (!mSocket->open(false)) {
569 SG_LOG( SG_NETWORK, SG_ALERT,
570 "Cannot enable multiplayer mode: creating data socket failed." );
573 mSocket->setBlocking(false);
574 if (mSocket->bind(rxAddress.c_str(), rxPort) != 0) {
575 SG_LOG( SG_NETWORK, SG_ALERT,
576 "Cannot enable multiplayer mode: binding receive socket failed. "
577 << strerror(errno) << "(errno " << errno << ")");
581 mPropertiesChanged = true;
582 mListener = new MPPropertyListener(this);
583 globals->get_props()->addChangeListener(mListener, false);
585 fgSetBool("/sim/multiplay/online", true);
588 SG_LOG(SG_NETWORK, SG_ALERT, "Multiplayer mode active!");
590 if (!fgGetBool("/sim/ai/enabled"))
592 // multiplayer depends on AI module
593 fgSetBool("/sim/ai/enabled", true);
595 } // FGMultiplayMgr::init()
596 //////////////////////////////////////////////////////////////////////
598 //////////////////////////////////////////////////////////////////////
600 // Closes and deletes the local player object. Closes
601 // and deletes the tx socket. Resets the object state to unitialised.
603 //////////////////////////////////////////////////////////////////////
605 FGMultiplayMgr::shutdown (void)
607 fgSetBool("/sim/multiplay/online", false);
614 MultiPlayerMap::iterator it = mMultiPlayerMap.begin(),
615 end = mMultiPlayerMap.end();
616 for (; it != end; ++it) {
617 it->second->setDie(true);
619 mMultiPlayerMap.clear();
622 globals->get_props()->removeChangeListener(mListener);
627 mInitialised = false;
628 } // FGMultiplayMgr::Close(void)
629 //////////////////////////////////////////////////////////////////////
632 FGMultiplayMgr::reinit()
638 //////////////////////////////////////////////////////////////////////
640 // Description: Sends the position data for the local position.
642 //////////////////////////////////////////////////////////////////////
645 * The buffer that holds a multi-player message, suitably aligned.
647 union FGMultiplayMgr::MsgBuf
651 memset(&Msg, 0, sizeof(Msg));
659 const T_MsgHdr* msgHdr() const
661 return reinterpret_cast<const T_MsgHdr*>(&Header);
664 T_PositionMsg* posMsg()
666 return reinterpret_cast<T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
669 const T_PositionMsg* posMsg() const
671 return reinterpret_cast<const T_PositionMsg*>(Msg + sizeof(T_MsgHdr));
674 xdr_data_t* properties()
676 return reinterpret_cast<xdr_data_t*>(Msg + sizeof(T_MsgHdr)
677 + sizeof(T_PositionMsg));
680 const xdr_data_t* properties() const
682 return reinterpret_cast<const xdr_data_t*>(Msg + sizeof(T_MsgHdr)
683 + sizeof(T_PositionMsg));
686 * The end of the properties buffer.
688 xdr_data_t* propsEnd()
690 return reinterpret_cast<xdr_data_t*>(Msg + MAX_PACKET_SIZE);
693 const xdr_data_t* propsEnd() const
695 return reinterpret_cast<const xdr_data_t*>(Msg + MAX_PACKET_SIZE);
698 * The end of properties actually in the buffer. This assumes that
699 * the message header is valid.
701 xdr_data_t* propsRecvdEnd()
703 return reinterpret_cast<xdr_data_t*>(Msg + Header.MsgLen);
706 const xdr_data_t* propsRecvdEnd() const
708 return reinterpret_cast<const xdr_data_t*>(Msg + Header.MsgLen);
711 xdr_data2_t double_val;
712 char Msg[MAX_PACKET_SIZE];
717 FGMultiplayMgr::isSane(const FGExternalMotionData& motionInfo)
719 // check for corrupted data (NaNs)
720 bool isCorrupted = false;
721 isCorrupted |= ((SGMisc<double>::isNaN(motionInfo.time )) ||
722 (SGMisc<double>::isNaN(motionInfo.lag )) ||
723 (osg::isNaN(motionInfo.orientation(3) )));
724 for (unsigned i = 0; (i < 3)&&(!isCorrupted); ++i)
726 isCorrupted |= ((osg::isNaN(motionInfo.position(i) ))||
727 (osg::isNaN(motionInfo.orientation(i) ))||
728 (osg::isNaN(motionInfo.linearVel(i)) )||
729 (osg::isNaN(motionInfo.angularVel(i)) )||
730 (osg::isNaN(motionInfo.linearAccel(i)) )||
731 (osg::isNaN(motionInfo.angularAccel(i)) ));
737 FGMultiplayMgr::SendMyPosition(const FGExternalMotionData& motionInfo)
739 if ((! mInitialised) || (! mHaveServer))
743 SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition - no server");
747 if (!isSane(motionInfo))
749 // Current local data is invalid (NaN), so stop MP transmission.
750 // => Be nice to older FG versions (no NaN checks) and don't waste bandwidth.
751 SG_LOG(SG_NETWORK, SG_ALERT, "FGMultiplayMgr::SendMyPosition - "
752 << "Local data is invalid (NaN). Data not transmitted.");
756 static MsgBuf msgBuf;
757 static unsigned msgLen = 0;
758 T_PositionMsg* PosMsg = msgBuf.posMsg();
760 strncpy(PosMsg->Model, fgGetString("/sim/model/path"), MAX_MODEL_NAME_LEN);
761 PosMsg->Model[MAX_MODEL_NAME_LEN - 1] = '\0';
762 if (fgGetBool("/sim/freeze/replay-state", true)&&
763 fgGetBool("/sim/multiplay/freeze-on-replay",true))
765 // do not send position updates during replay
766 for (unsigned i = 0 ; i < 3; ++i)
768 // no movement during replay
769 PosMsg->linearVel[i] = XDR_encode_float (0.0);
770 PosMsg->angularVel[i] = XDR_encode_float (0.0);
771 PosMsg->linearAccel[i] = XDR_encode_float (0.0);
772 PosMsg->angularAccel[i] = XDR_encode_float (0.0);
774 // all other data remains unchanged (resend last state)
778 PosMsg->time = XDR_encode_double (motionInfo.time);
779 PosMsg->lag = XDR_encode_double (motionInfo.lag);
780 for (unsigned i = 0 ; i < 3; ++i)
781 PosMsg->position[i] = XDR_encode_double (motionInfo.position(i));
783 motionInfo.orientation.getAngleAxis(angleAxis);
784 for (unsigned i = 0 ; i < 3; ++i)
785 PosMsg->orientation[i] = XDR_encode_float (angleAxis(i));
786 if (fgGetBool("/sim/crashed",true))
788 for (unsigned i = 0 ; i < 3; ++i)
790 // no speed or acceleration sent when crashed, for better mp patch
791 PosMsg->linearVel[i] = XDR_encode_float (0.0);
792 PosMsg->angularVel[i] = XDR_encode_float (0.0);
793 PosMsg->linearAccel[i] = XDR_encode_float (0.0);
794 PosMsg->angularAccel[i] = XDR_encode_float (0.0);
799 //including speed up time in velocity and acceleration
800 double timeAccel = fgGetDouble("/sim/speed-up");
801 for (unsigned i = 0 ; i < 3; ++i)
802 PosMsg->linearVel[i] = XDR_encode_float (motionInfo.linearVel(i) * timeAccel);
803 for (unsigned i = 0 ; i < 3; ++i)
804 PosMsg->angularVel[i] = XDR_encode_float (motionInfo.angularVel(i) * timeAccel);
805 for (unsigned i = 0 ; i < 3; ++i)
806 PosMsg->linearAccel[i] = XDR_encode_float (motionInfo.linearAccel(i) * timeAccel * timeAccel);
807 for (unsigned i = 0 ; i < 3; ++i)
808 PosMsg->angularAccel[i] = XDR_encode_float (motionInfo.angularAccel(i) * timeAccel * timeAccel);
810 xdr_data_t* ptr = msgBuf.properties();
811 std::vector<FGPropertyData*>::const_iterator it;
812 it = motionInfo.properties.begin();
813 //cout << "OUTPUT PROPERTIES\n";
814 xdr_data_t* msgEnd = msgBuf.propsEnd();
815 while (it != motionInfo.properties.end() && ptr + 2 < msgEnd) {
817 // First element is the ID. Write it out when we know we have room for
818 // the whole property.
819 xdr_data_t id = XDR_encode_uint32((*it)->id);
820 // The actual data representation depends on the type
821 switch ((*it)->type) {
822 case simgear::props::INT:
823 case simgear::props::BOOL:
824 case simgear::props::LONG:
826 *ptr++ = XDR_encode_uint32((*it)->int_value);
827 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->int_value << "\n";
829 case simgear::props::FLOAT:
830 case simgear::props::DOUBLE:
832 *ptr++ = XDR_encode_float((*it)->float_value);
833 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
835 case simgear::props::STRING:
836 case simgear::props::UNSPECIFIED:
838 // String is complicated. It consists of
839 // The length of the string
841 // Padding to the nearest 4-bytes.
842 const char* lcharptr = (*it)->string_value;
847 ////cout << "String length: " << strlen(lcharptr) << "\n";
848 uint32_t len = strlen(lcharptr);
849 if (len > MAX_TEXT_SIZE)
851 // XXX This should not be using 4 bytes per character!
852 // If there's not enough room for this property, drop it
854 if (ptr + 2 + ((len + 3) & ~3) > msgEnd)
856 //cout << "String length unint32: " << len << "\n";
858 *ptr++ = XDR_encode_uint32(len);
861 // Now the text itself
862 // XXX This should not be using 4 bytes per character!
864 while ((*lcharptr != '\0') && (lcount < MAX_TEXT_SIZE))
866 *ptr++ = XDR_encode_int8(*lcharptr);
871 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " " << len << " " << (*it)->string_value;
873 // Now pad if required
874 while ((lcount % 4) != 0)
876 *ptr++ = XDR_encode_int8(0);
888 *ptr++ = XDR_encode_uint32(0);
889 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " 0\n";
895 //cout << " Unknown Type: " << (*it)->type << "\n";
897 *ptr++ = XDR_encode_float((*it)->float_value);;
898 //cout << "Prop:" << (*it)->id << " " << (*it)->type << " "<< (*it)->float_value << "\n";
905 msgLen = reinterpret_cast<char*>(ptr) - msgBuf.Msg;
906 FillMsgHdr(msgBuf.msgHdr(), POS_DATA_ID, msgLen);
909 mSocket->sendto(msgBuf.Msg, msgLen, 0, &mServer);
910 SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::SendMyPosition");
911 } // FGMultiplayMgr::SendMyPosition()
913 //////////////////////////////////////////////////////////////////////
915 //////////////////////////////////////////////////////////////////////
917 // Name: SendTextMessage
918 // Description: Sends a message to the player. The message must
919 // contain a valid and correctly filled out header and optional
922 //////////////////////////////////////////////////////////////////////
924 FGMultiplayMgr::SendTextMessage(const string &MsgText)
926 if (!mInitialised || !mHaveServer)
930 FillMsgHdr(&MsgHdr, CHAT_MSG_ID);
931 //////////////////////////////////////////////////
932 // Divide the text string into blocks that fit
933 // in the message and send the blocks.
934 //////////////////////////////////////////////////
935 unsigned iNextBlockPosition = 0;
938 char Msg[sizeof(T_MsgHdr) + sizeof(T_ChatMsg)];
939 while (iNextBlockPosition < MsgText.length()) {
940 strncpy (ChatMsg.Text,
941 MsgText.substr(iNextBlockPosition, MAX_CHAT_MSG_LEN - 1).c_str(),
943 ChatMsg.Text[MAX_CHAT_MSG_LEN - 1] = '\0';
944 memcpy (Msg, &MsgHdr, sizeof(T_MsgHdr));
945 memcpy (Msg + sizeof(T_MsgHdr), &ChatMsg, sizeof(T_ChatMsg));
946 mSocket->sendto (Msg, sizeof(T_MsgHdr) + sizeof(T_ChatMsg), 0, &mServer);
947 iNextBlockPosition += MAX_CHAT_MSG_LEN - 1;
952 } // FGMultiplayMgr::SendTextMessage ()
953 //////////////////////////////////////////////////////////////////////
955 //////////////////////////////////////////////////////////////////////
958 // Description: Processes data waiting at the receive socket. The
959 // processing ends when there is no more data at the socket.
961 //////////////////////////////////////////////////////////////////////
963 FGMultiplayMgr::update(double dt)
969 long stamp = SGTimeStamp::now().getSeconds();
971 //////////////////////////////////////////////////
973 //////////////////////////////////////////////////
974 mTimeUntilSend -= dt;
975 if (mTimeUntilSend <= 0.0) {
979 //////////////////////////////////////////////////
980 // Read the receive socket and process any data
981 //////////////////////////////////////////////////
985 //////////////////////////////////////////////////
986 // Although the recv call asks for
987 // MAX_PACKET_SIZE of data, the number of bytes
988 // returned will only be that of the next
989 // packet waiting to be processed.
990 //////////////////////////////////////////////////
991 simgear::IPAddress SenderAddress;
992 int RecvStatus = mSocket->recvfrom(msgBuf.Msg, sizeof(msgBuf.Msg), 0,
994 //////////////////////////////////////////////////
996 //////////////////////////////////////////////////
1000 // socket error reported?
1001 // errno isn't thread-safe - so only check its value when
1002 // socket return status < 0 really indicates a failure.
1003 if ((RecvStatus < 0)&&
1004 ((errno == EAGAIN) || (errno == 0))) // MSVC output "NoError" otherwise
1006 // ignore "normal" errors
1012 SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - Unable to receive data. "
1013 << strerror(errno) << "(errno " << errno << ")");
1017 // status is positive: bytes received
1018 bytes = (ssize_t) RecvStatus;
1019 if (bytes <= static_cast<ssize_t>(sizeof(T_MsgHdr))) {
1020 SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1021 << "received message with insufficient data" );
1024 //////////////////////////////////////////////////
1026 //////////////////////////////////////////////////
1027 T_MsgHdr* MsgHdr = msgBuf.msgHdr();
1028 MsgHdr->Magic = XDR_decode_uint32 (MsgHdr->Magic);
1029 MsgHdr->Version = XDR_decode_uint32 (MsgHdr->Version);
1030 MsgHdr->MsgId = XDR_decode_uint32 (MsgHdr->MsgId);
1031 MsgHdr->MsgLen = XDR_decode_uint32 (MsgHdr->MsgLen);
1032 MsgHdr->ReplyPort = XDR_decode_uint32 (MsgHdr->ReplyPort);
1033 MsgHdr->Callsign[MAX_CALLSIGN_LEN -1] = '\0';
1034 if (MsgHdr->Magic != MSG_MAGIC) {
1035 SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1036 << "message has invalid magic number!" );
1039 if (MsgHdr->Version != PROTO_VER) {
1040 SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1041 << "message has invalid protocol number!" );
1044 if (static_cast<ssize_t>(MsgHdr->MsgLen) != bytes) {
1045 SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1046 << "message from " << MsgHdr->Callsign << " has invalid length!");
1049 //////////////////////////////////////////////////
1051 //////////////////////////////////////////////////
1052 switch (MsgHdr->MsgId) {
1054 ProcessChatMsg(msgBuf, SenderAddress);
1057 ProcessPosMsg(msgBuf, SenderAddress, stamp);
1059 case UNUSABLE_POS_DATA_ID:
1060 case OLD_OLD_POS_DATA_ID:
1061 case OLD_PROP_MSG_ID:
1062 case OLD_POS_DATA_ID:
1065 SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1066 << "Unknown message Id received: " << MsgHdr->MsgId );
1069 } while (bytes > 0);
1072 MultiPlayerMap::iterator it = mMultiPlayerMap.begin();
1073 while (it != mMultiPlayerMap.end()) {
1074 if (it->second->getLastTimestamp() + 10 < stamp) {
1075 std::string name = it->first;
1076 it->second->setDie(true);
1077 mMultiPlayerMap.erase(it);
1078 it = mMultiPlayerMap.upper_bound(name);
1082 } // FGMultiplayMgr::ProcessData(void)
1083 //////////////////////////////////////////////////////////////////////
1086 FGMultiplayMgr::Send()
1088 using namespace simgear;
1092 // smooth the send rate, by adjusting based on the 'remainder' time, which
1093 // is how -ve mTimeUntilSend is. Watch for large values and ignore them,
1095 if ((mTimeUntilSend < 0.0) && (fabs(mTimeUntilSend) < mDt)) {
1096 mTimeUntilSend = mDt + mTimeUntilSend;
1098 mTimeUntilSend = mDt;
1101 double sim_time = globals->get_sim_time_sec();
1102 // static double lastTime = 0.0;
1104 // SG_LOG(SG_GENERAL, SG_INFO, "actual dt=" << sim_time - lastTime);
1105 // lastTime = sim_time;
1107 FlightProperties ifce;
1109 // put together a motion info struct, you will get that later
1110 // from FGInterface directly ...
1111 FGExternalMotionData motionInfo;
1113 // The current simulation time we need to update for,
1114 // note that the simulation time is updated before calling all the
1115 // update methods. Thus it contains the time intervals *end* time.
1116 // The FDM is already run, so the states belong to that time.
1117 motionInfo.time = sim_time;
1118 motionInfo.lag = mDt;
1120 // These are for now converted from lat/lon/alt and euler angles.
1121 // But this should change in FGInterface ...
1122 double lon = ifce.get_Longitude();
1123 double lat = ifce.get_Latitude();
1124 // first the aprioriate structure for the geodetic one
1125 SGGeod geod = SGGeod::fromRadFt(lon, lat, ifce.get_Altitude());
1126 // Convert to cartesion coordinate
1127 motionInfo.position = SGVec3d::fromGeod(geod);
1129 // The quaternion rotating from the earth centered frame to the
1130 // horizontal local frame
1131 SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)lon, (float)lat);
1132 // The orientation wrt the horizontal local frame
1133 float heading = ifce.get_Psi();
1134 float pitch = ifce.get_Theta();
1135 float roll = ifce.get_Phi();
1136 SGQuatf hlOr = SGQuatf::fromYawPitchRoll(heading, pitch, roll);
1137 // The orientation of the vehicle wrt the earth centered frame
1138 motionInfo.orientation = qEc2Hl*hlOr;
1140 if (!globals->get_subsystem("flight")->is_suspended()) {
1142 motionInfo.linearVel = SG_FEET_TO_METER*SGVec3f(ifce.get_uBody(),
1145 motionInfo.angularVel = SGVec3f(ifce.get_P_body(),
1149 // accels, set that to zero for now.
1150 // Angular accelerations are missing from the interface anyway,
1151 // linear accelerations are screwed up at least for JSBSim.
1152 // motionInfo.linearAccel = SG_FEET_TO_METER*SGVec3f(ifce.get_U_dot_body(),
1153 // ifce.get_V_dot_body(),
1154 // ifce.get_W_dot_body());
1155 motionInfo.linearAccel = SGVec3f::zeros();
1156 motionInfo.angularAccel = SGVec3f::zeros();
1158 // if the interface is suspendend, prevent the client from
1159 // wild extrapolations
1160 motionInfo.linearVel = SGVec3f::zeros();
1161 motionInfo.angularVel = SGVec3f::zeros();
1162 motionInfo.linearAccel = SGVec3f::zeros();
1163 motionInfo.angularAccel = SGVec3f::zeros();
1166 // now send the properties
1167 PropertyMap::iterator it;
1168 for (it = mPropertyMap.begin(); it != mPropertyMap.end(); ++it) {
1169 FGPropertyData* pData = new FGPropertyData;
1170 pData->id = it->first;
1171 pData->type = it->second->getType();
1173 switch (pData->type) {
1177 pData->int_value = it->second->getIntValue();
1181 pData->float_value = it->second->getFloatValue();
1184 case props::UNSPECIFIED:
1186 // FIXME: We assume unspecified are strings for the moment.
1188 const char* cstr = it->second->getStringValue();
1189 int len = strlen(cstr);
1193 pData->string_value = new char[len + 1];
1194 strcpy(pData->string_value, cstr);
1199 pData->string_value = 0;
1202 //cout << " Sending property " << pData->id << " " << pData->type << " " << pData->string_value << "\n";
1206 // FIXME Currently default to a float.
1207 //cout << "Unknown type when iterating through props: " << pData->type << "\n";
1208 pData->float_value = it->second->getFloatValue();
1212 motionInfo.properties.push_back(pData);
1215 SendMyPosition(motionInfo);
1219 //////////////////////////////////////////////////////////////////////
1221 // handle a position message
1223 //////////////////////////////////////////////////////////////////////
1225 FGMultiplayMgr::ProcessPosMsg(const FGMultiplayMgr::MsgBuf& Msg,
1226 const simgear::IPAddress& SenderAddress, long stamp)
1228 const T_MsgHdr* MsgHdr = Msg.msgHdr();
1229 if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + sizeof(T_PositionMsg)) {
1230 SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1231 << "Position message received with insufficient data" );
1234 const T_PositionMsg* PosMsg = Msg.posMsg();
1235 FGExternalMotionData motionInfo;
1236 motionInfo.time = XDR_decode_double(PosMsg->time);
1237 motionInfo.lag = XDR_decode_double(PosMsg->lag);
1238 for (unsigned i = 0; i < 3; ++i)
1239 motionInfo.position(i) = XDR_decode_double(PosMsg->position[i]);
1241 for (unsigned i = 0; i < 3; ++i)
1242 angleAxis(i) = XDR_decode_float(PosMsg->orientation[i]);
1243 motionInfo.orientation = SGQuatf::fromAngleAxis(angleAxis);
1244 for (unsigned i = 0; i < 3; ++i)
1245 motionInfo.linearVel(i) = XDR_decode_float(PosMsg->linearVel[i]);
1246 for (unsigned i = 0; i < 3; ++i)
1247 motionInfo.angularVel(i) = XDR_decode_float(PosMsg->angularVel[i]);
1248 for (unsigned i = 0; i < 3; ++i)
1249 motionInfo.linearAccel(i) = XDR_decode_float(PosMsg->linearAccel[i]);
1250 for (unsigned i = 0; i < 3; ++i)
1251 motionInfo.angularAccel(i) = XDR_decode_float(PosMsg->angularAccel[i]);
1253 // sanity check: do not allow injection of corrupted data (NaNs)
1254 if (!isSane(motionInfo))
1256 // drop this message, keep old position until receiving valid data
1257 SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1258 << "Position message with invalid data (NaN) received from "
1259 << MsgHdr->Callsign);
1263 //cout << "INPUT MESSAGE\n";
1265 // There was a bug in 1.9.0 and before: T_PositionMsg was 196 bytes
1266 // on 32 bit architectures and 200 bytes on 64 bit, and this
1267 // structure is put directly on the wire. By looking at the padding,
1268 // we can sort through the mess, mostly:
1269 // If padding is 0 (which is not a valid property type), then the
1270 // message was produced by a new client or an old 64 bit client that
1271 // happened to have 0 on the stack;
1272 // Else if the property list starting with the padding word is
1273 // well-formed, then the client is probably an old 32 bit client and
1274 // we'll go with that;
1275 // Else it is an old 64-bit client and properties start after the
1277 // There is a chance that we could be fooled by garbage in the
1278 // padding looking like a valid property, so verifyProperties() is
1279 // strict about the validity of the property values.
1280 const xdr_data_t* xdr = Msg.properties();
1281 if (PosMsg->pad != 0) {
1282 if (verifyProperties(&PosMsg->pad, Msg.propsRecvdEnd()))
1284 else if (!verifyProperties(xdr, Msg.propsRecvdEnd()))
1287 while (xdr < Msg.propsRecvdEnd()) {
1288 // simgear::props::Type type = simgear::props::UNSPECIFIED;
1290 // First element is always the ID
1291 unsigned id = XDR_decode_uint32(*xdr);
1292 //cout << pData->id << " ";
1295 // Check the ID actually exists and get the type
1296 const IdPropertyList* plist = findProperty(id);
1300 FGPropertyData* pData = new FGPropertyData;
1302 pData->type = plist->type;
1303 // How we decode the remainder of the property depends on the type
1304 switch (pData->type) {
1305 case simgear::props::INT:
1306 case simgear::props::BOOL:
1307 case simgear::props::LONG:
1308 pData->int_value = XDR_decode_uint32(*xdr);
1310 //cout << pData->int_value << "\n";
1312 case simgear::props::FLOAT:
1313 case simgear::props::DOUBLE:
1314 pData->float_value = XDR_decode_float(*xdr);
1316 //cout << pData->float_value << "\n";
1318 case simgear::props::STRING:
1319 case simgear::props::UNSPECIFIED:
1321 // String is complicated. It consists of
1322 // The length of the string
1323 // The string itself
1324 // Padding to the nearest 4-bytes.
1325 uint32_t length = XDR_decode_uint32(*xdr);
1327 //cout << length << " ";
1328 // Old versions truncated the string but left the length unadjusted.
1329 if (length > MAX_TEXT_SIZE)
1330 length = MAX_TEXT_SIZE;
1331 pData->string_value = new char[length + 1];
1332 //cout << " String: ";
1333 for (unsigned i = 0; i < length; i++)
1335 pData->string_value[i] = (char) XDR_decode_int8(*xdr);
1337 //cout << pData->string_value[i];
1340 pData->string_value[length] = '\0';
1342 // Now handle the padding
1343 while ((length % 4) != 0)
1354 pData->float_value = XDR_decode_float(*xdr);
1355 SG_LOG(SG_NETWORK, SG_DEBUG, "Unknown Prop type " << pData->id << " " << pData->type);
1360 motionInfo.properties.push_back(pData);
1364 // We failed to find the property. We'll try the next packet immediately.
1365 SG_LOG(SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::ProcessPosMsg - "
1366 "message from " << MsgHdr->Callsign << " has unknown property id "
1371 FGAIMultiplayer* mp = getMultiplayer(MsgHdr->Callsign);
1373 mp = addMultiplayer(MsgHdr->Callsign, PosMsg->Model);
1374 mp->addMotionInfo(motionInfo, stamp);
1375 } // FGMultiplayMgr::ProcessPosMsg()
1376 //////////////////////////////////////////////////////////////////////
1378 //////////////////////////////////////////////////////////////////////
1380 // handle a chat message
1381 // FIXME: display chat message within flightgear
1383 //////////////////////////////////////////////////////////////////////
1385 FGMultiplayMgr::ProcessChatMsg(const MsgBuf& Msg,
1386 const simgear::IPAddress& SenderAddress)
1388 const T_MsgHdr* MsgHdr = Msg.msgHdr();
1389 if (MsgHdr->MsgLen < sizeof(T_MsgHdr) + 1) {
1390 SG_LOG( SG_NETWORK, SG_DEBUG, "FGMultiplayMgr::MP_ProcessData - "
1391 << "Chat message received with insufficient data" );
1395 char *chatStr = new char[MsgHdr->MsgLen - sizeof(T_MsgHdr)];
1396 const T_ChatMsg* ChatMsg
1397 = reinterpret_cast<const T_ChatMsg *>(Msg.Msg + sizeof(T_MsgHdr));
1398 strncpy(chatStr, ChatMsg->Text,
1399 MsgHdr->MsgLen - sizeof(T_MsgHdr));
1400 chatStr[MsgHdr->MsgLen - sizeof(T_MsgHdr) - 1] = '\0';
1402 SG_LOG (SG_NETWORK, SG_WARN, "Chat [" << MsgHdr->Callsign << "]"
1406 } // FGMultiplayMgr::ProcessChatMsg ()
1407 //////////////////////////////////////////////////////////////////////
1410 FGMultiplayMgr::FillMsgHdr(T_MsgHdr *MsgHdr, int MsgId, unsigned _len)
1415 len = sizeof(T_MsgHdr) + sizeof(T_ChatMsg);
1421 len = sizeof(T_MsgHdr);
1424 MsgHdr->Magic = XDR_encode_uint32(MSG_MAGIC);
1425 MsgHdr->Version = XDR_encode_uint32(PROTO_VER);
1426 MsgHdr->MsgId = XDR_encode_uint32(MsgId);
1427 MsgHdr->MsgLen = XDR_encode_uint32(len);
1428 MsgHdr->ReplyAddress = 0; // Are obsolete, keep them for the server for
1429 MsgHdr->ReplyPort = 0; // now
1430 strncpy(MsgHdr->Callsign, mCallsign.c_str(), MAX_CALLSIGN_LEN);
1431 MsgHdr->Callsign[MAX_CALLSIGN_LEN - 1] = '\0';
1435 FGMultiplayMgr::addMultiplayer(const std::string& callsign,
1436 const std::string& modelName)
1438 if (0 < mMultiPlayerMap.count(callsign))
1439 return mMultiPlayerMap[callsign].get();
1441 FGAIMultiplayer* mp = new FGAIMultiplayer;
1442 mp->setPath(modelName.c_str());
1443 mp->setCallSign(callsign);
1444 mMultiPlayerMap[callsign] = mp;
1446 FGAIManager *aiMgr = (FGAIManager*)globals->get_subsystem("ai-model");
1450 /// FIXME: that must follow the attach ATM ...
1451 for (unsigned i = 0; i < numProperties; ++i)
1452 mp->addPropertyId(sIdPropertyList[i].id, sIdPropertyList[i].name);
1459 FGMultiplayMgr::getMultiplayer(const std::string& callsign)
1461 if (0 < mMultiPlayerMap.count(callsign))
1462 return mMultiPlayerMap[callsign].get();
1468 FGMultiplayMgr::findProperties()
1470 if (!mPropertiesChanged) {
1474 mPropertiesChanged = false;
1476 for (unsigned i = 0; i < numProperties; ++i) {
1477 const char* name = sIdPropertyList[i].name;
1478 SGPropertyNode* pNode = globals->get_props()->getNode(name);
1483 int id = sIdPropertyList[i].id;
1484 if (mPropertyMap.find(id) != mPropertyMap.end()) {
1485 continue; // already activated
1488 mPropertyMap[id] = pNode;
1489 SG_LOG(SG_NETWORK, SG_DEBUG, "activating MP property:" << pNode->getPath());