1 // BaseDiagram.cxx - part of GUI launcher using Qt5
3 // Written by James Turner, started December 2014.
5 // Copyright (C) 2014 James Turner <zakalawe@mac.com>
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.
21 #include "BaseDiagram.hxx"
28 #include <QMouseEvent>
30 #include <Navaids/navrecord.hxx>
31 #include <Navaids/positioned.hxx>
32 #include <Airports/airport.hxx>
34 /* equatorial and polar earth radius */
35 const float rec = 6378137; // earth radius, equator (?)
36 const float rpol = 6356752.314f; // earth radius, polar (?)
38 //Returns Earth radius at a given latitude (Ellipsoide equation with two equal axis)
39 static float earth_radius_lat( float lat )
41 double a = cos(lat)/rec;
42 double b = sin(lat)/rpol;
43 return 1.0f / sqrt( a * a + b * b );
46 BaseDiagram::BaseDiagram(QWidget* pr) :
49 m_wheelAngleDeltaAccumulator(0)
51 setSizePolicy(QSizePolicy::MinimumExpanding,
52 QSizePolicy::MinimumExpanding);
53 setMinimumSize(100, 100);
56 QTransform BaseDiagram::transform() const
59 t.translate(width() / 2, height() / 2); // center projection origin in the widget
60 t.scale(m_scale, m_scale);
62 // apply any pan offset that exists
63 t.translate(m_panOffset.x(), m_panOffset.y());
64 // center the bounding box (may not be at the origin)
65 t.translate(-m_bounds.center().x(), -m_bounds.center().y());
69 void BaseDiagram::clearIgnoredNavaids()
74 void BaseDiagram::addIgnoredNavaid(FGPositionedRef pos)
76 if (isNavaidIgnored(pos))
78 m_ignored.push_back(pos);
81 void BaseDiagram::extendRect(QRectF &r, const QPointF &p)
83 if (p.x() < r.left()) {
85 } else if (p.x() > r.right()) {
89 if (p.y() < r.top()) {
91 } else if (p.y() > r.bottom()) {
96 void BaseDiagram::paintEvent(QPaintEvent* pe)
99 p.setRenderHints(QPainter::Antialiasing);
100 p.fillRect(rect(), QColor(0x3f, 0x3f, 0x3f));
102 if (m_autoScalePan) {
103 // fit bounds within our available space, allowing for a margin
104 const int MARGIN = 32; // pixels
105 double ratioInX = (width() - MARGIN * 2) / m_bounds.width();
106 double ratioInY = (height() - MARGIN * 2) / m_bounds.height();
107 m_scale = std::min(ratioInX, ratioInY);
110 QTransform t(transform());
118 void BaseDiagram::paintAirplaneIcon(QPainter* painter, const SGGeod& geod, int headingDeg)
120 QPointF pos = project(geod);
121 QPixmap pix(":/airplane-icon");
122 pos = painter->transform().map(pos);
123 painter->resetTransform();
124 painter->translate(pos.x(), pos.y());
125 painter->rotate(headingDeg);
127 painter->setRenderHint(QPainter::SmoothPixmapTransform, true);
128 QRect airplaneIconRect = pix.rect();
129 airplaneIconRect.moveCenter(QPoint(0,0));
130 painter->drawPixmap(airplaneIconRect, pix);
133 class MapFilter : public FGPositioned::TypeFilter
138 // addType(FGPositioned::FIX);
139 addType(FGPositioned::AIRPORT);
140 addType(FGPositioned::NDB);
141 addType(FGPositioned::VOR);
144 virtual bool pass(FGPositioned* aPos) const
146 bool ok = TypeFilter::pass(aPos);
147 if (ok && (aPos->type() == FGPositioned::FIX)) {
148 // ignore fixes which end in digits
149 if (aPos->ident().length() > 4 && isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
159 void BaseDiagram::paintNavaids(QPainter* painter)
161 QTransform xf = painter->transform();
162 painter->setTransform(QTransform()); // reset to identity
163 QTransform invT = xf.inverted();
164 SGGeod topLeft = unproject(invT.map(QPointF(0,0)), m_projectionCenter);
166 double minRunwayLengthFt = (16 / m_scale) * SG_METER_TO_FEET;
167 // add 10nm fudge factor
168 double drawRangeNm = SGGeodesy::distanceNm(m_projectionCenter, topLeft) + 10.0;
169 //qDebug() << "draw range computed as:" << drawRangeNm;
173 FGPositionedList items = FGPositioned::findWithinRange(m_projectionCenter, drawRangeNm, &f);
175 m_labelRects.clear();
176 m_labelRects.reserve(items.size());
178 FGPositionedList::const_iterator it;
179 for (it = items.begin(); it != items.end(); ++it) {
180 FGPositionedRef pos(*it);
181 bool drawAsIcon = true;
182 if (isNavaidIgnored(pos))
185 FGPositioned::Type ty(pos->type());
186 if (ty == FGPositioned::AIRPORT) {
187 FGAirport* apt = static_cast<FGAirport*>(pos.ptr());
188 if (apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
191 painter->setTransform(xf);
192 QVector<QLineF> lines = projectAirportRuwaysWithCenter(apt, m_projectionCenter);
194 QPen pen(QColor(0x03, 0x83, 0xbf), 8);
195 pen.setCosmetic(true);
196 painter->setPen(pen);
197 painter->drawLines(lines);
199 QPen linePen(Qt::white, 2);
200 linePen.setCosmetic(true);
201 painter->setPen(linePen);
202 painter->drawLines(lines);
204 painter->resetTransform();
209 QPixmap pm = iconForPositioned(pos);
210 QPointF loc = xf.map(project(pos->geod()));
211 QRect iconRect = pm.rect();
212 iconRect.moveCenter(loc.toPoint());
213 painter->drawPixmap(iconRect, pm);
215 // compute label text so we can measure it
217 if (FGAirport::isAirportType(pos.ptr())) {
218 label = QString::fromStdString((*it)->name());
220 label = QString::fromStdString((*it)->ident());
223 if (ty == FGPositioned::NDB) {
224 FGNavRecord* nav = static_cast<FGNavRecord*>(pos.ptr());
225 label.append("\n").append(QString::number(nav->get_freq() / 100));
226 } else if (ty == FGPositioned::VOR) {
227 FGNavRecord* nav = static_cast<FGNavRecord*>(pos.ptr());
228 label.append("\n").append(QString::number(nav->get_freq() / 100.0, 'f', 1));
231 QRect textBounds = painter->boundingRect(QRect(0, 0, 100, 100),
232 Qt::TextWordWrap, label);
234 textBounds = rectAndFlagsForLabel(pos->guid(), iconRect,
238 painter->setPen(QColor(0x03, 0x83, 0xbf));
239 painter->drawText(textBounds, textFlags, label);
244 painter->setTransform(xf);
247 bool BaseDiagram::isNavaidIgnored(const FGPositionedRef &pos) const
249 return m_ignored.contains(pos);
252 bool BaseDiagram::isLabelRectAvailable(const QRect &r) const
254 Q_FOREACH(const QRect& lr, m_labelRects) {
255 if (lr.intersects(r))
262 int BaseDiagram::textFlagsForLabelPosition(LabelPosition pos)
266 case LABEL_RIGHT: return Qt::AlignLeft | Qt::AlignVCenter;
267 case LABEL_ABOVE: return Qt::AlignHCenter | Qt::A
273 QRect BaseDiagram::rectAndFlagsForLabel(PositionedID guid, const QRect& item,
277 m_labelRects.append(item);
278 int pos = m_labelPositions.value(guid, LABEL_RIGHT);
279 bool firstAttempt = true;
280 flags = Qt::TextWordWrap;
282 while (pos < LAST_POSITION) {
283 QRect r = labelPositioned(item, bounds, static_cast<LabelPosition>(pos));
284 if (isLabelRectAvailable(r)) {
285 m_labelRects.append(r);
286 m_labelPositions[guid] = static_cast<LabelPosition>(pos);
287 flags |= textFlagsForLabelPosition(static_cast<LabelPosition>(pos));
289 } else if (firstAttempt && (pos != LABEL_RIGHT)) {
295 firstAttempt = false;
298 return QRect(item.x(), item.y(), bounds.width(), bounds.height());
301 QRect BaseDiagram::labelPositioned(const QRect& itemRect,
303 LabelPosition lp) const
305 const int SHORT_MARGIN = 4;
306 const int DIAGONAL_MARGIN = 20;
309 // cardinal compass points are short (close in)
311 return QRect(itemRect.right() + SHORT_MARGIN,
312 itemRect.center().y() - bounds.height() / 2,
316 return QRect(itemRect.center().x() - (bounds.width() / 2),
317 itemRect.top() - (SHORT_MARGIN + bounds.height()),
321 return QRect(itemRect.center().x() - (bounds.width() / 2),
322 itemRect.bottom() + SHORT_MARGIN,
326 return QRect(itemRect.left() - (SHORT_MARGIN + bounds.width()),
327 itemRect.center().y() - bounds.height() / 2,
331 // first diagonals are further out (to hopefully have a better chance
332 // of finding clear space
335 return QRect(itemRect.right() + DIAGONAL_MARGIN,
336 itemRect.top() - (DIAGONAL_MARGIN + bounds.height()),
341 qWarning() << Q_FUNC_INFO << "Implement me";
345 return QRect(itemRect.x(), itemRect.y(), bounds.width(), bounds.height());
348 void BaseDiagram::mousePressEvent(QMouseEvent *me)
350 m_lastMousePos = me->pos();
354 void BaseDiagram::mouseMoveEvent(QMouseEvent *me)
356 m_autoScalePan = false;
358 QPointF delta = me->pos() - m_lastMousePos;
359 m_lastMousePos = me->pos();
361 // offset is stored in metres so we don't have to modify it when
363 m_panOffset += (delta / m_scale);
371 return (v == 0) ? 0 : (v < 0) ? -1 : 1;
374 void BaseDiagram::wheelEvent(QWheelEvent *we)
376 m_autoScalePan = false;
378 int delta = we->angleDelta().y();
382 if (intSign(m_wheelAngleDeltaAccumulator) != intSign(delta)) {
383 m_wheelAngleDeltaAccumulator = 0;
386 m_wheelAngleDeltaAccumulator += delta;
387 if (m_wheelAngleDeltaAccumulator > 120) {
388 m_wheelAngleDeltaAccumulator = 0;
390 } else if (m_wheelAngleDeltaAccumulator < -120) {
391 m_wheelAngleDeltaAccumulator = 0;
398 void BaseDiagram::paintContents(QPainter* painter)
402 void BaseDiagram::recomputeBounds(bool resetZoom)
408 m_autoScalePan = true;
410 m_panOffset = QPointF();
416 void BaseDiagram::doComputeBounds()
418 // no-op in the base class
421 void BaseDiagram::extendBounds(const QPointF& p)
423 extendRect(m_bounds, p);
426 QPointF BaseDiagram::project(const SGGeod& geod, const SGGeod& center)
428 double r = earth_radius_lat(geod.getLatitudeRad());
429 double ref_lat = center.getLatitudeRad(),
430 ref_lon = center.getLongitudeRad(),
431 lat = geod.getLatitudeRad(),
432 lon = geod.getLongitudeRad(),
433 lonDiff = lon - ref_lon;
435 double c = acos( sin(ref_lat) * sin(lat) + cos(ref_lat) * cos(lat) * cos(lonDiff) );
437 // angular distance from center is 0
438 return QPointF(0.0, 0.0);
441 double k = c / sin(c);
443 if (ref_lat == (90 * SG_DEGREES_TO_RADIANS))
445 x = (SGD_PI / 2 - lat) * sin(lonDiff);
446 y = -(SGD_PI / 2 - lat) * cos(lonDiff);
448 else if (ref_lat == -(90 * SG_DEGREES_TO_RADIANS))
450 x = (SGD_PI / 2 + lat) * sin(lonDiff);
451 y = (SGD_PI / 2 + lat) * cos(lonDiff);
455 x = k * cos(lat) * sin(lonDiff);
456 y = k * ( cos(ref_lat) * sin(lat) - sin(ref_lat) * cos(lat) * cos(lonDiff) );
459 return QPointF(x, -y) * r;
462 SGGeod BaseDiagram::unproject(const QPointF& xy, const SGGeod& center)
464 double r = earth_radius_lat(center.getLatitudeRad());
467 ref_lat = center.getLatitudeRad(),
468 ref_lon = center.getLongitudeRad(),
469 rho = QVector2D(xy).length(),
476 double x = xy.x(), y = xy.y();
477 lat = asin( cos(c) * sin(ref_lat) + (y * sin(c) * cos(ref_lat)) / rho);
479 if (ref_lat == (90 * SG_DEGREES_TO_RADIANS)) // north pole
481 lon = ref_lon + atan(-x/y);
483 else if (ref_lat == -(90 * SG_DEGREES_TO_RADIANS)) // south pole
485 lon = ref_lon + atan(x/y);
489 lon = ref_lon + atan(x* sin(c) / (rho * cos(ref_lat) * cos(c) - y * sin(ref_lat) * sin(c)));
492 return SGGeod::fromRad(lon, lat);
495 QPointF BaseDiagram::project(const SGGeod& geod) const
497 return project(geod, m_projectionCenter);
500 QPixmap BaseDiagram::iconForPositioned(const FGPositionedRef& pos,
501 const IconOptions& options)
503 // if airport type, check towered or untowered
504 bool small = options.testFlag(SmallIcons);
506 bool isTowered = false;
507 if (FGAirport::isAirportType(pos)) {
508 FGAirport* apt = static_cast<FGAirport*>(pos.ptr());
509 isTowered = apt->hasTower();
512 switch (pos->type()) {
513 case FGPositioned::VOR:
514 if (static_cast<FGNavRecord*>(pos.ptr())->isVORTAC())
515 return QPixmap(":/vortac-icon");
517 if (static_cast<FGNavRecord*>(pos.ptr())->hasDME())
518 return QPixmap(":/vor-dme-icon");
520 return QPixmap(":/vor-icon");
522 case FGPositioned::AIRPORT:
523 return iconForAirport(static_cast<FGAirport*>(pos.ptr()), options);
525 case FGPositioned::HELIPORT:
526 return QPixmap(":/heliport-icon");
527 case FGPositioned::SEAPORT:
528 return QPixmap(isTowered ? ":/seaport-tower-icon" : ":/seaport-icon");
529 case FGPositioned::NDB:
530 return QPixmap(small ? ":/ndb-small-icon" : ":/ndb-icon");
531 case FGPositioned::FIX:
532 return QPixmap(":/waypoint-icon");
541 QPixmap BaseDiagram::iconForAirport(FGAirport* apt, const IconOptions& options)
543 if (!apt->hasHardRunwayOfLengthFt(1500)) {
544 return QPixmap(apt->hasTower() ? ":/airport-tower-icon" : ":/airport-icon");
547 if (options.testFlag(LargeAirportPlans) && apt->hasHardRunwayOfLengthFt(8500)) {
548 QPixmap result(32, 32);
549 result.fill(Qt::transparent);
552 p.setRenderHint(QPainter::Antialiasing, true);
553 QRectF b = result.rect().adjusted(4, 4, -4, -4);
554 QVector<QLineF> lines = projectAirportRuwaysIntoRect(apt, b);
556 p.setPen(QPen(QColor(0x03, 0x83, 0xbf), 8));
559 p.setPen(QPen(Qt::white, 2));
565 QPixmap result(25, 25);
566 result.fill(Qt::transparent);
570 p.setRenderHint(QPainter::Antialiasing, true);
573 p.setBrush(apt->hasTower() ? QColor(0x03, 0x83, 0xbf) :
574 QColor(0x9b, 0x5d, 0xa2));
575 p.drawEllipse(QPointF(13, 13), 10, 10);
577 FGRunwayRef r = apt->longestRunway();
579 p.setPen(QPen(Qt::white, 2));
581 p.rotate(r->headingDeg());
582 p.drawLine(0, -8, 0, 8);
588 QVector<QLineF> BaseDiagram::projectAirportRuwaysWithCenter(FGAirportRef apt, const SGGeod& c)
592 const FGRunwayList& runways(apt->getRunwaysWithoutReciprocals());
593 FGRunwayList::const_iterator it;
595 for (it = runways.begin(); it != runways.end(); ++it) {
596 FGRunwayRef rwy = *it;
597 QPointF p1 = project(rwy->geod(), c);
598 QPointF p2 = project(rwy->end(), c);
599 r.append(QLineF(p1, p2));
605 QVector<QLineF> BaseDiagram::projectAirportRuwaysIntoRect(FGAirportRef apt, const QRectF &bounds)
607 QVector<QLineF> r = projectAirportRuwaysWithCenter(apt, apt->geod());
610 Q_FOREACH(const QLineF& l, r) {
611 extendRect(extent, l.p1());
612 extendRect(extent, l.p2());
615 // find constraining scale factor
616 double ratioInX = bounds.width() / extent.width();
617 double ratioInY = bounds.height() / extent.height();
620 t.translate(bounds.left(), bounds.top());
621 t.scale(std::min(ratioInX, ratioInY),
622 std::min(ratioInX, ratioInY));
623 t.translate(-extent.left(), -extent.top()); // move unscaled to 0,0
625 for (int i=0; i<r.size(); ++i) {