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"
34 // #define SG_DEBUG SG_ALERT
36 FGAIMultiplayer::FGAIMultiplayer() :
37 FGAIBase(otMultiplayer, fgGetBool("/sim/multiplay/hot", false))
41 mTimeOffsetSet = false;
42 mAllowExtrapolation = true;
43 mLagAdjustSystemSpeed = 10;
49 FGAIMultiplayer::~FGAIMultiplayer() {
52 bool FGAIMultiplayer::init(bool search_in_AI_path) {
53 props->setStringValue("sim/model/path", model_path.c_str());
54 //refuel_node = fgGetNode("systems/refuel/contact", true);
55 isTanker = false; // do this until this property is
56 // passed over the net
58 const string& str1 = _getCallsign();
59 const string str2 = "MOBIL";
61 string::size_type loc1= str1.find( str2, 0 );
62 if ( (loc1 != string::npos && str2 != "") ){
63 // cout << " string found " << str2 << " in " << str1 << endl;
65 // cout << "isTanker " << isTanker << " " << mCallSign <<endl;
69 bool result = FGAIBase::init(search_in_AI_path);
70 // propagate installation state (used by MP pilot list)
71 props->setBoolValue("model-installed", _installed);
75 void FGAIMultiplayer::bind() {
78 tie("refuel/contact", SGRawValuePointer<bool>(&contact));
79 tie("tanker", SGRawValuePointer<bool>(&isTanker));
81 tie("controls/invisible",
82 SGRawValuePointer<bool>(&invisible));
83 _uBodyNode = props->getNode("velocities/uBody-fps", true);
84 _vBodyNode = props->getNode("velocities/vBody-fps", true);
85 _wBodyNode = props->getNode("velocities/wBody-fps", true);
87 #define AIMPROProp(type, name) \
88 SGRawValueMethods<FGAIMultiplayer, type>(*this, &FGAIMultiplayer::get##name)
90 #define AIMPRWProp(type, name) \
91 SGRawValueMethods<FGAIMultiplayer, type>(*this, \
92 &FGAIMultiplayer::get##name, &FGAIMultiplayer::set##name)
94 //tie("callsign", AIMPROProp(const char *, CallSign));
96 tie("controls/allow-extrapolation",
97 AIMPRWProp(bool, AllowExtrapolation));
98 tie("controls/lag-adjust-system-speed",
99 AIMPRWProp(double, LagAdjustSystemSpeed));
106 void FGAIMultiplayer::update(double dt)
108 using namespace simgear;
113 FGAIBase::update(dt);
115 // Check if we already got data
116 if (mMotionInfo.empty())
119 // The current simulation time we need to update for,
120 // note that the simulation time is updated before calling all the
121 // update methods. Thus it contains the time intervals *end* time
122 double curtime = globals->get_sim_time_sec();
124 // Get the last available time
125 MotionInfo::reverse_iterator it = mMotionInfo.rbegin();
126 double curentPkgTime = it->second.time;
128 // Dynamically optimize the time offset between the feeder and the client
129 // Well, 'dynamically' means that the dynamic of that update must be very
130 // slow. You would otherwise notice huge jumps in the multiplayer models.
131 // The reason is that we want to avoid huge extrapolation times since
132 // extrapolation is highly error prone. For that we need something
133 // approaching the average latency of the packets. This first order lag
134 // component will provide this. We just take the error of the currently
135 // requested time to the most recent available packet. This is the
136 // target we want to reach in average.
137 double lag = it->second.lag;
138 if (!mTimeOffsetSet) {
139 mTimeOffsetSet = true;
140 mTimeOffset = curentPkgTime - curtime - lag;
142 double offset = curentPkgTime - curtime - lag;
143 if ((!mAllowExtrapolation && offset + lag < mTimeOffset)
144 || (offset - 10 > mTimeOffset)) {
145 mTimeOffset = offset;
146 SG_LOG(SG_AI, SG_DEBUG, "Resetting time offset adjust system to "
147 "avoid extrapolation: time offset = " << mTimeOffset);
149 // the error of the offset, respectively the negative error to avoid
151 double err = offset - mTimeOffset;
152 // limit errors leading to shorter lag values somehow, that is late
153 // arriving packets will pessimize the overall lag much more than
154 // early packets will shorten the overall lag
157 // Ok, we have some very late packets and nothing newer increase the
158 // lag by the given speedadjust
159 sysSpeed = mLagAdjustSystemSpeed*err;
161 // We have a too pessimistic display delay shorten that a small bit
162 sysSpeed = SGMiscd::min(0.1*err*err, 0.5);
165 // simple euler integration for that first order system including some
166 // overshooting guard to prevent to aggressive system speeds
167 // (stiff systems) to explode the systems state
168 double systemIncrement = dt*sysSpeed;
169 if (fabs(err) < fabs(systemIncrement))
170 systemIncrement = err;
171 mTimeOffset += systemIncrement;
173 SG_LOG(SG_AI, SG_DEBUG, "Offset adjust system: time offset = "
174 << mTimeOffset << ", expected longitudinal position error due to "
175 " current adjustment of the offset: "
176 << fabs(norm(it->second.linearVel)*systemIncrement));
181 // Compute the time in the feeders time scale which fits the current time
183 double tInterp = curtime + mTimeOffset;
189 if (tInterp <= curentPkgTime) {
190 // Ok, we need a time prevous to the last available packet,
193 // Find the first packet before the target time
194 MotionInfo::iterator nextIt = mMotionInfo.upper_bound(tInterp);
195 if (nextIt == mMotionInfo.begin()) {
196 SG_LOG(SG_AI, SG_DEBUG, "Taking oldest packet!");
197 // We have no packet before the target time, just use the first one
198 MotionInfo::iterator firstIt = mMotionInfo.begin();
199 ecPos = firstIt->second.position;
200 ecOrient = firstIt->second.orientation;
201 ecLinearVel = firstIt->second.linearVel;
202 speed = norm(ecLinearVel) * SG_METER_TO_NM * 3600.0;
204 std::vector<FGPropertyData*>::const_iterator firstPropIt;
205 std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
206 firstPropIt = firstIt->second.properties.begin();
207 firstPropItEnd = firstIt->second.properties.end();
208 while (firstPropIt != firstPropItEnd) {
209 //cout << " Setting property..." << (*firstPropIt)->id;
210 PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
211 if (pIt != mPropertyMap.end())
213 //cout << "Found " << pIt->second->getPath() << ":";
214 switch ((*firstPropIt)->type) {
218 pIt->second->setIntValue((*firstPropIt)->int_value);
219 //cout << "Int: " << (*firstPropIt)->int_value << "\n";
223 pIt->second->setFloatValue((*firstPropIt)->float_value);
224 //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
227 case props::UNSPECIFIED:
228 pIt->second->setStringValue((*firstPropIt)->string_value);
229 //cout << "Str: " << (*firstPropIt)->string_value << "\n";
232 // FIXME - currently defaults to float values
233 pIt->second->setFloatValue((*firstPropIt)->float_value);
234 //cout << "Unknown: " << (*firstPropIt)->float_value << "\n";
240 SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
246 // Ok, we have really found something where our target time is in between
247 // do interpolation here
248 MotionInfo::iterator prevIt = nextIt;
251 // Interpolation coefficient is between 0 and 1
252 double intervalStart = prevIt->second.time;
253 double intervalEnd = nextIt->second.time;
254 double intervalLen = intervalEnd - intervalStart;
255 double tau = (tInterp - intervalStart)/intervalLen;
257 SG_LOG(SG_AI, SG_DEBUG, "Multiplayer vehicle interpolation: ["
258 << intervalStart << ", " << intervalEnd << "], intervalLen = "
259 << intervalLen << ", interpolation parameter = " << tau);
261 // Here we do just linear interpolation on the position
262 ecPos = ((1-tau)*prevIt->second.position + tau*nextIt->second.position);
263 ecOrient = interpolate((float)tau, prevIt->second.orientation,
264 nextIt->second.orientation);
265 ecLinearVel = ((1-tau)*prevIt->second.linearVel + tau*nextIt->second.linearVel);
266 speed = norm(ecLinearVel) * SG_METER_TO_NM * 3600.0;
268 if (prevIt->second.properties.size()
269 == nextIt->second.properties.size()) {
270 std::vector<FGPropertyData*>::const_iterator prevPropIt;
271 std::vector<FGPropertyData*>::const_iterator prevPropItEnd;
272 std::vector<FGPropertyData*>::const_iterator nextPropIt;
273 std::vector<FGPropertyData*>::const_iterator nextPropItEnd;
274 prevPropIt = prevIt->second.properties.begin();
275 prevPropItEnd = prevIt->second.properties.end();
276 nextPropIt = nextIt->second.properties.begin();
277 nextPropItEnd = nextIt->second.properties.end();
278 while (prevPropIt != prevPropItEnd) {
279 PropertyMap::iterator pIt = mPropertyMap.find((*prevPropIt)->id);
280 //cout << " Setting property..." << (*prevPropIt)->id;
282 if (pIt != mPropertyMap.end())
284 //cout << "Found " << pIt->second->getPath() << ":";
288 switch ((*prevPropIt)->type) {
292 ival = (int) (0.5+(1-tau)*((double) (*prevPropIt)->int_value) +
293 tau*((double) (*nextPropIt)->int_value));
294 pIt->second->setIntValue(ival);
295 //cout << "Int: " << ival << "\n";
299 val = (1-tau)*(*prevPropIt)->float_value +
300 tau*(*nextPropIt)->float_value;
301 //cout << "Flo: " << val << "\n";
302 pIt->second->setFloatValue(val);
305 case props::UNSPECIFIED:
306 //cout << "Str: " << (*nextPropIt)->string_value << "\n";
307 pIt->second->setStringValue((*nextPropIt)->string_value);
310 // FIXME - currently defaults to float values
311 val = (1-tau)*(*prevPropIt)->float_value +
312 tau*(*nextPropIt)->float_value;
313 //cout << "Unk: " << val << "\n";
314 pIt->second->setFloatValue(val);
320 SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*prevPropIt)->id << "\n");
328 // Now throw away too old data
329 if (prevIt != mMotionInfo.begin())
332 mMotionInfo.erase(mMotionInfo.begin(), prevIt);
336 // Ok, we need to predict the future, so, take the best data we can have
337 // and do some eom computation to guess that for now.
338 FGExternalMotionData& motionInfo = it->second;
340 // The time to predict, limit to 5 seconds
341 double t = tInterp - motionInfo.time;
342 t = SGMisc<double>::min(t, 5);
344 SG_LOG(SG_AI, SG_DEBUG, "Multiplayer vehicle extrapolation: "
345 "extrapolation time = " << t);
347 // Do a few explicit euler steps with the constant acceleration's
348 // This must be sufficient ...
349 ecPos = motionInfo.position;
350 ecOrient = motionInfo.orientation;
351 ecLinearVel = motionInfo.linearVel;
352 SGVec3f angularVel = motionInfo.angularVel;
358 SGVec3d ecVel = toVec3d(ecOrient.backTransform(ecLinearVel));
360 ecOrient += h*ecOrient.derivative(angularVel);
362 ecLinearVel += h*(cross(ecLinearVel, angularVel) + motionInfo.linearAccel);
363 angularVel += h*motionInfo.angularAccel;
368 std::vector<FGPropertyData*>::const_iterator firstPropIt;
369 std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
370 speed = norm(ecLinearVel) * SG_METER_TO_NM * 3600.0;
371 firstPropIt = it->second.properties.begin();
372 firstPropItEnd = it->second.properties.end();
373 while (firstPropIt != firstPropItEnd) {
374 PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
375 //cout << " Setting property..." << (*firstPropIt)->id;
377 if (pIt != mPropertyMap.end())
379 switch ((*firstPropIt)->type) {
383 pIt->second->setIntValue((*firstPropIt)->int_value);
384 //cout << "Int: " << (*firstPropIt)->int_value << "\n";
388 pIt->second->setFloatValue((*firstPropIt)->float_value);
389 //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
392 case props::UNSPECIFIED:
393 pIt->second->setStringValue((*firstPropIt)->string_value);
394 //cout << "Str: " << (*firstPropIt)->string_value << "\n";
397 // FIXME - currently defaults to float values
398 pIt->second->setFloatValue((*firstPropIt)->float_value);
399 //cout << "Unk: " << (*firstPropIt)->float_value << "\n";
405 SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
412 // extract the position
413 pos = SGGeod::fromCart(ecPos);
414 double recent_alt_ft = altitude_ft;
415 altitude_ft = pos.getElevationFt();
417 // expose a valid vertical speed
418 if (lastUpdateTime != 0)
420 double dT = curtime - lastUpdateTime;
424 // simple smoothing over 1 second
425 vs = (1.0-Weighting)*vs + Weighting * (altitude_ft - recent_alt_ft) / dT * 60;
427 lastUpdateTime = curtime;
429 // The quaternion rotating from the earth centered frame to the
430 // horizontal local frame
431 SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)pos.getLongitudeRad(),
432 (float)pos.getLatitudeRad());
433 // The orientation wrt the horizontal local frame
434 SGQuatf hlOr = conj(qEc2Hl)*ecOrient;
435 float hDeg, pDeg, rDeg;
436 hlOr.getEulerDeg(hDeg, pDeg, rDeg);
441 // expose velocities/u,v,wbody-fps in the mp tree
442 _uBodyNode->setValue(ecLinearVel[0] * SG_METER_TO_FEET);
443 _vBodyNode->setValue(ecLinearVel[1] * SG_METER_TO_FEET);
444 _wBodyNode->setValue(ecLinearVel[2] * SG_METER_TO_FEET);
446 SG_LOG(SG_AI, SG_DEBUG, "Multiplayer position and orientation: "
447 << ecPos << ", " << hlOr);
449 //###########################//
450 // do calculations for radar //
451 //###########################//
452 double range_ft2 = UpdateRadar(manager);
454 //************************************//
456 //************************************//
460 //cout << "IS tanker ";
461 if ( (range_ft2 < 250.0 * 250.0) &&
464 // refuel_node->setBoolValue(true);
465 //cout << "in contact" << endl;
468 // refuel_node->setBoolValue(false);
469 //cout << "not in contact" << endl;
473 //cout << "NOT tanker " << endl;
481 FGAIMultiplayer::addMotionInfo(FGExternalMotionData& motionInfo,
484 mLastTimestamp = stamp;
486 if (!mMotionInfo.empty()) {
487 double diff = motionInfo.time - mMotionInfo.rbegin()->first;
489 // packet is very old -- MP has probably reset (incl. his timebase)
493 // drop packets arriving out of order
497 mMotionInfo[motionInfo.time] = motionInfo;
498 // We just copied the property (pointer) list - they are ours now. Clear the
499 // properties list in given/returned object, so former owner won't deallocate them.
500 motionInfo.properties.clear();
504 FGAIMultiplayer::setDoubleProperty(const std::string& prop, double val)
506 SGPropertyNode* pNode = props->getChild(prop.c_str(), true);
507 pNode->setDoubleValue(val);