]> git.mxchange.org Git - flightgear.git/blob - src/GUI/BaseDiagram.cxx
Closed airport support.
[flightgear.git] / src / GUI / BaseDiagram.cxx
1 // BaseDiagram.cxx - part of GUI launcher using Qt5
2 //
3 // Written by James Turner, started December 2014.
4 //
5 // Copyright (C) 2014 James Turner <zakalawe@mac.com>
6 //
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.
11 //
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.
16 //
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.
20
21 #include "BaseDiagram.hxx"
22
23 #include <limits>
24
25 #include <QPainter>
26 #include <QDebug>
27 #include <QVector2D>
28 #include <QMouseEvent>
29
30 #include <Navaids/navrecord.hxx>
31 #include <Navaids/positioned.hxx>
32 #include <Airports/airport.hxx>
33
34 /* equatorial and polar earth radius */
35 const float rec  = 6378137;          // earth radius, equator (?)
36 const float rpol = 6356752.314f;      // earth radius, polar   (?)
37
38 //Returns Earth radius at a given latitude (Ellipsoide equation with two equal axis)
39 static float earth_radius_lat( float lat )
40 {
41     double a = cos(lat)/rec;
42     double b = sin(lat)/rpol;
43     return 1.0f / sqrt( a * a + b * b );
44 }
45
46 BaseDiagram::BaseDiagram(QWidget* pr) :
47     QWidget(pr),
48     m_autoScalePan(true),
49     m_wheelAngleDeltaAccumulator(0)
50 {
51     setSizePolicy(QSizePolicy::MinimumExpanding,
52                   QSizePolicy::MinimumExpanding);
53     setMinimumSize(100, 100);
54 }
55
56 QTransform BaseDiagram::transform() const
57 {
58     QTransform t;
59     t.translate(width() / 2, height() / 2); // center projection origin in the widget
60     t.scale(m_scale, m_scale);
61
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());
66     return t;
67 }
68
69 void BaseDiagram::clearIgnoredNavaids()
70 {
71     m_ignored.clear();
72 }
73
74 void BaseDiagram::addIgnoredNavaid(FGPositionedRef pos)
75 {
76     if (isNavaidIgnored(pos))
77         return;
78     m_ignored.push_back(pos);
79 }
80
81 void BaseDiagram::extendRect(QRectF &r, const QPointF &p)
82 {
83     if (p.x() < r.left()) {
84         r.setLeft(p.x());
85     } else if (p.x() > r.right()) {
86         r.setRight(p.x());
87     }
88
89     if (p.y() < r.top()) {
90         r.setTop(p.y());
91     } else if (p.y() > r.bottom()) {
92         r.setBottom(p.y());
93     }
94 }
95
96 void BaseDiagram::paintEvent(QPaintEvent* pe)
97 {
98     QPainter p(this);
99     p.setRenderHints(QPainter::Antialiasing);
100     p.fillRect(rect(), QColor(0x3f, 0x3f, 0x3f));
101
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);
108     }
109
110     QTransform t(transform());
111     p.setTransform(t);
112
113     paintNavaids(&p);
114
115     paintContents(&p);
116 }
117
118 void BaseDiagram::paintAirplaneIcon(QPainter* painter, const SGGeod& geod, int headingDeg)
119 {
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);
126
127     painter->setRenderHint(QPainter::SmoothPixmapTransform, true);
128     QRect airplaneIconRect = pix.rect();
129     airplaneIconRect.moveCenter(QPoint(0,0));
130     painter->drawPixmap(airplaneIconRect, pix);
131 }
132
133 class MapFilter : public FGPositioned::TypeFilter
134 {
135 public:
136     MapFilter()
137     {
138       //  addType(FGPositioned::FIX);
139         addType(FGPositioned::AIRPORT);
140         addType(FGPositioned::HELIPORT);
141         addType(FGPositioned::SEAPORT);
142         addType(FGPositioned::NDB);
143         addType(FGPositioned::VOR);
144     }
145
146     virtual bool pass(FGPositioned* aPos) const
147     {
148         bool ok = TypeFilter::pass(aPos);
149         if (ok && (aPos->type() == FGPositioned::FIX)) {
150             // ignore fixes which end in digits
151             if (aPos->ident().length() > 4 && isdigit(aPos->ident()[3]) && isdigit(aPos->ident()[4])) {
152                 return false;
153             }
154         }
155
156         return ok;
157     }
158 };
159
160
161 void BaseDiagram::paintNavaids(QPainter* painter)
162 {
163     QTransform xf = painter->transform();
164     painter->setTransform(QTransform()); // reset to identity
165     QTransform invT = xf.inverted();
166     SGGeod topLeft = unproject(invT.map(QPointF(0,0)), m_projectionCenter);
167
168     double minRunwayLengthFt = (16 / m_scale) * SG_METER_TO_FEET;
169     // add 10nm fudge factor
170     double drawRangeNm = SGGeodesy::distanceNm(m_projectionCenter, topLeft) + 10.0;
171     //qDebug() << "draw range computed as:" << drawRangeNm;
172
173
174     MapFilter f;
175     FGPositionedList items = FGPositioned::findWithinRange(m_projectionCenter, drawRangeNm, &f);
176
177     m_labelRects.clear();
178     m_labelRects.reserve(items.size());
179
180     FGPositionedList::const_iterator it;
181     for (it = items.begin(); it != items.end(); ++it) {
182         FGPositionedRef pos(*it);
183         bool drawAsIcon = true;
184         if (isNavaidIgnored(pos))
185             continue;
186
187         FGPositioned::Type ty(pos->type());
188         if (ty == FGPositioned::AIRPORT) {
189             FGAirport* apt = static_cast<FGAirport*>(pos.ptr());
190             if (apt->hasHardRunwayOfLengthFt(minRunwayLengthFt)) {
191
192                 drawAsIcon = false;
193                 painter->setTransform(xf);
194                 QVector<QLineF> lines = projectAirportRuwaysWithCenter(apt, m_projectionCenter);
195
196                 QPen pen(QColor(0x03, 0x83, 0xbf), 8);
197                 pen.setCosmetic(true);
198                 painter->setPen(pen);
199                 painter->drawLines(lines);
200
201                 QPen linePen(Qt::white, 2);
202                 linePen.setCosmetic(true);
203                 painter->setPen(linePen);
204                 painter->drawLines(lines);
205
206                 painter->resetTransform();
207             }
208         }
209
210         if (drawAsIcon) {
211             QPixmap pm = iconForPositioned(pos);
212             QPointF loc = xf.map(project(pos->geod()));
213             QRect iconRect = pm.rect();
214             iconRect.moveCenter(loc.toPoint());
215             painter->drawPixmap(iconRect, pm);
216             bool isNDB = (ty == FGPositioned::NDB);
217
218        // compute label text so we can measure it
219             QString label;
220             if (FGAirport::isAirportType(pos.ptr())) {
221                 label = QString::fromStdString((*it)->name());
222             } else {
223                 label = QString::fromStdString((*it)->ident());
224             }
225
226             if (ty == FGPositioned::NDB) {
227                 FGNavRecord* nav = static_cast<FGNavRecord*>(pos.ptr());
228                 label.append("\n").append(QString::number(nav->get_freq() / 100));
229             } else if (ty == FGPositioned::VOR) {
230                 FGNavRecord* nav = static_cast<FGNavRecord*>(pos.ptr());
231                 label.append("\n").append(QString::number(nav->get_freq() / 100.0, 'f', 1));
232             }
233
234             QRect textBounds = painter->boundingRect(QRect(0, 0, 100, 100),
235                                                      Qt::TextWordWrap, label);
236             int textFlags;
237             textBounds = rectAndFlagsForLabel(pos->guid(), iconRect,
238                                               textBounds.size(),
239                                               textFlags);
240
241             painter->setPen(isNDB ? QColor(0x9b, 0x5d, 0xa2) : QColor(0x03, 0x83, 0xbf));
242             painter->drawText(textBounds, textFlags, label);
243         }
244     }
245
246     // restore transform
247     painter->setTransform(xf);
248 }
249
250 bool BaseDiagram::isNavaidIgnored(const FGPositionedRef &pos) const
251 {
252     return m_ignored.contains(pos);
253 }
254
255 bool BaseDiagram::isLabelRectAvailable(const QRect &r) const
256 {
257     Q_FOREACH(const QRect& lr, m_labelRects) {
258         if (lr.intersects(r))
259             return false;
260     }
261
262     return true;
263 }
264
265 int BaseDiagram::textFlagsForLabelPosition(LabelPosition pos)
266 {
267 #if 0
268     switch (pos) {
269     case LABEL_RIGHT:       return Qt::AlignLeft | Qt::AlignVCenter;
270     case LABEL_ABOVE:       return Qt::AlignHCenter | Qt::A
271     }
272 #endif
273     return 0;
274 }
275
276 QRect BaseDiagram::rectAndFlagsForLabel(PositionedID guid, const QRect& item,
277                                         const QSize &bounds,
278                                         int& flags) const
279 {
280     m_labelRects.append(item);
281     int pos = m_labelPositions.value(guid, LABEL_RIGHT);
282     bool firstAttempt = true;
283     flags = Qt::TextWordWrap;
284
285     while (pos < LAST_POSITION) {
286         QRect r = labelPositioned(item, bounds, static_cast<LabelPosition>(pos));
287         if (isLabelRectAvailable(r)) {
288             m_labelRects.append(r);
289             m_labelPositions[guid] = static_cast<LabelPosition>(pos);
290             flags |= textFlagsForLabelPosition(static_cast<LabelPosition>(pos));
291             return r;
292         } else if (firstAttempt && (pos != LABEL_RIGHT)) {
293             pos = LABEL_RIGHT;
294         } else {
295             ++pos;
296         }
297
298         firstAttempt = false;
299     }
300
301     return QRect(item.x(), item.y(), bounds.width(), bounds.height());
302 }
303
304 QRect BaseDiagram::labelPositioned(const QRect& itemRect,
305                                    const QSize& bounds,
306                                    LabelPosition lp) const
307 {
308     const int SHORT_MARGIN = 4;
309     const int DIAGONAL_MARGIN = 12;
310
311     QPoint topLeft = itemRect.topLeft();
312
313     switch (lp) {
314     // cardinal compass points are short (close in)
315     case LABEL_RIGHT:
316         topLeft = QPoint(itemRect.right() + SHORT_MARGIN,
317                      itemRect.center().y() - bounds.height() / 2);
318         break;
319     case LABEL_ABOVE:
320         topLeft = QPoint(itemRect.center().x() - (bounds.width() / 2),
321                      itemRect.top() - (SHORT_MARGIN + bounds.height()));
322         break;
323     case LABEL_BELOW:
324         topLeft = QPoint(itemRect.center().x() - (bounds.width() / 2),
325                      itemRect.bottom() + SHORT_MARGIN);
326         break;
327     case LABEL_LEFT:
328         topLeft = QPoint(itemRect.left() - (SHORT_MARGIN + bounds.width()),
329                      itemRect.center().y() - bounds.height() / 2);
330         break;
331
332     // first diagonals are further out (to hopefully have a better chance
333     // of finding clear space
334
335     case LABEL_NE:
336         topLeft = QPoint(itemRect.right() + DIAGONAL_MARGIN,
337                      itemRect.top() - (DIAGONAL_MARGIN + bounds.height()));
338         break;
339
340     case LABEL_NW:
341         topLeft = QPoint(itemRect.left() - (DIAGONAL_MARGIN + bounds.width()),
342                      itemRect.top() - (DIAGONAL_MARGIN + bounds.height()));
343         break;
344
345     case LABEL_SE:
346         topLeft = QPoint(itemRect.right() + DIAGONAL_MARGIN,
347                      itemRect.bottom() + DIAGONAL_MARGIN);
348         break;
349
350     case LABEL_SW:
351         topLeft = QPoint(itemRect.left() - (DIAGONAL_MARGIN + bounds.width()),
352                      itemRect.bottom() + DIAGONAL_MARGIN);
353         break;
354     default:
355         qWarning() << Q_FUNC_INFO << "Implement me";
356
357     }
358
359     return QRect(topLeft, bounds);
360 }
361
362 void BaseDiagram::mousePressEvent(QMouseEvent *me)
363 {
364     m_lastMousePos = me->pos();
365     m_didPan = false;
366 }
367
368 void BaseDiagram::mouseMoveEvent(QMouseEvent *me)
369 {
370     m_autoScalePan = false;
371
372     QPointF delta = me->pos() - m_lastMousePos;
373     m_lastMousePos = me->pos();
374
375     // offset is stored in metres so we don't have to modify it when
376     // zooming
377     m_panOffset += (delta / m_scale);
378     m_didPan = true;
379
380     update();
381 }
382
383 int intSign(int v)
384 {
385     return (v == 0) ? 0 : (v < 0) ? -1 : 1;
386 }
387
388 void BaseDiagram::wheelEvent(QWheelEvent *we)
389 {
390     m_autoScalePan = false;
391
392     int delta = we->angleDelta().y();
393     if (delta == 0)
394         return;
395
396     if (intSign(m_wheelAngleDeltaAccumulator) != intSign(delta)) {
397         m_wheelAngleDeltaAccumulator = 0;
398     }
399
400     m_wheelAngleDeltaAccumulator += delta;
401     if (m_wheelAngleDeltaAccumulator > 120) {
402         m_wheelAngleDeltaAccumulator = 0;
403         m_scale *= 2.0;
404     } else if (m_wheelAngleDeltaAccumulator < -120) {
405         m_wheelAngleDeltaAccumulator = 0;
406         m_scale *= 0.5;
407     }
408
409     update();
410 }
411
412 void BaseDiagram::paintContents(QPainter* painter)
413 {
414 }
415
416 void BaseDiagram::recomputeBounds(bool resetZoom)
417 {
418     m_bounds = QRectF();
419     doComputeBounds();
420
421     if (resetZoom) {
422         m_autoScalePan = true;
423         m_scale = 1.0;
424         m_panOffset = QPointF();
425     }
426
427     update();
428 }
429
430 void BaseDiagram::doComputeBounds()
431 {
432     // no-op in the base class
433 }
434
435 void BaseDiagram::extendBounds(const QPointF& p)
436 {
437     extendRect(m_bounds, p);
438 }
439
440 QPointF BaseDiagram::project(const SGGeod& geod, const SGGeod& center)
441 {
442     double r = earth_radius_lat(geod.getLatitudeRad());
443     double ref_lat = center.getLatitudeRad(),
444     ref_lon = center.getLongitudeRad(),
445     lat = geod.getLatitudeRad(),
446     lon = geod.getLongitudeRad(),
447     lonDiff = lon - ref_lon;
448
449     double c = acos( sin(ref_lat) * sin(lat) + cos(ref_lat) * cos(lat) * cos(lonDiff) );
450     if (c == 0.0) {
451         // angular distance from center is 0
452         return QPointF(0.0, 0.0);
453     }
454
455     double k = c / sin(c);
456     double x, y;
457     if (ref_lat == (90 * SG_DEGREES_TO_RADIANS))
458     {
459         x = (SGD_PI / 2 - lat) * sin(lonDiff);
460         y = -(SGD_PI / 2 - lat) * cos(lonDiff);
461     }
462     else if (ref_lat == -(90 * SG_DEGREES_TO_RADIANS))
463     {
464         x = (SGD_PI / 2 + lat) * sin(lonDiff);
465         y = (SGD_PI / 2 + lat) * cos(lonDiff);
466     }
467     else
468     {
469         x = k * cos(lat) * sin(lonDiff);
470         y = k * ( cos(ref_lat) * sin(lat) - sin(ref_lat) * cos(lat) * cos(lonDiff) );
471     }
472
473     return QPointF(x, -y) * r;
474 }
475
476 SGGeod BaseDiagram::unproject(const QPointF& xy, const SGGeod& center)
477 {
478     double r = earth_radius_lat(center.getLatitudeRad());
479     double lat = 0,
480            lon = 0,
481            ref_lat = center.getLatitudeRad(),
482            ref_lon = center.getLongitudeRad(),
483            rho = QVector2D(xy).length(),
484            c = rho/r;
485
486     if (rho == 0) {
487         return center;
488     }
489
490     double x = xy.x(), y = xy.y();
491     lat = asin( cos(c) * sin(ref_lat) + (y * sin(c) * cos(ref_lat)) / rho);
492
493     if (ref_lat == (90 * SG_DEGREES_TO_RADIANS)) // north pole
494     {
495         lon = ref_lon + atan(-x/y);
496     }
497     else if (ref_lat == -(90 * SG_DEGREES_TO_RADIANS)) // south pole
498     {
499         lon = ref_lon + atan(x/y);
500     }
501     else
502     {
503         lon = ref_lon + atan(x* sin(c) / (rho * cos(ref_lat) * cos(c) - y * sin(ref_lat) * sin(c)));
504     }
505
506     return SGGeod::fromRad(lon, lat);
507 }
508
509 QPointF BaseDiagram::project(const SGGeod& geod) const
510 {
511     return project(geod, m_projectionCenter);
512 }
513
514 QPixmap BaseDiagram::iconForPositioned(const FGPositionedRef& pos,
515                                        const IconOptions& options)
516 {
517     // if airport type, check towered or untowered
518     bool small = options.testFlag(SmallIcons);
519
520     bool isTowered = false;
521     if (FGAirport::isAirportType(pos)) {
522         FGAirport* apt = static_cast<FGAirport*>(pos.ptr());
523         isTowered = apt->hasTower();
524     }
525
526     switch (pos->type()) {
527     case FGPositioned::VOR:
528         if (static_cast<FGNavRecord*>(pos.ptr())->isVORTAC())
529             return QPixmap(":/vortac-icon");
530
531         if (static_cast<FGNavRecord*>(pos.ptr())->hasDME())
532             return QPixmap(":/vor-dme-icon");
533
534         return QPixmap(":/vor-icon");
535
536     case FGPositioned::AIRPORT:
537         return iconForAirport(static_cast<FGAirport*>(pos.ptr()), options);
538
539     case FGPositioned::HELIPORT:
540         return QPixmap(":/heliport-icon");
541     case FGPositioned::SEAPORT:
542         return QPixmap(isTowered ? ":/seaport-tower-icon" : ":/seaport-icon");
543     case FGPositioned::NDB:
544         return QPixmap(small ? ":/ndb-small-icon" : ":/ndb-icon");
545     case FGPositioned::FIX:
546         return QPixmap(":/waypoint-icon");
547
548     default:
549         break;
550     }
551
552     return QPixmap();
553 }
554
555 QPixmap BaseDiagram::iconForAirport(FGAirport* apt, const IconOptions& options)
556 {
557     if (apt->isClosed()) {
558         return QPixmap(":/airport-closed-icon");
559     }
560
561     if (!apt->hasHardRunwayOfLengthFt(1500)) {
562         return QPixmap(apt->hasTower() ? ":/airport-tower-icon" : ":/airport-icon");
563     }
564
565     if (options.testFlag(LargeAirportPlans) && apt->hasHardRunwayOfLengthFt(8500)) {
566         QPixmap result(32, 32);
567         result.fill(Qt::transparent);
568         {
569             QPainter p(&result);
570             p.setRenderHint(QPainter::Antialiasing, true);
571             QRectF b = result.rect().adjusted(4, 4, -4, -4);
572             QVector<QLineF> lines = projectAirportRuwaysIntoRect(apt, b);
573
574             p.setPen(QPen(QColor(0x03, 0x83, 0xbf), 8));
575             p.drawLines(lines);
576
577             p.setPen(QPen(Qt::white, 2));
578             p.drawLines(lines);
579         }
580         return result;
581     }
582
583     QPixmap result(25, 25);
584     result.fill(Qt::transparent);
585
586     {
587         QPainter p(&result);
588         p.setRenderHint(QPainter::Antialiasing, true);
589         p.setPen(Qt::NoPen);
590
591         p.setBrush(apt->hasTower() ? QColor(0x03, 0x83, 0xbf) :
592                                      QColor(0x9b, 0x5d, 0xa2));
593         p.drawEllipse(QPointF(13, 13), 10, 10);
594
595         FGRunwayRef r = apt->longestRunway();
596
597         p.setPen(QPen(Qt::white, 2));
598         p.translate(13, 13);
599         p.rotate(r->headingDeg());
600         p.drawLine(0, -8, 0, 8);
601     }
602
603     return result;
604 }
605
606 QVector<QLineF> BaseDiagram::projectAirportRuwaysWithCenter(FGAirportRef apt, const SGGeod& c)
607 {
608     QVector<QLineF> r;
609
610     const FGRunwayList& runways(apt->getRunwaysWithoutReciprocals());
611     FGRunwayList::const_iterator it;
612
613     for (it = runways.begin(); it != runways.end(); ++it) {
614         FGRunwayRef rwy = *it;
615         QPointF p1 = project(rwy->geod(), c);
616         QPointF p2 = project(rwy->end(), c);
617         r.append(QLineF(p1, p2));
618     }
619
620     return r;
621 }
622
623 QVector<QLineF> BaseDiagram::projectAirportRuwaysIntoRect(FGAirportRef apt, const QRectF &bounds)
624 {
625     QVector<QLineF> r = projectAirportRuwaysWithCenter(apt, apt->geod());
626
627     QRectF extent;
628     Q_FOREACH(const QLineF& l, r) {
629         extendRect(extent, l.p1());
630         extendRect(extent, l.p2());
631     }
632
633  // find constraining scale factor
634     double ratioInX = bounds.width() / extent.width();
635     double ratioInY = bounds.height() / extent.height();
636
637     QTransform t;
638     t.translate(bounds.left(), bounds.top());
639     t.scale(std::min(ratioInX, ratioInY),
640             std::min(ratioInX, ratioInY));
641     t.translate(-extent.left(), -extent.top()); // move unscaled to 0,0
642
643     for (int i=0; i<r.size(); ++i) {
644         r[i] = t.map(r[i]);
645     }
646
647     return r;
648 }