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