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 // #define SG_DEBUG SG_ALERT
34 FGAIMultiplayer::FGAIMultiplayer() : FGAIBase(otMultiplayer) {
37 mTimeOffsetSet = false;
38 mAllowExtrapolation = true;
39 mLagAdjustSystemSpeed = 10;
43 FGAIMultiplayer::~FGAIMultiplayer() {
46 bool FGAIMultiplayer::init(bool search_in_AI_path) {
47 props->setStringValue("sim/model/path", model_path.c_str());
48 //refuel_node = fgGetNode("systems/refuel/contact", true);
49 isTanker = false; // do this until this property is
50 // passed over the net
52 string str1 = _getCallsign();
53 string str2 = "MOBIL";
55 string::size_type loc1= str1.find( str2, 0 );
56 if ( (loc1 != string::npos && str2 != "") ){
57 // cout << " string found " << str2 << " in " << str1 << endl;
59 // cout << "isTanker " << isTanker << " " << mCallSign <<endl;
61 return FGAIBase::init(search_in_AI_path);
64 void FGAIMultiplayer::bind() {
67 props->tie("refuel/contact", SGRawValuePointer<bool>(&contact));
68 props->setBoolValue("tanker",isTanker);
70 #define AIMPROProp(type, name) \
71 SGRawValueMethods<FGAIMultiplayer, type>(*this, &FGAIMultiplayer::get##name)
73 #define AIMPRWProp(type, name) \
74 SGRawValueMethods<FGAIMultiplayer, type>(*this, \
75 &FGAIMultiplayer::get##name, &FGAIMultiplayer::set##name)
77 //props->tie("callsign", AIMPROProp(const char *, CallSign));
79 props->tie("controls/allow-extrapolation",
80 AIMPRWProp(bool, AllowExtrapolation));
81 props->tie("controls/lag-adjust-system-speed",
82 AIMPRWProp(double, LagAdjustSystemSpeed));
89 void FGAIMultiplayer::unbind() {
92 //props->untie("callsign");
93 props->untie("controls/allow-extrapolation");
94 props->untie("controls/lag-adjust-system-speed");
95 props->untie("refuel/contact");
98 void FGAIMultiplayer::update(double dt)
100 using namespace simgear;
105 FGAIBase::update(dt);
107 // Check if we already got data
108 if (mMotionInfo.empty())
111 // The current simulation time we need to update for,
112 // note that the simulation time is updated before calling all the
113 // update methods. Thus it contains the time intervals *end* time
114 double curtime = globals->get_sim_time_sec();
116 // Get the last available time
117 MotionInfo::reverse_iterator it = mMotionInfo.rbegin();
118 double curentPkgTime = it->second.time;
120 // Dynamically optimize the time offset between the feeder and the client
121 // Well, 'dynamically' means that the dynamic of that update must be very
122 // slow. You would otherwise notice huge jumps in the multiplayer models.
123 // The reason is that we want to avoid huge extrapolation times since
124 // extrapolation is highly error prone. For that we need something
125 // approaching the average latency of the packets. This first order lag
126 // component will provide this. We just take the error of the currently
127 // requested time to the most recent available packet. This is the
128 // target we want to reach in average.
129 double lag = it->second.lag;
130 if (!mTimeOffsetSet) {
131 mTimeOffsetSet = true;
132 mTimeOffset = curentPkgTime - curtime - lag;
134 double offset = curentPkgTime - curtime - lag;
135 if ((!mAllowExtrapolation && offset + lag < mTimeOffset)
136 || (offset - 10 > mTimeOffset)) {
137 mTimeOffset = offset;
138 SG_LOG(SG_GENERAL, SG_DEBUG, "Resetting time offset adjust system to "
139 "avoid extrapolation: time offset = " << mTimeOffset);
141 // the error of the offset, respectively the negative error to avoid
143 double err = offset - mTimeOffset;
144 // limit errors leading to shorter lag values somehow, that is late
145 // arriving packets will pessimize the overall lag much more than
146 // early packets will shorten the overall lag
149 // Ok, we have some very late packets and nothing newer increase the
150 // lag by the given speedadjust
151 sysSpeed = mLagAdjustSystemSpeed*err;
153 // We have a too pessimistic display delay shorten that a small bit
154 sysSpeed = SGMiscd::min(0.1*err*err, 0.5);
157 // simple euler integration for that first order system including some
158 // overshooting guard to prevent to aggressive system speeds
159 // (stiff systems) to explode the systems state
160 double systemIncrement = dt*sysSpeed;
161 if (fabs(err) < fabs(systemIncrement))
162 systemIncrement = err;
163 mTimeOffset += systemIncrement;
165 SG_LOG(SG_GENERAL, SG_DEBUG, "Offset adjust system: time offset = "
166 << mTimeOffset << ", expected longitudinal position error due to "
167 " current adjustment of the offset: "
168 << fabs(norm(it->second.linearVel)*systemIncrement));
173 // Compute the time in the feeders time scale which fits the current time
175 double tInterp = curtime + mTimeOffset;
180 if (tInterp <= curentPkgTime) {
181 // Ok, we need a time prevous to the last available packet,
184 // Find the first packet before the target time
185 MotionInfo::iterator nextIt = mMotionInfo.upper_bound(tInterp);
186 if (nextIt == mMotionInfo.begin()) {
187 SG_LOG(SG_GENERAL, SG_DEBUG, "Taking oldest packet!");
188 // We have no packet before the target time, just use the first one
189 MotionInfo::iterator firstIt = mMotionInfo.begin();
190 ecPos = firstIt->second.position;
191 ecOrient = firstIt->second.orientation;
192 speed = norm(firstIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
194 std::vector<FGPropertyData*>::const_iterator firstPropIt;
195 std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
196 firstPropIt = firstIt->second.properties.begin();
197 firstPropItEnd = firstIt->second.properties.end();
198 while (firstPropIt != firstPropItEnd) {
199 //cout << " Setting property..." << (*firstPropIt)->id;
200 PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
201 if (pIt != mPropertyMap.end())
203 //cout << "Found " << pIt->second->getPath() << ":";
204 switch ((*firstPropIt)->type) {
208 pIt->second->setIntValue((*firstPropIt)->int_value);
209 //cout << "Int: " << (*firstPropIt)->int_value << "\n";
213 pIt->second->setFloatValue((*firstPropIt)->float_value);
214 //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
217 case props::UNSPECIFIED:
218 pIt->second->setStringValue((*firstPropIt)->string_value);
219 //cout << "Str: " << (*firstPropIt)->string_value << "\n";
222 // FIXME - currently defaults to float values
223 pIt->second->setFloatValue((*firstPropIt)->float_value);
224 //cout << "Unknown: " << (*firstPropIt)->float_value << "\n";
230 SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
236 // Ok, we have really found something where our target time is in between
237 // do interpolation here
238 MotionInfo::iterator prevIt = nextIt;
241 // Interpolation coefficient is between 0 and 1
242 double intervalStart = prevIt->second.time;
243 double intervalEnd = nextIt->second.time;
244 double intervalLen = intervalEnd - intervalStart;
245 double tau = (tInterp - intervalStart)/intervalLen;
247 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer vehicle interpolation: ["
248 << intervalStart << ", " << intervalEnd << "], intervalLen = "
249 << intervalLen << ", interpolation parameter = " << tau);
251 // Here we do just linear interpolation on the position
252 ecPos = ((1-tau)*prevIt->second.position + tau*nextIt->second.position);
253 ecOrient = interpolate((float)tau, prevIt->second.orientation,
254 nextIt->second.orientation);
255 speed = norm((1-tau)*prevIt->second.linearVel
256 + tau*nextIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
258 if (prevIt->second.properties.size()
259 == nextIt->second.properties.size()) {
260 std::vector<FGPropertyData*>::const_iterator prevPropIt;
261 std::vector<FGPropertyData*>::const_iterator prevPropItEnd;
262 std::vector<FGPropertyData*>::const_iterator nextPropIt;
263 std::vector<FGPropertyData*>::const_iterator nextPropItEnd;
264 prevPropIt = prevIt->second.properties.begin();
265 prevPropItEnd = prevIt->second.properties.end();
266 nextPropIt = nextIt->second.properties.begin();
267 nextPropItEnd = nextIt->second.properties.end();
268 while (prevPropIt != prevPropItEnd) {
269 PropertyMap::iterator pIt = mPropertyMap.find((*prevPropIt)->id);
270 //cout << " Setting property..." << (*prevPropIt)->id;
272 if (pIt != mPropertyMap.end())
274 //cout << "Found " << pIt->second->getPath() << ":";
278 switch ((*prevPropIt)->type) {
282 ival = (int) (0.5+(1-tau)*((double) (*prevPropIt)->int_value) +
283 tau*((double) (*nextPropIt)->int_value));
284 pIt->second->setIntValue(ival);
285 //cout << "Int: " << ival << "\n";
289 val = (1-tau)*(*prevPropIt)->float_value +
290 tau*(*nextPropIt)->float_value;
291 //cout << "Flo: " << val << "\n";
292 pIt->second->setFloatValue(val);
295 case props::UNSPECIFIED:
296 //cout << "Str: " << (*nextPropIt)->string_value << "\n";
297 pIt->second->setStringValue((*nextPropIt)->string_value);
300 // FIXME - currently defaults to float values
301 val = (1-tau)*(*prevPropIt)->float_value +
302 tau*(*nextPropIt)->float_value;
303 //cout << "Unk: " << val << "\n";
304 pIt->second->setFloatValue(val);
310 SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*prevPropIt)->id << "\n");
318 // Now throw away too old data
319 if (prevIt != mMotionInfo.begin())
323 MotionInfo::iterator delIt;
324 delIt = mMotionInfo.begin();
326 while (delIt != prevIt)
328 std::vector<FGPropertyData*>::const_iterator propIt;
329 std::vector<FGPropertyData*>::const_iterator propItEnd;
330 propIt = delIt->second.properties.begin();
331 propItEnd = delIt->second.properties.end();
333 //cout << "Deleting data\n";
335 while (propIt != propItEnd)
344 mMotionInfo.erase(mMotionInfo.begin(), prevIt);
348 // Ok, we need to predict the future, so, take the best data we can have
349 // and do some eom computation to guess that for now.
350 FGExternalMotionData motionInfo = it->second;
352 // The time to predict, limit to 5 seconds
353 double t = tInterp - motionInfo.time;
354 t = SGMisc<double>::min(t, 5);
356 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer vehicle extrapolation: "
357 "extrapolation time = " << t);
359 // Do a few explicit euler steps with the constant acceleration's
360 // This must be sufficient ...
361 ecPos = motionInfo.position;
362 ecOrient = motionInfo.orientation;
363 SGVec3f linearVel = motionInfo.linearVel;
364 SGVec3f angularVel = motionInfo.angularVel;
370 SGVec3d ecVel = toVec3d(ecOrient.backTransform(linearVel));
372 ecOrient += h*ecOrient.derivative(angularVel);
374 linearVel += h*(cross(linearVel, angularVel) + motionInfo.linearAccel);
375 angularVel += h*motionInfo.angularAccel;
380 std::vector<FGPropertyData*>::const_iterator firstPropIt;
381 std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
382 speed = norm(linearVel) * SG_METER_TO_NM * 3600.0;
383 firstPropIt = it->second.properties.begin();
384 firstPropItEnd = it->second.properties.end();
385 while (firstPropIt != firstPropItEnd) {
386 PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
387 //cout << " Setting property..." << (*firstPropIt)->id;
389 if (pIt != mPropertyMap.end())
391 switch ((*firstPropIt)->type) {
395 pIt->second->setIntValue((*firstPropIt)->int_value);
396 //cout << "Int: " << (*firstPropIt)->int_value << "\n";
400 pIt->second->setFloatValue((*firstPropIt)->float_value);
401 //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
404 case props::UNSPECIFIED:
405 pIt->second->setStringValue((*firstPropIt)->string_value);
406 //cout << "Str: " << (*firstPropIt)->string_value << "\n";
409 // FIXME - currently defaults to float values
410 pIt->second->setFloatValue((*firstPropIt)->float_value);
411 //cout << "Unk: " << (*firstPropIt)->float_value << "\n";
417 SG_LOG(SG_GENERAL, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
424 // extract the position
425 pos = SGGeod::fromCart(ecPos);
426 altitude_ft = pos.getElevationFt();
428 // The quaternion rotating from the earth centered frame to the
429 // horizontal local frame
430 SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)pos.getLongitudeRad(),
431 (float)pos.getLatitudeRad());
432 // The orientation wrt the horizontal local frame
433 SGQuatf hlOr = conj(qEc2Hl)*ecOrient;
434 float hDeg, pDeg, rDeg;
435 hlOr.getEulerDeg(hDeg, pDeg, rDeg);
440 SG_LOG(SG_GENERAL, SG_DEBUG, "Multiplayer position and orientation: "
441 << ecPos << ", " << hlOr);
443 //###########################//
444 // do calculations for radar //
445 //###########################//
446 double range_ft2 = UpdateRadar(manager);
448 //************************************//
450 //************************************//
454 if ( (range_ft2 < 250.0 * 250.0) &&
457 // refuel_node->setBoolValue(true);
460 // refuel_node->setBoolValue(false);
471 FGAIMultiplayer::addMotionInfo(const FGExternalMotionData& motionInfo,
474 mLastTimestamp = stamp;
476 if (!mMotionInfo.empty()) {
477 double diff = motionInfo.time - mMotionInfo.rbegin()->first;
479 // packet is very old -- MP has probably reset (incl. his timebase)
483 // drop packets arriving out of order
487 mMotionInfo[motionInfo.time] = motionInfo;
491 FGAIMultiplayer::setDoubleProperty(const std::string& prop, double val)
493 SGPropertyNode* pNode = props->getChild(prop.c_str(), true);
494 pNode->setDoubleValue(val);