]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIMultiplayer.cxx
PerformanceDB improvements.
[flightgear.git] / src / AIModel / AIMultiplayer.cxx
1 // FGAIMultiplayer - FGAIBase-derived class creates an AI multiplayer aircraft
2 //
3 // Based on FGAIAircraft
4 // Written by David Culp, started October 2003.
5 // Also by Gregor Richards, started December 2005.
6 //
7 // Copyright (C) 2003  David P. Culp - davidculp2@comcast.net
8 // Copyright (C) 2005  Gregor Richards
9 //
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.
14 //
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.
19 //
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.
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <string>
29
30 #include "AIMultiplayer.hxx"
31
32
33 // #define SG_DEBUG SG_ALERT
34
35 FGAIMultiplayer::FGAIMultiplayer() :
36    FGAIBase(otMultiplayer, false)
37 {
38    no_roll = false;
39
40    mTimeOffsetSet = false;
41    mAllowExtrapolation = true;
42    mLagAdjustSystemSpeed = 10;
43    mLastTimestamp = 0;
44    lastUpdateTime = 0;
45
46
47
48 FGAIMultiplayer::~FGAIMultiplayer() {
49 }
50
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
56
57     string str1 = _getCallsign();
58     string str2 = "MOBIL";
59
60     string::size_type loc1= str1.find( str2, 0 );
61     if ( (loc1 != string::npos && str2 != "") ){
62         //         cout << " string found "     << str2 << " in " << str1 << endl;
63         isTanker = true;
64         //         cout << "isTanker " << isTanker << " " << mCallSign <<endl;
65     }
66
67     // load model
68     bool result = FGAIBase::init(search_in_AI_path);
69     // propagate installation state (used by MP pilot list)
70     props->setBoolValue("model-installed", _installed);
71     return result;
72 }
73
74 void FGAIMultiplayer::bind() {
75     FGAIBase::bind();
76
77     tie("refuel/contact", SGRawValuePointer<bool>(&contact));
78     tie("tanker", SGRawValuePointer<bool>(&isTanker));
79
80     tie("controls/invisible",
81         SGRawValuePointer<bool>(&invisible));
82
83 #define AIMPROProp(type, name) \
84 SGRawValueMethods<FGAIMultiplayer, type>(*this, &FGAIMultiplayer::get##name)
85
86 #define AIMPRWProp(type, name) \
87 SGRawValueMethods<FGAIMultiplayer, type>(*this, \
88       &FGAIMultiplayer::get##name, &FGAIMultiplayer::set##name)
89
90     //tie("callsign", AIMPROProp(const char *, CallSign));
91
92     tie("controls/allow-extrapolation",
93         AIMPRWProp(bool, AllowExtrapolation));
94     tie("controls/lag-adjust-system-speed",
95         AIMPRWProp(double, LagAdjustSystemSpeed));
96
97
98 #undef AIMPROProp
99 #undef AIMPRWProp
100 }
101
102 void FGAIMultiplayer::update(double dt)
103 {
104   using namespace simgear;
105
106   if (dt <= 0)
107     return;
108
109   FGAIBase::update(dt);
110
111   // Check if we already got data
112   if (mMotionInfo.empty())
113     return;
114
115   // The current simulation time we need to update for,
116   // note that the simulation time is updated before calling all the
117   // update methods. Thus it contains the time intervals *end* time
118   double curtime = globals->get_sim_time_sec();
119
120   // Get the last available time
121   MotionInfo::reverse_iterator it = mMotionInfo.rbegin();
122   double curentPkgTime = it->second.time;
123
124   // Dynamically optimize the time offset between the feeder and the client
125   // Well, 'dynamically' means that the dynamic of that update must be very
126   // slow. You would otherwise notice huge jumps in the multiplayer models.
127   // The reason is that we want to avoid huge extrapolation times since
128   // extrapolation is highly error prone. For that we need something
129   // approaching the average latency of the packets. This first order lag
130   // component will provide this. We just take the error of the currently
131   // requested time to the most recent available packet. This is the
132   // target we want to reach in average.
133   double lag = it->second.lag;
134   if (!mTimeOffsetSet) {
135     mTimeOffsetSet = true;
136     mTimeOffset = curentPkgTime - curtime - lag;
137   } else {
138     double offset = curentPkgTime - curtime - lag;
139     if ((!mAllowExtrapolation && offset + lag < mTimeOffset)
140         || (offset - 10 > mTimeOffset)) {
141       mTimeOffset = offset;
142       SG_LOG(SG_AI, SG_DEBUG, "Resetting time offset adjust system to "
143              "avoid extrapolation: time offset = " << mTimeOffset);
144     } else {
145       // the error of the offset, respectively the negative error to avoid
146       // a minus later ...
147       double err = offset - mTimeOffset;
148       // limit errors leading to shorter lag values somehow, that is late
149       // arriving packets will pessimize the overall lag much more than
150       // early packets will shorten the overall lag
151       double sysSpeed;
152       if (err < 0) {
153         // Ok, we have some very late packets and nothing newer increase the
154         // lag by the given speedadjust
155         sysSpeed = mLagAdjustSystemSpeed*err;
156       } else {
157         // We have a too pessimistic display delay shorten that a small bit
158         sysSpeed = SGMiscd::min(0.1*err*err, 0.5);
159       }
160
161       // simple euler integration for that first order system including some
162       // overshooting guard to prevent to aggressive system speeds
163       // (stiff systems) to explode the systems state
164       double systemIncrement = dt*sysSpeed;
165       if (fabs(err) < fabs(systemIncrement))
166         systemIncrement = err;
167       mTimeOffset += systemIncrement;
168       
169       SG_LOG(SG_AI, SG_DEBUG, "Offset adjust system: time offset = "
170              << mTimeOffset << ", expected longitudinal position error due to "
171              " current adjustment of the offset: "
172              << fabs(norm(it->second.linearVel)*systemIncrement));
173     }
174   }
175
176
177   // Compute the time in the feeders time scale which fits the current time
178   // we need to 
179   double tInterp = curtime + mTimeOffset;
180
181   SGVec3d ecPos;
182   SGQuatf ecOrient;
183
184   if (tInterp <= curentPkgTime) {
185     // Ok, we need a time prevous to the last available packet,
186     // that is good ...
187
188     // Find the first packet before the target time
189     MotionInfo::iterator nextIt = mMotionInfo.upper_bound(tInterp);
190     if (nextIt == mMotionInfo.begin()) {
191       SG_LOG(SG_AI, SG_DEBUG, "Taking oldest packet!");
192       // We have no packet before the target time, just use the first one
193       MotionInfo::iterator firstIt = mMotionInfo.begin();
194       ecPos = firstIt->second.position;
195       ecOrient = firstIt->second.orientation;
196       speed = norm(firstIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
197
198       std::vector<FGPropertyData*>::const_iterator firstPropIt;
199       std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
200       firstPropIt = firstIt->second.properties.begin();
201       firstPropItEnd = firstIt->second.properties.end();
202       while (firstPropIt != firstPropItEnd) {
203         //cout << " Setting property..." << (*firstPropIt)->id;
204         PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
205         if (pIt != mPropertyMap.end())
206         {
207           //cout << "Found " << pIt->second->getPath() << ":";
208           switch ((*firstPropIt)->type) {
209             case props::INT:
210             case props::BOOL:
211             case props::LONG:
212               pIt->second->setIntValue((*firstPropIt)->int_value);
213               //cout << "Int: " << (*firstPropIt)->int_value << "\n";
214               break;
215             case props::FLOAT:
216             case props::DOUBLE:
217               pIt->second->setFloatValue((*firstPropIt)->float_value);
218               //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
219               break;
220             case props::STRING:
221             case props::UNSPECIFIED:
222               pIt->second->setStringValue((*firstPropIt)->string_value);
223               //cout << "Str: " << (*firstPropIt)->string_value << "\n";    
224               break;
225             default:
226               // FIXME - currently defaults to float values
227               pIt->second->setFloatValue((*firstPropIt)->float_value);
228               //cout << "Unknown: " << (*firstPropIt)->float_value << "\n";
229               break;
230           }            
231         }
232         else
233         {
234           SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
235         }
236         ++firstPropIt;
237       }
238
239     } else {
240       // Ok, we have really found something where our target time is in between
241       // do interpolation here
242       MotionInfo::iterator prevIt = nextIt;
243       --prevIt;
244
245       // Interpolation coefficient is between 0 and 1
246       double intervalStart = prevIt->second.time;
247       double intervalEnd = nextIt->second.time;
248       double intervalLen = intervalEnd - intervalStart;
249       double tau = (tInterp - intervalStart)/intervalLen;
250
251       SG_LOG(SG_AI, SG_DEBUG, "Multiplayer vehicle interpolation: ["
252              << intervalStart << ", " << intervalEnd << "], intervalLen = "
253              << intervalLen << ", interpolation parameter = " << tau);
254
255       // Here we do just linear interpolation on the position
256       ecPos = ((1-tau)*prevIt->second.position + tau*nextIt->second.position);
257       ecOrient = interpolate((float)tau, prevIt->second.orientation,
258                              nextIt->second.orientation);
259       speed = norm((1-tau)*prevIt->second.linearVel
260                    + tau*nextIt->second.linearVel) * SG_METER_TO_NM * 3600.0;
261
262       if (prevIt->second.properties.size()
263           == nextIt->second.properties.size()) {
264         std::vector<FGPropertyData*>::const_iterator prevPropIt;
265         std::vector<FGPropertyData*>::const_iterator prevPropItEnd;
266         std::vector<FGPropertyData*>::const_iterator nextPropIt;
267         std::vector<FGPropertyData*>::const_iterator nextPropItEnd;
268         prevPropIt = prevIt->second.properties.begin();
269         prevPropItEnd = prevIt->second.properties.end();
270         nextPropIt = nextIt->second.properties.begin();
271         nextPropItEnd = nextIt->second.properties.end();
272         while (prevPropIt != prevPropItEnd) {
273           PropertyMap::iterator pIt = mPropertyMap.find((*prevPropIt)->id);
274           //cout << " Setting property..." << (*prevPropIt)->id;
275           
276           if (pIt != mPropertyMap.end())
277           {
278             //cout << "Found " << pIt->second->getPath() << ":";
279           
280             int ival;
281             float val;
282             switch ((*prevPropIt)->type) {
283               case props::INT:
284               case props::BOOL:
285               case props::LONG:
286                 ival = (int) (0.5+(1-tau)*((double) (*prevPropIt)->int_value) +
287                   tau*((double) (*nextPropIt)->int_value));
288                 pIt->second->setIntValue(ival);
289                 //cout << "Int: " << ival << "\n";
290                 break;
291               case props::FLOAT:
292               case props::DOUBLE:
293                 val = (1-tau)*(*prevPropIt)->float_value +
294                   tau*(*nextPropIt)->float_value;
295                 //cout << "Flo: " << val << "\n";
296                 pIt->second->setFloatValue(val);
297                 break;
298               case props::STRING:
299               case props::UNSPECIFIED:
300                 //cout << "Str: " << (*nextPropIt)->string_value << "\n";
301                 pIt->second->setStringValue((*nextPropIt)->string_value);
302                 break;
303               default:
304                 // FIXME - currently defaults to float values
305                 val = (1-tau)*(*prevPropIt)->float_value +
306                   tau*(*nextPropIt)->float_value;
307                 //cout << "Unk: " << val << "\n";
308                 pIt->second->setFloatValue(val);
309                 break;
310             }            
311           }
312           else
313           {
314             SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*prevPropIt)->id << "\n");
315           }
316           
317           ++prevPropIt;
318           ++nextPropIt;
319         }
320       }
321
322       // Now throw away too old data
323       if (prevIt != mMotionInfo.begin()) 
324       {
325         --prevIt;
326         mMotionInfo.erase(mMotionInfo.begin(), prevIt);
327       }
328     }
329   } else {
330     // Ok, we need to predict the future, so, take the best data we can have
331     // and do some eom computation to guess that for now.
332     FGExternalMotionData& motionInfo = it->second;
333
334     // The time to predict, limit to 5 seconds
335     double t = tInterp - motionInfo.time;
336     t = SGMisc<double>::min(t, 5);
337
338     SG_LOG(SG_AI, SG_DEBUG, "Multiplayer vehicle extrapolation: "
339            "extrapolation time = " << t);
340
341     // Do a few explicit euler steps with the constant acceleration's
342     // This must be sufficient ...
343     ecPos = motionInfo.position;
344     ecOrient = motionInfo.orientation;
345     SGVec3f linearVel = motionInfo.linearVel;
346     SGVec3f angularVel = motionInfo.angularVel;
347     while (0 < t) {
348       double h = 1e-1;
349       if (t < h)
350         h = t;
351
352       SGVec3d ecVel = toVec3d(ecOrient.backTransform(linearVel));
353       ecPos += h*ecVel;
354       ecOrient += h*ecOrient.derivative(angularVel);
355
356       linearVel += h*(cross(linearVel, angularVel) + motionInfo.linearAccel);
357       angularVel += h*motionInfo.angularAccel;
358       
359       t -= h;
360     }
361
362     std::vector<FGPropertyData*>::const_iterator firstPropIt;
363     std::vector<FGPropertyData*>::const_iterator firstPropItEnd;
364     speed = norm(linearVel) * SG_METER_TO_NM * 3600.0;
365     firstPropIt = it->second.properties.begin();
366     firstPropItEnd = it->second.properties.end();
367     while (firstPropIt != firstPropItEnd) {
368       PropertyMap::iterator pIt = mPropertyMap.find((*firstPropIt)->id);
369       //cout << " Setting property..." << (*firstPropIt)->id;
370       
371       if (pIt != mPropertyMap.end())
372       {
373         switch ((*firstPropIt)->type) {
374           case props::INT:
375           case props::BOOL:
376           case props::LONG:
377             pIt->second->setIntValue((*firstPropIt)->int_value);
378             //cout << "Int: " << (*firstPropIt)->int_value << "\n";
379             break;
380           case props::FLOAT:
381           case props::DOUBLE:
382             pIt->second->setFloatValue((*firstPropIt)->float_value);
383             //cout << "Flo: " << (*firstPropIt)->float_value << "\n";
384             break;
385           case props::STRING:
386           case props::UNSPECIFIED:
387             pIt->second->setStringValue((*firstPropIt)->string_value);
388             //cout << "Str: " << (*firstPropIt)->string_value << "\n";
389             break;
390           default:
391             // FIXME - currently defaults to float values
392             pIt->second->setFloatValue((*firstPropIt)->float_value);
393             //cout << "Unk: " << (*firstPropIt)->float_value << "\n";
394             break;
395         }            
396       }
397       else
398       {
399         SG_LOG(SG_AI, SG_DEBUG, "Unable to find property: " << (*firstPropIt)->id << "\n");
400       }
401       
402       ++firstPropIt;
403     }
404   }
405   
406   // extract the position
407   pos = SGGeod::fromCart(ecPos);
408   double recent_alt_ft = altitude_ft;
409   altitude_ft = pos.getElevationFt();
410
411   // expose a valid vertical speed
412   if (lastUpdateTime != 0)
413   {
414       double dT = curtime - lastUpdateTime;
415       double Weighting=1;
416       if (dt < 1.0)
417           Weighting = dt;
418       // simple smoothing over 1 second
419       vs = (1.0-Weighting)*vs +  Weighting * (altitude_ft - recent_alt_ft) / dT * 60;
420   }
421   lastUpdateTime = curtime;
422
423   // The quaternion rotating from the earth centered frame to the
424   // horizontal local frame
425   SGQuatf qEc2Hl = SGQuatf::fromLonLatRad((float)pos.getLongitudeRad(),
426                                           (float)pos.getLatitudeRad());
427   // The orientation wrt the horizontal local frame
428   SGQuatf hlOr = conj(qEc2Hl)*ecOrient;
429   float hDeg, pDeg, rDeg;
430   hlOr.getEulerDeg(hDeg, pDeg, rDeg);
431   hdg = hDeg;
432   roll = rDeg;
433   pitch = pDeg;
434
435   SG_LOG(SG_AI, SG_DEBUG, "Multiplayer position and orientation: "
436          << ecPos << ", " << hlOr);
437
438   //###########################//
439   // do calculations for radar //
440   //###########################//
441     double range_ft2 = UpdateRadar(manager);
442
443     //************************************//
444     // Tanker code                        //
445     //************************************//
446
447
448     if ( isTanker) {
449         //cout << "IS tanker ";
450         if ( (range_ft2 < 250.0 * 250.0) &&
451             (y_shift > 0.0)    &&
452             (elevation > 0.0) ){
453                 // refuel_node->setBoolValue(true);
454                  //cout << "in contact"  << endl;
455             contact = true;
456         } else {
457             // refuel_node->setBoolValue(false);
458             //cout << "not in contact"  << endl;
459             contact = false;
460         }
461     } else {
462         //cout << "NOT tanker " << endl;
463         contact = false;
464     }
465
466   Transform();
467 }
468
469 void
470 FGAIMultiplayer::addMotionInfo(FGExternalMotionData& motionInfo,
471                                long stamp)
472 {
473   mLastTimestamp = stamp;
474
475   if (!mMotionInfo.empty()) {
476     double diff = motionInfo.time - mMotionInfo.rbegin()->first;
477
478     // packet is very old -- MP has probably reset (incl. his timebase)
479     if (diff < -10.0)
480       mMotionInfo.clear();
481
482     // drop packets arriving out of order
483     else if (diff < 0.0)
484       return;
485   }
486   mMotionInfo[motionInfo.time] = motionInfo;
487   // We just copied the property (pointer) list - they are ours now. Clear the
488   // properties list in given/returned object, so former owner won't deallocate them.
489   motionInfo.properties.clear();
490 }
491
492 void
493 FGAIMultiplayer::setDoubleProperty(const std::string& prop, double val)
494 {
495   SGPropertyNode* pNode = props->getChild(prop.c_str(), true);
496   pNode->setDoubleValue(val);
497 }