]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIFlightPlan.cxx
AIFlihtPlan: Proper member initialization
[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/math/sg_geodesy.hxx>
28 #include <simgear/structure/exception.hxx>
29 #include <simgear/constants.h>
30 #include <simgear/props/props.hxx>
31 #include <simgear/props/props_io.hxx>
32
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/dynamics.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 FGAIWaypoint::FGAIWaypoint() {
50   speed       = 0;
51   crossat     = 0;
52   finished    = 0;
53   gear_down   = 0;
54   flaps_down  = 0;
55   on_ground   = 0;
56   routeIndex  = 0;
57   time_sec    = 0;
58   trackLength = 0;
59 }
60
61 bool FGAIWaypoint::contains(const string& target) {
62     size_t found = name.find(target);
63     if (found == string::npos)
64         return false;
65     else
66         return true;
67 }
68
69 double FGAIWaypoint::getLatitude()
70 {
71   return pos.getLatitudeDeg();
72 }
73
74 double FGAIWaypoint::getLongitude()
75 {
76   return pos.getLongitudeDeg();
77 }
78
79 double FGAIWaypoint::getAltitude()
80 {
81   return pos.getElevationFt();
82 }
83
84 void FGAIWaypoint::setLatitude(double lat)
85 {
86   pos.setLatitudeDeg(lat);
87 }
88
89 void FGAIWaypoint::setLongitude(double lon)
90 {
91   pos.setLongitudeDeg(lon);
92 }
93
94 void FGAIWaypoint::setAltitude(double alt)
95 {
96   pos.setElevationFt(alt);
97 }
98
99 FGAIFlightPlan::FGAIFlightPlan() :
100     sid(NULL),
101     repeat(false),
102     distance_to_go(0),
103     lead_distance(0),
104     leadInAngle(0),
105     start_time(0),
106     arrivalTime(0),
107     leg(0),
108     lastNodeVisited(0),
109     isValid(true)
110 {
111     wpt_iterator    = waypoints.begin();
112 }
113
114 FGAIFlightPlan::FGAIFlightPlan(const string& filename) :
115     sid(NULL),
116     repeat(false),
117     distance_to_go(0),
118     lead_distance(0),
119     leadInAngle(0),
120     start_time(0),
121     arrivalTime(0),
122     leg(10),
123     lastNodeVisited(0),
124     isValid(parseProperties(filename))
125 {
126 }
127
128
129 // This is a modified version of the constructor,
130 // Which not only reads the waypoints from a 
131 // Flight plan file, but also adds the current
132 // Position computed by the traffic manager, as well
133 // as setting speeds and altitude computed by the
134 // traffic manager. 
135 FGAIFlightPlan::FGAIFlightPlan(FGAIAircraft *ac,
136                                const std::string& p,
137                                double course,
138                                time_t start,
139                                FGAirport *dep,
140                                FGAirport *arr,
141                                bool firstLeg,
142                                double radius,
143                                double alt,
144                                double lat,
145                                double lon,
146                                double speed,
147                                const string& fltType,
148                                const string& acType,
149                                const string& airline) :
150     sid(NULL),
151     repeat(false),
152     distance_to_go(0),
153     lead_distance(0),
154     leadInAngle(0),
155     start_time(start),
156     arrivalTime(0),
157     leg(10),
158     lastNodeVisited(0),
159     isValid(false),
160     departure(dep),
161     arrival(arr)
162 {
163   if (parseProperties(p)) {
164     isValid = true;
165   } else {
166     createWaypoints(ac, course, start, dep, arr, firstLeg, radius,
167                     alt, lat, lon, speed, fltType, acType, airline);
168   }
169 }
170
171 FGAIFlightPlan::~FGAIFlightPlan()
172 {
173   deleteWaypoints();
174   //delete taxiRoute;
175 }
176
177 void FGAIFlightPlan::createWaypoints(FGAIAircraft *ac,
178                                      double course,
179                                      time_t start,
180                                      FGAirport *dep,
181                                      FGAirport *arr,
182                                      bool firstLeg,
183                                      double radius,
184                                      double alt,
185                                      double lat,
186                                      double lon,
187                                      double speed,
188                                      const string& fltType,
189                                      const string& acType,
190                                      const string& airline)
191 {
192   time_t now = time(NULL) + fgGetLong("/sim/time/warp");
193   time_t timeDiff = now-start;
194   leg = 1;
195   
196   if ((timeDiff > 60) && (timeDiff < 1500))
197     leg = 2;
198   //else if ((timeDiff >= 1200) && (timeDiff < 1500)) {
199         //leg = 3;
200   //ac->setTakeOffStatus(2);
201   //}
202   else if ((timeDiff >= 1500) && (timeDiff < 2000))
203     leg = 4;
204   else if (timeDiff >= 2000)
205     leg = 5;
206   /*
207    if (timeDiff >= 2000)
208    leg = 5;
209    */
210   SG_LOG(SG_AI, SG_INFO, "Route from " << dep->getId() << " to " << arr->getId() << ". Set leg to : " << leg << " " << ac->getTrafficRef()->getCallSign());
211   wpt_iterator = waypoints.begin();
212   bool dist = 0;
213   isValid = create(ac, dep, arr, leg, alt, speed, lat, lon,
214                    firstLeg, radius, fltType, acType, airline, dist);
215   wpt_iterator = waypoints.begin();
216 }
217
218 bool FGAIFlightPlan::parseProperties(const std::string& filename)
219 {
220   SGPath path( globals->get_fg_root() );
221   path.append( "/AI/FlightPlans/" + filename );
222   if (!path.exists()) {
223     return false;
224   }
225   
226   SGPropertyNode root;
227   try {
228     readProperties(path.str(), &root);
229   } catch (const sg_exception &e) {
230     SG_LOG(SG_AI, SG_ALERT, "Error reading AI flight plan: " << path.str()
231            << "message:" << e.getFormattedMessage());
232     return false;
233   }
234   
235   SGPropertyNode * node = root.getNode("flightplan");
236   for (int i = 0; i < node->nChildren(); i++) {
237     FGAIWaypoint* wpt = new FGAIWaypoint;
238     SGPropertyNode * wpt_node = node->getChild(i);
239     wpt->setName       (wpt_node->getStringValue("name", "END"     ));
240     wpt->setLatitude   (wpt_node->getDoubleValue("lat", 0          ));
241     wpt->setLongitude  (wpt_node->getDoubleValue("lon", 0          ));
242     wpt->setAltitude   (wpt_node->getDoubleValue("alt", 0          ));
243     wpt->setSpeed      (wpt_node->getDoubleValue("ktas", 0         ));
244     wpt->setCrossat    (wpt_node->getDoubleValue("crossat", -10000 ));
245     wpt->setGear_down  (wpt_node->getBoolValue("gear-down", false  ));
246     wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
247     wpt->setOn_ground  (wpt_node->getBoolValue("on-ground", false  ));
248     wpt->setTime_sec   (wpt_node->getDoubleValue("time-sec", 0     ));
249     wpt->setTime       (wpt_node->getStringValue("time", ""        ));
250     wpt->setFinished   ((wpt->getName() == "END"));
251     pushBackWaypoint( wpt );
252   }
253   
254   wpt_iterator = waypoints.begin();
255   return true;
256 }
257
258 FGAIWaypoint* const FGAIFlightPlan::getPreviousWaypoint( void ) const
259 {
260   if (wpt_iterator == waypoints.begin()) {
261     return 0;
262   } else {
263     wpt_vector_iterator prev = wpt_iterator;
264     return *(--prev);
265   }
266 }
267
268 FGAIWaypoint* const FGAIFlightPlan::getCurrentWaypoint( void ) const
269 {
270   if (wpt_iterator == waypoints.end())
271       return 0;
272   return *wpt_iterator;
273 }
274
275 FGAIWaypoint* const FGAIFlightPlan::getNextWaypoint( void ) const
276 {
277   wpt_vector_iterator i = waypoints.end();
278   i--;  // end() points to one element after the last one. 
279   if (wpt_iterator == i) {
280     return 0;
281   } else {
282     wpt_vector_iterator next = wpt_iterator;
283     return *(++next);
284   }
285 }
286
287 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
288 {
289   if (eraseWaypoints)
290     {
291       if (wpt_iterator == waypoints.begin())
292         wpt_iterator++;
293       else
294         {
295           delete *(waypoints.begin());
296           waypoints.erase(waypoints.begin());
297           wpt_iterator = waypoints.begin();
298           wpt_iterator++;
299         }
300     }
301   else
302     wpt_iterator++;
303
304 }
305
306 void FGAIFlightPlan::DecrementWaypoint(bool eraseWaypoints )
307 {
308     if (eraseWaypoints)
309     {
310         if (wpt_iterator == waypoints.end())
311             wpt_iterator--;
312         else
313         {
314             delete *(waypoints.end());
315             waypoints.erase(waypoints.end());
316             wpt_iterator = waypoints.end();
317             wpt_iterator--;
318         }
319     }
320     else
321         wpt_iterator--;
322 }
323
324 void FGAIFlightPlan::eraseLastWaypoint()
325 {
326     delete (waypoints.back());
327     waypoints.pop_back();;
328     wpt_iterator = waypoints.begin();
329     wpt_iterator++;
330 }
331
332
333
334
335 // gives distance in feet from a position to a waypoint
336 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, FGAIWaypoint* wp) const{
337   return SGGeodesy::distanceM(SGGeod::fromDeg(lon, lat), wp->getPos());
338 }
339
340 // sets distance in feet from a lead point to the current waypoint
341 void FGAIFlightPlan::setLeadDistance(double speed, double bearing, 
342                                      FGAIWaypoint* current, FGAIWaypoint* next){
343   double turn_radius;
344   // Handle Ground steering
345   // At a turn rate of 30 degrees per second, it takes 12 seconds to do a full 360 degree turn
346   // So, to get an estimate of the turn radius, calculate the cicumference of the circle
347   // we travel on. Get the turn radius by dividing by PI (*2).
348   if (speed < 0.5) {
349         lead_distance = 0.5;
350         return;
351   }
352   if (speed < 25) {
353        turn_radius = ((360/30)*fabs(speed)) / (2*M_PI);
354   } else 
355       turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
356
357   double inbound = bearing;
358   double outbound = getBearing(current, next);
359   leadInAngle = fabs(inbound - outbound);
360   if (leadInAngle > 180.0) 
361     leadInAngle = 360.0 - leadInAngle;
362   //if (leadInAngle < 30.0) // To prevent lead_dist from getting so small it is skipped 
363   //  leadInAngle = 30.0;
364   
365   //lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS); 
366   lead_distance = turn_radius * tan((leadInAngle * SG_DEGREES_TO_RADIANS)/2);
367   /*
368   if ((lead_distance > (3*turn_radius)) && (current->on_ground == false)) {
369       // cerr << "Warning: Lead-in distance is large. Inbound = " << inbound
370       //      << ". Outbound = " << outbound << ". Lead in angle = " << leadInAngle  << ". Turn radius = " << turn_radius << endl;
371        lead_distance = 3 * turn_radius;
372        return;
373   }
374   if ((leadInAngle > 90) && (current->on_ground == true)) {
375       lead_distance = turn_radius * tan((90 * SG_DEGREES_TO_RADIANS)/2);
376       return;
377   }*/
378 }
379
380 void FGAIFlightPlan::setLeadDistance(double distance_ft){
381   lead_distance = distance_ft;
382 }
383
384
385 double FGAIFlightPlan::getBearing(FGAIWaypoint* first, FGAIWaypoint* second) const
386 {
387   return SGGeodesy::courseDeg(first->getPos(), second->getPos());
388 }
389
390 double FGAIFlightPlan::getBearing(const SGGeod& aPos, FGAIWaypoint* wp) const
391 {
392   return SGGeodesy::courseDeg(aPos, wp->getPos());
393 }
394
395 void FGAIFlightPlan::deleteWaypoints()
396 {
397   for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
398     delete (*i);
399   waypoints.clear();
400 }
401
402 // Delete all waypoints except the last, 
403 // which we will recycle as the first waypoint in the next leg;
404 void FGAIFlightPlan::resetWaypoints()
405 {
406   if (waypoints.begin() == waypoints.end())
407     return;
408   else
409     {
410       FGAIWaypoint *wpt = new FGAIWaypoint;
411       wpt_vector_iterator i = waypoints.end();
412       i--;
413       wpt->setName        ( (*i)->getName()       );
414       wpt->setPos         ( (*i)->getPos()        );
415       wpt->setCrossat     ( (*i)->getCrossat()    );
416       wpt->setGear_down   ( (*i)->getGear_down()  );
417       wpt->setFlaps_down  ( (*i)->getFlaps_down() );
418       wpt->setFinished    ( false                 );
419       wpt->setOn_ground   ( (*i)->getOn_ground()  );
420       //cerr << "Recycling waypoint " << wpt->name << endl;
421       deleteWaypoints();
422       pushBackWaypoint(wpt);
423     }
424 }
425
426 void FGAIFlightPlan::pushBackWaypoint(FGAIWaypoint *wpt)
427 {
428   // std::vector::push_back invalidates waypoints
429   //  so we should restore wpt_iterator after push_back
430   //  (or it could be an index in the vector)
431   size_t pos = wpt_iterator - waypoints.begin();
432   waypoints.push_back(wpt);
433   wpt_iterator = waypoints.begin() + pos;
434 }
435
436 // Start flightplan over from the beginning
437 void FGAIFlightPlan::restart()
438 {
439   wpt_iterator = waypoints.begin();
440 }
441
442 int FGAIFlightPlan::getRouteIndex(int i) {
443   if ((i > 0) && (i < (int)waypoints.size())) {
444     return waypoints[i]->getRouteIndex();
445   }
446   else
447     return 0;
448 }
449
450 double FGAIFlightPlan::checkTrackLength(const string& wptName) {
451     // skip the first two waypoints: first one is behind, second one is partially done;
452     double trackDistance = 0;
453     wpt_vector_iterator wptvec = waypoints.begin();
454     wptvec++;
455     wptvec++;
456     while ((wptvec != waypoints.end()) && (!((*wptvec)->contains(wptName)))) {
457            trackDistance += (*wptvec)->getTrackLength();
458            wptvec++;
459     }
460     if (wptvec == waypoints.end()) {
461         trackDistance = 0; // name not found
462     }
463     return trackDistance;
464 }
465
466 void FGAIFlightPlan::shortenToFirst(unsigned int number, string name)
467 {
468     while (waypoints.size() > number + 3) {
469         eraseLastWaypoint();
470     }
471     (waypoints.back())->setName((waypoints.back())->getName() + name);
472 }
473
474 void FGAIFlightPlan::setGate(ParkingAssignment pka)
475 {
476   gate = pka;
477 }
478
479 FGParking* FGAIFlightPlan::getParkingGate()
480 {
481   return gate.parking();
482 }