]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
Traffic improvements.
[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/dynamics.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   speed       = 0;
51   crossat     = 0;
52   finished    = 0;
53   gear_down   = 0;
54   flaps_down  = 0;
55   on_ground   = 0;
56   routeIndex  = 0;
57   time_sec    = 0;
58   trackLength = 0;
59 }
60
61 bool FGAIWaypoint::contains(string target) {
62     size_t found = name.find(target);
63     if (found == string::npos)
64         return false;
65     else
66         return true;
67 }
68
69 double FGAIWaypoint::getLatitude()
70 {
71   return pos.getLatitudeDeg();
72 }
73
74 double FGAIWaypoint::getLongitude()
75 {
76   return pos.getLongitudeDeg();
77 }
78
79 double FGAIWaypoint::getAltitude()
80 {
81   return pos.getElevationFt();
82 }
83
84 void FGAIWaypoint::setLatitude(double lat)
85 {
86   pos.setLatitudeDeg(lat);
87 }
88
89 void FGAIWaypoint::setLongitude(double lon)
90 {
91   pos.setLongitudeDeg(lon);
92 }
93
94 void FGAIWaypoint::setAltitude(double alt)
95 {
96   pos.setElevationFt(alt);
97 }
98
99 FGAIFlightPlan::FGAIFlightPlan()
100 {
101     sid             = 0;
102     repeat          = false;
103     distance_to_go  = 0;
104     lead_distance   = 0;
105     start_time      = 0;
106     arrivalTime     = 0;
107     leg             = 10;
108     gateId          = 0;
109     lastNodeVisited = 0;
110     taxiRoute       = 0;
111     wpt_iterator    = waypoints.begin();
112     isValid         = true;
113 }
114
115 FGAIFlightPlan::FGAIFlightPlan(const string& filename)
116 {
117   sid               = 0;
118   repeat            = false;
119   distance_to_go    = 0;
120   lead_distance     = 0;
121   start_time        = 0;
122   arrivalTime       = 0;
123   leg               = 10;
124   gateId            = 0;
125   lastNodeVisited   = 0;
126   taxiRoute         = 0;
127
128
129   isValid = parseProperties(filename);
130 }
131
132
133 // This is a modified version of the constructor,
134 // Which not only reads the waypoints from a 
135 // Flight plan file, but also adds the current
136 // Position computed by the traffic manager, as well
137 // as setting speeds and altitude computed by the
138 // traffic manager. 
139 FGAIFlightPlan::FGAIFlightPlan(FGAIAircraft *ac,
140                                const std::string& p,
141                                double course,
142                                time_t start,
143                                FGAirport *dep,
144                                FGAirport *arr,
145                                bool firstLeg,
146                                double radius,
147                                double alt,
148                                double lat,
149                                double lon,
150                                double speed,
151                                const string& fltType,
152                                const string& acType,
153                                const string& airline) :
154   departure(dep),
155   arrival(arr)
156 {
157   sid               = 0;
158   repeat            = false;
159   distance_to_go    = 0;
160   lead_distance     = 0;
161   start_time        = start;
162   arrivalTime       = 0;
163   leg               = 10;
164   gateId            = 0;
165   lastNodeVisited   = 0;
166   taxiRoute         = 0;
167
168   if (parseProperties(p)) {
169     isValid = true;
170   } else {
171     createWaypoints(ac, course, start, dep, arr, firstLeg, radius,
172                     alt, lat, lon, speed, fltType, acType, airline);
173   }
174 }
175
176 FGAIFlightPlan::~FGAIFlightPlan()
177 {
178   deleteWaypoints();
179   delete taxiRoute;
180
181 // if we're parked at a gate, release it
182   if (gateId >= 0) {
183     FGAirport* apt = (leg >= 7) ? arrival : departure;
184     if (apt) {
185       SG_LOG(SG_AI, SG_INFO, "releasing parking gate " << gateId << " at " << apt->ident());
186       apt->getDynamics()->releaseParking(gateId);
187     }
188   }
189 }
190
191 void FGAIFlightPlan::createWaypoints(FGAIAircraft *ac,
192                                      double course,
193                                      time_t start,
194                                      FGAirport *dep,
195                                      FGAirport *arr,
196                                      bool firstLeg,
197                                      double radius,
198                                      double alt,
199                                      double lat,
200                                      double lon,
201                                      double speed,
202                                      const string& fltType,
203                                      const string& acType,
204                                      const string& airline)
205 {
206   time_t now = time(NULL) + fgGetLong("/sim/time/warp");
207   time_t timeDiff = now-start;
208   leg = 1;
209   
210   if ((timeDiff > 60) && (timeDiff < 1500))
211     leg = 2;
212   //else if ((timeDiff >= 1200) && (timeDiff < 1500)) {
213         //leg = 3;
214   //ac->setTakeOffStatus(2);
215   //}
216   else if ((timeDiff >= 1500) && (timeDiff < 2000))
217     leg = 4;
218   else if (timeDiff >= 2000)
219     leg = 5;
220   /*
221    if (timeDiff >= 2000)
222    leg = 5;
223    */
224   SG_LOG(SG_AI, SG_INFO, "Route from " << dep->getId() << " to " << arr->getId() << ". Set leg to : " << leg << " " << ac->getTrafficRef()->getCallSign());
225   wpt_iterator = waypoints.begin();
226   bool dist = 0;
227   isValid = create(ac, dep, arr, leg, alt, speed, lat, lon,
228                    firstLeg, radius, fltType, acType, airline, dist);
229   wpt_iterator = waypoints.begin();
230  
231 }
232
233 bool FGAIFlightPlan::parseProperties(const std::string& filename)
234 {
235   SGPath path( globals->get_fg_root() );
236   path.append( "/AI/FlightPlans/" + filename );
237   if (!path.exists()) {
238     return false;
239   }
240   
241   SGPropertyNode root;
242   try {
243     readProperties(path.str(), &root);
244   } catch (const sg_exception &e) {
245     SG_LOG(SG_AI, SG_ALERT, "Error reading AI flight plan: " << path.str()
246            << "message:" << e.getFormattedMessage());
247     return false;
248   }
249   
250   SGPropertyNode * node = root.getNode("flightplan");
251   for (int i = 0; i < node->nChildren(); i++) {
252     FGAIWaypoint* wpt = new FGAIWaypoint;
253     SGPropertyNode * wpt_node = node->getChild(i);
254     wpt->setName       (wpt_node->getStringValue("name", "END"     ));
255     wpt->setLatitude   (wpt_node->getDoubleValue("lat", 0          ));
256     wpt->setLongitude  (wpt_node->getDoubleValue("lon", 0          ));
257     wpt->setAltitude   (wpt_node->getDoubleValue("alt", 0          ));
258     wpt->setSpeed      (wpt_node->getDoubleValue("ktas", 0         ));
259     wpt->setCrossat    (wpt_node->getDoubleValue("crossat", -10000 ));
260     wpt->setGear_down  (wpt_node->getBoolValue("gear-down", false  ));
261     wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
262     wpt->setOn_ground  (wpt_node->getBoolValue("on-ground", false  ));
263     wpt->setTime_sec   (wpt_node->getDoubleValue("time-sec", 0     ));
264     wpt->setTime       (wpt_node->getStringValue("time", ""        ));
265     wpt->setFinished   ((wpt->getName() == "END"));
266     pushBackWaypoint( wpt );
267   }
268   
269   wpt_iterator = waypoints.begin();
270   return true;
271 }
272
273 FGAIWaypoint* const FGAIFlightPlan::getPreviousWaypoint( void ) const
274 {
275   if (wpt_iterator == waypoints.begin()) {
276     return 0;
277   } else {
278     wpt_vector_iterator prev = wpt_iterator;
279     return *(--prev);
280   }
281 }
282
283 FGAIWaypoint* const FGAIFlightPlan::getCurrentWaypoint( void ) const
284 {
285   if (wpt_iterator == waypoints.end())
286       return 0;
287   return *wpt_iterator;
288 }
289
290 FGAIWaypoint* const FGAIFlightPlan::getNextWaypoint( void ) const
291 {
292   wpt_vector_iterator i = waypoints.end();
293   i--;  // end() points to one element after the last one. 
294   if (wpt_iterator == i) {
295     return 0;
296   } else {
297     wpt_vector_iterator next = wpt_iterator;
298     return *(++next);
299   }
300 }
301
302 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
303 {
304   if (eraseWaypoints)
305     {
306       if (wpt_iterator == waypoints.begin())
307         wpt_iterator++;
308       else
309         {
310           delete *(waypoints.begin());
311           waypoints.erase(waypoints.begin());
312           wpt_iterator = waypoints.begin();
313           wpt_iterator++;
314         }
315     }
316   else
317     wpt_iterator++;
318
319 }
320
321 void FGAIFlightPlan::DecrementWaypoint(bool eraseWaypoints )
322 {
323     if (eraseWaypoints)
324     {
325         if (wpt_iterator == waypoints.end())
326             wpt_iterator--;
327         else
328         {
329             delete *(waypoints.end());
330             waypoints.erase(waypoints.end());
331             wpt_iterator = waypoints.end();
332             wpt_iterator--;
333         }
334     }
335     else
336         wpt_iterator--;
337 }
338
339 void FGAIFlightPlan::eraseLastWaypoint()
340 {
341     delete (waypoints.back());
342     waypoints.pop_back();;
343     wpt_iterator = waypoints.begin();
344     wpt_iterator++;
345 }
346
347
348
349
350 // gives distance in feet from a position to a waypoint
351 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, FGAIWaypoint* wp) const{
352   return SGGeodesy::distanceM(SGGeod::fromDeg(lon, lat), wp->getPos());
353 }
354
355 // sets distance in feet from a lead point to the current waypoint
356 void FGAIFlightPlan::setLeadDistance(double speed, double bearing, 
357                                      FGAIWaypoint* current, FGAIWaypoint* next){
358   double turn_radius;
359   // Handle Ground steering
360   // At a turn rate of 30 degrees per second, it takes 12 seconds to do a full 360 degree turn
361   // So, to get an estimate of the turn radius, calculate the cicumference of the circle
362   // we travel on. Get the turn radius by dividing by PI (*2).
363   if (speed < 0.5) {
364         lead_distance = 0.5;
365         return;
366   }
367   if (speed < 25) {
368        turn_radius = ((360/30)*fabs(speed)) / (2*M_PI);
369   } else 
370       turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
371
372   double inbound = bearing;
373   double outbound = getBearing(current, next);
374   leadInAngle = fabs(inbound - outbound);
375   if (leadInAngle > 180.0) 
376     leadInAngle = 360.0 - leadInAngle;
377   //if (leadInAngle < 30.0) // To prevent lead_dist from getting so small it is skipped 
378   //  leadInAngle = 30.0;
379   
380   //lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); 
381   lead_distance = turn_radius * tan((leadInAngle * SG_DEGREES_TO_RADIANS)/2);
382   /*
383   if ((lead_distance > (3*turn_radius)) && (current->on_ground == false)) {
384       // cerr << "Warning: Lead-in distance is large. Inbound = " << inbound
385       //      << ". Outbound = " << outbound << ". Lead in angle = " << leadInAngle  << ". Turn radius = " << turn_radius << endl;
386        lead_distance = 3 * turn_radius;
387        return;
388   }
389   if ((leadInAngle > 90) && (current->on_ground == true)) {
390       lead_distance = turn_radius * tan((90 * SG_DEGREES_TO_RADIANS)/2);
391       return;
392   }*/
393 }
394
395 void FGAIFlightPlan::setLeadDistance(double distance_ft){
396   lead_distance = distance_ft;
397 }
398
399
400 double FGAIFlightPlan::getBearing(FGAIWaypoint* first, FGAIWaypoint* second) const
401 {
402   return SGGeodesy::courseDeg(first->getPos(), second->getPos());
403 }
404
405 double FGAIFlightPlan::getBearing(const SGGeod& aPos, FGAIWaypoint* wp) const
406 {
407   return SGGeodesy::courseDeg(aPos, wp->getPos());
408 }
409
410 void FGAIFlightPlan::deleteWaypoints()
411 {
412   for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
413     delete (*i);
414   waypoints.clear();
415 }
416
417 // Delete all waypoints except the last, 
418 // which we will recycle as the first waypoint in the next leg;
419 void FGAIFlightPlan::resetWaypoints()
420 {
421   if (waypoints.begin() == waypoints.end())
422     return;
423   else
424     {
425       FGAIWaypoint *wpt = new FGAIWaypoint;
426       wpt_vector_iterator i = waypoints.end();
427       i--;
428       wpt->setName        ( (*i)->getName()       );
429       wpt->setPos         ( (*i)->getPos()        );
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 }