]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
2d1887582eda1e42151cbd26e78b861d918d2445
[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 <simgear/misc/sg_path.hxx>
24 #include <simgear/debug/logstream.hxx>
25 #include <simgear/route/waypoint.hxx>
26 #include <simgear/math/sg_geodesy.hxx>
27 #include <simgear/structure/exception.hxx>
28 #include <simgear/constants.h>
29 #ifdef __BORLANDC__
30 #  define exception c_exception
31 #endif
32 #include <simgear/props/props.hxx>
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
39
40 #include <Environment/environment_mgr.hxx>
41 #include <Environment/environment.hxx>
42
43 #include "AIFlightPlan.hxx"
44
45
46 FGAIFlightPlan::FGAIFlightPlan(const string& filename)
47 {
48   int i;
49   start_time = 0;
50   leg = 10;
51   gateId = 0;
52   taxiRoute = 0;
53   SGPath path( globals->get_fg_root() );
54   path.append( ("/AI/FlightPlans/" + filename).c_str() );
55   SGPropertyNode root;
56   repeat = false;
57
58   try {
59       readProperties(path.str(), &root);
60   } catch (const sg_exception &e) {
61       SG_LOG(SG_GENERAL, SG_ALERT,
62        "Error reading AI flight plan: " << path.str());
63        // cout << path.str() << endl;
64      return;
65   }
66
67   SGPropertyNode * node = root.getNode("flightplan");
68   for (i = 0; i < node->nChildren(); i++) { 
69      //cout << "Reading waypoint " << i << endl;        
70      waypoint* wpt = new waypoint;
71      SGPropertyNode * wpt_node = node->getChild(i);
72      wpt->name      = wpt_node->getStringValue("name", "END");
73      wpt->latitude  = wpt_node->getDoubleValue("lat", 0);
74      wpt->longitude = wpt_node->getDoubleValue("lon", 0);
75      wpt->altitude  = wpt_node->getDoubleValue("alt", 0);
76      wpt->speed     = wpt_node->getDoubleValue("ktas", 0);
77      wpt->crossat   = wpt_node->getDoubleValue("crossat", -10000);
78      wpt->gear_down = wpt_node->getBoolValue("gear-down", false);
79      wpt->flaps_down= wpt_node->getBoolValue("flaps-down", false);
80      wpt->on_ground = wpt_node->getBoolValue("on-ground", false);
81      wpt->time_sec   = wpt_node->getDoubleValue("time-sec", 0);
82      wpt->time       = wpt_node->getStringValue("time", "");
83
84      if (wpt->name == "END") wpt->finished = true;
85      else wpt->finished = false;
86
87      waypoints.push_back( wpt );
88    }
89
90   wpt_iterator = waypoints.begin();
91   //cout << waypoints.size() << " waypoints read." << endl;
92 }
93
94
95 // This is a modified version of the constructor,
96 // Which not only reads the waypoints from a 
97 // Flight plan file, but also adds the current
98 // Position computed by the traffic manager, as well
99 // as setting speeds and altitude computed by the
100 // traffic manager. 
101 FGAIFlightPlan::FGAIFlightPlan(const std::string& p,
102                                double course,
103                                time_t start,
104                                FGAirport *dep,
105                                FGAirport *arr,
106                                bool firstLeg,
107                                double radius,
108                                double alt,
109                                double lat,
110                                double lon,
111                                double speed,
112                                const string& fltType,
113                                const string& acType,
114                                const string& airline)
115 {
116   repeat = false;
117   leg = 10;
118   gateId=0;
119   taxiRoute = 0;
120   start_time = start;
121   bool useInitialWayPoint = true;
122   bool useCurrentWayPoint = false;
123   SGPath path( globals->get_fg_root() );
124   path.append( "/AI/FlightPlans" );
125   path.append( p );
126   
127   SGPropertyNode root;
128   
129   // This is a bit of a hack:
130   // Normally the value of course will be used to evaluate whether
131   // or not a waypoint will be used for midair initialization of 
132   // an AI aircraft. However, if a course value of 999 will be passed
133   // when an update request is received, which will by definition always be
134   // on the ground and should include all waypoints.
135   if (course == 999) 
136     {
137       useInitialWayPoint = false;
138       useCurrentWayPoint = true;
139     }
140
141   if (path.exists()) 
142     {
143       try 
144         {
145           readProperties(path.str(), &root);
146           
147           SGPropertyNode * node = root.getNode("flightplan");
148           
149           //waypoints.push_back( init_waypoint );
150           for (int i = 0; i < node->nChildren(); i++) { 
151             //cout << "Reading waypoint " << i << endl;
152             waypoint* wpt = new waypoint;
153             SGPropertyNode * wpt_node = node->getChild(i);
154             wpt->name      = wpt_node->getStringValue("name", "END");
155             wpt->latitude  = wpt_node->getDoubleValue("lat", 0);
156             wpt->longitude = wpt_node->getDoubleValue("lon", 0);
157             wpt->altitude  = wpt_node->getDoubleValue("alt", 0);
158             wpt->speed     = wpt_node->getDoubleValue("ktas", 0);
159             //wpt->speed     = speed;
160             wpt->crossat   = wpt_node->getDoubleValue("crossat", -10000);
161             wpt->gear_down = wpt_node->getBoolValue("gear-down", false);
162             wpt->flaps_down= wpt_node->getBoolValue("flaps-down", false);
163             
164             if (wpt->name == "END") wpt->finished = true;
165             else wpt->finished = false;
166             waypoints.push_back(wpt);
167           }
168         }
169       catch (const sg_exception &e) {
170         SG_LOG(SG_GENERAL, SG_WARN,
171                "Error reading AI flight plan: ");
172         cerr << "Errno = " << errno << endl;
173         if (errno == ENOENT)
174           {
175             cerr << "Reason: No such file or directory" << endl;
176           }
177       }
178     }
179   else
180     {
181       // cout << path.str() << endl;
182       // cout << "Trying to create this plan dynamically" << endl;
183       // cout << "Route from " << dep->id << " to " << arr->id << endl;
184       time_t now = time(NULL) + fgGetLong("/sim/time/warp");
185       time_t timeDiff = now-start; 
186       leg = 1;
187       if ((timeDiff > 300) && (timeDiff < 1200))
188         leg = 2;
189       else if ((timeDiff >= 1200) && (timeDiff < 1500))
190         leg = 3;
191       else if ((timeDiff >= 1500) && (timeDiff < 2000))
192         leg = 4;
193       else if (timeDiff >= 2000)
194         leg = 5;
195       
196       //cerr << "Set leg to : " << leg << endl;  
197       wpt_iterator = waypoints.begin();
198       create(dep,arr, leg, alt, speed, lat, lon,
199              firstLeg, radius, fltType, acType, airline);
200       wpt_iterator = waypoints.begin();
201       //cerr << "after create: " << (*wpt_iterator)->name << endl;
202       //leg++;
203       // Now that we have dynamically created a flight plan,
204       // we need to add some code that pops any waypoints already past.
205       //return;
206     }
207   /*
208     waypoint* init_waypoint   = new waypoint;
209     init_waypoint->name       = string("initial position");
210     init_waypoint->latitude   = entity->latitude;
211     init_waypoint->longitude  = entity->longitude;
212     init_waypoint->altitude   = entity->altitude;
213     init_waypoint->speed      = entity->speed;
214     init_waypoint->crossat    = - 10000;
215     init_waypoint->gear_down  = false;
216     init_waypoint->flaps_down = false;
217     init_waypoint->finished   = false;
218     
219     wpt_vector_iterator i = waypoints.begin();
220     while (i != waypoints.end())
221     {
222       //cerr << "Checking status of each waypoint: " << (*i)->name << endl;
223        SGWayPoint first(init_waypoint->longitude, 
224                        init_waypoint->latitude, 
225                        init_waypoint->altitude);
226       SGWayPoint curr ((*i)->longitude, 
227                        (*i)->latitude, 
228                        (*i)->altitude);
229       double crse, crsDiff;
230       double dist;
231       curr.CourseAndDistance(first, &crse, &dist);
232       
233       dist *= SG_METER_TO_NM;
234       
235       // We're only interested in the absolute value of crsDiff
236       // wich should fall in the 0-180 deg range.
237       crsDiff = fabs(crse-course);
238       if (crsDiff > 180)
239         crsDiff = 360-crsDiff;
240       // These are the three conditions that we consider including
241       // in our flight plan:
242       // 1) current waypoint is less then 100 miles away OR
243       // 2) curren waypoint is ahead of us, at any distance
244      
245       if ((dist > 20.0) && (crsDiff > 90.0) && ((*i)->name != string ("EOF")))
246         {
247           //useWpt = false;
248           // Once we start including waypoints, we have to continue, even though
249           // one of the following way point would suffice. 
250           // so once is the useWpt flag is set to true, we cannot reset it to false.
251           //cerr << "Discarding waypoint: " << (*i)->name 
252           //   << ": Course difference = " << crsDiff
253           //  << "Course = " << course
254           // << "crse   = " << crse << endl;
255         }
256       else
257         useCurrentWayPoint = true;
258       
259       if (useCurrentWayPoint)
260         {
261           if ((dist > 100.0) && (useInitialWayPoint))
262             {
263               //waypoints.push_back(init_waypoint);;
264               waypoints.insert(i, init_waypoint);
265               //cerr << "Using waypoint : " << init_waypoint->name <<  endl;
266             }
267           //if (useInitialWayPoint)
268           // {
269           //    (*i)->speed = dist; // A hack
270           //  }
271           //waypoints.push_back( wpt );
272           //cerr << "Using waypoint : " << (*i)->name 
273           //  << ": course diff : " << crsDiff 
274           //   << "Course = " << course
275           //   << "crse   = " << crse << endl
276           //    << "distance      : " << dist << endl;
277           useInitialWayPoint = false;
278           i++;
279         }
280       else 
281         {
282           //delete wpt;
283           delete *(i);
284           i = waypoints.erase(i);
285           }
286           
287         }
288   */
289   //for (i = waypoints.begin(); i != waypoints.end(); i++)
290   //  cerr << "Using waypoint : " << (*i)->name << endl;
291   //wpt_iterator = waypoints.begin();
292   //cout << waypoints.size() << " waypoints read." << endl;
293 }
294
295
296
297
298 FGAIFlightPlan::~FGAIFlightPlan()
299 {
300   deleteWaypoints();
301   if (taxiRoute)
302     delete taxiRoute;
303 }
304
305
306 FGAIFlightPlan::waypoint* const
307 FGAIFlightPlan::getPreviousWaypoint( void ) const
308 {
309   if (wpt_iterator == waypoints.begin()) {
310     return 0;
311   } else {
312     wpt_vector_iterator prev = wpt_iterator;
313     return *(--prev);
314   }
315 }
316
317 FGAIFlightPlan::waypoint* const
318 FGAIFlightPlan::getCurrentWaypoint( void ) const
319 {
320   return *wpt_iterator;
321 }
322
323 FGAIFlightPlan::waypoint* const
324 FGAIFlightPlan::getNextWaypoint( void ) const
325 {
326   wpt_vector_iterator i = waypoints.end();
327   i--;  // end() points to one element after the last one. 
328   if (wpt_iterator == i) {
329     return 0;
330   } else {
331     wpt_vector_iterator next = wpt_iterator;
332     return *(++next);
333   }
334 }
335
336 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
337 {
338   if (eraseWaypoints)
339     {
340       if (wpt_iterator == waypoints.begin())
341         wpt_iterator++;
342       else
343         {
344           delete *(waypoints.begin());
345           waypoints.erase(waypoints.begin());
346           wpt_iterator = waypoints.begin();
347           wpt_iterator++;
348         }
349     }
350   else
351     wpt_iterator++;
352
353 }
354
355 // gives distance in feet from a position to a waypoint
356 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, waypoint* wp) const{
357    // get size of a degree2 at the present latitude
358    // this won't work over large distances
359    double ft_per_deg_lat = 366468.96 - 3717.12 * cos(lat / SG_RADIANS_TO_DEGREES);
360    double ft_per_deg_lon = 365228.16 * cos(lat / SG_RADIANS_TO_DEGREES);
361    double lat_diff_ft = fabs(wp->latitude - lat) * ft_per_deg_lat;
362    double lon_diff_ft = fabs(wp->longitude - lon) * ft_per_deg_lon;
363    return sqrt((lat_diff_ft * lat_diff_ft) + (lon_diff_ft * lon_diff_ft));
364 }
365
366 // sets distance in feet from a lead point to the current waypoint
367 void FGAIFlightPlan::setLeadDistance(double speed, double bearing, 
368                                      waypoint* current, waypoint* next){
369   double turn_radius;
370     if (fabs(speed) > 1) 
371       turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
372     else
373       turn_radius = 1.0;
374
375   double inbound = bearing;
376   double outbound = getBearing(current, next);
377   leadInAngle = fabs(inbound - outbound);
378   if (leadInAngle > 180.0) 
379     leadInAngle = 360.0 - leadInAngle;
380   if (leadInAngle < 1.0) // To prevent lead_dist from getting so small it is skipped 
381     leadInAngle = 1.0;
382   
383   lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); 
384   //  if ((errno == EDOM) || (errno == ERANGE) || lead_distance < 1.0)
385   //  {
386   //    cerr << "Lead Distance = " << lead_distance
387   //       << "Diff          = " << diff
388   //       << "Turn Radius   = " << turn_radius 
389   //       << "Speed         = " << speed << endl;
390   //  }
391 }
392
393 void FGAIFlightPlan::setLeadDistance(double distance_ft){
394   lead_distance = distance_ft;
395 }
396
397
398 double FGAIFlightPlan::getBearing(waypoint* first, waypoint* second) const{
399   return getBearing(first->latitude, first->longitude, second);
400 }
401
402
403 double FGAIFlightPlan::getBearing(double lat, double lon, waypoint* wp) const{
404   double course, distance;
405  //  double latd = lat;
406 //   double lond = lon;
407 //   double latt = wp->latitude;
408 //   double lont = wp->longitude;
409 //   double ft_per_deg_lat = 366468.96 - 3717.12 * cos(lat/SG_RADIANS_TO_DEGREES);
410 //   double ft_per_deg_lon = 365228.16 * cos(lat/SG_RADIANS_TO_DEGREES);
411
412 //   if (lond < 0.0) {
413 //     lond+=360.0;
414 //     lont+=360;
415 //   }
416 //   if (lont < 0.0) {
417 //     lond+=360.0;
418 //     lont+=360.0;
419 //   }
420 //   latd+=90.0;
421 //   latt+=90.0;
422
423 //   double lat_diff = (latt - latd) * ft_per_deg_lat;
424 //   double lon_diff = (lont - lond) * ft_per_deg_lon;
425 //   double angle = atan(fabs(lat_diff / lon_diff)) * SG_RADIANS_TO_DEGREES;
426
427 //   bool southerly = true;
428 //   if (latt > latd) southerly = false;
429 //   bool easterly = false;
430 //   if (lont > lond) easterly = true;
431 //   if (southerly && easterly) return 90.0 + angle;
432 //   if (!southerly && easterly) return 90.0 - angle;
433 //   if (southerly && !easterly) return 270.0 - angle;
434 //   if (!southerly && !easterly) return 270.0 + angle; 
435   SGWayPoint sgWp(wp->longitude,wp->latitude, wp->altitude, SGWayPoint::WGS84, string("temp"));
436   sgWp.CourseAndDistance(lon, lat, wp->altitude, &course, &distance);
437   
438   return course;
439   // Omit a compiler warning. 
440   //if ((errno == EDOM) || (errno == ERANGE))
441   //  {
442   //    cerr << "Lon:  " << wp->longitude
443   //       << "Lat       = " << wp->latitude
444   //   << "Tgt Lon   = " <<  
445   //   << "TgT Lat   = " << speed << endl;
446   //  }
447   
448 }
449
450
451
452 void FGAIFlightPlan::deleteWaypoints()
453 {
454   for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
455     delete (*i);
456   waypoints.clear();
457 }
458
459 // Delete all waypoints except the last, 
460 // which we will recycle as the first waypoint in the next leg;
461 void FGAIFlightPlan::resetWaypoints()
462 {
463   if (waypoints.begin() == waypoints.end())
464     return;
465   else
466     {
467       waypoint *wpt = new waypoint;
468       wpt_vector_iterator i = waypoints.end();
469       i--;
470       wpt->name      = (*i)->name;
471       wpt->latitude  = (*i)->latitude;
472       wpt->longitude =  (*i)->longitude;
473       wpt->altitude  =  (*i)->altitude;
474       wpt->speed     =  (*i)->speed;
475       wpt->crossat   =  (*i)->crossat;
476       wpt->gear_down =  (*i)->gear_down;
477       wpt->flaps_down=  (*i)->flaps_down;
478       wpt->finished  = false;
479       wpt->on_ground =  (*i)->on_ground;
480       //cerr << "Recycling waypoint " << wpt->name << endl;
481       deleteWaypoints();
482       waypoints.push_back(wpt);
483     }
484 }
485
486 // Start flightplan over from the beginning
487 void FGAIFlightPlan::restart()
488 {
489   wpt_iterator = waypoints.begin();
490 }
491
492
493 void FGAIFlightPlan::deleteTaxiRoute() 
494 {
495   if (taxiRoute)
496     delete taxiRoute;
497   taxiRoute = 0;
498 }
499
500
501 int FGAIFlightPlan::getRouteIndex(int i) {
502   if ((i > 0) && (i < waypoints.size())) {
503     return waypoints[i]->routeIndex;
504   }
505   else
506     return 0;
507 }