]> git.mxchange.org Git - flightgear.git/blobdiff - src/Autopilot/route_mgr.cxx
Expose a radio function (receiveBeacon) to the Nasal subsystem
[flightgear.git] / src / Autopilot / route_mgr.cxx
index d5411b8af7d73960644590d5d37714e423d007f4..178b7cfa2bc01ac333b19524fe7511c4a566b337 100644 (file)
@@ -40,6 +40,7 @@
 
 #include <simgear/misc/strutils.hxx>
 #include <simgear/structure/exception.hxx>
+#include <simgear/structure/commands.hxx>
 #include <simgear/misc/sgstream.hxx>
 
 #include <simgear/props/props_io.hxx>
@@ -109,6 +110,151 @@ PropertyWatcher* createWatcher(T* obj, void (T::*m)())
   return new MethodPropertyWatcher<T>(obj, m);
 }
 
+static bool commandLoadFlightPlan(const SGPropertyNode* arg)
+{
+  FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
+  SGPath path(arg->getStringValue("path"));
+  return self->loadRoute(path);
+}
+
+static bool commandSaveFlightPlan(const SGPropertyNode* arg)
+{
+  FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
+  SGPath path(arg->getStringValue("path"));
+  return self->saveRoute(path);
+}
+
+static bool commandActivateFlightPlan(const SGPropertyNode* arg)
+{
+  FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
+  bool activate = arg->getBoolValue("activate", true);
+  if (activate) {
+    self->activate();
+  } else {
+    
+  }
+  
+  return true;
+}
+
+static bool commandClearFlightPlan(const SGPropertyNode*)
+{
+  FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
+  self->clearRoute();
+  return true;
+}
+
+static bool commandSetActiveWaypt(const SGPropertyNode* arg)
+{
+  FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
+  int index = arg->getIntValue("index");
+  if ((index < 0) || (index >= self->numWaypts())) {
+    return false;
+  }
+  
+  self->jumpToIndex(index);
+  return true;
+}
+
+static bool commandInsertWaypt(const SGPropertyNode* arg)
+{
+  FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
+  int index = arg->getIntValue("index");
+  std::string ident(arg->getStringValue("id"));
+  int alt = arg->getIntValue("altitude-ft", -999);
+  int ias = arg->getIntValue("speed-knots", -999);
+  
+  WayptRef wp;
+// lat/lon may be supplied to narrow down navaid search, or to specify
+// a raw waypoint
+  SGGeod pos;
+  if (arg->hasChild("longitude-deg")) {
+    pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
+                               arg->getDoubleValue("latitude-deg"));
+  }
+  
+  if (arg->hasChild("navaid")) {
+    FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
+    
+    if (arg->hasChild("navaid", 1)) {
+      // intersection of two radials
+      FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
+      if (!p2) {
+        SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
+        return false;
+      }
+      
+      double r1 = arg->getDoubleValue("radial"),
+        r2 = arg->getDoubleValue("radial[1]");
+      
+      SGGeod intersection;
+      bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
+      if (!ok) {
+        SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident() 
+                << "," << p2->ident());
+        return false;
+      }
+      
+      std::string name = p->ident() + "-" + p2->ident();
+      wp = new BasicWaypt(intersection, name, NULL);
+    } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
+      // offset radial from navaid
+      double radial = arg->getDoubleValue("radial");
+      double distanceNm = arg->getDoubleValue("offset-nm");
+      //radial += magvar->getDoubleValue(); // convert to true bearing
+      wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
+    } else {
+      wp = new NavaidWaypoint(p, NULL);
+    }
+  } else if (arg->hasChild("airport")) {
+    const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
+    if (!apt) {
+      SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
+      return false;
+    }
+    
+    if (arg->hasChild("runway")) {
+      if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
+        SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
+        return false;
+      }
+      
+      FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
+      wp = new RunwayWaypt(runway, NULL);
+    } else {
+      wp = new NavaidWaypoint((FGAirport*) apt, NULL);
+    }
+  } else if (arg->hasChild("text")) {
+    wp = self->waypointFromString(arg->getStringValue("text"));
+  } else if (!(pos == SGGeod())) {
+    // just a raw lat/lon
+    wp = new BasicWaypt(pos, ident, NULL);
+  } else {
+    return false; // failed to build waypoint
+  }
+  
+  if (alt >= 0) {
+    wp->setAltitude(alt, flightgear::RESTRICT_AT);
+  }
+  
+  if (ias > 0) {
+    wp->setSpeed(ias, flightgear::RESTRICT_AT);
+  }
+
+  self->insertWayptAtIndex(wp, index);
+  return true;
+}
+
+static bool commandDeleteWaypt(const SGPropertyNode* arg)
+{
+  FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
+  int index = arg->getIntValue("index");
+  self->removeWayptAtIndex(index);
+  return true;
+}
+
+/////////////////////////////////////////////////////////////////////////////
+
 FGRouteMgr::FGRouteMgr() :
   _currentIndex(0),
   input(fgGetNode( RM "input", true )),
@@ -117,6 +263,14 @@ FGRouteMgr::FGRouteMgr() :
   listener = new InputListener(this);
   input->setStringValue("");
   input->addChangeListener(listener);
+  
+  SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
+  SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
+  SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
+  SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
+  SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
+  SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
+  SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
 }
 
 
@@ -224,6 +378,15 @@ void FGRouteMgr::init() {
 
 void FGRouteMgr::postinit()
 {
+  SGPath path(_pathNode->getStringValue());
+  if (!path.isNull()) {
+    SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
+    loadRoute(path);
+  }
+  
+// this code only matters for the --wp option now - perhaps the option
+// should be deprecated in favour of an explicit flight-plan file?
+// then the global initial waypoint list could die.
   string_list *waypoints = globals->get_initial_waypoints();
   if (waypoints) {
     string_list::iterator it;
@@ -310,6 +473,8 @@ void FGRouteMgr::update( double dt )
     if (w->flag(WPT_DYNAMIC)) continue;
     totalDistanceRemaining += SGGeodesy::distanceM(prev->position(), w->position());
     prev = w;
+    
+    
   }
   
   wpn->setDoubleValue("dist", totalDistanceRemaining * SG_METER_TO_NM);
@@ -345,18 +510,13 @@ flightgear::WayptRef FGRouteMgr::removeWayptAtIndex(int aIndex)
 {
   int index = aIndex;
   if (aIndex < 0) { // negative indices count the the end
-    index = _route.size()  index;
+    index = _route.size() + index;
   }
   
   if ((index < 0) || (index >= numWaypts())) {
     SG_LOG(SG_AUTOPILOT, SG_WARN, "removeWayptAtIndex with invalid index:" << aIndex);
     return NULL;
   }
-  
-  if (_currentIndex > index) {
-    --_currentIndex; // shift current index down if necessary
-  }
-
   WayptVec::iterator it = _route.begin();
   it += index;
   
@@ -364,6 +524,15 @@ flightgear::WayptRef FGRouteMgr::removeWayptAtIndex(int aIndex)
   _route.erase(it);
   
   update_mirror();
+  
+  if (_currentIndex == index) {
+    currentWaypointChanged(); // current waypoint was removed
+  }
+  else
+  if (_currentIndex > index) {
+    --_currentIndex; // shift current index down if necessary
+  }
+
   _edited->fireValueChanged();
   checkFinished();
   
@@ -673,14 +842,14 @@ void FGRouteMgr::insertWayptAtIndex(Waypt* aWpt, int aIndex)
   }
   
   int index = aIndex;
-  if ((aIndex == -1) || (aIndex > _route.size())) {
+  if ((aIndex == -1) || (aIndex > (int) _route.size())) {
     index = _route.size();
   }
   
   WayptVec::iterator it = _route.begin();
   it += index;
       
-  if (_currentIndex > index) {
+  if (_currentIndex >= index) {
     ++_currentIndex;
   }
   
@@ -801,26 +970,39 @@ WayptRef FGRouteMgr::waypointFromString(const string& tgt )
 void FGRouteMgr::update_mirror()
 {
   mirror->removeChildren("wp");
-  for (int i = 0; i < numWaypts(); i++) {
+  
+  int num = numWaypts();
+  for (int i = 0; i < num; i++) {
     Waypt* wp = _route[i];
     SGPropertyNode *prop = mirror->getChild("wp", i, 1);
 
     const SGGeod& pos(wp->position());
     prop->setStringValue("id", wp->ident().c_str());
-    //prop->setStringValue("name", wp.get_name().c_str());
     prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
     prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
    
+    // leg course+distance
+    if (i < (num - 1)) {
+      Waypt* next = _route[i+1];
+      std::pair<double, double> crsDist =
+        next->courseAndDistanceFrom(pos);
+      prop->setDoubleValue("leg-bearing-true-deg", crsDist.first);
+      prop->setDoubleValue("leg-distance-nm", crsDist.second * SG_METER_TO_NM);
+    }
+    
     if (wp->altitudeRestriction() != RESTRICT_NONE) {
       double ft = wp->altitudeFt();
       prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
       prop->setDoubleValue("altitude-ft", ft);
+      prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
     } else {
       prop->setDoubleValue("altitude-m", -9999.9);
       prop->setDoubleValue("altitude-ft", -9999.9);
     }
     
-    if (wp->speedRestriction() != RESTRICT_NONE) {
+    if (wp->speedRestriction() == SPEED_RESTRICT_MACH) {
+      prop->setDoubleValue("speed-mach", wp->speedMach());
+    } else if (wp->speedRestriction() != RESTRICT_NONE) {
       prop->setDoubleValue("speed-kts", wp->speedKts());
     }
     
@@ -869,11 +1051,11 @@ void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
     else if (!strcmp(s, "@ACTIVATE"))
         mgr->activate();
     else if (!strcmp(s, "@LOAD")) {
-      mgr->loadRoute();
+      SGPath path(mgr->_pathNode->getStringValue());
+      mgr->loadRoute(path);
     } else if (!strcmp(s, "@SAVE")) {
-      mgr->saveRoute();
-    } else if (!strcmp(s, "@POP")) {
-      SG_LOG(SG_AUTOPILOT, SG_WARN, "route-manager @POP command is deprecated");
+      SGPath path(mgr->_pathNode->getStringValue());
+      mgr->saveRoute(path);
     } else if (!strcmp(s, "@NEXT")) {
       mgr->jumpToIndex(mgr->_currentIndex + 1);
     } else if (!strcmp(s, "@PREVIOUS")) {
@@ -924,11 +1106,20 @@ void FGRouteMgr::initAtPosition()
   }
   
 // on the ground
-  SGGeod pos = SGGeod::fromDegFt(lon->getDoubleValue(), lat->getDoubleValue(), alt->getDoubleValue());
-  _departure = FGAirport::findClosest(pos, 20.0);
+  SGGeod pos = SGGeod::fromDegFt(lon->getDoubleValue(), 
+    lat->getDoubleValue(), alt->getDoubleValue());
   if (!_departure) {
-    SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
-    departure->setStringValue("runway", "");
+    _departure = FGAirport::findClosest(pos, 20.0);
+    if (!_departure) {
+      SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
+      departure->setStringValue("runway", "");
+      return;
+    }
+  }
+  
+  std::string rwy = departure->getStringValue("runway");
+  if (!rwy.empty()) {
+    // runway already set, fine
     return;
   }
   
@@ -1050,6 +1241,8 @@ int FGRouteMgr::findWayptIndex(const SGGeod& aPos) const
 
 Waypt* FGRouteMgr::currentWaypt() const
 {
+  if ((_currentIndex < 0) || (_currentIndex >= numWaypts()))
+      return NULL;
   return wayptAtIndex(_currentIndex);
 }
 
@@ -1064,7 +1257,7 @@ Waypt* FGRouteMgr::previousWaypt() const
 
 Waypt* FGRouteMgr::nextWaypt() const
 {
-  if ((_currentIndex + 1) >= numWaypts()) {
+  if ((_currentIndex < 0) || ((_currentIndex + 1) >= numWaypts())) {
     return NULL;
   }
   
@@ -1080,9 +1273,17 @@ Waypt* FGRouteMgr::wayptAtIndex(int index) const
   return _route[index];
 }
 
-void FGRouteMgr::saveRoute()
+SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
+{
+    if ((index < 0) || (index >= numWaypts())) {
+        throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
+    }
+    
+    return mirror->getChild("wp", index);
+}
+
+bool FGRouteMgr::saveRoute(const SGPath& path)
 {
-  SGPath path(_pathNode->getStringValue());
   SG_LOG(SG_IO, SG_INFO, "Saving route to " << path.str());
   try {
     SGPropertyNode_ptr d(new SGPropertyNode);
@@ -1109,27 +1310,34 @@ void FGRouteMgr::saveRoute()
       wpt->saveAsNode(routeNode->getChild("wp", i, true));
     } // of waypoint iteration
     writeProperties(path.str(), d, true /* write-all */);
+    return true;
   } catch (sg_exception& e) {
-    SG_LOG(SG_IO, SG_WARN, "failed to save flight-plan:" << e.getMessage());
+    SG_LOG(SG_IO, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
+    return false;
   }
 }
 
-void FGRouteMgr::loadRoute()
+bool FGRouteMgr::loadRoute(const SGPath& path)
 {
+  if (!path.exists())
+  {
+      SG_LOG(SG_IO, SG_ALERT, "Failed to load flight-plan '" << path.str()
+              << "'. The file does not exist.");
+      return false;
+  }
+    
   // deactivate route first
   active->setBoolValue(false);
   
   SGPropertyNode_ptr routeData(new SGPropertyNode);
-  SGPath path(_pathNode->getStringValue());
   
   SG_LOG(SG_IO, SG_INFO, "going to read flight-plan from:" << path.str());
     
   try {
     readProperties(path.str(), routeData);
-  } catch (sg_exception& e) {
+  } catch (sg_exception& ) {
     // if XML parsing fails, the file might be simple textual list of waypoints
-    loadPlainTextRoute(path);
-    return;
+    return loadPlainTextRoute(path);
   }
   
   try {
@@ -1141,9 +1349,11 @@ void FGRouteMgr::loadRoute()
     } else {
       throw sg_io_exception("unsupported XML route version");
     }
+    return true;
   } catch (sg_exception& e) {
-    SG_LOG(SG_IO, SG_WARN, "failed to load flight-plan (from '" << e.getOrigin()
-      << "'):" << e.getMessage());
+    SG_LOG(SG_IO, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
+      << "'. " << e.getMessage());
+    return false;
   }
 }
 
@@ -1260,14 +1470,14 @@ WayptRef FGRouteMgr::parseVersion1XMLWaypt(SGPropertyNode* aWP)
   return w;
 }
 
-void FGRouteMgr::loadPlainTextRoute(const SGPath& path)
+bool FGRouteMgr::loadPlainTextRoute(const SGPath& path)
 {
-  sg_gzifstream in(path.str().c_str());
-  if (!in.is_open()) {
-    return;
-  }
-  
   try {
+    sg_gzifstream in(path.str().c_str());
+    if (!in.is_open()) {
+        throw sg_io_exception("Cannot open file for reading.");
+    }
+  
     WayptVec wpts;
     while (!in.eof()) {
       string line;
@@ -1284,15 +1494,17 @@ void FGRouteMgr::loadPlainTextRoute(const SGPath& path)
       
       WayptRef w = waypointFromString(line);
       if (!w) {
-        throw sg_io_exception("failed to create waypoint from line:" + line);
+        throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
       }
       
       wpts.push_back(w);
     } // of line iteration
   
     _route = wpts;
+    return true;
   } catch (sg_exception& e) {
-    SG_LOG(SG_IO, SG_WARN, "failed to load route from:" << path.str() << ":" << e.getMessage());
+    SG_LOG(SG_IO, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
+    return false;
   }
 }
 
@@ -1353,4 +1565,42 @@ void FGRouteMgr::setDestinationICAO(const char* aIdent)
   
   arrivalChanged();
 }
+
+FGAirportRef FGRouteMgr::departureAirport() const
+{
+    return _departure;
+}
+
+FGAirportRef FGRouteMgr::destinationAirport() const
+{
+    return _destination;
+}
+
+FGRunway* FGRouteMgr::departureRunway() const
+{
+    if (!_departure) {
+        return NULL;
+    }
+    
+    string runwayId(departure->getStringValue("runway"));
+    if (!_departure->hasRunwayWithIdent(runwayId)) {
+        return NULL;
+    }
+    
+    return _departure->getRunwayByIdent(runwayId);
+}
+
+FGRunway* FGRouteMgr::destinationRunway() const
+{
+    if (!_destination) {
+        return NULL;
+    }
     
+    string runwayId(destination->getStringValue("runway"));
+    if (!_destination->hasRunwayWithIdent(runwayId)) {
+        return NULL;
+    }
+    
+    return _destination->getRunwayByIdent(runwayId);
+}
+