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