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