]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
1ec20e1881935e65dec9a4ef61566c11c15e423e
[flightgear.git] / src / AIModel / AIFlightPlan.cxx
1 // // FGAIFlightPlan - class for loading and storing  AI flight plans
2 // Written by David Culp, started May 2004
3 // - davidculp2@comcast.net
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 #ifdef HAVE_CONFIG_H
20 #  include <config.h>
21 #endif
22
23 #include <iostream>
24
25 #include <simgear/misc/sg_path.hxx>
26 #include <simgear/debug/logstream.hxx>
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/structure/exception.hxx>
29 #include <simgear/constants.h>
30 #include <simgear/props/props.hxx>
31 #include <simgear/props/props_io.hxx>
32
33 #include <Main/globals.hxx>
34 #include <Main/fg_props.hxx>
35 #include <Main/fg_init.hxx>
36 #include <Airports/simple.hxx>
37 #include <Airports/runways.hxx>
38 #include <Airports/groundnetwork.hxx>
39
40 #include <Environment/environment_mgr.hxx>
41 #include <Environment/environment.hxx>
42
43 #include "AIFlightPlan.hxx"
44 #include "AIAircraft.hxx"
45
46 using std::cerr;
47
48 FGAIWaypoint::FGAIWaypoint() {
49   speed       = 0;
50   crossat     = 0;
51   finished    = 0;
52   gear_down   = 0;
53   flaps_down  = 0;
54   on_ground   = 0;
55   routeIndex  = 0;
56   time_sec    = 0;
57   trackLength = 0;
58 }
59
60 bool FGAIWaypoint::contains(string target) {
61     size_t found = name.find(target);
62     if (found == string::npos)
63         return false;
64     else
65         return true;
66 }
67
68 double FGAIWaypoint::getLatitude()
69 {
70   return pos.getLatitudeDeg();
71 }
72
73 double FGAIWaypoint::getLongitude()
74 {
75   return pos.getLongitudeDeg();
76 }
77
78 double FGAIWaypoint::getAltitude()
79 {
80   return pos.getElevationFt();
81 }
82
83 void FGAIWaypoint::setLatitude(double lat)
84 {
85   pos.setLatitudeDeg(lat);
86 }
87
88 void FGAIWaypoint::setLongitude(double lon)
89 {
90   pos.setLongitudeDeg(lon);
91 }
92
93 void FGAIWaypoint::setAltitude(double alt)
94 {
95   pos.setElevationFt(alt);
96 }
97
98 FGAIFlightPlan::FGAIFlightPlan()
99 {
100     sid             = 0;
101     repeat          = false;
102     distance_to_go  = 0;
103     lead_distance   = 0;
104     start_time      = 0;
105     arrivalTime     = 0;
106     leg             = 10;
107     gateId          = 0;
108     lastNodeVisited = 0;
109     taxiRoute       = 0;
110     wpt_iterator    = waypoints.begin();
111     isValid         = true;
112 }
113
114 FGAIFlightPlan::FGAIFlightPlan(const string& filename)
115 {
116   sid               = 0;
117   repeat            = false;
118   distance_to_go    = 0;
119   lead_distance     = 0;
120   start_time        = 0;
121   arrivalTime       = 0;
122   leg               = 10;
123   gateId            = 0;
124   lastNodeVisited   = 0;
125   taxiRoute         = 0;
126
127   SGPath path( globals->get_fg_root() );
128   path.append( ("/AI/FlightPlans/" + filename).c_str() );
129   SGPropertyNode root;
130
131   try {
132       readProperties(path.str(), &root);
133   } catch (const sg_exception &) {
134       SG_LOG(SG_AI, SG_ALERT,
135        "Error reading AI flight plan: " << path.str());
136        // cout << path.str() << endl;
137      return;
138   }
139
140   SGPropertyNode * node = root.getNode("flightplan");
141   for (int i = 0; i < node->nChildren(); i++) {
142      //cout << "Reading waypoint " << i << endl;        
143      FGAIWaypoint* wpt = new FGAIWaypoint;
144      SGPropertyNode * wpt_node = node->getChild(i);
145      wpt->setName       (wpt_node->getStringValue("name", "END"     ));
146      wpt->setLatitude   (wpt_node->getDoubleValue("lat", 0          ));
147      wpt->setLongitude  (wpt_node->getDoubleValue("lon", 0          ));
148      wpt->setAltitude   (wpt_node->getDoubleValue("alt", 0          ));
149      wpt->setSpeed      (wpt_node->getDoubleValue("ktas", 0         ));
150      wpt->setCrossat    (wpt_node->getDoubleValue("crossat", -10000 ));
151      wpt->setGear_down  (wpt_node->getBoolValue("gear-down", false  ));
152      wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
153      wpt->setOn_ground  (wpt_node->getBoolValue("on-ground", false  ));
154      wpt->setTime_sec   (wpt_node->getDoubleValue("time-sec", 0     ));
155      wpt->setTime       (wpt_node->getStringValue("time", ""        ));
156
157      if (wpt->getName() == "END") wpt->setFinished(true);
158      else wpt->setFinished(false);
159
160      pushBackWaypoint( wpt );
161    }
162
163   wpt_iterator = waypoints.begin();
164   isValid = true;
165   //cout << waypoints.size() << " waypoints read." << endl;
166 }
167
168
169 // This is a modified version of the constructor,
170 // Which not only reads the waypoints from a 
171 // Flight plan file, but also adds the current
172 // Position computed by the traffic manager, as well
173 // as setting speeds and altitude computed by the
174 // traffic manager. 
175 FGAIFlightPlan::FGAIFlightPlan(FGAIAircraft *ac,
176                                const std::string& p,
177                                double course,
178                                time_t start,
179                                FGAirport *dep,
180                                FGAirport *arr,
181                                bool firstLeg,
182                                double radius,
183                                double alt,
184                                double lat,
185                                double lon,
186                                double speed,
187                                const string& fltType,
188                                const string& acType,
189                                const string& airline)
190 {
191   sid               = 0;
192   repeat            = false;
193   distance_to_go    = 0;
194   lead_distance     = 0;
195   start_time        = start;
196   arrivalTime       = 0;
197   leg               = 10;
198   gateId            = 0;
199   lastNodeVisited   = 0;
200   taxiRoute         = 0;
201
202   SGPath path( globals->get_fg_root() );
203   path.append( "/AI/FlightPlans" );
204   path.append( p );
205   
206   SGPropertyNode root;
207   isValid = true;
208
209   // This is a bit of a hack:
210   // Normally the value of course will be used to evaluate whether
211   // or not a waypoint will be used for midair initialization of 
212   // an AI aircraft. However, if a course value of 999 will be passed
213   // when an update request is received, which will by definition always be
214   // on the ground and should include all waypoints.
215 //  bool useInitialWayPoint = true;
216 //  bool useCurrentWayPoint = false;
217 //  if (course == 999)
218 //    {
219 //      useInitialWayPoint = false;
220 //      useCurrentWayPoint = true;
221 //    }
222
223   if (path.exists()) 
224     {
225       try 
226         {
227           readProperties(path.str(), &root);
228           
229           SGPropertyNode * node = root.getNode("flightplan");
230           
231           //pushBackWaypoint( init_waypoint );
232           for (int i = 0; i < node->nChildren(); i++) { 
233             //cout << "Reading waypoint " << i << endl;
234             FGAIWaypoint* wpt = new FGAIWaypoint;
235             SGPropertyNode * wpt_node = node->getChild(i);
236             wpt->setName       (wpt_node->getStringValue("name", "END"     ));
237             wpt->setLatitude   (wpt_node->getDoubleValue("lat", 0          ));
238             wpt->setLongitude  (wpt_node->getDoubleValue("lon", 0          ));
239             wpt->setAltitude   (wpt_node->getDoubleValue("alt", 0          ));
240             wpt->setSpeed      (wpt_node->getDoubleValue("ktas", 0         ));
241             wpt->setCrossat    (wpt_node->getDoubleValue("crossat", -10000 ));
242             wpt->setGear_down  (wpt_node->getBoolValue("gear-down", false  ));
243             wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
244             
245             if (wpt->getName() == "END") wpt->setFinished(true);
246             else wpt->setFinished(false);
247             pushBackWaypoint(wpt);
248           } // of node loop
249           wpt_iterator = waypoints.begin();
250         } catch (const sg_exception &e) {
251       SG_LOG(SG_AI, SG_WARN, "Error reading AI flight plan: " <<
252         e.getMessage() << " from " << e.getOrigin());
253     }
254   } else {
255       // cout << path.str() << endl;
256       // cout << "Trying to create this plan dynamically" << endl;
257       // cout << "Route from " << dep->id << " to " << arr->id << endl;
258       time_t now = time(NULL) + fgGetLong("/sim/time/warp");
259       time_t timeDiff = now-start; 
260       leg = 1;
261       
262       if ((timeDiff > 60) && (timeDiff < 1500))
263         leg = 2;
264       //else if ((timeDiff >= 1200) && (timeDiff < 1500)) {
265         //leg = 3;
266         //ac->setTakeOffStatus(2);
267       //}
268       else if ((timeDiff >= 1500) && (timeDiff < 2000))
269         leg = 4;
270       else if (timeDiff >= 2000)
271         leg = 5;
272       /*
273       if (timeDiff >= 2000)
274           leg = 5;
275       */
276       SG_LOG(SG_AI, SG_INFO, "Route from " << dep->getId() << " to " << arr->getId() << ". Set leg to : " << leg << " " << ac->getTrafficRef()->getCallSign());
277       wpt_iterator = waypoints.begin();
278       bool dist = 0;
279       isValid = create(ac, dep,arr, leg, alt, speed, lat, lon,
280              firstLeg, radius, fltType, acType, airline, dist);
281       wpt_iterator = waypoints.begin();
282     }
283
284 }
285
286
287
288
289 FGAIFlightPlan::~FGAIFlightPlan()
290 {
291   deleteWaypoints();
292   delete taxiRoute;
293 }
294
295
296 FGAIWaypoint* const FGAIFlightPlan::getPreviousWaypoint( void ) const
297 {
298   if (wpt_iterator == waypoints.begin()) {
299     return 0;
300   } else {
301     wpt_vector_iterator prev = wpt_iterator;
302     return *(--prev);
303   }
304 }
305
306 FGAIWaypoint* const FGAIFlightPlan::getCurrentWaypoint( void ) const
307 {
308   if (wpt_iterator == waypoints.end())
309       return 0;
310   return *wpt_iterator;
311 }
312
313 FGAIWaypoint* const FGAIFlightPlan::getNextWaypoint( void ) const
314 {
315   wpt_vector_iterator i = waypoints.end();
316   i--;  // end() points to one element after the last one. 
317   if (wpt_iterator == i) {
318     return 0;
319   } else {
320     wpt_vector_iterator next = wpt_iterator;
321     return *(++next);
322   }
323 }
324
325 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
326 {
327   if (eraseWaypoints)
328     {
329       if (wpt_iterator == waypoints.begin())
330         wpt_iterator++;
331       else
332         {
333           delete *(waypoints.begin());
334           waypoints.erase(waypoints.begin());
335           wpt_iterator = waypoints.begin();
336           wpt_iterator++;
337         }
338     }
339   else
340     wpt_iterator++;
341
342 }
343
344 void FGAIFlightPlan::DecrementWaypoint(bool eraseWaypoints )
345 {
346     if (eraseWaypoints)
347     {
348         if (wpt_iterator == waypoints.end())
349             wpt_iterator--;
350         else
351         {
352             delete *(waypoints.end());
353             waypoints.erase(waypoints.end());
354             wpt_iterator = waypoints.end();
355             wpt_iterator--;
356         }
357     }
358     else
359         wpt_iterator--;
360 }
361
362 void FGAIFlightPlan::eraseLastWaypoint()
363 {
364     delete (waypoints.back());
365     waypoints.pop_back();;
366     wpt_iterator = waypoints.begin();
367     wpt_iterator++;
368 }
369
370
371
372
373 // gives distance in feet from a position to a waypoint
374 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, FGAIWaypoint* wp) const{
375   return SGGeodesy::distanceM(SGGeod::fromDeg(lon, lat), wp->getPos());
376 }
377
378 // sets distance in feet from a lead point to the current waypoint
379 void FGAIFlightPlan::setLeadDistance(double speed, double bearing, 
380                                      FGAIWaypoint* current, FGAIWaypoint* next){
381   double turn_radius;
382   // Handle Ground steering
383   // At a turn rate of 30 degrees per second, it takes 12 seconds to do a full 360 degree turn
384   // So, to get an estimate of the turn radius, calculate the cicumference of the circle
385   // we travel on. Get the turn radius by dividing by PI (*2).
386   if (speed < 0.5) {
387         lead_distance = 0.5;
388         return;
389   }
390   if (speed < 25) {
391        turn_radius = ((360/30)*fabs(speed)) / (2*M_PI);
392   } else 
393       turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
394
395   double inbound = bearing;
396   double outbound = getBearing(current, next);
397   leadInAngle = fabs(inbound - outbound);
398   if (leadInAngle > 180.0) 
399     leadInAngle = 360.0 - leadInAngle;
400   //if (leadInAngle < 30.0) // To prevent lead_dist from getting so small it is skipped 
401   //  leadInAngle = 30.0;
402   
403   //lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); 
404   lead_distance = turn_radius * tan((leadInAngle * SG_DEGREES_TO_RADIANS)/2);
405   /*
406   if ((lead_distance > (3*turn_radius)) && (current->on_ground == false)) {
407       // cerr << "Warning: Lead-in distance is large. Inbound = " << inbound
408       //      << ". Outbound = " << outbound << ". Lead in angle = " << leadInAngle  << ". Turn radius = " << turn_radius << endl;
409        lead_distance = 3 * turn_radius;
410        return;
411   }
412   if ((leadInAngle > 90) && (current->on_ground == true)) {
413       lead_distance = turn_radius * tan((90 * SG_DEGREES_TO_RADIANS)/2);
414       return;
415   }*/
416 }
417
418 void FGAIFlightPlan::setLeadDistance(double distance_ft){
419   lead_distance = distance_ft;
420 }
421
422
423 double FGAIFlightPlan::getBearing(FGAIWaypoint* first, FGAIWaypoint* second) const
424 {
425   return SGGeodesy::courseDeg(first->getPos(), second->getPos());
426 }
427
428
429 double FGAIFlightPlan::getBearing(double lat, double lon, FGAIWaypoint* wp) const
430 {
431   return SGGeodesy::courseDeg(SGGeod::fromDeg(lon, lat), wp->getPos());
432 }
433
434 void FGAIFlightPlan::deleteWaypoints()
435 {
436   for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
437     delete (*i);
438   waypoints.clear();
439 }
440
441 // Delete all waypoints except the last, 
442 // which we will recycle as the first waypoint in the next leg;
443 void FGAIFlightPlan::resetWaypoints()
444 {
445   if (waypoints.begin() == waypoints.end())
446     return;
447   else
448     {
449       FGAIWaypoint *wpt = new FGAIWaypoint;
450       wpt_vector_iterator i = waypoints.end();
451       i--;
452       wpt->setName        ( (*i)->getName()       );
453       wpt->setPos         ( (*i)->getPos()        );
454       wpt->setCrossat     ( (*i)->getCrossat()    );
455       wpt->setGear_down   ( (*i)->getGear_down()  );
456       wpt->setFlaps_down  ( (*i)->getFlaps_down() );
457       wpt->setFinished    ( false                 );
458       wpt->setOn_ground   ( (*i)->getOn_ground()  );
459       //cerr << "Recycling waypoint " << wpt->name << endl;
460       deleteWaypoints();
461       pushBackWaypoint(wpt);
462     }
463 }
464
465 void FGAIFlightPlan::pushBackWaypoint(FGAIWaypoint *wpt)
466 {
467   // std::vector::push_back invalidates waypoints
468   //  so we should restore wpt_iterator after push_back
469   //  (or it could be an index in the vector)
470   size_t pos = wpt_iterator - waypoints.begin();
471   waypoints.push_back(wpt);
472   wpt_iterator = waypoints.begin() + pos;
473 }
474
475 // Start flightplan over from the beginning
476 void FGAIFlightPlan::restart()
477 {
478   wpt_iterator = waypoints.begin();
479 }
480
481
482 void FGAIFlightPlan::deleteTaxiRoute() 
483 {
484   delete taxiRoute;
485   taxiRoute = 0;
486 }
487
488
489 int FGAIFlightPlan::getRouteIndex(int i) {
490   if ((i > 0) && (i < (int)waypoints.size())) {
491     return waypoints[i]->getRouteIndex();
492   }
493   else
494     return 0;
495 }
496
497
498 double FGAIFlightPlan::checkTrackLength(string wptName) {
499     // skip the first two waypoints: first one is behind, second one is partially done;
500     double trackDistance = 0;
501     wpt_vector_iterator wptvec = waypoints.begin();
502     wptvec++;
503     wptvec++;
504     while ((wptvec != waypoints.end()) && (!((*wptvec)->contains(wptName)))) {
505            trackDistance += (*wptvec)->getTrackLength();
506            wptvec++;
507     }
508     if (wptvec == waypoints.end()) {
509         trackDistance = 0; // name not found
510     }
511     return trackDistance;
512 }
513
514 void FGAIFlightPlan::shortenToFirst(unsigned int number, string name)
515 {
516     while (waypoints.size() > number + 3) {
517         eraseLastWaypoint();
518     }
519     (waypoints.back())->setName((waypoints.back())->getName() + name);
520 }