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