1 // FGAIMultiplayer - FGAIBase-derived class creates an AI multiplayer aircraft
3 // Based on FGAIAircraft
4 // Written by David Culp, started October 2003.
5 // Also by Gregor Richards, started December 2005.
7 // Copyright (C) 2003 David P. Culp - davidculp2@comcast.net
8 // Copyright (C) 2005 Gregor Richards
10 // This program is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU General Public License as
12 // published by the Free Software Foundation; either version 2 of the
13 // License, or (at your option) any later version.
15 // This program is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // General Public License for more details.
20 // You should have received a copy of the GNU General Public License
21 // along with this program; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include "AIMultiplayer.hxx"
32 #include <simgear/scene/util/SGNodeMasks.hxx>
34 // #define SG_DEBUG SG_ALERT
36 FGAIMultiplayer::FGAIMultiplayer() : FGAIBase(otMultiplayer) {
39 mTimeOffsetSet = false;
40 mAllowExtrapolation = true;
41 mLagAdjustSystemSpeed = 10;
43 aip.getSceneGraph()->setNodeMask(~SG_NODEMASK_TERRAIN_BIT);
48 FGAIMultiplayer::~FGAIMultiplayer() {
51 bool FGAIMultiplayer::init(bool search_in_AI_path) {
52 props->setStringValue("sim/model/path", model_path.c_str());
53 //refuel_node = fgGetNode("systems/refuel/contact", true);
54 isTanker = false; // do this until this property is
55 // passed over the net
57 string str1 = _getCallsign();
58 string str2 = "MOBIL";
60 string::size_type loc1= str1.find( str2, 0 );
61 if ( (loc1 != string::npos && str2 != "") ){
62 // cout << " string found " << str2 << " in " << str1 << endl;
64 // cout << "isTanker " << isTanker << " " << mCallSign <<endl;
68 bool result = FGAIBase::init(search_in_AI_path);
69 // propagate installation state (used by MP pilot list)
70 props->setBoolValue("model-installed", _installed);
74 void FGAIMultiplayer::bind() {
77 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
78 props->tie("tanker", SGRawValuePointer<bool>(&isTanker));
80 props->tie("controls/invisible",
81 SGRawValuePointer<bool>(&invisible));
83 #define AIMPROProp(type, name) \
84 SGRawValueMethods<FGAIMultiplayer, type>(*this, &FGAIMultiplayer::get##name)
86 #define AIMPRWProp(type, name) \
87 SGRawValueMethods<FGAIMultiplayer, type>(*this, \
88 &FGAIMultiplayer::get##name, &FGAIMultiplayer::set##name)
90 //props->tie("callsign", AIMPROProp(const char *, CallSign));
92 props->tie("controls/allow-extrapolation",
93 AIMPRWProp(bool, AllowExtrapolation));
94 props->tie("controls/lag-adjust-system-speed",
95 AIMPRWProp(double, LagAdjustSystemSpeed));
102 void FGAIMultiplayer::unbind() {
105 //props->untie("callsign");
106 props->untie("controls/allow-extrapolation");
107 props->untie("controls/lag-adjust-system-speed");
108 props->untie("controls/invisible");
109 props->untie("refuel/contact");
110 props->untie("tanker");
114 void FGAIMultiplayer::update(double dt)
116 using namespace simgear;
121 FGAIBase::update(dt);
123 // Check if we already got data
124 if (mMotionInfo.empty())
127 // The current simulation time we need to update for,
128 // note that the simulation time is updated before calling all the
129 // update methods. Thus it contains the time intervals *end* time
130 double curtime = globals->get_sim_time_sec();
132 // Get the last available time
133 MotionInfo::reverse_iterator it = mMotionInfo.rbegin();
134 double curentPkgTime = it->second.time;
136 // Dynamically optimize the time offset between the feeder and the client
137 // Well, 'dynamically' means that the dynamic of that update must be very
138 // slow. You would otherwise notice huge jumps in the multiplayer models.
139 // The reason is that we want to avoid huge extrapolation times since
140 // extrapolation is highly error prone. For that we need something
141 // approaching the average latency of the packets. This first order lag
142 // component will provide this. We just take the error of the currently
143 // requested time to the most recent available packet. This is the
144 // target we want to reach in average.
145 double lag = it->second.lag;
146 if (!mTimeOffsetSet) {
147 mTimeOffsetSet = true;
148 mTimeOffset = curentPkgTime - curtime - lag;
150 double offset = curentPkgTime - curtime - lag;
151 if ((!mAllowExtrapolation && offset + lag < mTimeOffset)
152 || (offset - 10 > mTimeOffset)) {
153 mTimeOffset = offset;
154 SG_LOG(SG_GENERAL, SG_DEBUG, "Resetting time offset adjust system to "
155 "avoid extrapolation: time offset = " << mTimeOffset);
157 // the error of the offset, respectively the negative error to avoid
159 double err = offset - mTimeOffset;
160 // limit errors leading to shorter lag values somehow, that is late
161 // arriving packets will pessimize the overall lag much more than
162 // early packets will shorten the overall lag
165 // Ok, we have some very late packets and nothing newer increase the
166 // lag by the given speedadjust
167 sysSpeed = mLagAdjustSystemSpeed*err;
169 // We have a too pessimistic display delay shorten that a small bit
170 sysSpeed = SGMiscd::min(0.1*err*err, 0.5);
173 // simple euler integration for that first order system including some
174 // overshooting guard to prevent to aggressive system speeds
175 // (stiff systems) to explode the systems state
176 double systemIncrement = dt*sysSpeed;
177 if (fabs(err) < fabs(systemIncrement))
178 systemIncrement = err;
179 mTimeOffset += systemIncrement;
181 SG_LOG(SG_GENERAL, SG_DEBUG, "Offset adjust system: time offset = "
182 << mTimeOffset << ", expected longitudinal position error due to "
183 " current adjustment of the offset: "
184 << fabs(norm(it->second.linearVel)*systemIncrement));
189 // Compute the time in the feeders time scale which fits the current time
191 double tInterp = curtime + mTimeOffset;
196 if (tInterp <= curentPkgTime) {
197 // Ok, we need a time prevous to the last available packet,
200 // Find the first packet before the target time
201 MotionInfo::iterator nextIt = mMotionInfo.upper_bound(tInterp);
202 if (nextIt == mMotionInfo.begin()) {
203 SG_LOG(SG_GENERAL, SG_DEBUG, "Taking oldest packet!");
204 // We have no packet before the target time, just use the first one
205 MotionInfo::iterator firstIt = mMotionInfo.begin();
206 ecPos = firstIt->second.position;
207 ecOrient = firstIt->second.orientation;
208 speed = norm(firstIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
210 std::vector<FGPropertyData*>::const_iterator firstPropIt;
211 std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
212 firstPropIt = firstIt->second.properties.begin();
213 firstPropItEnd = firstIt->second.properties.end();
214 while (firstPropIt != firstPropItEnd) {
215 //cout << " Setting property..." << (*firstPropIt)->id;
216 PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
217 if (pIt != mPropertyMap.end())
219 //cout << "Found " << pIt->second->getPath() << ":";
220 switch ((*firstPropIt)->type) {
224 pIt->second->setIntValue((*firstPropIt)->int_value);
225 //cout << "Int: " << (*firstPropIt)->int_value << "\n";
229 pIt->second->setFloatValue((*firstPropIt)->float_value);
230 //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
233 case props::UNSPECIFIED:
234 pIt->second->setStringValue((*firstPropIt)->string_value);
235 //cout << "Str: " << (*firstPropIt)->string_value << "\n";
238 // FIXME - currently defaults to float values
239 pIt->second->setFloatValue((*firstPropIt)->float_value);
240 //cout << "Unknown: " << (*firstPropIt)->float_value << "\n";
246 SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
252 // Ok, we have really found something where our target time is in between
253 // do interpolation here
254 MotionInfo::iterator prevIt = nextIt;
257 // Interpolation coefficient is between 0 and 1
258 double intervalStart = prevIt->second.time;
259 double intervalEnd = nextIt->second.time;
260 double intervalLen = intervalEnd - intervalStart;
261 double tau = (tInterp - intervalStart)/intervalLen;
263 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer vehicle interpolation: ["
264 << intervalStart << ", " << intervalEnd << "], intervalLen = "
265 << intervalLen << ", interpolation parameter = " << tau);
267 // Here we do just linear interpolation on the position
268 ecPos = ((1-tau)*prevIt->second.position + tau*nextIt->second.position);
269 ecOrient = interpolate((float)tau, prevIt->second.orientation,
270 nextIt->second.orientation);
271 speed = norm((1-tau)*prevIt->second.linearVel
272 + tau*nextIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
274 if (prevIt->second.properties.size()
275 == nextIt->second.properties.size()) {
276 std::vector<FGPropertyData*>::const_iterator prevPropIt;
277 std::vector<FGPropertyData*>::const_iterator prevPropItEnd;
278 std::vector<FGPropertyData*>::const_iterator nextPropIt;
279 std::vector<FGPropertyData*>::const_iterator nextPropItEnd;
280 prevPropIt = prevIt->second.properties.begin();
281 prevPropItEnd = prevIt->second.properties.end();
282 nextPropIt = nextIt->second.properties.begin();
283 nextPropItEnd = nextIt->second.properties.end();
284 while (prevPropIt != prevPropItEnd) {
285 PropertyMap::iterator pIt = mPropertyMap.find((*prevPropIt)->id);
286 //cout << " Setting property..." << (*prevPropIt)->id;
288 if (pIt != mPropertyMap.end())
290 //cout << "Found " << pIt->second->getPath() << ":";
294 switch ((*prevPropIt)->type) {
298 ival = (int) (0.5+(1-tau)*((double) (*prevPropIt)->int_value) +
299 tau*((double) (*nextPropIt)->int_value));
300 pIt->second->setIntValue(ival);
301 //cout << "Int: " << ival << "\n";
305 val = (1-tau)*(*prevPropIt)->float_value +
306 tau*(*nextPropIt)->float_value;
307 //cout << "Flo: " << val << "\n";
308 pIt->second->setFloatValue(val);
311 case props::UNSPECIFIED:
312 //cout << "Str: " << (*nextPropIt)->string_value << "\n";
313 pIt->second->setStringValue((*nextPropIt)->string_value);
316 // FIXME - currently defaults to float values
317 val = (1-tau)*(*prevPropIt)->float_value +
318 tau*(*nextPropIt)->float_value;
319 //cout << "Unk: " << val << "\n";
320 pIt->second->setFloatValue(val);
326 SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*prevPropIt)->id << "\n");
334 // Now throw away too old data
335 if (prevIt != mMotionInfo.begin())
339 MotionInfo::iterator delIt;
340 delIt = mMotionInfo.begin();
342 while (delIt != prevIt)
344 std::vector<FGPropertyData*>::const_iterator propIt;
345 std::vector<FGPropertyData*>::const_iterator propItEnd;
346 propIt = delIt->second.properties.begin();
347 propItEnd = delIt->second.properties.end();
349 //cout << "Deleting data\n";
351 while (propIt != propItEnd)
360 mMotionInfo.erase(mMotionInfo.begin(), prevIt);
364 // Ok, we need to predict the future, so, take the best data we can have
365 // and do some eom computation to guess that for now.
366 FGExternalMotionData motionInfo = it->second;
368 // The time to predict, limit to 5 seconds
369 double t = tInterp - motionInfo.time;
370 t = SGMisc<double>::min(t, 5);
372 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer vehicle extrapolation: "
373 "extrapolation time = " << t);
375 // Do a few explicit euler steps with the constant acceleration's
376 // This must be sufficient ...
377 ecPos = motionInfo.position;
378 ecOrient = motionInfo.orientation;
379 SGVec3f linearVel = motionInfo.linearVel;
380 SGVec3f angularVel = motionInfo.angularVel;
386 SGVec3d ecVel = toVec3d(ecOrient.backTransform(linearVel));
388 ecOrient += h*ecOrient.derivative(angularVel);
390 linearVel += h*(cross(linearVel, angularVel) + motionInfo.linearAccel);
391 angularVel += h*motionInfo.angularAccel;
396 std::vector<FGPropertyData*>::const_iterator firstPropIt;
397 std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
398 speed = norm(linearVel) * SG_METER_TO_NM * 3600.0;
399 firstPropIt = it->second.properties.begin();
400 firstPropItEnd = it->second.properties.end();
401 while (firstPropIt != firstPropItEnd) {
402 PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
403 //cout << " Setting property..." << (*firstPropIt)->id;
405 if (pIt != mPropertyMap.end())
407 switch ((*firstPropIt)->type) {
411 pIt->second->setIntValue((*firstPropIt)->int_value);
412 //cout << "Int: " << (*firstPropIt)->int_value << "\n";
416 pIt->second->setFloatValue((*firstPropIt)->float_value);
417 //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
420 case props::UNSPECIFIED:
421 pIt->second->setStringValue((*firstPropIt)->string_value);
422 //cout << "Str: " << (*firstPropIt)->string_value << "\n";
425 // FIXME - currently defaults to float values
426 pIt->second->setFloatValue((*firstPropIt)->float_value);
427 //cout << "Unk: " << (*firstPropIt)->float_value << "\n";
433 SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
440 // extract the position
441 pos = SGGeod::fromCart(ecPos);
442 altitude_ft = pos.getElevationFt();
444 // The quaternion rotating from the earth centered frame to the
445 // horizontal local frame
446 SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)pos.getLongitudeRad(),
447 (float)pos.getLatitudeRad());
448 // The orientation wrt the horizontal local frame
449 SGQuatf hlOr = conj(qEc2Hl)*ecOrient;
450 float hDeg, pDeg, rDeg;
451 hlOr.getEulerDeg(hDeg, pDeg, rDeg);
456 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer position and orientation: "
457 << ecPos << ", " << hlOr);
459 //###########################//
460 // do calculations for radar //
461 //###########################//
462 double range_ft2 = UpdateRadar(manager);
464 //************************************//
466 //************************************//
470 //cout << "IS tanker ";
471 if ( (range_ft2 < 250.0 * 250.0) &&
474 // refuel_node->setBoolValue(true);
475 //cout << "in contact" << endl;
478 // refuel_node->setBoolValue(false);
479 //cout << "not in contact" << endl;
483 //cout << "NOT tanker " << endl;
491 FGAIMultiplayer::addMotionInfo(const FGExternalMotionData& motionInfo,
494 mLastTimestamp = stamp;
496 if (!mMotionInfo.empty()) {
497 double diff = motionInfo.time - mMotionInfo.rbegin()->first;
499 // packet is very old -- MP has probably reset (incl. his timebase)
503 // drop packets arriving out of order
507 mMotionInfo[motionInfo.time] = motionInfo;
511 FGAIMultiplayer::setDoubleProperty(const std::string& prop, double val)
513 SGPropertyNode* pNode = props->getChild(prop.c_str(), true);
514 pNode->setDoubleValue(val);