]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
model paging patch from Till Busch
[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       SG_LOG(SG_GENERAL, SG_INFO, "Route from " << dep->getId() << " to " << arr->getId() << ". Set leg to : " << leg);
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   delete taxiRoute;
302 }
303
304
305 FGAIFlightPlan::waypoint* const
306 FGAIFlightPlan::getPreviousWaypoint( void ) const
307 {
308   if (wpt_iterator == waypoints.begin()) {
309     return 0;
310   } else {
311     wpt_vector_iterator prev = wpt_iterator;
312     return *(--prev);
313   }
314 }
315
316 FGAIFlightPlan::waypoint* const
317 FGAIFlightPlan::getCurrentWaypoint( void ) const
318 {
319   return *wpt_iterator;
320 }
321
322 FGAIFlightPlan::waypoint* const
323 FGAIFlightPlan::getNextWaypoint( void ) const
324 {
325   wpt_vector_iterator i = waypoints.end();
326   i--;  // end() points to one element after the last one. 
327   if (wpt_iterator == i) {
328     return 0;
329   } else {
330     wpt_vector_iterator next = wpt_iterator;
331     return *(++next);
332   }
333 }
334
335 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
336 {
337   if (eraseWaypoints)
338     {
339       if (wpt_iterator == waypoints.begin())
340         wpt_iterator++;
341       else
342         {
343           delete *(waypoints.begin());
344           waypoints.erase(waypoints.begin());
345           wpt_iterator = waypoints.begin();
346           wpt_iterator++;
347         }
348     }
349   else
350     wpt_iterator++;
351
352 }
353
354 // gives distance in feet from a position to a waypoint
355 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, waypoint* wp) const{
356    // get size of a degree2 at the present latitude
357    // this won't work over large distances
358    double ft_per_deg_lat = 366468.96 - 3717.12 * cos(lat / SG_RADIANS_TO_DEGREES);
359    double ft_per_deg_lon = 365228.16 * cos(lat / SG_RADIANS_TO_DEGREES);
360    double lat_diff_ft = fabs(wp->latitude - lat) * ft_per_deg_lat;
361    double lon_diff_ft = fabs(wp->longitude - lon) * ft_per_deg_lon;
362    return sqrt((lat_diff_ft * lat_diff_ft) + (lon_diff_ft * lon_diff_ft));
363 }
364
365 // sets distance in feet from a lead point to the current waypoint
366 void FGAIFlightPlan::setLeadDistance(double speed, double bearing, 
367                                      waypoint* current, waypoint* next){
368   double turn_radius;
369     if (fabs(speed) > 1) 
370       turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
371     else
372       turn_radius = 1.0;
373
374   double inbound = bearing;
375   double outbound = getBearing(current, next);
376   leadInAngle = fabs(inbound - outbound);
377   if (leadInAngle > 180.0) 
378     leadInAngle = 360.0 - leadInAngle;
379   if (leadInAngle < 1.0) // To prevent lead_dist from getting so small it is skipped 
380     leadInAngle = 1.0;
381   
382   lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); 
383   //  if ((errno == EDOM) || (errno == ERANGE) || lead_distance < 1.0)
384   //  {
385   //    cerr << "Lead Distance = " << lead_distance
386   //       << "Diff          = " << diff
387   //       << "Turn Radius   = " << turn_radius 
388   //       << "Speed         = " << speed << endl;
389   //  }
390 }
391
392 void FGAIFlightPlan::setLeadDistance(double distance_ft){
393   lead_distance = distance_ft;
394 }
395
396
397 double FGAIFlightPlan::getBearing(waypoint* first, waypoint* second) const{
398   return getBearing(first->latitude, first->longitude, second);
399 }
400
401
402 double FGAIFlightPlan::getBearing(double lat, double lon, waypoint* wp) const{
403   double course, distance;
404  //  double latd = lat;
405 //   double lond = lon;
406 //   double latt = wp->latitude;
407 //   double lont = wp->longitude;
408 //   double ft_per_deg_lat = 366468.96 - 3717.12 * cos(lat/SG_RADIANS_TO_DEGREES);
409 //   double ft_per_deg_lon = 365228.16 * cos(lat/SG_RADIANS_TO_DEGREES);
410
411 //   if (lond < 0.0) {
412 //     lond+=360.0;
413 //     lont+=360;
414 //   }
415 //   if (lont < 0.0) {
416 //     lond+=360.0;
417 //     lont+=360.0;
418 //   }
419 //   latd+=90.0;
420 //   latt+=90.0;
421
422 //   double lat_diff = (latt - latd) * ft_per_deg_lat;
423 //   double lon_diff = (lont - lond) * ft_per_deg_lon;
424 //   double angle = atan(fabs(lat_diff / lon_diff)) * SG_RADIANS_TO_DEGREES;
425
426 //   bool southerly = true;
427 //   if (latt > latd) southerly = false;
428 //   bool easterly = false;
429 //   if (lont > lond) easterly = true;
430 //   if (southerly && easterly) return 90.0 + angle;
431 //   if (!southerly && easterly) return 90.0 - angle;
432 //   if (southerly && !easterly) return 270.0 - angle;
433 //   if (!southerly && !easterly) return 270.0 + angle; 
434   SGWayPoint sgWp(wp->longitude,wp->latitude, wp->altitude, SGWayPoint::WGS84, string("temp"));
435   sgWp.CourseAndDistance(lon, lat, wp->altitude, &course, &distance);
436   
437   return course;
438   // Omit a compiler warning. 
439   //if ((errno == EDOM) || (errno == ERANGE))
440   //  {
441   //    cerr << "Lon:  " << wp->longitude
442   //       << "Lat       = " << wp->latitude
443   //   << "Tgt Lon   = " <<  
444   //   << "TgT Lat   = " << speed << endl;
445   //  }
446   
447 }
448
449
450
451 void FGAIFlightPlan::deleteWaypoints()
452 {
453   for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
454     delete (*i);
455   waypoints.clear();
456 }
457
458 // Delete all waypoints except the last, 
459 // which we will recycle as the first waypoint in the next leg;
460 void FGAIFlightPlan::resetWaypoints()
461 {
462   if (waypoints.begin() == waypoints.end())
463     return;
464   else
465     {
466       waypoint *wpt = new waypoint;
467       wpt_vector_iterator i = waypoints.end();
468       i--;
469       wpt->name      = (*i)->name;
470       wpt->latitude  = (*i)->latitude;
471       wpt->longitude =  (*i)->longitude;
472       wpt->altitude  =  (*i)->altitude;
473       wpt->speed     =  (*i)->speed;
474       wpt->crossat   =  (*i)->crossat;
475       wpt->gear_down =  (*i)->gear_down;
476       wpt->flaps_down=  (*i)->flaps_down;
477       wpt->finished  = false;
478       wpt->on_ground =  (*i)->on_ground;
479       //cerr << "Recycling waypoint " << wpt->name << endl;
480       deleteWaypoints();
481       waypoints.push_back(wpt);
482     }
483 }
484
485 // Start flightplan over from the beginning
486 void FGAIFlightPlan::restart()
487 {
488   wpt_iterator = waypoints.begin();
489 }
490
491
492 void FGAIFlightPlan::deleteTaxiRoute() 
493 {
494   delete taxiRoute;
495   taxiRoute = 0;
496 }
497
498
499 int FGAIFlightPlan::getRouteIndex(int i) {
500   if ((i > 0) && (i < waypoints.size())) {
501     return waypoints[i]->routeIndex;
502   }
503   else
504     return 0;
505 }