5 #include "MapWidget.hxx"
8 #include <algorithm> // for std::sort
9 #include <plib/puAux.h>
11 #include <simgear/sg_inlines.h>
12 #include <simgear/misc/strutils.hxx>
13 #include <simgear/magvar/magvar.hxx>
14 #include <simgear/timing/sg_time.hxx> // for magVar julianDate
15 #include <simgear/structure/exception.hxx>
17 #include <Main/globals.hxx>
18 #include <Main/fg_props.hxx>
19 #include <Autopilot/route_mgr.hxx>
20 #include <Navaids/positioned.hxx>
21 #include <Navaids/navrecord.hxx>
22 #include <Navaids/navlist.hxx>
23 #include <Navaids/fix.hxx>
24 #include <Airports/airport.hxx>
25 #include <Airports/runways.hxx>
26 #include <Main/fg_os.hxx> // fgGetKeyModifiers()
27 #include <Navaids/routePath.hxx>
28 #include <Aircraft/FlightHistory.hxx>
29 #include <AIModel/AIAircraft.hxx>
30 #include <AIModel/AIFlightPlan.hxx>
32 const char* RULER_LEGEND_KEY = "ruler-legend";
34 /* equatorial and polar earth radius */
35 const float rec = 6378137; // earth radius, equator (?)
36 const float rpol = 6356752.314f; // earth radius, polar (?)
38 /************************************************************************
39 some trigonometric helper functions
40 (translated more or less directly from Alexei Novikovs perl original)
41 *************************************************************************/
43 //Returns Earth radius at a given latitude (Ellipsoide equation with two equal axis)
44 static float earth_radius_lat( float lat )
46 double a = cos(lat)/rec;
47 double b = sin(lat)/rpol;
48 return 1.0f / sqrt( a * a + b * b );
51 ///////////////////////////////////////////////////////////////////////////
53 static puBox makePuBox(int x, int y, int w, int h)
63 static bool puBoxIntersect(const puBox& a, const puBox& b)
65 int x0 = SG_MAX2(a.min[0], b.min[0]);
66 int y0 = SG_MAX2(a.min[1], b.min[1]);
67 int x1 = SG_MIN2(a.max[0], b.max[0]);
68 int y1 = SG_MIN2(a.max[1], b.max[1]);
70 return (x0 <= x1) && (y0 <= y1);
74 typedef std::vector<MapData*> MapDataVec;
79 static const int HALIGN_LEFT = 1;
80 static const int HALIGN_CENTER = 2;
81 static const int HALIGN_RIGHT = 3;
83 static const int VALIGN_TOP = 1 << 4;
84 static const int VALIGN_CENTER = 2 << 4;
85 static const int VALIGN_BOTTOM = 3 << 4;
87 MapData(int priority) :
93 _offsetDir(HALIGN_LEFT | VALIGN_CENTER),
99 void setLabel(const std::string& label)
101 if (label == _label) {
102 return; // common case, and saves invalidation
109 void setText(const std::string &text)
111 if (_rawText == text) {
112 return; // common case, and saves invalidation
119 void setDataVisible(bool vis) {
120 if (vis == _dataVisible) {
124 if (_rawText.empty()) {
132 static void setFont(puFont f)
135 _fontHeight = f.getStringHeight();
136 _fontDescender = f.getStringDescender();
139 static void setPalette(puColor* pal)
144 void setPriority(int pri)
150 { return _priority; }
152 void setAnchor(const SGVec2d& anchor)
157 void setOffset(int direction, int px)
159 if ((_offsetPx == px) && (_offsetDir == direction)) {
164 _offsetDir = direction;
168 bool isClipped(const puBox& vis) const
171 if ((_width < 1) || (_height < 1)) {
175 return !puBoxIntersect(vis, box());
178 bool overlaps(const MapDataVec& l) const
183 MapDataVec::const_iterator it;
184 for (it = l.begin(); it != l.end(); ++it) {
185 if (puBoxIntersect(b, (*it)->box())) {
188 } // of list iteration
197 _anchor.x() + _offset.x(),
198 _anchor.y() + _offset.y(),
202 void drawStringUtf8(std::string& utf8Str, double x, double y, puFont fnt)
204 fnt.drawString(simgear::strutils::utf8ToLatin1(utf8Str).c_str(), x, y);
211 int xx = _anchor.x() + _offset.x();
212 int yy = _anchor.y() + _offset.y();
215 puBox box(makePuBox(0,0,_width, _height));
217 box.draw(xx, yy, PUSTYLE_DROPSHADOW, _palette, FALSE, border);
220 int lineHeight = _fontHeight;
221 int xPos = xx + MARGIN;
222 int yPos = yy + _height - (lineHeight + MARGIN);
223 glColor3f(0.8, 0.8, 0.8);
225 for (unsigned int ln=0; ln<_lines.size(); ++ln) {
226 drawStringUtf8(_lines[ln], xPos, yPos, _font);
227 yPos -= lineHeight + LINE_LEADING;
230 glColor3f(0.8, 0.8, 0.8);
231 drawStringUtf8(_label, xx, yy + _fontDescender, _font);
245 bool isExpired() const
246 { return (_age > 100); }
248 static bool order(MapData* a, MapData* b)
250 return a->_priority > b->_priority;
253 void validate() const
273 void measureData() const
275 _lines = simgear::strutils::split(_rawText, "\n");
276 // measure text to find width and height
280 for (unsigned int ln=0; ln<_lines.size(); ++ln) {
281 _height += _fontHeight;
283 _height += LINE_LEADING;
286 int lw = _font.getStringWidth(_lines[ln].c_str());
287 _width = std::max(_width, lw);
288 } // of line measurement
290 if ((_width < 1) || (_height < 1)) {
295 _height += MARGIN * 2;
296 _width += MARGIN * 2;
299 void measureLabel() const
301 if (_label.empty()) {
302 _width = _height = -1;
306 _height = _fontHeight;
307 _width = _font.getStringWidth(_label.c_str());
310 void computeOffset() const
312 _dirtyOffset = false;
313 if ((_width <= 0) || (_height <= 0)) {
320 switch (_offsetDir & 0x0f) {
327 hOffset = -(_width>>1);
331 hOffset = -(_offsetPx + _width);
335 switch (_offsetDir & 0xf0) {
338 vOffset = -(_offsetPx + _height);
342 vOffset = -(_height>>1);
350 _offset = SGVec2d(hOffset, vOffset);
353 static const int LINE_LEADING = 3;
354 static const int MARGIN = 3;
356 mutable bool _dirtyText;
357 mutable bool _dirtyOffset;
359 std::string _rawText;
361 mutable std::vector<std::string> _lines;
363 mutable int _width, _height;
367 mutable SGVec2d _offset;
371 static puColor* _palette;
372 static int _fontHeight;
373 static int _fontDescender;
376 puFont MapData::_font;
377 puColor* MapData::_palette;
378 int MapData::_fontHeight = 0;
379 int MapData::_fontDescender = 0;
381 ///////////////////////////////////////////////////////////////////////////
383 // anonymous namespace
387 class MapAirportFilter : public FGAirport::AirportFilter
390 MapAirportFilter(SGPropertyNode_ptr nd)
392 _heliports = nd->getBoolValue("show-heliports", false);
393 _hardRunwaysOnly = nd->getBoolValue("hard-surfaced-airports", true);
394 _minLengthFt = fgGetDouble("/sim/navdb/min-runway-length-ft", 2000);
397 virtual FGPositioned::Type maxType() const {
398 return _heliports ? FGPositioned::HELIPORT : FGPositioned::AIRPORT;
401 virtual bool passAirport(FGAirport* aApt) const {
402 if (_hardRunwaysOnly) {
403 return aApt->hasHardRunwayOfLengthFt(_minLengthFt);
411 _hardRunwaysOnly = false;
416 bool _hardRunwaysOnly;
420 class NavaidFilter : public FGPositioned::Filter
423 NavaidFilter(bool fixesEnabled, bool navaidsEnabled) :
424 _fixes(fixesEnabled),
425 _navaids(navaidsEnabled)
428 virtual bool pass(FGPositioned* aPos) const {
429 if (_fixes && (aPos->type() == FGPositioned::FIX)) {
430 // ignore fixes which end in digits - expirmental
431 if (aPos->ident().length() > 4 && isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
439 virtual FGPositioned::Type minType() const {
440 return _fixes ? FGPositioned::FIX : FGPositioned::NDB;
443 virtual FGPositioned::Type maxType() const {
444 return _navaids ? FGPositioned::VOR : FGPositioned::FIX;
448 bool _fixes, _navaids;
451 } // of anonymous namespace
453 const int MAX_ZOOM = 12;
454 const int SHOW_DETAIL_ZOOM = 8;
455 const int SHOW_DETAIL2_ZOOM = 5;
456 const int CURSOR_PAN_STEP = 32;
458 MapWidget::MapWidget(int x, int y, int maxX, int maxY) :
459 puObject(x,y,maxX, maxY)
461 _route = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
462 _gps = fgGetNode("/instrumentation/gps");
467 _projection = PROJECTION_SAMSON_FLAMSTEED;
468 _magneticHeadings = false;
470 MapData::setFont(legendFont);
471 MapData::setPalette(colour);
473 _magVar = new SGMagVar();
476 MapWidget::~MapWidget()
482 void MapWidget::setProperty(SGPropertyNode_ptr prop)
485 int zoom = _root->getIntValue("zoom", -1);
487 _root->setIntValue("zoom", 6); // default zoom
490 // expose MAX_ZOOM to the UI
491 _root->setIntValue("max-zoom", MAX_ZOOM);
492 _root->setBoolValue("centre-on-aircraft", true);
493 _root->setBoolValue("draw-data", false);
494 _root->setBoolValue("draw-flight-history", false);
495 _root->setBoolValue("magnetic-headings", true);
498 void MapWidget::setSize(int w, int h)
500 puObject::setSize(w, h);
507 void MapWidget::doHit( int button, int updown, int x, int y )
509 puObject::doHit(button, updown, x, y);
510 if (updown == PU_DRAG) {
515 if (button == 3) { // mouse-wheel up
517 } else if (button == 4) { // mouse-wheel down
521 if (button != active_mouse_button) {
525 _hitLocation = SGVec2d(x - abox.min[0], y - abox.min[1]);
527 if (updown == PU_UP) {
528 puDeactivateWidget();
529 } else if (updown == PU_DOWN) {
530 puSetActiveWidget(this, x, y);
532 if (fgGetKeyModifiers() & KEYMOD_CTRL) {
533 _clickGeod = unproject(_hitLocation - SGVec2d(_width>>1, _height>>1));
538 void MapWidget::handlePan(int x, int y)
540 SGVec2d delta = SGVec2d(x, y) - _hitLocation;
542 _hitLocation = SGVec2d(x,y);
545 int MapWidget::checkKey (int key, int updown )
547 if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
555 pan(SGVec2d(0, -CURSOR_PAN_STEP));
559 pan(SGVec2d(0, CURSOR_PAN_STEP));
563 pan(SGVec2d(CURSOR_PAN_STEP, 0));
567 pan(SGVec2d(-CURSOR_PAN_STEP, 0));
586 void MapWidget::pan(const SGVec2d& delta)
589 _projectionCenter = unproject(-delta);
592 int MapWidget::zoom() const
594 int z = _root->getIntValue("zoom");
595 SG_CLAMP_RANGE(z, 0, MAX_ZOOM);
599 void MapWidget::zoomIn()
601 if (zoom() >= MAX_ZOOM) {
605 _root->setIntValue("zoom", zoom() + 1);
608 void MapWidget::zoomOut()
614 _root->setIntValue("zoom", zoom() - 1);
617 void MapWidget::update()
619 _aircraft = globals->get_aircraft_position();
621 bool mag = _root->getBoolValue("magnetic-headings");
622 if (mag != _magneticHeadings) {
623 clearData(); // flush cached data text, since it often includes heading
624 _magneticHeadings = mag;
628 _root->setBoolValue("centre-on-aircraft", false);
631 else if (_root->getBoolValue("centre-on-aircraft")) {
632 _projectionCenter = _aircraft;
635 double julianDate = globals->get_time_params()->getJD();
636 _magVar->update(_projectionCenter, julianDate);
638 _aircraftUp = _root->getBoolValue("aircraft-heading-up");
640 _upHeading = fgGetDouble("/orientation/heading-deg");
645 if (_magneticHeadings) {
646 _displayHeading = (int) fgGetDouble("/orientation/heading-magnetic-deg");
648 _displayHeading = (int) _upHeading;
651 _cachedZoom = MAX_ZOOM - zoom();
652 SGGeod topLeft = unproject(SGVec2d(_width/2, _height/2));
653 // compute draw range, including a fudge factor for ILSs and other 'long'
655 _drawRangeNm = SGGeodesy::distanceNm(_projectionCenter, topLeft) + 10.0;
658 FGFlightHistory* history = (FGFlightHistory*) globals->get_subsystem("history");
659 if (history && _root->getBoolValue("draw-flight-history")) {
660 _flightHistoryPath = history->pathForHistory();
662 _flightHistoryPath.clear();
665 // make spatial queries. This can trigger loading of XML files, etc, so we do
666 // not want to do it in draw(), which can be called from an arbitrary OSG
669 MapAirportFilter af(_root);
670 if (_cachedZoom <= SHOW_DETAIL2_ZOOM) {
671 // show all airports when zoomed in sufficently
675 bool partial = false;
676 FGPositionedList newItemsToDraw =
677 FGPositioned::findWithinRangePartial(_projectionCenter, _drawRangeNm, &af, partial);
679 bool fixes = _root->getBoolValue("draw-fixes");
680 NavaidFilter f(fixes, _root->getBoolValue("draw-navaids"));
681 if (f.minType() <= f.maxType()) {
682 FGPositionedList navs = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &f);
683 newItemsToDraw.insert(newItemsToDraw.end(), navs.begin(), navs.end());
686 FGPositioned::TypeFilter tf(FGPositioned::COUNTRY);
687 if (_cachedZoom <= SHOW_DETAIL_ZOOM) {
688 tf.addType(FGPositioned::CITY);
691 if (_cachedZoom <= SHOW_DETAIL2_ZOOM) {
692 tf.addType(FGPositioned::TOWN);
695 FGPositionedList poi = FGPositioned::findWithinRange(_projectionCenter, _drawRangeNm, &tf);
696 newItemsToDraw.insert(newItemsToDraw.end(), poi.begin(), poi.end());
698 _itemsToDraw.swap(newItemsToDraw);
703 void MapWidget::updateAIObjects()
705 if (!_root->getBoolValue("draw-traffic") || (_cachedZoom > SHOW_DETAIL_ZOOM)) {
710 AIDrawVec newDrawVec;
712 const SGPropertyNode* ai = fgGetNode("/ai/models", true);
713 for (int i = 0; i < ai->nChildren(); ++i) {
714 const SGPropertyNode *model = ai->getChild(i);
715 // skip bad or dead entries
716 if (!model || model->getIntValue("id", -1) == -1) {
720 SGGeod pos = SGGeod::fromDegFt(
721 model->getDoubleValue("position/longitude-deg"),
722 model->getDoubleValue("position/latitude-deg"),
723 model->getDoubleValue("position/altitude-ft"));
725 double dist = SGGeodesy::distanceNm(_projectionCenter, pos);
726 if (dist > _drawRangeNm) {
730 newDrawVec.push_back(DrawAIObject((SGPropertyNode*) model, pos));
731 } // of ai/models iteration
733 _aiDrawVec.swap(newDrawVec);
736 void MapWidget::draw(int dx, int dy)
738 GLint sx = (int) abox.min[0],
739 sy = (int) abox.min[1];
740 glScissor(dx + sx, dy + sy, _width, _height);
741 glEnable(GL_SCISSOR_TEST);
743 glMatrixMode(GL_MODELVIEW);
745 // cetere drawing about the widget center (which is also the
746 // projection centre)
747 glTranslated(dx + sx + (_width/2), dy + sy + (_height/2), 0.0);
752 int textHeight = legendFont.getStringHeight() + 5;
755 SGVec2d loc = project(_aircraft);
756 glColor3f(1.0, 1.0, 1.0);
757 drawLine(loc, SGVec2d(loc.x(), (_height / 2) - textHeight));
759 double y = (_height / 2) - textHeight;
761 ::snprintf(buf, 16, "%d", _displayHeading);
762 int sw = legendFont.getStringWidth(buf);
763 legendFont.drawString(buf, loc.x() - sw/2, y);
769 drawNavRadio(fgGetNode("/instrumentation/nav[0]", false));
770 drawNavRadio(fgGetNode("/instrumentation/nav[1]", false));
771 paintAircraftLocation(_aircraft);
779 glDisable(GL_SCISSOR_TEST);
782 void MapWidget::paintRuler()
784 if (_clickGeod == SGGeod()) {
788 SGVec2d acftPos = project(_aircraft);
789 SGVec2d clickPos = project(_clickGeod);
791 glColor4f(0.0, 1.0, 1.0, 0.6);
792 drawLine(acftPos, clickPos);
794 circleAtAlt(clickPos, 8, 10, 5);
796 double dist, az, az2;
797 SGGeodesy::inverse(_aircraft, _clickGeod, az, az2, dist);
799 ::snprintf(buffer, 1024, "%03d/%.1fnm",
800 displayHeading(az), dist * SG_METER_TO_NM);
802 MapData* d = getOrCreateDataForKey((void*) RULER_LEGEND_KEY);
804 d->setAnchor(clickPos);
805 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
806 d->setPriority(20000);
809 void MapWidget::paintAircraftLocation(const SGGeod& aircraftPos)
811 SGVec2d loc = project(aircraftPos);
813 double hdg = fgGetDouble("/orientation/heading-deg");
816 glColor4f(1.0, 1.0, 0.0, 1.0);
818 glTranslated(loc.x(), loc.y(), 0.0);
819 glRotatef(hdg - _upHeading, 0.0, 0.0, -1.0);
821 const SGVec2d wingspan(12, 0);
822 const SGVec2d nose(0, 8);
823 const SGVec2d tail(0, -14);
824 const SGVec2d tailspan(4,0);
826 drawLine(-wingspan, wingspan);
827 drawLine(nose, tail);
828 drawLine(tail - tailspan, tail + tailspan);
834 void MapWidget::paintRoute()
836 if (_route->numWaypts() < 2) {
840 RoutePath path(_route->flightPlan());
842 // first pass, draw the actual lines
845 for (int w=0; w<_route->numWaypts(); ++w) {
846 SGGeodVec gv(path.pathForIndex(w));
851 if (w < _route->currentIndex()) {
852 glColor4f(0.5, 0.5, 0.5, 0.7);
854 glColor4f(1.0, 0.0, 1.0, 1.0);
857 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
858 if (wpt->flag(flightgear::WPT_MISS)) {
859 glEnable(GL_LINE_STIPPLE);
860 glLineStipple(1, 0x00FF);
863 glBegin(GL_LINE_STRIP);
864 for (unsigned int i=0; i<gv.size(); ++i) {
865 SGVec2d p = project(gv[i]);
866 glVertex2d(p.x(), p.y());
870 glDisable(GL_LINE_STIPPLE);
874 // second pass, draw waypoint symbols and data
875 for (int w=0; w < _route->numWaypts(); ++w) {
876 flightgear::WayptRef wpt(_route->wayptAtIndex(w));
877 SGGeod g = path.positionForIndex(w);
879 continue; // Vectors or similar
882 SGVec2d p = project(g);
883 glColor4f(1.0, 0.0, 1.0, 1.0);
884 circleAtAlt(p, 8, 12, 5);
886 std::ostringstream legend;
887 legend << wpt->ident();
888 if (wpt->altitudeRestriction() != flightgear::RESTRICT_NONE) {
889 legend << '\n' << SGMiscd::roundToInt(wpt->altitudeFt()) << '\'';
892 if (wpt->speedRestriction() == flightgear::SPEED_RESTRICT_MACH) {
893 legend << '\n' << wpt->speedMach() << "M";
894 } else if (wpt->speedRestriction() != flightgear::RESTRICT_NONE) {
895 legend << '\n' << SGMiscd::roundToInt(wpt->speedKts()) << "Kts";
898 MapData* d = getOrCreateDataForKey(reinterpret_cast<void*>(w * 2));
899 d->setText(legend.str());
900 d->setLabel(wpt->ident());
902 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 15);
903 d->setPriority(w < _route->currentIndex() ? 9000 : 12000);
905 } // of second waypoint iteration
908 void MapWidget::drawFlightHistory()
910 if (_flightHistoryPath.empty())
913 // first pass, draw the actual lines
916 glColor4f(0.0, 0.0, 1.0, 0.7);
918 glBegin(GL_LINE_STRIP);
919 for (unsigned int i=0; i<_flightHistoryPath.size(); ++i) {
920 SGVec2d p = project(_flightHistoryPath[i]);
921 glVertex2d(p.x(), p.y());
928 * Round a SGGeod to an arbitrary precision.
929 * For example, passing precision of 0.5 will round to the nearest 0.5 of
930 * a degree in both lat and lon - passing in 3.0 rounds to the nearest 3 degree
931 * multiple, and so on.
933 static SGGeod roundGeod(double precision, const SGGeod& g)
935 double lon = SGMiscd::round(g.getLongitudeDeg() / precision);
936 double lat = SGMiscd::round(g.getLatitudeDeg() / precision);
938 return SGGeod::fromDeg(lon * precision, lat * precision);
941 bool MapWidget::drawLineClipped(const SGVec2d& a, const SGVec2d& b)
943 double minX = SGMiscd::min(a.x(), b.x()),
944 minY = SGMiscd::min(a.y(), b.y()),
945 maxX = SGMiscd::max(a.x(), b.x()),
946 maxY = SGMiscd::max(a.y(), b.y());
948 int hh = _height >> 1, hw = _width >> 1;
950 if ((maxX < -hw) || (minX > hw) || (minY > hh) || (maxY < -hh)) {
954 glVertex2dv(a.data());
955 glVertex2dv(b.data());
959 SGVec2d MapWidget::gridPoint(int ix, int iy)
961 int key = (ix + 0x7fff) | ((iy + 0x7fff) << 16);
962 GridPointCache::iterator it = _gridCache.find(key);
963 if (it != _gridCache.end()) {
967 SGGeod gp = SGGeod::fromDeg(
968 _gridCenter.getLongitudeDeg() + ix * _gridSpacing,
969 _gridCenter.getLatitudeDeg() + iy * _gridSpacing);
971 SGVec2d proj = project(gp);
972 _gridCache[key] = proj;
976 void MapWidget::drawLatLonGrid()
979 _gridCenter = roundGeod(_gridSpacing, _projectionCenter);
985 glColor4f(0.8, 0.8, 0.8, 0.4);
993 for (int x = -ix; x < ix; ++x) {
994 didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x+1, -iy));
995 didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x+1, iy));
996 didDraw |= drawLineClipped(gridPoint(x, -iy), gridPoint(x, -iy + 1));
997 didDraw |= drawLineClipped(gridPoint(x, iy), gridPoint(x, iy - 1));
1001 for (int y = -iy; y < iy; ++y) {
1002 didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix, y+1));
1003 didDraw |= drawLineClipped(gridPoint(-ix, y), gridPoint(-ix + 1, y));
1004 didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix, y+1));
1005 didDraw |= drawLineClipped(gridPoint(ix, y), gridPoint(ix - 1, y));
1016 void MapWidget::drawGPSData()
1018 std::string gpsMode = _gps->getStringValue("mode");
1020 SGGeod wp0Geod = SGGeod::fromDeg(
1021 _gps->getDoubleValue("wp/wp[0]/longitude-deg"),
1022 _gps->getDoubleValue("wp/wp[0]/latitude-deg"));
1024 SGGeod wp1Geod = SGGeod::fromDeg(
1025 _gps->getDoubleValue("wp/wp[1]/longitude-deg"),
1026 _gps->getDoubleValue("wp/wp[1]/latitude-deg"));
1029 double gpsTrackDeg = _gps->getDoubleValue("indicated-track-true-deg");
1030 double gpsSpeed = _gps->getDoubleValue("indicated-ground-speed-kt");
1033 if (gpsSpeed > 3.0) { // only draw track line if valid
1035 SGGeodesy::direct(_aircraft, gpsTrackDeg, _drawRangeNm * SG_NM_TO_METER, trackRadial, az2);
1037 glColor4f(1.0, 1.0, 0.0, 1.0);
1038 glEnable(GL_LINE_STIPPLE);
1039 glLineStipple(1, 0x00FF);
1040 drawLine(project(_aircraft), project(trackRadial));
1041 glDisable(GL_LINE_STIPPLE);
1044 if (gpsMode == "dto") {
1045 SGVec2d wp0Pos = project(wp0Geod);
1046 SGVec2d wp1Pos = project(wp1Geod);
1048 glColor4f(1.0, 0.0, 1.0, 1.0);
1049 drawLine(wp0Pos, wp1Pos);
1053 if (_gps->getBoolValue("scratch/valid")) {
1054 // draw scratch data
1059 void MapWidget::drawPositioned()
1061 for (unsigned int i=0; i<_itemsToDraw.size(); ++i) {
1062 FGPositionedRef p = _itemsToDraw[i];
1063 switch (p->type()) {
1064 case FGPositioned::AIRPORT:
1065 drawAirport((FGAirport*) p.get());
1067 case FGPositioned::NDB:
1068 drawNDB(false, (FGNavRecord*) p.get());
1070 case FGPositioned::VOR:
1071 drawVOR(false, (FGNavRecord*) p.get());
1073 case FGPositioned::FIX:
1074 drawFix((FGFix*) p.get());
1076 case FGPositioned::TOWN:
1077 case FGPositioned::CITY:
1078 case FGPositioned::COUNTRY:
1083 SG_LOG(SG_GENERAL, SG_WARN, "unhandled type in MapWidget::drawPositioned");
1084 } // of positioned type switch
1085 } // of items to draw iteration
1088 void MapWidget::drawNDB(bool tuned, FGNavRecord* ndb)
1090 SGVec2d pos = project(ndb->geod());
1093 glColor3f(0.0, 1.0, 1.0);
1095 glColor3f(0.0, 0.0, 0.0);
1098 glEnable(GL_LINE_STIPPLE);
1099 glLineStipple(1, 0x00FF);
1100 circleAt(pos, 20, 6);
1101 circleAt(pos, 20, 10);
1102 glDisable(GL_LINE_STIPPLE);
1104 if (validDataForKey(ndb)) {
1105 setAnchorForKey(ndb, pos);
1110 ::snprintf(buffer, 1024, "%s\n%s %3.0fKhz",
1111 ndb->name().c_str(), ndb->ident().c_str(),ndb->get_freq()/100.0);
1113 MapData* d = createDataForKey(ndb);
1115 d->setLabel(ndb->ident());
1117 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1122 void MapWidget::drawVOR(bool tuned, FGNavRecord* vor)
1124 SGVec2d pos = project(vor->geod());
1126 glColor3f(0.0, 1.0, 1.0);
1128 glColor3f(0.0, 0.0, 1.0);
1131 circleAt(pos, 6, 9);
1132 circleAt(pos, 8, 1);
1137 if (validDataForKey(vor)) {
1138 setAnchorForKey(vor, pos);
1143 ::snprintf(buffer, 1024, "%s\n%s %6.3fMhz",
1144 vor->name().c_str(), vor->ident().c_str(),
1145 vor->get_freq() / 100.0);
1147 MapData* d = createDataForKey(vor);
1149 d->setLabel(vor->ident());
1150 d->setPriority(tuned ? 10000 : 100);
1151 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1155 void MapWidget::drawFix(FGFix* fix)
1157 SGVec2d pos = project(fix->geod());
1158 glColor3f(0.0, 0.0, 0.0);
1159 circleAt(pos, 3, 6);
1161 if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1162 return; // hide fix labels beyond a certain zoom level
1165 if (validDataForKey(fix)) {
1166 setAnchorForKey(fix, pos);
1170 MapData* d = createDataForKey(fix);
1171 d->setLabel(fix->ident());
1173 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1177 void MapWidget::drawNavRadio(SGPropertyNode_ptr radio)
1179 if (!radio || radio->getBoolValue("slaved-to-gps", false)
1180 || !radio->getBoolValue("in-range", false)) {
1184 if (radio->getBoolValue("nav-loc", false)) {
1185 drawTunedLocalizer(radio);
1188 // identify the tuned station - unfortunately we don't get lat/lon directly,
1189 // need to do the frequency search again
1190 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1192 FGNavRecord* nav = FGNavList::findByFreq(mhz, _aircraft,
1193 FGNavList::navFilter());
1194 if (!nav || (nav->ident() != radio->getStringValue("nav-id"))) {
1195 // mismatch between navradio selection logic and ours!
1202 SGVec2d pos = project(nav->geod());
1205 double trueRadial = radio->getDoubleValue("radials/target-radial-deg");
1206 SGGeodesy::direct(nav->geod(), trueRadial, nav->get_range() * SG_NM_TO_METER, range, az2);
1207 SGVec2d prange = project(range);
1209 SGVec2d norm = normalize(prange - pos);
1210 SGVec2d perp(norm.y(), -norm.x());
1212 circleAt(pos, 64, length(prange - pos));
1213 drawLine(pos, prange);
1215 // draw to/from arrows
1216 SGVec2d midPoint = (pos + prange) * 0.5;
1217 if (radio->getBoolValue("from-flag")) {
1223 SGVec2d arrowB = midPoint - (norm * sz) + (perp * sz);
1224 SGVec2d arrowC = midPoint - (norm * sz) - (perp * sz);
1225 drawLine(midPoint, arrowB);
1226 drawLine(arrowB, arrowC);
1227 drawLine(arrowC, midPoint);
1229 drawLine(pos, (2 * pos) - prange); // reciprocal radial
1232 void MapWidget::drawTunedLocalizer(SGPropertyNode_ptr radio)
1234 double mhz = radio->getDoubleValue("frequencies/selected-mhz", 0.0);
1235 FGNavRecord* loc = FGNavList::findByFreq(mhz, _aircraft, FGNavList::locFilter());
1236 if (!loc || (loc->ident() != radio->getStringValue("nav-id"))) {
1237 // mismatch between navradio selection logic and ours!
1241 if (loc->runway()) {
1242 drawILS(true, loc->runway());
1246 void MapWidget::drawPOI(FGPositioned* poi)
1248 SGVec2d pos = project(poi->geod());
1249 glColor3f(1.0, 1.0, 0.0);
1253 if (poi->type() == FGPositioned::CITY) {
1255 glColor3f(0.0, 1.0, 0.0);
1256 } else if (poi->type() == FGPositioned::TOWN) {
1258 glColor3f(0.2, 1.0, 0.0);
1261 circleAt(pos, 4, radius);
1263 if (validDataForKey(poi)) {
1264 setAnchorForKey(poi, pos);
1269 ::snprintf(buffer, 1024, "%s",
1270 poi->name().c_str());
1272 MapData* d = createDataForKey(poi);
1273 d->setPriority(200);
1274 d->setLabel(poi->ident());
1276 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1281 void MapWidget::drawObstacle(FGPositioned* obs)
1283 SGVec2d pos = project(obs->geod());
1284 glColor3f(0.0, 0.0, 0.0);
1286 drawLine(pos, pos + SGVec2d());
1290 void MapWidget::drawAirport(FGAirport* apt)
1292 // draw tower location
1293 SGVec2d towerPos = project(apt->getTowerLocation());
1295 if (_cachedZoom <= SHOW_DETAIL_ZOOM) {
1296 glColor3f(1.0, 1.0, 1.0);
1299 drawLine(towerPos + SGVec2d(3, 0), towerPos + SGVec2d(3, 10));
1300 drawLine(towerPos + SGVec2d(-3, 0), towerPos + SGVec2d(-3, 10));
1301 drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(-3, 10));
1302 drawLine(towerPos + SGVec2d(6, 20), towerPos + SGVec2d(3, 10));
1303 drawLine(towerPos + SGVec2d(-6, 20), towerPos + SGVec2d(6, 20));
1306 if (validDataForKey(apt)) {
1307 setAnchorForKey(apt, towerPos);
1310 ::snprintf(buffer, 1024, "%s\n%s",
1311 apt->ident().c_str(), apt->name().c_str());
1313 MapData* d = createDataForKey(apt);
1315 d->setLabel(apt->ident());
1316 d->setPriority(100 + scoreAirportRunways(apt));
1317 d->setOffset(MapData::VALIGN_TOP | MapData::HALIGN_CENTER, 6);
1318 d->setAnchor(towerPos);
1321 if (_cachedZoom > SHOW_DETAIL_ZOOM) {
1325 FGRunwayList runways(apt->getRunwaysWithoutReciprocals());
1327 for (unsigned int r=0; r<runways.size(); ++r) {
1328 drawRunwayPre(runways[r]);
1331 for (unsigned int r=0; r<runways.size(); ++r) {
1332 FGRunway* rwy = runways[r];
1336 drawILS(false, rwy);
1339 if (rwy->reciprocalRunway()) {
1340 FGRunway* recip = rwy->reciprocalRunway();
1342 drawILS(false, recip);
1347 for (unsigned int r=0; r<apt->numHelipads(); ++r) {
1348 FGHelipad* hp = apt->getHelipadByIndex(r);
1350 } // of runway iteration
1354 int MapWidget::scoreAirportRunways(FGAirport* apt)
1356 bool needHardSurface = _root->getBoolValue("hard-surfaced-airports", true);
1357 double minLength = _root->getDoubleValue("min-runway-length-ft", 2000.0);
1359 FGRunwayList runways(apt->getRunwaysWithoutReciprocals());
1362 for (unsigned int r=0; r<runways.size(); ++r) {
1363 FGRunway* rwy = runways[r];
1364 if (needHardSurface && !rwy->isHardSurface()) {
1368 if (rwy->lengthFt() < minLength) {
1372 int scoreLength = SGMiscd::roundToInt(rwy->lengthFt() / 200.0);
1373 score += scoreLength;
1374 } // of runways iteration
1379 void MapWidget::drawRunwayPre(FGRunway* rwy)
1381 SGVec2d p1 = project(rwy->begin());
1382 SGVec2d p2 = project(rwy->end());
1385 glColor3f(1.0, 0.0, 1.0);
1389 void MapWidget::drawRunway(FGRunway* rwy)
1392 // optionally show active, stopway, etc
1393 // in legend, show published heading and length
1394 // and threshold elevation
1396 SGVec2d p1 = project(rwy->begin());
1397 SGVec2d p2 = project(rwy->end());
1399 glColor3f(1.0, 1.0, 1.0);
1400 SGVec2d inset = normalize(p2 - p1) * 2;
1402 drawLine(p1 + inset, p2 - inset);
1404 if (validDataForKey(rwy)) {
1405 setAnchorForKey(rwy, (p1 + p2) * 0.5);
1410 ::snprintf(buffer, 1024, "%s/%s\n%03d/%03d\n%.0f'",
1411 rwy->ident().c_str(),
1412 rwy->reciprocalRunway()->ident().c_str(),
1413 displayHeading(rwy->headingDeg()),
1414 displayHeading(rwy->reciprocalRunway()->headingDeg()),
1417 MapData* d = createDataForKey(rwy);
1419 d->setLabel(rwy->ident() + "/" + rwy->reciprocalRunway()->ident());
1421 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 12);
1422 d->setAnchor((p1 + p2) * 0.5);
1425 void MapWidget::drawILS(bool tuned, FGRunway* rwy)
1427 // arrow, tip centered on the landing threshold
1428 // using LOC transmitter position would be more accurate, but
1429 // is visually cluttered
1430 // arrow width is based upon the computed localizer width
1432 FGNavRecord* loc = rwy->ILS();
1433 double halfBeamWidth = loc->localizerWidth() * 0.5;
1434 SGVec2d t = project(rwy->threshold());
1436 double rangeM = loc->get_range() * SG_NM_TO_METER;
1437 double radial = loc->get_multiuse();
1438 SG_NORMALIZE_RANGE(radial, 0.0, 360.0);
1441 // compute the three end points at the widge end of the arrow
1442 SGGeodesy::direct(loc->geod(), radial, -rangeM, locEnd, az2);
1443 SGVec2d endCentre = project(locEnd);
1445 SGGeodesy::direct(loc->geod(), radial + halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1446 SGVec2d endR = project(locEnd);
1448 SGGeodesy::direct(loc->geod(), radial - halfBeamWidth, -rangeM * 1.1, locEnd, az2);
1449 SGVec2d endL = project(locEnd);
1451 // outline two triangles
1454 glColor3f(0.0, 1.0, 1.0);
1456 glColor3f(0.0, 0.0, 1.0);
1459 glBegin(GL_LINE_LOOP);
1460 glVertex2dv(t.data());
1461 glVertex2dv(endCentre.data());
1462 glVertex2dv(endL.data());
1464 glBegin(GL_LINE_LOOP);
1465 glVertex2dv(t.data());
1466 glVertex2dv(endCentre.data());
1467 glVertex2dv(endR.data());
1470 if (validDataForKey(loc)) {
1471 setAnchorForKey(loc, endR);
1476 ::snprintf(buffer, 1024, "%s\n%s\n%03d - %3.2fMHz",
1477 loc->ident().c_str(), loc->name().c_str(),
1478 displayHeading(radial),
1479 loc->get_freq()/100.0);
1481 MapData* d = createDataForKey(loc);
1483 d->setLabel(loc->ident());
1485 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 10);
1489 void MapWidget::drawTraffic()
1491 AIDrawVec::const_iterator it;
1492 for (it = _aiDrawVec.begin(); it != _aiDrawVec.end(); ++it) {
1497 void MapWidget::drawHelipad(FGHelipad* hp)
1499 SGVec2d pos = project(hp->geod());
1501 glColor3f(1.0, 0.0, 1.0);
1502 circleAt(pos, 16, 5.0);
1504 if (validDataForKey(hp)) {
1505 setAnchorForKey(hp, pos);
1510 ::snprintf(buffer, 1024, "%s\n%03d\n%.0f'",
1511 hp->ident().c_str(),
1512 displayHeading(hp->headingDeg()),
1515 MapData* d = createDataForKey(hp);
1517 d->setLabel(hp->ident());
1519 d->setOffset(MapData::HALIGN_CENTER | MapData::VALIGN_BOTTOM, 8);
1523 void MapWidget::drawAI(const DrawAIObject& dai)
1525 SGVec2d p = project(dai.pos);
1528 glColor3f(0.0, 0.0, 0.5);
1531 glColor3f(0.0, 0.0, 0.0);
1534 circleAt(p, 4, 6.0); // black diamond
1536 // draw heading vector
1537 if (dai.speedKts > 1) {
1539 const double dt = 15.0 / (3600.0); // 15 seconds look-ahead
1540 double distanceM = dai.speedKts * SG_NM_TO_METER * dt;
1541 SGGeod advance = SGGeodesy::direct(dai.pos, dai.heading, distanceM);
1542 drawLine(p, project(advance));
1545 MapData* d = getOrCreateDataForKey((void*) dai.model);
1546 d->setText(dai.legend);
1547 d->setLabel(dai.label);
1548 d->setPriority(dai.speedKts > 5 ? 60 : 10); // low priority for parked aircraft
1549 d->setOffset(MapData::VALIGN_CENTER | MapData::HALIGN_LEFT, 10);
1553 SGVec2d MapWidget::project(const SGGeod& geod) const
1556 double r = earth_radius_lat(geod.getLatitudeRad());
1558 switch (_projection) {
1559 case PROJECTION_SAMSON_FLAMSTEED:
1561 // Sanson-Flamsteed projection, relative to the projection center
1562 double lonDiff = geod.getLongitudeRad() - _projectionCenter.getLongitudeRad(),
1563 latDiff = geod.getLatitudeRad() - _projectionCenter.getLatitudeRad();
1565 p = SGVec2d(cos(geod.getLatitudeRad()) * lonDiff, latDiff) * r * currentScale();
1569 case PROJECTION_ORTHO_AZIMUTH:
1571 // http://mathworld.wolfram.com/OrthographicProjection.html
1572 double cosTheta = cos(geod.getLatitudeRad());
1573 double sinDLambda = sin(geod.getLongitudeRad() - _projectionCenter.getLongitudeRad());
1574 double cosDLambda = cos(geod.getLongitudeRad() - _projectionCenter.getLongitudeRad());
1575 double sinTheta1 = sin(_projectionCenter.getLatitudeRad());
1576 double sinTheta = sin(geod.getLatitudeRad());
1577 double cosTheta1 = cos(_projectionCenter.getLatitudeRad());
1579 p = SGVec2d(cosTheta * sinDLambda,
1580 (cosTheta1 * sinTheta) - (sinTheta1 * cosTheta * cosDLambda)) * r * currentScale();
1584 case PROJECTION_SPHERICAL:
1586 SGVec3d cartCenter = SGVec3d::fromGeod(_projectionCenter);
1587 SGVec3d cartPt = SGVec3d::fromGeod(geod) - cartCenter;
1589 // rotate relative to projection center
1590 SGQuatd orient = SGQuatd::fromLonLat(_projectionCenter);
1591 cartPt = orient.rotateBack(cartPt);
1592 return SGVec2d(cartPt.y(), cartPt.x()) * currentScale();
1595 } // of projection mode switch
1598 // rotate as necessary
1599 double cost = cos(_upHeading * SG_DEGREES_TO_RADIANS),
1600 sint = sin(_upHeading * SG_DEGREES_TO_RADIANS);
1601 double rx = cost * p.x() - sint * p.y();
1602 double ry = sint * p.x() + cost * p.y();
1603 return SGVec2d(rx, ry);
1606 SGGeod MapWidget::unproject(const SGVec2d& p) const
1608 // unrotate, if necessary
1609 double cost = cos(-_upHeading * SG_DEGREES_TO_RADIANS),
1610 sint = sin(-_upHeading * SG_DEGREES_TO_RADIANS);
1611 SGVec2d ur(cost * p.x() - sint * p.y(),
1612 sint * p.x() + cost * p.y());
1616 switch (_projection) {
1617 case PROJECTION_SAMSON_FLAMSTEED:
1619 double r = earth_radius_lat(_projectionCenter.getLatitudeRad());
1620 SGVec2d unscaled = ur * (1.0 / (currentScale() * r));
1621 double lat = unscaled.y() + _projectionCenter.getLatitudeRad();
1622 double lon = (unscaled.x() / cos(lat)) + _projectionCenter.getLongitudeRad();
1623 return SGGeod::fromRad(lon, lat);
1626 case PROJECTION_ORTHO_AZIMUTH:
1628 double r = earth_radius_lat(_projectionCenter.getLatitudeRad());
1629 SGVec2d unscaled = ur * (1.0 / (currentScale() * r));
1631 double phi = length(p);
1632 double c = asin(phi);
1633 double sinTheta1 = sin(_projectionCenter.getLatitudeRad());
1634 double cosTheta1 = cos(_projectionCenter.getLatitudeRad());
1636 double lat = asin(cos(c) * sinTheta1 + ((unscaled.y() * sin(c) * cosTheta1) / phi));
1637 double lon = _projectionCenter.getLongitudeRad() +
1638 atan((unscaled.x()* sin(c)) / (phi * cosTheta1 * cos(c) - unscaled.y() * sinTheta1 * sin(c)));
1639 return SGGeod::fromRad(lon, lat);
1642 case PROJECTION_SPHERICAL:
1644 SGVec2d unscaled = ur * (1.0 / currentScale());
1645 SGQuatd orient = SGQuatd::fromLonLat(_projectionCenter);
1646 SGVec3d cartCenter = SGVec3d::fromGeod(_projectionCenter);
1647 SGVec3d cartPt = orient.rotate(SGVec3d(unscaled.x(), unscaled.y(), 0.0));
1648 return SGGeod::fromCart(cartPt + cartCenter);
1650 } // of projection mode switch
1653 double MapWidget::currentScale() const
1655 return 1.0 / pow(2.0, _cachedZoom);
1658 void MapWidget::circleAt(const SGVec2d& center, int nSides, double r)
1660 glBegin(GL_LINE_LOOP);
1661 double advance = (SGD_PI * 2) / nSides;
1662 glVertex2d(center.x() +r, center.y());
1664 for (int i=1; i<nSides; ++i) {
1665 glVertex2d(center.x() + (cos(t) * r), center.y() + (sin(t) * r));
1671 void MapWidget::squareAt(const SGVec2d& center, double r)
1673 glBegin(GL_LINE_LOOP);
1674 glVertex2d(center.x() + r, center.y() + r);
1675 glVertex2d(center.x() + r, center.y() - r);
1676 glVertex2d(center.x() - r, center.y() - r);
1677 glVertex2d(center.x() - r, center.y() + r);
1681 void MapWidget::circleAtAlt(const SGVec2d& center, int nSides, double r, double r2)
1683 glBegin(GL_LINE_LOOP);
1684 double advance = (SGD_PI * 2) / nSides;
1685 glVertex2d(center.x(), center.y() + r);
1687 for (int i=1; i<nSides; ++i) {
1688 double rr = (i%2 == 0) ? r : r2;
1689 glVertex2d(center.x() + (sin(t) * rr), center.y() + (cos(t) * rr));
1695 void MapWidget::drawLine(const SGVec2d& p1, const SGVec2d& p2)
1698 glVertex2dv(p1.data());
1699 glVertex2dv(p2.data());
1703 void MapWidget::drawLegendBox(const SGVec2d& pos, const std::string& t)
1705 std::vector<std::string> lines(simgear::strutils::split(t, "\n"));
1706 const int LINE_LEADING = 4;
1707 const int MARGIN = 4;
1710 int maxWidth = -1, totalHeight = 0;
1711 int lineHeight = legendFont.getStringHeight();
1713 for (unsigned int ln=0; ln<lines.size(); ++ln) {
1714 totalHeight += lineHeight;
1716 totalHeight += LINE_LEADING;
1719 int lw = legendFont.getStringWidth(lines[ln].c_str());
1720 maxWidth = std::max(maxWidth, lw);
1721 } // of line measurement
1724 return; // all lines are empty, don't draw
1727 totalHeight += MARGIN * 2;
1732 box.min[1] = -totalHeight;
1733 box.max[0] = maxWidth + (MARGIN * 2);
1736 box.draw (pos.x(), pos.y(), PUSTYLE_DROPSHADOW, colour, FALSE, border);
1739 int xPos = pos.x() + MARGIN;
1740 int yPos = pos.y() - (lineHeight + MARGIN);
1741 glColor3f(0.8, 0.8, 0.8);
1743 for (unsigned int ln=0; ln<lines.size(); ++ln) {
1744 legendFont.drawString(lines[ln].c_str(), xPos, yPos);
1745 yPos -= lineHeight + LINE_LEADING;
1749 void MapWidget::drawData()
1751 std::sort(_dataQueue.begin(), _dataQueue.end(), MapData::order);
1753 int hw = _width >> 1,
1755 puBox visBox(makePuBox(-hw, -hh, _width, _height));
1759 std::vector<MapData*> drawQueue;
1761 bool drawData = _root->getBoolValue("draw-data");
1762 const int MAX_DRAW_DATA = 25;
1763 const int MAX_DRAW = 50;
1765 for (; (d < _dataQueue.size()) && (drawn < MAX_DRAW); ++d) {
1766 MapData* md = _dataQueue[d];
1767 md->setDataVisible(drawData);
1769 if (md->isClipped(visBox)) {
1773 if (md->overlaps(drawQueue)) {
1774 if (drawData) { // overlapped with data, let's try just the label
1775 md->setDataVisible(false);
1776 if (md->overlaps(drawQueue)) {
1782 } // of overlaps case
1784 drawQueue.push_back(md);
1786 if (drawData && (drawn >= MAX_DRAW_DATA)) {
1791 // draw lowest-priority first, so higher-priorty items appear on top
1792 std::vector<MapData*>::reverse_iterator r;
1793 for (r = drawQueue.rbegin(); r!= drawQueue.rend(); ++r) {
1798 KeyDataMap::iterator it = _mapData.begin();
1799 for (; it != _mapData.end(); ) {
1801 if (it->second->isExpired()) {
1803 KeyDataMap::iterator cur = it++;
1804 _mapData.erase(cur);
1808 } // of expiry iteration
1811 bool MapWidget::validDataForKey(void* key)
1813 KeyDataMap::iterator it = _mapData.find(key);
1814 if (it == _mapData.end()) {
1815 return false; // no valid data for the key!
1818 it->second->resetAge(); // mark data as valid this frame
1819 _dataQueue.push_back(it->second);
1823 void MapWidget::setAnchorForKey(void* key, const SGVec2d& anchor)
1825 KeyDataMap::iterator it = _mapData.find(key);
1826 if (it == _mapData.end()) {
1827 throw sg_exception("no valid data for key!");
1830 it->second->setAnchor(anchor);
1833 MapData* MapWidget::getOrCreateDataForKey(void* key)
1835 KeyDataMap::iterator it = _mapData.find(key);
1836 if (it == _mapData.end()) {
1837 return createDataForKey(key);
1840 it->second->resetAge(); // mark data as valid this frame
1841 _dataQueue.push_back(it->second);
1845 MapData* MapWidget::createDataForKey(void* key)
1847 KeyDataMap::iterator it = _mapData.find(key);
1848 if (it != _mapData.end()) {
1849 throw sg_exception("duplicate data requested for key!");
1852 MapData* d = new MapData(0);
1854 _dataQueue.push_back(d);
1859 void MapWidget::clearData()
1861 KeyDataMap::iterator it = _mapData.begin();
1862 for (; it != _mapData.end(); ++it) {
1869 int MapWidget::displayHeading(double h) const
1871 if (_magneticHeadings) {
1872 h -= _magVar->get_magvar() * SG_RADIANS_TO_DEGREES;
1875 SG_NORMALIZE_RANGE(h, 0.0, 360.0);
1876 return SGMiscd::roundToInt(h);
1879 MapWidget::DrawAIObject::DrawAIObject(SGPropertyNode* m, const SGGeod& g) :
1885 std::string name(model->getNameString());
1886 heading = model->getDoubleValue("orientation/true-heading-deg");
1888 if ((name == "aircraft") || (name == "multiplayer") ||
1889 (name == "wingman") || (name == "tanker"))
1891 speedKts = static_cast<int>(model->getDoubleValue("velocities/true-airspeed-kt"));
1892 label = model->getStringValue("callsign", "<>");
1894 // try to access the flight-plan of the aircraft. There are several layers
1895 // of potential NULL-ness here, so we have to be defensive at each stage.
1896 std::string originICAO, destinationICAO;
1897 FGAIManager* aiManager = static_cast<FGAIManager*>(globals->get_subsystem("ai-model"));
1898 FGAIBasePtr aircraft = aiManager ? aiManager->getObjectFromProperty(model) : NULL;
1900 FGAIAircraft* p = static_cast<FGAIAircraft*>(aircraft.get());
1901 if (p->GetFlightPlan()) {
1902 if (p->GetFlightPlan()->departureAirport()) {
1903 originICAO = p->GetFlightPlan()->departureAirport()->ident();
1906 if (p->GetFlightPlan()->arrivalAirport()) {
1907 destinationICAO = p->GetFlightPlan()->arrivalAirport()->ident();
1909 } // of flight-plan exists
1910 } // of check for AIBase-derived instance
1912 // draw callsign / altitude / speed
1913 int altFt50 = static_cast<int>(pos.getElevationFt() / 50.0) * 50;
1914 std::ostringstream ss;
1915 ss << model->getStringValue("callsign", "<>");
1917 ss << "\n" << altFt50 << "' " << speedKts << "kts";
1920 if (!originICAO.empty() || ! destinationICAO.empty()) {
1921 ss << "\n" << originICAO << " -> " << destinationICAO;
1925 } else if ((name == "ship") || (name == "carrier") || (name == "escort")) {
1927 speedKts = static_cast<int>(model->getDoubleValue("velocities/speed-kts"));
1928 label = model->getStringValue("name", "<>");
1931 ::snprintf(buffer, 1024, "%s\n%dkts",
1932 model->getStringValue("name", "<>"),