1 // // FGAIFlightPlan - class for loading and storing AI flight plans
2 // Written by David Culp, started May 2004
3 // - davidculp2@comcast.net
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.
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.
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.
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>
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>
41 #include <Environment/environment_mgr.hxx>
42 #include <Environment/environment.hxx>
44 #include "AIFlightPlan.hxx"
45 #include "AIAircraft.hxx"
49 FGAIWaypoint::FGAIWaypoint() {
64 bool FGAIWaypoint::contains(string target) {
65 size_t found = name.find(target);
66 if (found == string::npos)
72 FGAIFlightPlan::FGAIFlightPlan()
85 wpt_iterator = waypoints.begin();
89 FGAIFlightPlan::FGAIFlightPlan(const string& filename)
97 SGPath path( globals->get_fg_root() );
98 path.append( ("/AI/FlightPlans/" + filename).c_str() );
103 readProperties(path.str(), &root);
104 } catch (const sg_exception &) {
105 SG_LOG(SG_GENERAL, SG_ALERT,
106 "Error reading AI flight plan: " << path.str());
107 // cout << path.str() << endl;
111 SGPropertyNode * node = root.getNode("flightplan");
112 for (i = 0; i < node->nChildren(); i++) {
113 //cout << "Reading waypoint " << i << endl;
114 FGAIWaypoint* wpt = new FGAIWaypoint;
115 SGPropertyNode * wpt_node = node->getChild(i);
116 wpt->setName (wpt_node->getStringValue("name", "END" ));
117 wpt->setLatitude (wpt_node->getDoubleValue("lat", 0 ));
118 wpt->setLongitude (wpt_node->getDoubleValue("lon", 0 ));
119 wpt->setAltitude (wpt_node->getDoubleValue("alt", 0 ));
120 wpt->setSpeed (wpt_node->getDoubleValue("ktas", 0 ));
121 wpt->setCrossat (wpt_node->getDoubleValue("crossat", -10000 ));
122 wpt->setGear_down (wpt_node->getBoolValue("gear-down", false ));
123 wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
124 wpt->setOn_ground (wpt_node->getBoolValue("on-ground", false ));
125 wpt->setTime_sec (wpt_node->getDoubleValue("time-sec", 0 ));
126 wpt->setTime (wpt_node->getStringValue("time", "" ));
128 if (wpt->getName() == "END") wpt->setFinished(true);
129 else wpt->setFinished(false);
131 waypoints.push_back( wpt );
134 wpt_iterator = waypoints.begin();
136 //cout << waypoints.size() << " waypoints read." << endl;
140 // This is a modified version of the constructor,
141 // Which not only reads the waypoints from a
142 // Flight plan file, but also adds the current
143 // Position computed by the traffic manager, as well
144 // as setting speeds and altitude computed by the
146 FGAIFlightPlan::FGAIFlightPlan(FGAIAircraft *ac,
147 const std::string& p,
158 const string& fltType,
159 const string& acType,
160 const string& airline)
168 bool useInitialWayPoint = true;
169 bool useCurrentWayPoint = false;
170 SGPath path( globals->get_fg_root() );
171 path.append( "/AI/FlightPlans" );
176 // This is a bit of a hack:
177 // Normally the value of course will be used to evaluate whether
178 // or not a waypoint will be used for midair initialization of
179 // an AI aircraft. However, if a course value of 999 will be passed
180 // when an update request is received, which will by definition always be
181 // on the ground and should include all waypoints.
184 useInitialWayPoint = false;
185 useCurrentWayPoint = true;
192 readProperties(path.str(), &root);
194 SGPropertyNode * node = root.getNode("flightplan");
196 //waypoints.push_back( init_waypoint );
197 for (int i = 0; i < node->nChildren(); i++) {
198 //cout << "Reading waypoint " << i << endl;
199 FGAIWaypoint* wpt = new FGAIWaypoint;
200 SGPropertyNode * wpt_node = node->getChild(i);
201 wpt->setName (wpt_node->getStringValue("name", "END" ));
202 wpt->setLatitude (wpt_node->getDoubleValue("lat", 0 ));
203 wpt->setLongitude (wpt_node->getDoubleValue("lon", 0 ));
204 wpt->setAltitude (wpt_node->getDoubleValue("alt", 0 ));
205 wpt->setSpeed (wpt_node->getDoubleValue("ktas", 0 ));
206 wpt->setCrossat (wpt_node->getDoubleValue("crossat", -10000 ));
207 wpt->setGear_down (wpt_node->getBoolValue("gear-down", false ));
208 wpt->setFlaps_down (wpt_node->getBoolValue("flaps-down", false ));
210 if (wpt->getName() == "END") wpt->setFinished(true);
211 else wpt->setFinished(false);
212 waypoints.push_back(wpt);
214 wpt_iterator = waypoints.begin();
215 } catch (const sg_exception &e) {
216 SG_LOG(SG_GENERAL, SG_WARN, "Error reading AI flight plan: " <<
217 e.getMessage() << " from " << e.getOrigin());
220 // cout << path.str() << endl;
221 // cout << "Trying to create this plan dynamically" << endl;
222 // cout << "Route from " << dep->id << " to " << arr->id << endl;
223 time_t now = time(NULL) + fgGetLong("/sim/time/warp");
224 time_t timeDiff = now-start;
227 if ((timeDiff > 60) && (timeDiff < 1200))
229 else if ((timeDiff >= 1200) && (timeDiff < 1500)) {
231 ac->setTakeOffStatus(2);
233 else if ((timeDiff >= 1500) && (timeDiff < 2000))
235 else if (timeDiff >= 2000)
238 if (timeDiff >= 2000)
241 SG_LOG(SG_GENERAL, SG_INFO, "Route from " << dep->getId() << " to " << arr->getId() << ". Set leg to : " << leg << " " << ac->getTrafficRef()->getCallSign());
242 wpt_iterator = waypoints.begin();
244 isValid = create(ac, dep,arr, leg, alt, speed, lat, lon,
245 firstLeg, radius, fltType, acType, airline, dist);
246 wpt_iterator = waypoints.begin();
247 //cerr << "after create: " << (*wpt_iterator)->name << endl;
249 // Now that we have dynamically created a flight plan,
250 // we need to add some code that pops any waypoints already past.
254 waypoint* init_waypoint = new waypoint;
255 init_waypoint->name = string("initial position");
256 init_waypoint->latitude = entity->latitude;
257 init_waypoint->longitude = entity->longitude;
258 init_waypoint->altitude = entity->altitude;
259 init_waypoint->speed = entity->speed;
260 init_waypoint->crossat = - 10000;
261 init_waypoint->gear_down = false;
262 init_waypoint->flaps_down = false;
263 init_waypoint->finished = false;
265 wpt_vector_iterator i = waypoints.begin();
266 while (i != waypoints.end())
268 //cerr << "Checking status of each waypoint: " << (*i)->name << endl;
269 SGWayPoint first(init_waypoint->longitude,
270 init_waypoint->latitude,
271 init_waypoint->altitude);
272 SGWayPoint curr ((*i)->longitude,
275 double crse, crsDiff;
277 curr.CourseAndDistance(first, &crse, &dist);
279 dist *= SG_METER_TO_NM;
281 // We're only interested in the absolute value of crsDiff
282 // wich should fall in the 0-180 deg range.
283 crsDiff = fabs(crse-course);
285 crsDiff = 360-crsDiff;
286 // These are the three conditions that we consider including
287 // in our flight plan:
288 // 1) current waypoint is less then 100 miles away OR
289 // 2) curren waypoint is ahead of us, at any distance
291 if ((dist > 20.0) && (crsDiff > 90.0) && ((*i)->name != string ("EOF")))
294 // Once we start including waypoints, we have to continue, even though
295 // one of the following way point would suffice.
296 // so once is the useWpt flag is set to true, we cannot reset it to false.
297 //cerr << "Discarding waypoint: " << (*i)->name
298 // << ": Course difference = " << crsDiff
299 // << "Course = " << course
300 // << "crse = " << crse << endl;
303 useCurrentWayPoint = true;
305 if (useCurrentWayPoint)
307 if ((dist > 100.0) && (useInitialWayPoint))
309 //waypoints.push_back(init_waypoint);;
310 waypoints.insert(i, init_waypoint);
311 //cerr << "Using waypoint : " << init_waypoint->name << endl;
313 //if (useInitialWayPoint)
315 // (*i)->speed = dist; // A hack
317 //waypoints.push_back( wpt );
318 //cerr << "Using waypoint : " << (*i)->name
319 // << ": course diff : " << crsDiff
320 // << "Course = " << course
321 // << "crse = " << crse << endl
322 // << "distance : " << dist << endl;
323 useInitialWayPoint = false;
330 i = waypoints.erase(i);
335 //for (i = waypoints.begin(); i != waypoints.end(); i++)
336 // cerr << "Using waypoint : " << (*i)->name << endl;
337 //wpt_iterator = waypoints.begin();
338 //cout << waypoints.size() << " waypoints read." << endl;
344 FGAIFlightPlan::~FGAIFlightPlan()
351 FGAIWaypoint* const FGAIFlightPlan::getPreviousWaypoint( void ) const
353 if (wpt_iterator == waypoints.begin()) {
356 wpt_vector_iterator prev = wpt_iterator;
361 FGAIWaypoint* const FGAIFlightPlan::getCurrentWaypoint( void ) const
363 return *wpt_iterator;
366 FGAIWaypoint* const FGAIFlightPlan::getNextWaypoint( void ) const
368 wpt_vector_iterator i = waypoints.end();
369 i--; // end() points to one element after the last one.
370 if (wpt_iterator == i) {
373 wpt_vector_iterator next = wpt_iterator;
378 void FGAIFlightPlan::IncrementWaypoint(bool eraseWaypoints )
382 if (wpt_iterator == waypoints.begin())
386 delete *(waypoints.begin());
387 waypoints.erase(waypoints.begin());
388 wpt_iterator = waypoints.begin();
397 void FGAIFlightPlan::DecrementWaypoint(bool eraseWaypoints )
401 if (wpt_iterator == waypoints.end())
405 delete *(waypoints.end());
406 waypoints.erase(waypoints.end());
407 wpt_iterator = waypoints.end();
417 // gives distance in feet from a position to a waypoint
418 double FGAIFlightPlan::getDistanceToGo(double lat, double lon, FGAIWaypoint* wp) const{
419 return SGGeodesy::distanceM(SGGeod::fromDeg(lon, lat),
420 SGGeod::fromDeg(wp->getLongitude(), wp->getLatitude()));
423 // sets distance in feet from a lead point to the current waypoint
424 void FGAIFlightPlan::setLeadDistance(double speed, double bearing,
425 FGAIWaypoint* current, FGAIWaypoint* next){
427 // Handle Ground steering
428 // At a turn rate of 30 degrees per second, it takes 12 seconds to do a full 360 degree turn
429 // So, to get an estimate of the turn radius, calculate the cicumference of the circle
430 // we travel on. Get the turn radius by dividing by PI (*2).
436 turn_radius = ((360/30)*fabs(speed)) / (2*M_PI);
438 turn_radius = 0.1911 * speed * speed; // an estimate for 25 degrees bank
440 double inbound = bearing;
441 double outbound = getBearing(current, next);
442 leadInAngle = fabs(inbound - outbound);
443 if (leadInAngle > 180.0)
444 leadInAngle = 360.0 - leadInAngle;
445 //if (leadInAngle < 30.0) // To prevent lead_dist from getting so small it is skipped
446 // leadInAngle = 30.0;
448 //lead_distance = turn_radius * sin(leadInAngle * SG_DEGREES_TO_RADIANS);
449 lead_distance = turn_radius * tan((leadInAngle * SG_DEGREES_TO_RADIANS)/2);
451 if ((lead_distance > (3*turn_radius)) && (current->on_ground == false)) {
452 // cerr << "Warning: Lead-in distance is large. Inbound = " << inbound
453 // << ". Outbound = " << outbound << ". Lead in angle = " << leadInAngle << ". Turn radius = " << turn_radius << endl;
454 lead_distance = 3 * turn_radius;
457 if ((leadInAngle > 90) && (current->on_ground == true)) {
458 lead_distance = turn_radius * tan((90 * SG_DEGREES_TO_RADIANS)/2);
463 void FGAIFlightPlan::setLeadDistance(double distance_ft){
464 lead_distance = distance_ft;
468 double FGAIFlightPlan::getBearing(FGAIWaypoint* first, FGAIWaypoint* second) const{
469 return getBearing(first->getLatitude(), first->getLongitude(), second);
473 double FGAIFlightPlan::getBearing(double lat, double lon, FGAIWaypoint* wp) const{
474 return SGGeodesy::courseDeg(SGGeod::fromDeg(lon, lat),
475 SGGeod::fromDeg(wp->getLongitude(), wp->getLatitude()));
478 void FGAIFlightPlan::deleteWaypoints()
480 for (wpt_vector_iterator i = waypoints.begin(); i != waypoints.end();i++)
485 // Delete all waypoints except the last,
486 // which we will recycle as the first waypoint in the next leg;
487 void FGAIFlightPlan::resetWaypoints()
489 if (waypoints.begin() == waypoints.end())
493 FGAIWaypoint *wpt = new FGAIWaypoint;
494 wpt_vector_iterator i = waypoints.end();
496 wpt->setName ( (*i)->getName() );
497 wpt->setLatitude ( (*i)->getLatitude() );
498 wpt->setLongitude ( (*i)->getLongitude() );
499 wpt->setAltitude ( (*i)->getAltitude() );
500 wpt->setSpeed ( (*i)->getSpeed() );
501 wpt->setCrossat ( (*i)->getCrossat() );
502 wpt->setGear_down ( (*i)->getGear_down() );
503 wpt->setFlaps_down ( (*i)->getFlaps_down() );
504 wpt->setFinished ( false );
505 wpt->setOn_ground ( (*i)->getOn_ground() );
506 //cerr << "Recycling waypoint " << wpt->name << endl;
508 waypoints.push_back(wpt);
512 // Start flightplan over from the beginning
513 void FGAIFlightPlan::restart()
515 wpt_iterator = waypoints.begin();
519 void FGAIFlightPlan::deleteTaxiRoute()
526 int FGAIFlightPlan::getRouteIndex(int i) {
527 if ((i > 0) && (i < (int)waypoints.size())) {
528 return waypoints[i]->getRouteIndex();
535 double FGAIFlightPlan::checkTrackLength(string wptName) {
536 // skip the first two waypoints: first one is behind, second one is partially done;
537 double trackDistance = 0;
538 wpt_vector_iterator wptvec = waypoints.begin();
541 while ((wptvec != waypoints.end()) && (!((*wptvec)->contains(wptName)))) {
542 trackDistance += (*wptvec)->getTrackLength();
545 if (wptvec == waypoints.end()) {
546 trackDistance = 0; // name not found
548 return trackDistance;