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