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