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