1 // route.cxx - classes supporting waypoints and route structures
3 // Written by James Turner, started 2009.
5 // Copyright (C) 2009 Curtis L. Olson
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
32 #include <boost/algorithm/string/case_conv.hpp>
33 #include <boost/algorithm/string.hpp>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/xml/easyxml.hxx>
38 #include <simgear/misc/sg_path.hxx>
39 #include <simgear/magvar/magvar.hxx>
40 #include <simgear/timing/sg_time.hxx>
43 #include <Main/globals.hxx>
44 #include <Navaids/procedure.hxx>
45 #include <Navaids/waypoint.hxx>
46 #include <Airports/simple.hxx>
53 namespace flightgear {
55 const double NO_MAG_VAR = -1000.0; // an impossible mag-var value
57 Waypt::Waypt(Route* aOwner) :
60 _altRestrict(RESTRICT_NONE),
61 _speedRestrict(RESTRICT_NONE),
64 _magVarDeg(NO_MAG_VAR)
72 std::string Waypt::ident() const
77 bool Waypt::flag(WayptFlag aFlag) const
79 return ((_flags & aFlag) != 0);
82 void Waypt::setFlag(WayptFlag aFlag, bool aV)
84 _flags = (_flags & ~aFlag);
85 if (aV) _flags |= aFlag;
88 bool Waypt::matches(Waypt* aOther) const
91 if (ident() != aOther->ident()) { // cheap check first
95 return matches(aOther->position());
99 bool Waypt::matches(const SGGeod& aPos) const
101 double d = SGGeodesy::distanceM(position(), aPos);
102 return (d < 100.0); // 100 metres seems plenty
105 void Waypt::setAltitude(double aAlt, RouteRestriction aRestrict)
108 _altRestrict = aRestrict;
111 void Waypt::setSpeed(double aSpeed, RouteRestriction aRestrict)
114 _speedRestrict = aRestrict;
117 double Waypt::speedKts() const
119 assert(_speedRestrict != SPEED_RESTRICT_MACH);
123 double Waypt::speedMach() const
125 assert(_speedRestrict == SPEED_RESTRICT_MACH);
129 std::pair<double, double>
130 Waypt::courseAndDistanceFrom(const SGGeod& aPos) const
132 if (flag(WPT_DYNAMIC)) {
133 return std::make_pair(0.0, 0.0);
136 double course, az2, distance;
137 SGGeodesy::inverse(aPos, position(), course, az2, distance);
138 return std::make_pair(course, distance);
141 double Waypt::magvarDeg() const
143 if (_magVarDeg == NO_MAG_VAR) {
144 // derived classes with a default pos must override this method
145 assert(!(position() == SGGeod()));
147 double jd = globals->get_time_params()->getJD();
148 _magVarDeg = sgGetMagVar(position(), jd) * SG_RADIANS_TO_DEGREES;
154 double Waypt::headingRadialDeg() const
159 ///////////////////////////////////////////////////////////////////////////
162 static RouteRestriction restrictionFromString(const char* aStr)
164 std::string l = boost::to_lower_copy(std::string(aStr));
166 if (l == "at") return RESTRICT_AT;
167 if (l == "above") return RESTRICT_ABOVE;
168 if (l == "below") return RESTRICT_BELOW;
169 if (l == "none") return RESTRICT_NONE;
170 if (l == "mach") return SPEED_RESTRICT_MACH;
172 if (l.empty()) return RESTRICT_NONE;
173 throw sg_io_exception("unknown restriction specification:" + l,
174 "Route restrictFromString");
177 static const char* restrictionToString(RouteRestriction aRestrict)
180 case RESTRICT_AT: return "at";
181 case RESTRICT_BELOW: return "below";
182 case RESTRICT_ABOVE: return "above";
183 case RESTRICT_NONE: return "none";
184 case SPEED_RESTRICT_MACH: return "mach";
187 throw sg_exception("invalid route restriction",
188 "Route restrictToString");
192 Waypt* Waypt::createInstance(Route* aOwner, const std::string& aTypeName)
195 if (aTypeName == "basic") {
196 r = new BasicWaypt(aOwner);
197 } else if (aTypeName == "navaid") {
198 r = new NavaidWaypoint(aOwner);
199 } else if (aTypeName == "offset-navaid") {
200 r = new OffsetNavaidWaypoint(aOwner);
201 } else if (aTypeName == "hold") {
202 r = new Hold(aOwner);
203 } else if (aTypeName == "runway") {
204 r = new RunwayWaypt(aOwner);
205 } else if (aTypeName == "hdgToAlt") {
206 r = new HeadingToAltitude(aOwner);
207 } else if (aTypeName == "dmeIntercept") {
208 r = new DMEIntercept(aOwner);
209 } else if (aTypeName == "radialIntercept") {
210 r = new RadialIntercept(aOwner);
211 } else if (aTypeName == "vectors") {
212 r = new ATCVectors(aOwner);
215 if (!r || (r->type() != aTypeName)) {
216 throw sg_exception("broken factory method for type:" + aTypeName,
217 "Waypt::createInstance");
223 WayptRef Waypt::createFromProperties(Route* aOwner, SGPropertyNode_ptr aProp)
225 if (!aProp->hasChild("type")) {
226 throw sg_io_exception("bad props node, no type provided",
227 "Waypt::createFromProperties");
230 WayptRef nd(createInstance(aOwner, aProp->getStringValue("type")));
231 nd->initFromProperties(aProp);
235 void Waypt::saveAsNode(SGPropertyNode* n) const
237 n->setStringValue("type", type());
238 writeToProperties(n);
241 void Waypt::initFromProperties(SGPropertyNode_ptr aProp)
243 if (aProp->hasChild("generated")) {
244 setFlag(WPT_GENERATED, aProp->getBoolValue("generated"));
247 if (aProp->hasChild("overflight")) {
248 setFlag(WPT_OVERFLIGHT, aProp->getBoolValue("overflight"));
251 if (aProp->hasChild("arrival")) {
252 setFlag(WPT_ARRIVAL, aProp->getBoolValue("arrival"));
255 if (aProp->hasChild("departure")) {
256 setFlag(WPT_DEPARTURE, aProp->getBoolValue("departure"));
259 if (aProp->hasChild("miss")) {
260 setFlag(WPT_MISS, aProp->getBoolValue("miss"));
263 if (aProp->hasChild("alt-restrict")) {
264 _altRestrict = restrictionFromString(aProp->getStringValue("alt-restrict"));
265 _altitudeFt = aProp->getDoubleValue("altitude-ft");
268 if (aProp->hasChild("speed-restrict")) {
269 _speedRestrict = restrictionFromString(aProp->getStringValue("speed-restrict"));
270 _speed = aProp->getDoubleValue("speed");
276 void Waypt::writeToProperties(SGPropertyNode_ptr aProp) const
278 if (flag(WPT_OVERFLIGHT)) {
279 aProp->setBoolValue("overflight", true);
282 if (flag(WPT_DEPARTURE)) {
283 aProp->setBoolValue("departure", true);
286 if (flag(WPT_ARRIVAL)) {
287 aProp->setBoolValue("arrival", true);
290 if (flag(WPT_MISS)) {
291 aProp->setBoolValue("miss", true);
294 if (flag(WPT_GENERATED)) {
295 aProp->setBoolValue("generated", true);
298 if (_altRestrict != RESTRICT_NONE) {
299 aProp->setStringValue("alt-restrict", restrictionToString(_altRestrict));
300 aProp->setDoubleValue("altitude-ft", _altitudeFt);
303 if (_speedRestrict != RESTRICT_NONE) {
304 aProp->setStringValue("speed-restrict", restrictionToString(_speedRestrict));
305 aProp->setDoubleValue("speed", _speed);
309 void Route::dumpRouteToFile(const WayptVec& aRoute, const std::string& aName)
311 SGPath p = "/Users/jmt/Desktop/" + aName + ".kml";
313 f.open(p.str().c_str(), fstream::out | fstream::app);
315 SG_LOG(SG_GENERAL, SG_WARN, "unable to open:" << p.str());
320 f << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
321 "<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n"
324 dumpRouteToLineString(aName, aRoute, f);
332 void Route::dumpRouteToLineString(const std::string& aIdent,
333 const WayptVec& aRoute, std::ostream& aStream)
336 aStream << "<Placemark>\n";
337 aStream << "<name>" << aIdent << "</name>\n";
338 aStream << "<LineString>\n";
339 aStream << "<tessellate>1</tessellate>\n";
340 aStream << "<coordinates>\n";
343 for (unsigned int i=0; i<aRoute.size(); ++i) {
344 SGGeod pos = aRoute[i]->position();
345 aStream << pos.getLongitudeDeg() << "," << pos.getLatitudeDeg() << " " << endl;
349 aStream << "</coordinates>\n"
351 "</Placemark>\n" << endl;
354 ///////////////////////////////////////////////////////////////////////////
356 class NavdataVisitor : public XMLVisitor {
358 NavdataVisitor(FGAirport* aApt, const SGPath& aPath);
361 virtual void startXML ();
362 virtual void endXML ();
363 virtual void startElement (const char * name, const XMLAttributes &atts);
364 virtual void endElement (const char * name);
365 virtual void data (const char * s, int len);
366 virtual void pi (const char * target, const char * data);
367 virtual void warning (const char * message, int line, int column);
368 virtual void error (const char * message, int line, int column);
371 Waypt* buildWaypoint();
372 void processRunways(ArrivalDeparture* aProc, const XMLAttributes &atts);
374 void finishApproach();
380 string _text; ///< last element text value
386 WayptVec _waypoints; ///< waypoint list for current approach/sid/star
387 WayptVec _transWaypts; ///< waypoint list for current transition
391 string _ident; // id of segment under construction
393 double _longitude, _latitude, _altitude, _speed;
394 RouteRestriction _altRestrict;
396 double _holdRadial; // inbound hold radial, or -1 if radial is 'inbound'
397 double _holdTD; ///< hold time (seconds) or distance (nm), based on flag below
398 bool _holdRighthanded;
399 bool _holdDistance; // true, TD is distance in nm; false, TD is time in seconds
401 double _course, _radial, _dmeDistance;
404 void Route::loadAirportProcedures(const SGPath& aPath, FGAirport* aApt)
408 NavdataVisitor visitor(aApt, aPath);
409 readXML(aPath.str(), visitor);
410 } catch (sg_io_exception& ex) {
411 SG_LOG(SG_GENERAL, SG_WARN, "failured parsing procedures: " << aPath.str() <<
412 "\n\t" << ex.getMessage() << "\n\tat:" << ex.getLocation().asString());
413 } catch (sg_exception& ex) {
414 SG_LOG(SG_GENERAL, SG_WARN, "failured parsing procedures: " << aPath.str() <<
415 "\n\t" << ex.getMessage());
419 NavdataVisitor::NavdataVisitor(FGAirport* aApt, const SGPath& aPath):
428 void NavdataVisitor::startXML()
432 void NavdataVisitor::endXML()
436 void NavdataVisitor::startElement(const char* name, const XMLAttributes &atts)
440 if (tag == "Airport") {
441 string icao(atts.getValue("ICAOcode"));
442 if (_airport->ident() != icao) {
443 throw sg_format_exception("Airport and ICAO mismatch", icao, _path.str());
445 } else if (tag == "Sid") {
446 string ident(atts.getValue("Name"));
447 _sid = new SID(ident);
449 processRunways(_sid, atts);
450 } else if (tag == "Star") {
451 string ident(atts.getValue("Name"));
452 _star = new STAR(ident);
454 processRunways(_star, atts);
455 } else if ((tag == "Sid_Waypoint") ||
456 (tag == "App_Waypoint") ||
457 (tag == "Star_Waypoint") ||
458 (tag == "AppTr_Waypoint") ||
459 (tag == "SidTr_Waypoint") ||
460 (tag == "RwyTr_Waypoint"))
462 // reset waypoint data
464 _altRestrict = RESTRICT_NONE;
466 } else if (tag == "Approach") {
467 _ident = atts.getValue("Name");
469 _approach = new Approach(_ident);
470 } else if ((tag == "Sid_Transition") ||
471 (tag == "App_Transition") ||
472 (tag == "Star_Transition")) {
473 _transIdent = atts.getValue("Name");
474 _transWaypts.clear();
475 } else if (tag == "RunwayTransition") {
476 _transIdent = atts.getValue("Runway");
477 _transWaypts.clear();
483 void NavdataVisitor::processRunways(ArrivalDeparture* aProc, const XMLAttributes &atts)
486 if (atts.hasAttribute("Runways")) {
487 v = atts.getValue("Runways");
491 for (unsigned int r=0; r<_airport->numRunways(); ++r) {
492 aProc->addRunway(_airport->getRunwayByIndex(r));
498 boost::split(rwys, v, boost::is_any_of(" ,"));
499 for (unsigned int r=0; r<rwys.size(); ++r) {
500 FGRunway* rwy = _airport->getRunwayByIdent(rwys[r]);
501 aProc->addRunway(rwy);
505 void NavdataVisitor::endElement(const char* name)
508 if ((tag == "Sid_Waypoint") ||
509 (tag == "App_Waypoint") ||
510 (tag == "Star_Waypoint"))
512 _waypoints.push_back(buildWaypoint());
513 } else if ((tag == "AppTr_Waypoint") ||
514 (tag == "SidTr_Waypoint") ||
515 (tag == "RwyTr_Waypoint") ||
516 (tag == "StarTr_Waypoint"))
518 _transWaypts.push_back(buildWaypoint());
519 } else if (tag == "Sid_Transition") {
521 // SID waypoints are stored backwards, to share code with STARs
522 std::reverse(_transWaypts.begin(), _transWaypts.end());
523 Transition* t = new Transition(_transIdent, _sid, _transWaypts);
524 _sid->addTransition(t);
525 } else if (tag == "Star_Transition") {
527 Transition* t = new Transition(_transIdent, _star, _transWaypts);
528 _star->addTransition(t);
529 } else if (tag == "App_Transition") {
531 Transition* t = new Transition(_transIdent, _approach, _transWaypts);
532 _approach->addTransition(t);
533 } else if (tag == "RunwayTransition") {
534 ArrivalDeparture* ad;
536 // SID waypoints are stored backwards, to share code with STARs
537 std::reverse(_transWaypts.begin(), _transWaypts.end());
543 Transition* t = new Transition(_transIdent, ad, _transWaypts);
544 FGRunwayRef rwy = _airport->getRunwayByIdent(_transIdent);
545 ad->addRunwayTransition(rwy, t);
546 } else if (tag == "Approach") {
548 } else if (tag == "Sid") {
550 } else if (tag == "Star") {
552 } else if (tag == "Longitude") {
553 _longitude = atof(_text.c_str());
554 } else if (tag == "Latitude") {
555 _latitude = atof(_text.c_str());
556 } else if (tag == "Name") {
558 } else if (tag == "Type") {
560 } else if (tag == "Speed") {
561 _speed = atoi(_text.c_str());
562 } else if (tag == "Altitude") {
563 _altitude = atof(_text.c_str());
564 } else if (tag == "AltitudeRestriction") {
566 _altRestrict = RESTRICT_AT;
567 } else if (_text == "above") {
568 _altRestrict = RESTRICT_ABOVE;
569 } else if (_text == "below") {
570 _altRestrict = RESTRICT_BELOW;
572 throw sg_format_exception("Unrecognized altitude restriction", _text);
574 } else if (tag == "Hld_Rad_or_Inbd") {
575 if (_text == "Inbd") {
578 } else if (tag == "Hld_Time_or_Dist") {
579 _holdDistance = (_text == "Dist");
580 } else if (tag == "Hld_Rad_value") {
581 _holdRadial = atof(_text.c_str());
582 } else if (tag == "Hld_Turn") {
583 _holdRighthanded = (_text == "Right");
584 } else if (tag == "Hld_td_value") {
585 _holdTD = atof(_text.c_str());
586 } else if (tag == "Hdg_Crs_value") {
587 _course = atof(_text.c_str());
588 } else if (tag == "DMEtoIntercept") {
589 _dmeDistance = atof(_text.c_str());
590 } else if (tag == "RadialtoIntercept") {
591 _radial = atof(_text.c_str());
597 Waypt* NavdataVisitor::buildWaypoint()
600 if (_wayptType == "Normal") {
601 // new LatLonWaypoint
602 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
603 wp = new BasicWaypt(pos, _wayptName, NULL);
604 } else if (_wayptType == "Runway") {
605 string ident = _wayptName.substr(2);
606 FGRunwayRef rwy = _airport->getRunwayByIdent(ident);
607 wp = new RunwayWaypt(rwy, NULL);
608 } else if (_wayptType == "Hold") {
609 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
610 Hold* h = new Hold(pos, _wayptName, NULL);
612 if (_holdRighthanded) {
619 h->setHoldDistance(_holdTD);
621 h->setHoldTime(_holdTD * 60.0);
624 if (_holdRadial >= 0.0) {
625 h->setHoldRadial(_holdRadial);
627 } else if (_wayptType == "Vectors") {
628 wp = new ATCVectors(NULL, _airport);
629 } else if ((_wayptType == "Intc") || (_wayptType == "VorRadialIntc")) {
630 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
631 wp = new RadialIntercept(NULL, _wayptName, pos, _course, _radial);
632 } else if (_wayptType == "DmeIntc") {
633 SGGeod pos(SGGeod::fromDeg(_longitude, _latitude));
634 wp = new DMEIntercept(NULL, _wayptName, pos, _course, _dmeDistance);
635 } else if (_wayptType == "ConstHdgtoAlt") {
636 wp = new HeadingToAltitude(NULL, _wayptName, _course);
638 SG_LOG(SG_GENERAL, SG_ALERT, "implement waypoint type:" << _wayptType);
639 throw sg_format_exception("Unrecognized waypt type", _wayptType);
643 if ((_altitude > 0.0) && (_altRestrict != RESTRICT_NONE)) {
644 wp->setAltitude(_altitude,_altRestrict);
648 wp->setSpeed(_speed, RESTRICT_AT); // or _BELOW?
654 void NavdataVisitor::finishApproach()
656 WayptVec::iterator it;
659 // find the runway node
660 for (it = _waypoints.begin(); it != _waypoints.end(); ++it) {
661 FGPositionedRef navid = (*it)->source();
666 if (navid->type() == FGPositioned::RUNWAY) {
667 rwy = (FGRunway*) navid.get();
673 throw sg_format_exception("Malformed approach, no runway waypt", _ident);
676 WayptVec primary(_waypoints.begin(), it);
677 // erase all points up to and including the runway, to leave only the
679 _waypoints.erase(_waypoints.begin(), ++it);
681 _approach->setRunway(rwy);
682 _approach->setPrimaryAndMissed(primary, _waypoints);
683 _airport->addApproach(_approach);
687 void NavdataVisitor::finishSid()
689 // reverse order, because that's how we deal with commonality between
690 // STARs and SIDs. SID::route undoes this
691 std::reverse(_waypoints.begin(), _waypoints.end());
692 _sid->setCommon(_waypoints);
693 _airport->addSID(_sid);
697 void NavdataVisitor::finishStar()
699 _star->setCommon(_waypoints);
700 _airport->addSTAR(_star);
704 void NavdataVisitor::data (const char * s, int len)
706 _text += string(s, len);
710 void NavdataVisitor::pi (const char * target, const char * data) {
711 //cout << "Processing instruction " << target << ' ' << data << endl;
714 void NavdataVisitor::warning (const char * message, int line, int column) {
715 SG_LOG(SG_IO, SG_WARN, "Warning: " << message << " (" << line << ',' << column << ')');
718 void NavdataVisitor::error (const char * message, int line, int column) {
719 SG_LOG(SG_IO, SG_ALERT, "Error: " << message << " (" << line << ',' << column << ')');
722 } // of namespace flightgear