PrimaryFlightDisplay.cc 47.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
#include "PrimaryFlightDisplay.h"
#include "UASManager.h"

#include <QDebug>
#include <QRectF>
#include <cmath>
#include <QPen>
#include <QPainter>
#include <QPainterPath>
#include <QResizeEvent>
dongfang's avatar
dongfang committed
11
#include <QtCore/qmath.h>
12

13 14 15 16
static const float LINEWIDTH = 0.0036f;
static const float SMALL_TEXT_SIZE = 0.028f;
static const float MEDIUM_TEXT_SIZE = SMALL_TEXT_SIZE*1.2f;
static const float LARGE_TEXT_SIZE = MEDIUM_TEXT_SIZE*1.2f;
17

18
static const bool SHOW_ZERO_ON_SCALES = true;
19 20

// all in units of display height
21 22 23 24
static const float ROLL_SCALE_RADIUS = 0.42f;
static const float ROLL_SCALE_TICKMARKLENGTH = 0.04f;
static const float ROLL_SCALE_MARKERWIDTH = 0.06f;
static const float ROLL_SCALE_MARKERHEIGHT = 0.04f;
25
// scale max. degrees
26
static const int ROLL_SCALE_RANGE = 60;
27 28

// fraction of height to translate for each degree of pitch.
29 30 31 32
static const float PITCHTRANSLATION = 65;
// 5 degrees for each line
static const int PITCH_SCALE_RESOLUTION = 5;
static const float PITCH_SCALE_MAJORWIDTH = 0.1f;
33
static const float PITCH_SCALE_MINORWIDTH = 0.066f;
34 35 36 37

// Beginning from PITCH_SCALE_WIDTHREDUCTION_FROM degrees of +/- pitch, the
// width of the lines is reduced, down to PITCH_SCALE_WIDTHREDUCTION times
// the normal width. This helps keep orientation in extreme attitudes.
38 39
static const int PITCH_SCALE_WIDTHREDUCTION_FROM = 30;
static const float PITCH_SCALE_WIDTHREDUCTION = 0.3f;
40

41
static const int PITCH_SCALE_HALFRANGE = 15;
42 43 44 45 46

// The number of degrees to either side of the heading to draw the compass disk.
// 180 is valid, this will draw a complete disk. If the disk is partly clipped
// away, less will do.

47 48 49
static const int  COMPASS_DISK_MAJORTICK = 10;
static const int  COMPASS_DISK_ARROWTICK = 45;
static const int  COMPASS_DISK_RESOLUTION = 10;
50 51
static const float COMPASS_DISK_MARKERWIDTH = 0.2f;
static const float COMPASS_DISK_MARKERHEIGHT = 0.133f;
52

53
static const int  CROSSTRACK_MAX = 1000;
54
static const float CROSSTRACK_RADIUS = 0.6f;
55

56 57
static const float TAPE_GAUGES_TICKWIDTH_MAJOR = 0.25f;
static const float TAPE_GAUGES_TICKWIDTH_MINOR = 0.15f;
58 59

// The altitude difference between top and bottom of scale
60
static const int ALTIMETER_LINEAR_SPAN = 50;
61
// every 5 meters there is a tick mark
62
static const int ALTIMETER_LINEAR_RESOLUTION = 5;
63
// every 10 meters there is a number
64
static const int ALTIMETER_LINEAR_MAJOR_RESOLUTION = 10;
65 66

// min. and max. vertical velocity
67 68
static const int ALTIMETER_VVI_SPAN = 5;
static const float ALTIMETER_VVI_WIDTH = 0.2f;
69 70

// Now the same thing for airspeed!
71 72 73
static const int AIRSPEED_LINEAR_SPAN = 15;
static const int AIRSPEED_LINEAR_RESOLUTION = 1;
static const int AIRSPEED_LINEAR_MAJOR_RESOLUTION = 5;
74

75 76
/*
 *@TODO:
dongfang's avatar
dongfang committed
77
 * global fixed pens (and painters too?)
78 79 80
 * repaint on demand multiple canvases
 * multi implementation with shared model class
 */
dongfang's avatar
dongfang committed
81
double PrimaryFlightDisplay_round(double value, int digits=0)
82
{
83
    return floor(value * pow(10.0, digits) + 0.5) / pow(10.0, digits);
84
}
85

86 87 88 89 90 91
qreal PrimaryFlightDisplay_constrain(qreal value, qreal min, qreal max) {
    if (value<min) value=min;
    else if(value>max) value=max;
    return value;
}

92 93 94 95 96 97 98 99 100 101 102 103
const int PrimaryFlightDisplay::tickValues[] = {10, 20, 30, 45, 60};
const QString PrimaryFlightDisplay::compassWindNames[] = {
    QString("N"),
    QString("NE"),
    QString("E"),
    QString("SE"),
    QString("S"),
    QString("SW"),
    QString("W"),
    QString("NW")
};

104
PrimaryFlightDisplay::PrimaryFlightDisplay(QWidget *parent) :
105 106
    QWidget(parent),

107 108 109
    _valuesChanged(false),
    _valuesLastPainted(QGC::groundTimeMilliseconds()),

110
    uas(NULL),
111

112 113 114
    roll(0),
    pitch(0),
    heading(0),
115

Don Gagne's avatar
Don Gagne committed
116
    altitudeAMSL(std::numeric_limits<double>::quiet_NaN()),
117
    altitudeWGS84(std::numeric_limits<double>::quiet_NaN()),
Don Gagne's avatar
Don Gagne committed
118
    altitudeRelative(std::numeric_limits<double>::quiet_NaN()),
119

Don Gagne's avatar
Don Gagne committed
120 121 122
    groundSpeed(std::numeric_limits<double>::quiet_NaN()),
    airSpeed(std::numeric_limits<double>::quiet_NaN()),
    climbRate(std::numeric_limits<double>::quiet_NaN()),
123

124
    navigationCrosstrackError(std::numeric_limits<double>::quiet_NaN()),
Don Gagne's avatar
Don Gagne committed
125
    navigationTargetBearing(std::numeric_limits<double>::quiet_NaN()),
126

127 128
    layout(COMPASS_INTEGRATED),
    style(OVERLAY_HSI),
129

dongfang's avatar
dongfang committed
130
    redColor(QColor::fromHsvF(0, 0.75, 0.9)),
dongfang's avatar
dongfang committed
131 132 133 134 135 136 137
    amberColor(QColor::fromHsvF(0.12, 0.6, 1.0)),
    greenColor(QColor::fromHsvF(0.25, 0.8, 0.8)),

    lineWidth(2),
    fineLineWidth(1),

    instrumentEdgePen(QColor::fromHsvF(0, 0, 0.65, 0.5)),
dongfang's avatar
dongfang committed
138
    instrumentBackground(QColor::fromHsvF(0, 0, 0.3, 0.3)),
139 140 141
    instrumentOpagueBackground(QColor::fromHsvF(0, 0, 0.3, 1.0)),

    font("Bitstream Vera Sans"),
142
    refreshTimer(new QTimer(this))
dongfang's avatar
dongfang committed
143
{
144 145 146
    setMinimumSize(120, 80);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

Lorenz Meier's avatar
Lorenz Meier committed
147 148
    setActiveUAS(UASManager::instance()->getActiveUAS());

149
    // Connect with UAS signal
150
    connect(UASManager::instance(), SIGNAL(UASDeleted(UASInterface*)), this, SLOT(forgetUAS(UASInterface*)));
151
    connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setActiveUAS(UASInterface*)));
152

153 154
    // Refresh timer
    refreshTimer->setInterval(updateInterval);
155
    connect(refreshTimer, SIGNAL(timeout()), this, SLOT(checkUpdate()));
156 157 158 159 160 161 162 163 164
}

PrimaryFlightDisplay::~PrimaryFlightDisplay()
{
    refreshTimer->stop();
}

QSize PrimaryFlightDisplay::sizeHint() const
{
165
    return QSize(width(), (int)(width() * 3.0f / 4.0f));
166 167
}

168

169 170
void PrimaryFlightDisplay::showEvent(QShowEvent* event)
{
171
    // React only to internal (pre-display) events
172 173 174 175 176 177 178
    QWidget::showEvent(event);
    refreshTimer->start(updateInterval);
    emit visibilityChanged(true);
}

void PrimaryFlightDisplay::hideEvent(QHideEvent* event)
{
179
    // React only to internal (pre-display) events
180 181 182 183 184
    refreshTimer->stop();
    QWidget::hideEvent(event);
    emit visibilityChanged(false);
}

dongfang's avatar
dongfang committed
185 186 187 188 189
void PrimaryFlightDisplay::resizeEvent(QResizeEvent *e) {
    QWidget::resizeEvent(e);

    qreal size = e->size().width();

190 191
    lineWidth = PrimaryFlightDisplay_constrain(size*LINEWIDTH, 1, 6);
    fineLineWidth = PrimaryFlightDisplay_constrain(size*LINEWIDTH*2/3, 1, 2);
dongfang's avatar
dongfang committed
192 193 194

    instrumentEdgePen.setWidthF(fineLineWidth);

195
    smallTextSize = size * SMALL_TEXT_SIZE;
dongfang's avatar
dongfang committed
196 197 198
    mediumTextSize = size * MEDIUM_TEXT_SIZE;
    largeTextSize = size * LARGE_TEXT_SIZE;
}
199

dongfang's avatar
dongfang committed
200 201 202 203 204
void PrimaryFlightDisplay::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    doPaint();
}
205

206 207 208 209 210 211 212 213 214
void PrimaryFlightDisplay::checkUpdate()
{
    if (uas && (_valuesChanged || (QGC::groundTimeMilliseconds() - _valuesLastPainted) > 260)) {
        update();
        _valuesChanged = false;
        _valuesLastPainted = QGC::groundTimeMilliseconds();
    }
}

215
void PrimaryFlightDisplay::forgetUAS(UASInterface* uas)
216
{
217
    if (this->uas != NULL && this->uas == uas) {
218
        // Disconnect any previously connected active MAV
219 220 221
        disconnect(this->uas, SIGNAL(attitudeChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*, double, double, double, quint64)));
        disconnect(this->uas, SIGNAL(attitudeChanged(UASInterface*,int,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*,int,double, double, double, quint64)));
        disconnect(this->uas, SIGNAL(speedChanged(UASInterface*, double, double, quint64)), this, SLOT(updateSpeed(UASInterface*, double, double, quint64)));
222
        disconnect(this->uas, SIGNAL(altitudeChanged(UASInterface*, double, double, double, double, quint64)), this, SLOT(updateAltitude(UASInterface*, double, double, double, double, quint64)));
223
        disconnect(this->uas, SIGNAL(navigationControllerErrorsChanged(UASInterface*, double, double, double)), this, SLOT(updateNavigationControllerErrors(UASInterface*, double, double, double)));
224
        disconnect(this->uas, &UASInterface::NavigationControllerDataChanged, this, &PrimaryFlightDisplay::UpdateNavigationControllerData);
225
    }
226
    this->uas = NULL;
227 228 229 230 231 232 233 234
}

/**
 *
 * @param uas the UAS/MAV to monitor/display with the HUD
 */
void PrimaryFlightDisplay::setActiveUAS(UASInterface* uas)
{
tstellanova's avatar
tstellanova committed
235 236 237
    if (uas == this->uas)
        return; //no need to rewire

238 239
    // Disconnect the previous one (if any)
    forgetUAS(this->uas);
240 241 242 243 244 245

    if (uas) {
        // Now connect the new UAS
        // Setup communication
        connect(uas, SIGNAL(attitudeChanged(UASInterface*,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*, double, double, double, quint64)));
        connect(uas, SIGNAL(attitudeChanged(UASInterface*,int,double,double,double,quint64)), this, SLOT(updateAttitude(UASInterface*,int,double, double, double, quint64)));
246
        connect(uas, SIGNAL(speedChanged(UASInterface*, double, double, quint64)), this, SLOT(updateSpeed(UASInterface*, double, double, quint64)));
247
        connect(uas, SIGNAL(altitudeChanged(UASInterface*, double, double, double, double, quint64)), this, SLOT(updateAltitude(UASInterface*, double, double, double, double, quint64)));
248
        connect(uas, SIGNAL(navigationControllerErrorsChanged(UASInterface*, double, double, double)), this, SLOT(updateNavigationControllerErrors(UASInterface*, double, double, double)));
249
        connect(uas, &UASInterface::NavigationControllerDataChanged, this, &PrimaryFlightDisplay::UpdateNavigationControllerData);
250 251 252 253 254 255 256 257 258 259

        // Set new UAS
        this->uas = uas;
    }
}

void PrimaryFlightDisplay::updateAttitude(UASInterface* uas, double roll, double pitch, double yaw, quint64 timestamp)
{
    Q_UNUSED(uas);
    Q_UNUSED(timestamp);
260

261
        if (isinf(roll)) {
Don Gagne's avatar
Don Gagne committed
262
            this->roll = std::numeric_limits<double>::quiet_NaN();
263
        } else {
264 265 266

            float rolldeg = roll * (180.0 / M_PI);

Don Gagne's avatar
Don Gagne committed
267
            if (fabsf((float)roll - rolldeg) > 2.5f) {
268 269 270 271
                _valuesChanged = true;
            }

            this->roll = rolldeg;
272
        }
273

274
        if (isinf(pitch)) {
Don Gagne's avatar
Don Gagne committed
275
            this->pitch = std::numeric_limits<double>::quiet_NaN();
276
        } else {
277 278 279

            float pitchdeg = pitch * (180.0 / M_PI);

Don Gagne's avatar
Don Gagne committed
280
            if (fabsf((float)pitch - pitchdeg) > 2.5f) {
281 282 283 284
                _valuesChanged = true;
            }

            this->pitch = pitchdeg;
285 286
        }

287
        if (isinf(yaw)) {
Don Gagne's avatar
Don Gagne committed
288
            this->heading = std::numeric_limits<double>::quiet_NaN();
289
        } else {
290

291 292
            yaw = yaw * (180.0 / M_PI);
            if (yaw<0) yaw+=360;
293

Don Gagne's avatar
Don Gagne committed
294
            if (fabs(heading - yaw) > 10.0) {
295 296 297
                _valuesChanged = true;
            }

298 299
            this->heading = yaw;
        }
Lorenz Meier's avatar
Lorenz Meier committed
300

301 302 303 304 305
}

void PrimaryFlightDisplay::updateAttitude(UASInterface* uas, int component, double roll, double pitch, double yaw, quint64 timestamp)
{
    Q_UNUSED(component);
306
    this->updateAttitude(uas, roll, pitch, yaw, timestamp);
307 308
}

309
void PrimaryFlightDisplay::updateSpeed(UASInterface* uas, double _groundSpeed, double _airSpeed, quint64 timestamp)
310 311 312 313
{
    Q_UNUSED(uas);
    Q_UNUSED(timestamp);

Don Gagne's avatar
Don Gagne committed
314
    if (fabs(groundSpeed - _groundSpeed) > 0.5) {
315 316 317
        _valuesChanged = true;
    }

Don Gagne's avatar
Don Gagne committed
318
    if (fabs(airSpeed - _airSpeed) > 1.0) {
319 320 321
        _valuesChanged = true;
    }

322 323
    groundSpeed = _groundSpeed;
    airSpeed = _airSpeed;
324
}
325

326
void PrimaryFlightDisplay::updateAltitude(UASInterface* uas, double _altitudeAMSL, double _altitudeWGS84, double _altitudeRelative, double _climbRate, quint64 timestamp) {
327 328
    Q_UNUSED(uas);
    Q_UNUSED(timestamp);
329

Don Gagne's avatar
Don Gagne committed
330
    if (fabs(altitudeAMSL - _altitudeAMSL) > 0.5) {
331 332 333
        _valuesChanged = true;
    }

Don Gagne's avatar
Don Gagne committed
334
    if (fabs(altitudeWGS84 - _altitudeWGS84) > 0.5) {
335 336 337
        _valuesChanged = true;
    }

Don Gagne's avatar
Don Gagne committed
338
    if (fabs(altitudeRelative - _altitudeRelative) > 0.5) {
339 340 341
        _valuesChanged = true;
    }

Don Gagne's avatar
Don Gagne committed
342
    if (fabs(climbRate - _climbRate) > 0.5) {
343 344 345
        _valuesChanged = true;
    }

346
    altitudeAMSL = _altitudeAMSL;
347
    altitudeWGS84 = _altitudeWGS84;
348 349
    altitudeRelative = _altitudeRelative;
    climbRate = _climbRate;
350 351
}

352 353 354 355 356 357 358 359 360 361
void PrimaryFlightDisplay::UpdateNavigationControllerData(UASInterface *uas, float navRoll, float navPitch, float navBearing, float targetBearing, float targetDistance) {
    Q_UNUSED(navRoll);
    Q_UNUSED(navPitch);
    Q_UNUSED(navBearing);
    Q_UNUSED(targetDistance);
    if (this->uas == uas) {
        this->navigationTargetBearing = targetBearing;
    }
}

362 363 364 365 366 367 368 369
void PrimaryFlightDisplay::updateNavigationControllerErrors(UASInterface* uas, double altitudeError, double speedError, double xtrackError) {
    Q_UNUSED(uas);
    this->navigationAltitudeError = altitudeError;
    this->navigationSpeedError = speedError;
    this->navigationCrosstrackError = xtrackError;
}


370 371 372
/*
 * Private and such
 */
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

// TODO: Move to UAS. Real working implementation.
bool PrimaryFlightDisplay::isAirplane() {
    if (!this->uas)
        return false;
    switch(this->uas->getSystemType()) {
    case MAV_TYPE_GENERIC:
    case MAV_TYPE_FIXED_WING:
    case MAV_TYPE_AIRSHIP:
    case MAV_TYPE_FLAPPING_WING:
        return true;
    default:
        return false;
    }
}

389 390 391 392 393 394 395
// TODO: Implement. Should return true when navigating.
// That would be (APM) in AUTO and RTL modes.
// This could forward to a virtual on UAS bool isNavigatingAutonomusly() or whatever.
bool PrimaryFlightDisplay::shouldDisplayNavigationData() {
    return true;
}

396 397 398
void PrimaryFlightDisplay::drawTextCenter (
        QPainter& painter,
        QString text,
dongfang's avatar
dongfang committed
399
        float pixelSize,
400 401 402
        float x,
        float y)
{
dongfang's avatar
dongfang committed
403
    font.setPixelSize(pixelSize);
404 405 406 407 408
    painter.setFont(font);

    QFontMetrics metrics = QFontMetrics(font);
    QRect bounds = metrics.boundingRect(text);
    int flags = Qt::AlignCenter |  Qt::TextDontClip; // For some reason the bounds rect is too small!
409
    painter.drawText(x - bounds.width()/2, y - bounds.height()/2, bounds.width(), bounds.height(), flags, text);
410 411 412 413 414
}

void PrimaryFlightDisplay::drawTextLeftCenter (
        QPainter& painter,
        QString text,
dongfang's avatar
dongfang committed
415
        float pixelSize,
416 417 418
        float x,
        float y)
{
dongfang's avatar
dongfang committed
419
    font.setPixelSize(pixelSize);
420 421 422 423 424
    painter.setFont(font);

    QFontMetrics metrics = QFontMetrics(font);
    QRect bounds = metrics.boundingRect(text);
    int flags = Qt::AlignLeft | Qt::TextDontClip; // For some reason the bounds rect is too small!
425
    painter.drawText(x, y - bounds.height()/2, bounds.width(), bounds.height(), flags, text);
426 427 428 429 430
}

void PrimaryFlightDisplay::drawTextRightCenter (
        QPainter& painter,
        QString text,
dongfang's avatar
dongfang committed
431
        float pixelSize,
432 433 434
        float x,
        float y)
{
dongfang's avatar
dongfang committed
435
    font.setPixelSize(pixelSize);
436 437 438 439 440
    painter.setFont(font);

    QFontMetrics metrics = QFontMetrics(font);
    QRect bounds = metrics.boundingRect(text);
    int flags = Qt::AlignRight | Qt::TextDontClip; // For some reason the bounds rect is too small!
441
    painter.drawText(x - bounds.width(), y - bounds.height()/2, bounds.width(), bounds.height(), flags, text);
442 443 444 445 446
}

void PrimaryFlightDisplay::drawTextCenterTop (
        QPainter& painter,
        QString text,
dongfang's avatar
dongfang committed
447
        float pixelSize,
448 449 450
        float x,
        float y)
{
dongfang's avatar
dongfang committed
451
    font.setPixelSize(pixelSize);
452 453 454 455 456
    painter.setFont(font);

    QFontMetrics metrics = QFontMetrics(font);
    QRect bounds = metrics.boundingRect(text);
    int flags = Qt::AlignCenter | Qt::TextDontClip; // For some reason the bounds rect is too small!
457
    painter.drawText(x - bounds.width()/2, y+bounds.height(), bounds.width(), bounds.height(), flags, text);
458 459 460 461 462
}

void PrimaryFlightDisplay::drawTextCenterBottom (
        QPainter& painter,
        QString text,
dongfang's avatar
dongfang committed
463
        float pixelSize,
464 465 466
        float x,
        float y)
{
dongfang's avatar
dongfang committed
467
    font.setPixelSize(pixelSize);
468 469
    painter.setFont(font);

470
    QFontMetrics metrics(font);
471 472
    QRect bounds = metrics.boundingRect(text);
    int flags = Qt::AlignCenter;
473
    painter.drawText(x - bounds.width()/2, y, bounds.width(), bounds.height(), flags, text);
474 475 476 477 478 479 480 481 482 483 484 485 486 487
}

void PrimaryFlightDisplay::drawInstrumentBackground(QPainter& painter, QRectF edge) {
    painter.setPen(instrumentEdgePen);
    painter.drawRect(edge);
}

void PrimaryFlightDisplay::fillInstrumentBackground(QPainter& painter, QRectF edge) {
    painter.setPen(instrumentEdgePen);
    painter.setBrush(instrumentBackground);
    painter.drawRect(edge);
    painter.setBrush(Qt::NoBrush);
}

dongfang's avatar
dongfang committed
488 489 490 491 492 493 494
void PrimaryFlightDisplay::fillInstrumentOpagueBackground(QPainter& painter, QRectF edge) {
    painter.setPen(instrumentEdgePen);
    painter.setBrush(instrumentOpagueBackground);
    painter.drawRect(edge);
    painter.setBrush(Qt::NoBrush);
}

495
qreal pitchAngleToTranslation(qreal viewHeight, float pitch) {
496
    if (isnan(pitch))
497
        return 0;
498
    return pitch * viewHeight / PITCHTRANSLATION;
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
}

void PrimaryFlightDisplay::drawAIAirframeFixedFeatures(QPainter& painter, QRectF area) {
    // red line from -7/10 to -5/10 half-width
    // red line from 7/10 to 5/10 half-width
    // red slanted line from -2/10 half-width to 0
    // red slanted line from 2/10 half-width to 0
    // red arrow thing under roll scale
    // prepareTransform(painter, width, height);
    painter.resetTransform();
    painter.translate(area.center());

    qreal w = area.width();
    qreal h = area.height();

dongfang's avatar
dongfang committed
514
    QPen pen;
515
    pen.setWidthF(lineWidth * 1.5f);
dongfang's avatar
dongfang committed
516 517
    pen.setColor(redColor);
    painter.setPen(pen);
518

519 520
    float length = 0.15f;
    float side = 0.5f;
dongfang's avatar
dongfang committed
521 522 523 524
    // The 2 lines at sides.
    painter.drawLine(QPointF(-side*w, 0), QPointF(-(side-length)*w, 0));
    painter.drawLine(QPointF(side*w, 0), QPointF((side-length)*w, 0));

525
    float rel = length/qSqrt(2.0f);
dongfang's avatar
dongfang committed
526 527 528 529 530 531 532 533
    // The gull
    painter.drawLine(QPointF(rel*w, rel*w/2), QPoint(0, 0));
    painter.drawLine(QPointF(-rel*w, rel*w/2), QPoint(0, 0));

    // The roll scale marker.
    QPainterPath markerPath(QPointF(0, -w*ROLL_SCALE_RADIUS+1));
    markerPath.lineTo(-h*ROLL_SCALE_MARKERWIDTH/2, -w*(ROLL_SCALE_RADIUS-ROLL_SCALE_MARKERHEIGHT)+1);
    markerPath.lineTo(h*ROLL_SCALE_MARKERWIDTH/2, -w*(ROLL_SCALE_RADIUS-ROLL_SCALE_MARKERHEIGHT)+1);
534 535 536 537
    markerPath.closeSubpath();
    painter.drawPath(markerPath);
}

538 539 540 541 542 543 544 545 546 547 548 549 550 551
inline qreal min4(qreal a, qreal b, qreal c, qreal d) {
    if(b<a) a=b;
    if(c<a) a=c;
    if(d<a) a=d;
    return a;
}

inline qreal max4(qreal a, qreal b, qreal c, qreal d) {
    if(b>a) a=b;
    if(c>a) a=c;
    if(d>a) a=d;
    return a;
}

552 553
void PrimaryFlightDisplay::drawAIGlobalFeatures(
        QPainter& painter,
554 555
        QRectF mainArea,
        QRectF paintArea) {
556

557
    float displayRoll = this->roll;
558
    if (isnan(displayRoll))
559 560
        displayRoll = 0;

561
    painter.resetTransform();
562
    painter.translate(mainArea.center());
563

564 565
    qreal pitchPixels = pitchAngleToTranslation(mainArea.height(), pitch);
    qreal gradientEnd = pitchAngleToTranslation(mainArea.height(), 60);
566

567
    painter.rotate(-displayRoll);
568 569 570 571 572 573 574 575 576
    painter.translate(0, pitchPixels);

    // Calculate the radius of area we need to paint to cover all.
    QTransform rtx = painter.transform().inverted();

    QPointF topLeft = rtx.map(paintArea.topLeft());
    QPointF topRight = rtx.map(paintArea.topRight());
    QPointF bottomLeft = rtx.map(paintArea.bottomLeft());
    QPointF bottomRight = rtx.map(paintArea.bottomRight());
577

578 579 580 581 582 583 584 585 586 587 588 589 590
    // Just KISS... make a rectangluar basis.
    qreal minx = min4(topLeft.x(), topRight.x(), bottomLeft.x(), bottomRight.x());
    qreal maxx = max4(topLeft.x(), topRight.x(), bottomLeft.x(), bottomRight.x());
    qreal miny = min4(topLeft.y(), topRight.y(), bottomLeft.y(), bottomRight.y());
    qreal maxy = max4(topLeft.y(), topRight.y(), bottomLeft.y(), bottomRight.y());

    QPointF hzonLeft = QPoint(minx, 0);
    QPointF hzonRight = QPoint(maxx, 0);

    QPainterPath skyPath(hzonLeft);
    skyPath.lineTo(QPointF(minx, miny));
    skyPath.lineTo(QPointF(maxx, miny));
    skyPath.lineTo(hzonRight);
591 592
    skyPath.closeSubpath();

593
    QLinearGradient skyGradient(0, -gradientEnd, 0, 0);
594 595 596 597 598
    skyGradient.setColorAt(0, QColor::fromHsvF(0.6, 1.0, 0.7));
    skyGradient.setColorAt(1, QColor::fromHsvF(0.6, 0.25, 0.9));
    QBrush skyBrush(skyGradient);
    painter.fillPath(skyPath, skyBrush);

599 600 601 602
    QPainterPath groundPath(hzonRight);
    groundPath.lineTo(maxx, maxy);
    groundPath.lineTo(minx, maxy);
    groundPath.lineTo(hzonLeft);
603 604
    groundPath.closeSubpath();

605
    QLinearGradient groundGradient(0, gradientEnd, 0, 0);
606 607 608 609 610
    groundGradient.setColorAt(0, QColor::fromHsvF(0.25, 1, 0.5));
    groundGradient.setColorAt(1, QColor::fromHsvF(0.25, 0.25, 0.5));
    QBrush groundBrush(groundGradient);
    painter.fillPath(groundPath, groundBrush);

dongfang's avatar
dongfang committed
611 612 613 614 615
    QPen pen;
    pen.setWidthF(lineWidth);
    pen.setColor(greenColor);
    painter.setPen(pen);

616 617
    QPointF start(-mainArea.width(), 0);
    QPoint end(mainArea.width(), 0);
618 619 620 621 622 623
    painter.drawLine(start, end);
}

void PrimaryFlightDisplay::drawPitchScale(
        QPainter& painter,
        QRectF area,
dongfang's avatar
dongfang committed
624
        float intrusion,
625 626 627 628
        bool drawNumbersLeft,
        bool drawNumbersRight
        ) {

629 630
    Q_UNUSED(intrusion);
    
631
    float displayPitch = this->pitch;
632
    if (isnan(displayPitch))
633 634
        displayPitch = 0;

dongfang's avatar
dongfang committed
635 636 637
    // The area should be quadratic but if not width is the major size.
    qreal w = area.width();
    if (w<area.height()) w = area.height();
638

dongfang's avatar
dongfang committed
639 640 641 642
    QPen pen;
    pen.setWidthF(lineWidth);
    pen.setColor(Qt::white);
    painter.setPen(pen);
643 644 645 646

    QTransform savedTransform = painter.transform();

    // find the mark nearest center
647
    int snap = qRound((double)(displayPitch/PITCH_SCALE_RESOLUTION))*PITCH_SCALE_RESOLUTION;
648 649 650 651
    int _min = snap-PITCH_SCALE_HALFRANGE;
    int _max = snap+PITCH_SCALE_HALFRANGE;
    for (int degrees=_min; degrees<=_max; degrees+=PITCH_SCALE_RESOLUTION) {
        bool isMajor = degrees % (PITCH_SCALE_RESOLUTION*2) == 0;
652 653 654 655 656 657 658 659
        float linewidth =  isMajor ? PITCH_SCALE_MAJORWIDTH : PITCH_SCALE_MINORWIDTH;
        if (abs(degrees) > PITCH_SCALE_WIDTHREDUCTION_FROM) {
            // we want: 1 at PITCH_SCALE_WIDTHREDUCTION_FROM and PITCH_SCALE_WIDTHREDUCTION at 90.
            // That is PITCH_SCALE_WIDTHREDUCTION + (1-PITCH_SCALE_WIDTHREDUCTION) * f(pitch)
            // where f(90)=0 and f(PITCH_SCALE_WIDTHREDUCTION_FROM)=1
            // f(p) = (90-p) * 1/(90-PITCH_SCALE_WIDTHREDUCTION_FROM)
            // or PITCH_SCALE_WIDTHREDUCTION + f(pitch) - f(pitch) * PITCH_SCALE_WIDTHREDUCTION
            // or PITCH_SCALE_WIDTHREDUCTION (1-f(pitch)) + f(pitch)
Don Gagne's avatar
Don Gagne committed
660
            int fromVertical = fabs(pitch>=0 ? 90-pitch : -90-pitch);
661 662 663
            float temp = fromVertical * 1/(90.0f-PITCH_SCALE_WIDTHREDUCTION_FROM);
            linewidth *= (PITCH_SCALE_WIDTHREDUCTION * (1-temp) + temp);
        }
dongfang's avatar
dongfang committed
664

665
        float shift = pitchAngleToTranslation(w, displayPitch-degrees);
dongfang's avatar
dongfang committed
666 667 668 669

        // TODO: Intrusion detection and evasion. That is, don't draw
        // where the compass has intruded.

670
        painter.translate(0, shift);
dongfang's avatar
dongfang committed
671 672
        QPointF start(-linewidth*w, 0);
        QPointF end(linewidth*w, 0);
673 674 675 676 677 678 679
        painter.drawLine(start, end);

        if (isMajor && (drawNumbersLeft||drawNumbersRight)) {
            int displayDegrees = degrees;
            if(displayDegrees>90) displayDegrees = 180-displayDegrees;
            else if (displayDegrees<-90) displayDegrees = -180 - displayDegrees;
            if (SHOW_ZERO_ON_SCALES || degrees) {
680
                QString s_number;
681
                if (isnan(this->pitch))
682 683 684
                    s_number.sprintf("-");
                else
                    s_number.sprintf("%d", displayDegrees);
dongfang's avatar
dongfang committed
685 686
                if (drawNumbersLeft)  drawTextRightCenter(painter, s_number, mediumTextSize, -PITCH_SCALE_MAJORWIDTH * w-10, 0);
                if (drawNumbersRight) drawTextLeftCenter(painter, s_number, mediumTextSize, PITCH_SCALE_MAJORWIDTH * w+10, 0);
687 688 689 690 691 692 693 694 695 696 697 698 699
            }
        }

        painter.setTransform(savedTransform);
    }
}

void PrimaryFlightDisplay::drawRollScale(
        QPainter& painter,
        QRectF area,
        bool drawTicks,
        bool drawNumbers) {

700
    qreal w = area.width();
dongfang's avatar
dongfang committed
701
    if (w<area.height()) w = area.height();
702

dongfang's avatar
dongfang committed
703 704 705 706
    QPen pen;
    pen.setWidthF(lineWidth);
    pen.setColor(Qt::white);
    painter.setPen(pen);
707

708
    // We should really do these transforms but they are assumed done by caller:
709 710 711 712
    // painter.resetTransform();
    // painter.translate(area.center());
    // painter.rotate(roll);

713
    qreal _size = w * ROLL_SCALE_RADIUS*2;
dongfang's avatar
dongfang committed
714
    QRectF arcArea(-_size/2, - _size/2, _size, _size);
715 716 717 718 719 720 721 722 723 724 725 726 727 728
    painter.drawArc(arcArea, (90-ROLL_SCALE_RANGE)*16, ROLL_SCALE_RANGE*2*16);
    if (drawTicks) {
        int length = sizeof(tickValues)/sizeof(int);
        qreal previousRotation = 0;
        for (int i=0; i<length*2+1; i++) {
            int degrees = (i==length) ? 0 : (i>length) ?-tickValues[i-length-1] : tickValues[i];
            painter.rotate(degrees - previousRotation);
            previousRotation = degrees;

            QPointF start(0, -_size/2);
            QPointF end(0, -(1.0+ROLL_SCALE_TICKMARKLENGTH)*_size/2);

            painter.drawLine(start, end);

729
            QString s_number;
730 731 732 733
            if (SHOW_ZERO_ON_SCALES || degrees)
                s_number.sprintf("%d", abs(degrees));

            if (drawNumbers) {
734
                drawTextCenterBottom(painter, s_number, mediumTextSize, 0, -(ROLL_SCALE_RADIUS+ROLL_SCALE_TICKMARKLENGTH*1.7)*w);
735 736 737 738 739 740 741
            }
        }
    }
}

void PrimaryFlightDisplay::drawAIAttitudeScales(
        QPainter& painter,
dongfang's avatar
dongfang committed
742 743
        QRectF area,
        float intrusion
dongfang's avatar
dongfang committed
744
        ) {
745
    float displayRoll = this->roll;
746
    if (isnan(displayRoll))
747
        displayRoll = 0;
748 749 750
    // To save computations, we do these transformations once for both scales:
    painter.resetTransform();
    painter.translate(area.center());
751
    painter.rotate(-displayRoll);
752 753 754 755
    QTransform saved = painter.transform();

    drawRollScale(painter, area, true, true);
    painter.setTransform(saved);
dongfang's avatar
dongfang committed
756
    drawPitchScale(painter, area, intrusion, true, true);
757 758
}

dongfang's avatar
dongfang committed
759
void PrimaryFlightDisplay::drawAICompassDisk(QPainter& painter, QRectF area, float halfspan) {
760
    float displayHeading = this->heading;
761
    if (isnan(displayHeading))
762 763 764 765
        displayHeading = 0;

    float start = displayHeading - halfspan;
    float end = displayHeading + halfspan;
dongfang's avatar
dongfang committed
766

dongfang's avatar
dongfang committed
767 768
    int firstTick = ceil(start / COMPASS_DISK_RESOLUTION) * COMPASS_DISK_RESOLUTION;
    int lastTick = floor(end / COMPASS_DISK_RESOLUTION) * COMPASS_DISK_RESOLUTION;
769 770 771 772

    float radius = area.width()/2;
    float innerRadius = radius * 0.96;
    painter.resetTransform();
dongfang's avatar
dongfang committed
773 774
    painter.setBrush(instrumentBackground);
    painter.setPen(instrumentEdgePen);
775 776 777
    painter.drawEllipse(area);
    painter.setBrush(Qt::NoBrush);

dongfang's avatar
dongfang committed
778 779
    QPen scalePen(Qt::black);
    scalePen.setWidthF(fineLineWidth);
780

dongfang's avatar
dongfang committed
781
    for (int tickYaw = firstTick; tickYaw <= lastTick; tickYaw += COMPASS_DISK_RESOLUTION) {
782 783 784 785 786
        int displayTick = tickYaw;
        if (displayTick < 0) displayTick+=360;
        else if (displayTick>=360) displayTick-=360;

        // yaw is in center.
787
        float off = tickYaw - displayHeading;
788
        // wrap that to [-180..180]
dongfang's avatar
dongfang committed
789
        if (off<=-180) off+= 360; else if (off>180) off -= 360;
790 791 792 793

        painter.translate(area.center());
        painter.rotate(off);
        bool drewArrow = false;
dongfang's avatar
dongfang committed
794
        bool isMajor = displayTick % COMPASS_DISK_MAJORTICK == 0;
795

796
        // If heading unknown, still draw marks but no numbers.
797
        if (!isnan(this->heading) &&
798
                (displayTick==30 || displayTick==60 ||
dongfang's avatar
dongfang committed
799 800
                displayTick==120 || displayTick==150 ||
                displayTick==210 || displayTick==240 ||
801 802
                displayTick==300 || displayTick==330)
        ) {
803 804 805
            // draw a number
            QString s_number;
            s_number.sprintf("%d", displayTick/10);
dongfang's avatar
dongfang committed
806
            painter.setPen(scalePen);
807
            drawTextCenter(painter, s_number, smallTextSize, 0, -innerRadius*0.75);
808
        } else {
dongfang's avatar
dongfang committed
809
            if (displayTick % COMPASS_DISK_ARROWTICK == 0) {
810 811 812 813 814
                if (displayTick!=0) {
                    QPainterPath markerPath(QPointF(0, -innerRadius*(1-COMPASS_DISK_MARKERHEIGHT/2)));
                    markerPath.lineTo(innerRadius*COMPASS_DISK_MARKERWIDTH/4, -innerRadius);
                    markerPath.lineTo(-innerRadius*COMPASS_DISK_MARKERWIDTH/4, -innerRadius);
                    markerPath.closeSubpath();
dongfang's avatar
dongfang committed
815
                    painter.setPen(scalePen);
816 817 818 819 820
                    painter.setBrush(Qt::SolidPattern);
                    painter.drawPath(markerPath);
                    painter.setBrush(Qt::NoBrush);
                    drewArrow = true;
                }
821
                // If heading unknown, still draw marks but no N S E W.
822
                if (!isnan(this->heading) && displayTick%90 == 0) {
823
                    // Also draw a label
dongfang's avatar
dongfang committed
824 825 826
                    QString name = compassWindNames[displayTick / 45];
                    painter.setPen(scalePen);
                    drawTextCenter(painter, name, mediumTextSize, 0, -innerRadius*0.75);
827
                }
dongfang's avatar
dongfang committed
828
            }
829
        }
dongfang's avatar
dongfang committed
830
        // draw the scale lines. If an arrow was drawn, stay off from it.
831

dongfang's avatar
dongfang committed
832 833
        QPointF p_start = drewArrow ? QPoint(0, -innerRadius*0.94) : QPoint(0, -innerRadius);
        QPoint p_end = isMajor ? QPoint(0, -innerRadius*0.86) : QPoint(0, -innerRadius*0.90);
834

dongfang's avatar
dongfang committed
835
        painter.setPen(scalePen);
836 837 838 839
        painter.drawLine(p_start, p_end);
        painter.resetTransform();
    }

dongfang's avatar
dongfang committed
840
    painter.setPen(scalePen);
841 842 843 844 845 846 847
    painter.translate(area.center());
    QPainterPath markerPath(QPointF(0, -radius-2));
    markerPath.lineTo(radius*COMPASS_DISK_MARKERWIDTH/2,  -radius-radius*COMPASS_DISK_MARKERHEIGHT-2);
    markerPath.lineTo(-radius*COMPASS_DISK_MARKERWIDTH/2, -radius-radius*COMPASS_DISK_MARKERHEIGHT-2);
    markerPath.closeSubpath();
    painter.drawPath(markerPath);

dongfang's avatar
dongfang committed
848 849 850 851 852 853 854 855 856
    qreal digitalCompassYCenter = -radius*0.52;
    qreal digitalCompassHeight = radius*0.28;

    QPointF digitalCompassBottom(0, digitalCompassYCenter+digitalCompassHeight);
    QPointF  digitalCompassAbsoluteBottom = painter.transform().map(digitalCompassBottom);

    qreal digitalCompassUpshift = digitalCompassAbsoluteBottom.y()>height() ? digitalCompassAbsoluteBottom.y()-height() : 0;

    QRectF digitalCompassRect(-radius/3, -radius*0.52-digitalCompassUpshift, radius*2/3, radius*0.28);
857
    painter.setPen(instrumentEdgePen);
dongfang's avatar
dongfang committed
858
    painter.drawRoundedRect(digitalCompassRect, instrumentEdgePen.widthF()*2/3, instrumentEdgePen.widthF()*2/3);
859

dongfang's avatar
dongfang committed
860
    QString s_digitalCompass;
861

862
    if (isnan(this->heading))
863 864 865 866 867 868
        s_digitalCompass.sprintf("---");
    else {
    /* final safeguard for really stupid systems */
        int digitalCompassValue = static_cast<int>(qRound((double)heading)) % 360;
        s_digitalCompass.sprintf("%03d", digitalCompassValue);
    }
869

dongfang's avatar
dongfang committed
870 871 872 873
    QPen pen;
    pen.setWidthF(lineWidth);
    pen.setColor(Qt::white);
    painter.setPen(pen);
874

dongfang's avatar
dongfang committed
875
    drawTextCenter(painter, s_digitalCompass, largeTextSize, 0, -radius*0.38-digitalCompassUpshift);
876

877
    // The CDI
878 879
    // We only display this navigation data if both the target bearing and crosstrack error are valid
    if (shouldDisplayNavigationData() && !isnan(navigationTargetBearing) && !isnan(navigationCrosstrackError)) {
880 881 882 883 884
        painter.resetTransform();
        painter.translate(area.center());
        // TODO : Sign might be wrong?
        // TODO : The case where error exceeds max. Truncate to max. and make that visible somehow.
        bool errorBeyondRadius = false;
Don Gagne's avatar
Don Gagne committed
885
        if (fabs(navigationCrosstrackError) > CROSSTRACK_MAX) {
886 887 888 889 890 891 892
            errorBeyondRadius = true;
            navigationCrosstrackError = navigationCrosstrackError>0 ? CROSSTRACK_MAX : -CROSSTRACK_MAX;
        }

        float r = radius * CROSSTRACK_RADIUS;
        float x = navigationCrosstrackError / CROSSTRACK_MAX * r;
        float y = qSqrt(r*r - x*x); // the positive y, there is also a negative.
dongfang's avatar
dongfang committed
893

894 895 896 897 898 899 900
        float sillyHeading = 0;
        float angle = sillyHeading - navigationTargetBearing; // TODO: sign.
        painter.rotate(-angle);

        QPen pen;
        pen.setWidthF(lineWidth);
        pen.setColor(Qt::black);
901 902 903
        if(errorBeyondRadius) {
            pen.setStyle(Qt::DotLine);
        }
904 905 906 907 908 909
        painter.setPen(pen);

        painter.drawLine(QPointF(x, y), QPointF(x, -y));
    }
}

910 911
void PrimaryFlightDisplay::drawAltimeter(
        QPainter& painter,
912
        QRectF area
913
    ) {
914

915
    float primaryAltitude = altitudeWGS84;
916
    float secondaryAltitude = std::numeric_limits<double>::quiet_NaN();
917

918
    painter.resetTransform();
919
    fillInstrumentBackground(painter, area);
920

dongfang's avatar
dongfang committed
921 922
    QPen pen;
    pen.setWidthF(lineWidth);
dongfang's avatar
dongfang committed
923

dongfang's avatar
dongfang committed
924 925
    pen.setColor(Qt::white);
    painter.setPen(pen);
926

dongfang's avatar
dongfang committed
927 928
    float h = area.height();
    float w = area.width();
929
    float secondaryAltitudeBoxHeight = mediumTextSize * 2;
dongfang's avatar
dongfang committed
930
    // The height where we being with new tickmarks.
dongfang's avatar
dongfang committed
931
    float effectiveHalfHeight = h*0.45;
932 933

    // not yet implemented: Display of secondary altitude.
934
    if (!isnan(secondaryAltitude)) {
935
        effectiveHalfHeight -= secondaryAltitudeBoxHeight;
936
    }
937

938
    float markerHalfHeight = mediumTextSize;
dongfang's avatar
dongfang committed
939 940 941 942 943
    float leftEdge = instrumentEdgePen.widthF()*2;
    float rightEdge = w-leftEdge;
    float tickmarkLeft = leftEdge;
    float tickmarkRightMajor = tickmarkLeft+TAPE_GAUGES_TICKWIDTH_MAJOR*w;
    float tickmarkRightMinor = tickmarkLeft+TAPE_GAUGES_TICKWIDTH_MINOR*w;
dongfang's avatar
dongfang committed
944
    float numbersLeft = 0.42*w;
dongfang's avatar
dongfang committed
945
    float markerTip = (tickmarkLeft*2+tickmarkRightMajor)/3;
946 947 948
	float markerOffset = 0.2* markerHalfHeight;
	float scaleCenterAltitude = isnan(primaryAltitude) ? 0 : primaryAltitude;
	
949
    // altitude scale
dongfang's avatar
dongfang committed
950 951
    float start = scaleCenterAltitude - ALTIMETER_LINEAR_SPAN/2;
    float end = scaleCenterAltitude + ALTIMETER_LINEAR_SPAN/2;
952 953 954
    int firstTick = ceil(start / ALTIMETER_LINEAR_RESOLUTION) * ALTIMETER_LINEAR_RESOLUTION;
    int lastTick = floor(end / ALTIMETER_LINEAR_RESOLUTION) * ALTIMETER_LINEAR_RESOLUTION;
    for (int tickAlt = firstTick; tickAlt <= lastTick; tickAlt += ALTIMETER_LINEAR_RESOLUTION) {
dongfang's avatar
dongfang committed
955 956
        float y = (tickAlt-scaleCenterAltitude)*effectiveHalfHeight/(ALTIMETER_LINEAR_SPAN/2);
        bool isMajor = tickAlt % ALTIMETER_LINEAR_MAJOR_RESOLUTION == 0;
957

958 959
        painter.resetTransform();
        painter.translate(area.left(), area.center().y() - y);
dongfang's avatar
dongfang committed
960 961 962 963
        pen.setColor(tickAlt<0 ? redColor : Qt::white);
        painter.setPen(pen);
        if (isMajor) {
            painter.drawLine(tickmarkLeft, 0, tickmarkRightMajor, 0);
964
            QString s_alt;
dongfang's avatar
dongfang committed
965
            s_alt.sprintf("%d", abs(tickAlt));
dongfang's avatar
dongfang committed
966
            drawTextLeftCenter(painter, s_alt, mediumTextSize, numbersLeft, 0);
dongfang's avatar
dongfang committed
967 968
        } else {
            painter.drawLine(tickmarkLeft, 0, tickmarkRightMinor, 0);
969 970 971
        }
    }

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    QPainterPath primaryMarkerPath(QPoint(markerTip, 0));
	primaryMarkerPath.lineTo(markerTip + markerHalfHeight, markerHalfHeight);
	primaryMarkerPath.lineTo(rightEdge, markerHalfHeight);
	primaryMarkerPath.lineTo(rightEdge, -markerHalfHeight);
	primaryMarkerPath.lineTo(markerTip + markerHalfHeight, -markerHalfHeight);
	primaryMarkerPath.closeSubpath();

	QPainterPath secondaryMarkerPath(QPoint(markerTip + markerHalfHeight, markerHalfHeight + markerOffset));
	if (!isnan(climbRate)) {
		secondaryMarkerPath.lineTo(markerTip + markerHalfHeight, 2 * markerHalfHeight + markerOffset);
		secondaryMarkerPath.lineTo(rightEdge, 2 * markerHalfHeight + markerOffset);
		secondaryMarkerPath.lineTo(rightEdge, 1 * markerHalfHeight + markerOffset);
		secondaryMarkerPath.closeSubpath();
	}

	painter.resetTransform();
988
    painter.translate(area.left(), area.center().y());
dongfang's avatar
dongfang committed
989

dongfang's avatar
dongfang committed
990
    pen.setWidthF(lineWidth);
dongfang's avatar
dongfang committed
991 992 993
    pen.setColor(Qt::white);
    painter.setPen(pen);

994
    painter.setBrush(Qt::SolidPattern);
995 996
    painter.drawPath(primaryMarkerPath);
	if (!isnan(climbRate)) painter.drawPath(secondaryMarkerPath);
997 998
    painter.setBrush(Qt::NoBrush);

dongfang's avatar
dongfang committed
999 1000
    pen.setColor(Qt::white);
    painter.setPen(pen);
1001
	
1002
    QString s_alt;
1003
    if (isnan(primaryAltitude))
dongfang's avatar
dongfang committed
1004 1005
        s_alt.sprintf("---");
    else
1006
        s_alt.sprintf("h:%3.0f", primaryAltitude);
dongfang's avatar
dongfang committed
1007

1008
    drawTextRightCenter(painter, s_alt, mediumTextSize, rightEdge - 4 * lineWidth, 0);
dongfang's avatar
dongfang committed
1009

1010
    // draw simple in-tape VVI.
1011
    if (!isnan(climbRate)) {
1012 1013 1014 1015
		// Draw label
		QString s_climb;
		s_climb.sprintf("vZ:%2.1f", climbRate);
		drawTextRightCenter(painter, s_climb, smallTextSize, rightEdge - 4 * lineWidth, 1.5*mediumTextSize + markerOffset);
1016

1017 1018
		// Draw climb rate indicator as an arrow
		float vvPixHeight = -climbRate/ALTIMETER_VVI_SPAN * effectiveHalfHeight;
1019
		if (vvPixHeight > -markerHalfHeight && vvPixHeight < 2 * markerHalfHeight + markerOffset)
1020
            return; // hidden behind marker.
dongfang's avatar
dongfang committed
1021

1022
        float vvSign = vvPixHeight>0 ? 1 : -1; // reverse y sign
dongfang's avatar
dongfang committed
1023

1024
		QPointF vvArrowBegin(rightEdge - w*ALTIMETER_VVI_WIDTH / 2, (vvSign>0 ? 2*markerHalfHeight+markerOffset : -markerHalfHeight));
1025 1026
        QPointF vvArrowEnd(rightEdge - w*ALTIMETER_VVI_WIDTH/2, vvPixHeight);
        painter.drawLine(vvArrowBegin, vvArrowEnd);
dongfang's avatar
dongfang committed
1027

1028
        // Yeah this is a repetition of above code but we are going to trash it all anyway, so no fix.
Don Gagne's avatar
Don Gagne committed
1029
        float vvArowHeadSize = fabs(vvPixHeight - markerHalfHeight*vvSign);
1030
        if (vvArowHeadSize > w*ALTIMETER_VVI_WIDTH/3) vvArowHeadSize = w*ALTIMETER_VVI_WIDTH/3;
1031

1032
        float xcenter = rightEdge-w*ALTIMETER_VVI_WIDTH/2;
1033

1034 1035
        QPointF vvArrowHead(xcenter+vvArowHeadSize, vvPixHeight - vvSign *vvArowHeadSize);
        painter.drawLine(vvArrowHead, vvArrowEnd);
dongfang's avatar
dongfang committed
1036

1037 1038
        vvArrowHead = QPointF(xcenter-vvArowHeadSize, vvPixHeight - vvSign * vvArowHeadSize);
        painter.drawLine(vvArrowHead, vvArrowEnd);
1039 1040 1041
    }

    // print secondary altitude
1042
    if (!isnan(secondaryAltitude)) {
1043 1044 1045 1046 1047 1048 1049
        QRectF saBox(area.x(), area.y()-secondaryAltitudeBoxHeight, w, secondaryAltitudeBoxHeight);
        painter.resetTransform();
        painter.translate(saBox.center());
        QString s_salt;
        s_salt.sprintf("%3.0f", secondaryAltitude);
        drawTextCenter(painter, s_salt, mediumTextSize, 0, 0);
    }
1050 1051
}

1052
void PrimaryFlightDisplay::drawVelocityMeter(
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	QPainter& painter,
	QRectF area
	) {

	painter.resetTransform();
	fillInstrumentBackground(painter, area);

	QPen pen;
	pen.setWidthF(lineWidth);

	float h = area.height();
	float w = area.width();
	float effectiveHalfHeight = h*0.45;
	float markerHalfHeight = mediumTextSize;
	float leftEdge = instrumentEdgePen.widthF() * 2;
	float tickmarkRight = w - leftEdge;
	float tickmarkLeftMajor = tickmarkRight - w*TAPE_GAUGES_TICKWIDTH_MAJOR;
	float tickmarkLeftMinor = tickmarkRight - w*TAPE_GAUGES_TICKWIDTH_MINOR;
	float numbersRight = 0.42*w;
	float markerTip = (tickmarkLeftMajor + tickmarkRight * 2) / 3;
	float markerOffset = 0.2 * markerHalfHeight;

	// Select between air and ground speed:
1076 1077 1078 1079
	bool bSpeedIsAirspeed = (isAirplane() && !isnan(airSpeed));
	float primarySpeed = bSpeedIsAirspeed ? airSpeed : groundSpeed;
	float secondarySpeed = !bSpeedIsAirspeed ? airSpeed : groundSpeed;
	float centerScaleSpeed = isnan(primarySpeed) ? 0 : primarySpeed;
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
	
	float start = centerScaleSpeed - AIRSPEED_LINEAR_SPAN / 2;
	float end = centerScaleSpeed + AIRSPEED_LINEAR_SPAN / 2;

	int firstTick = ceil(start / AIRSPEED_LINEAR_RESOLUTION) * AIRSPEED_LINEAR_RESOLUTION;
	int lastTick = floor(end / AIRSPEED_LINEAR_RESOLUTION) * AIRSPEED_LINEAR_RESOLUTION;
	for (int tickSpeed = firstTick; tickSpeed <= lastTick; tickSpeed += AIRSPEED_LINEAR_RESOLUTION) {
		pen.setColor(tickSpeed < 0 ? redColor : Qt::white);
		painter.setPen(pen);

		float y = (tickSpeed - centerScaleSpeed)*effectiveHalfHeight / (AIRSPEED_LINEAR_SPAN / 2);
		bool hasText = tickSpeed % AIRSPEED_LINEAR_MAJOR_RESOLUTION == 0;
		painter.resetTransform();

		painter.translate(area.left(), area.center().y() - y);

		if (hasText) {
			painter.drawLine(tickmarkLeftMajor, 0, tickmarkRight, 0);
			QString s_speed;
			s_speed.sprintf("%d", abs(tickSpeed));
			drawTextRightCenter(painter, s_speed, mediumTextSize, numbersRight, 0);
		}
		else {
			painter.drawLine(tickmarkLeftMinor, 0, tickmarkRight, 0);
		}
	}

	//Paint the label background
	QPainterPath primaryMarkerPath(QPoint(markerTip, 0));
	primaryMarkerPath.lineTo(markerTip - markerHalfHeight, markerHalfHeight);
	primaryMarkerPath.lineTo(leftEdge, markerHalfHeight);
	primaryMarkerPath.lineTo(leftEdge, -markerHalfHeight);
	primaryMarkerPath.lineTo(markerTip - markerHalfHeight, -markerHalfHeight);
	primaryMarkerPath.closeSubpath();

	QPainterPath secondaryMarkerPath(QPoint(markerTip - markerHalfHeight, 1 * markerHalfHeight + markerOffset));
	if (!isnan(secondarySpeed)) {
		secondaryMarkerPath.lineTo(markerTip - markerHalfHeight, 2 * markerHalfHeight + markerOffset);
		secondaryMarkerPath.lineTo(leftEdge, 2 * markerHalfHeight + markerOffset);
		secondaryMarkerPath.lineTo(leftEdge, 1 * markerHalfHeight + markerOffset);
		secondaryMarkerPath.closeSubpath();
	}
	
	painter.resetTransform();
	painter.translate(area.left(), area.center().y());

	pen.setWidthF(lineWidth);
1127
	pen.setColor(Qt::white);
1128
	painter.setPen(pen);
1129

1130 1131 1132 1133 1134 1135
	painter.setBrush(Qt::SolidPattern);
	painter.drawPath(primaryMarkerPath);
	if (!isnan(secondarySpeed)) painter.drawPath(secondaryMarkerPath);
	painter.setBrush(Qt::NoBrush);

	// Draw primary speed
1136 1137
	pen.setColor(Qt::white);
	painter.setPen(pen);
1138 1139
	QString s_alt;
	if (isnan(primarySpeed))
1140 1141
		s_alt.sprintf("---");
	else
1142 1143 1144 1145 1146 1147 1148
		s_alt.sprintf("%s:%3.1f", (bSpeedIsAirspeed ? "AS" : "GS"), primarySpeed);
	drawTextLeftCenter(painter, s_alt, mediumTextSize, 4 * lineWidth, 0);

	// Draw secondary speed
	if (!isnan(secondarySpeed)) {
		pen.setColor(Qt::white);
		painter.setPen(pen);
1149
		s_alt.sprintf("%s:%3.1f", (!bSpeedIsAirspeed ? "AS" : "GS"), secondarySpeed);
1150 1151
		drawTextLeftCenter(painter, s_alt, smallTextSize, 4 * lineWidth, 1.5 * markerHalfHeight + markerOffset);
	}
1152 1153
}

1154 1155 1156 1157
static const int TOP = (1<<0);
static const int BOTTOM = (1<<1);
static const int LEFT = (1<<2);
static const int RIGHT = (1<<3);
dongfang's avatar
dongfang committed
1158

1159 1160 1161 1162
static const int TOP_HALF = (1<<4);
static const int BOTTOM_HALF = (1<<5);
static const int LEFT_HALF = (1<<6);
static const int RIGHT_HALF = (1<<7);
dongfang's avatar
dongfang committed
1163 1164 1165 1166 1167 1168 1169 1170 1171

void applyMargin(QRectF& area, float margin, int where) {
    if (margin < 0.01) return;

    QRectF save(area);
    qreal consumed;

    if (where & LEFT) {
        area.setX(save.x() + (consumed = margin));
1172
    } else if (where & LEFT_HALF) {
dongfang's avatar
dongfang committed
1173 1174 1175 1176 1177 1178 1179
        area.setX(save.x() + (consumed = margin/2));
    } else {
        consumed = 0;
    }

    if (where & RIGHT) {
        area.setWidth(save.width()-consumed-margin);
1180
    } else if (where & RIGHT_HALF) {
dongfang's avatar
dongfang committed
1181 1182 1183 1184 1185 1186 1187
        area.setWidth(save.width()-consumed-margin/2);
    } else {
        area.setWidth(save.width()-consumed);
    }

    if (where & TOP) {
        area.setY(save.y() + (consumed = margin));
1188
    } else if (where & TOP_HALF) {
dongfang's avatar
dongfang committed
1189 1190 1191 1192 1193 1194 1195
        area.setY(save.y() + (consumed = margin/2));
    } else {
        consumed = 0;
    }

    if (where & BOTTOM) {
        area.setHeight(save.height()-consumed-margin);
1196
    } else if (where & BOTTOM_HALF) {
dongfang's avatar
dongfang committed
1197 1198 1199 1200 1201 1202 1203
        area.setHeight(save.height()-consumed-margin/2);
    } else {
        area.setHeight(save.height()-consumed);
    }
}

void setMarginsForInlineLayout(qreal margin, QRectF& panel1, QRectF& panel2, QRectF& panel3, QRectF& panel4) {
1204 1205 1206 1207
    applyMargin(panel1, margin, BOTTOM|LEFT|RIGHT_HALF);
    applyMargin(panel2, margin, BOTTOM|LEFT_HALF|RIGHT_HALF);
    applyMargin(panel3, margin, BOTTOM|LEFT_HALF|RIGHT_HALF);
    applyMargin(panel4, margin, BOTTOM|LEFT_HALF|RIGHT);
1208 1209
}

dongfang's avatar
dongfang committed
1210
void setMarginsForCornerLayout(qreal margin, QRectF& panel1, QRectF& panel2, QRectF& panel3, QRectF& panel4) {
1211 1212 1213 1214
    applyMargin(panel1, margin, BOTTOM|LEFT|RIGHT_HALF);
    applyMargin(panel2, margin, BOTTOM|LEFT_HALF|RIGHT_HALF);
    applyMargin(panel3, margin, BOTTOM|LEFT_HALF|RIGHT_HALF);
    applyMargin(panel4, margin, BOTTOM|LEFT_HALF|RIGHT);
dongfang's avatar
dongfang committed
1215 1216 1217 1218
}

inline qreal tapesGaugeWidthFor(qreal containerWidth, qreal preferredAIWidth) {
    qreal result = (containerWidth - preferredAIWidth) / 2.0f;
dongfang's avatar
dongfang committed
1219
    qreal minimum = containerWidth / 5.5f;
dongfang's avatar
dongfang committed
1220 1221 1222 1223 1224
    if (result < minimum) result = minimum;
    return result;
}

void PrimaryFlightDisplay::doPaint() {
1225 1226 1227 1228 1229
    QPainter painter;
    painter.begin(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::HighQualityAntialiasing, true);

dongfang's avatar
dongfang committed
1230
    qreal margin = height()/100.0f;
1231

1232 1233 1234 1235 1236
    // The AI centers on this area.
    QRectF AIMainArea;
    // The AI paints on this area. It should contain the AIMainArea.
    QRectF AIPaintArea;

dongfang's avatar
dongfang committed
1237 1238 1239 1240 1241 1242 1243
    QRectF compassArea;
    QRectF altimeterArea;
    QRectF velocityMeterArea;
    QRectF sensorsStatsArea;
    QRectF linkStatsArea;
    QRectF sysStatsArea;
    QRectF missionStatsArea;
1244 1245

    painter.fillRect(rect(), Qt::black);
dongfang's avatar
dongfang committed
1246 1247
    qreal tapeGaugeWidth;

dongfang's avatar
dongfang committed
1248 1249 1250
    qreal compassHalfSpan = 180;
    float compassAIIntrusion = 0;

dongfang's avatar
dongfang committed
1251
    switch(layout) {
1252
    case COMPASS_INTEGRATED: {
dongfang's avatar
dongfang committed
1253
        tapeGaugeWidth = tapesGaugeWidthFor(width(), width());
1254
        qreal aiheight = height();
dongfang's avatar
dongfang committed
1255 1256
        qreal aiwidth = width()-tapeGaugeWidth*2;
        if (aiheight > aiwidth) aiheight = aiwidth;
1257 1258 1259 1260

        AIMainArea = QRectF(
                    tapeGaugeWidth,
                    0,
dongfang's avatar
dongfang committed
1261
                    aiwidth,
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
                    aiheight);

        AIPaintArea = QRectF(
                    0,
                    0,
                    width(),
                    height());

        // Tape gauges get so much width that the AI area not covered by them is perfectly square.
        velocityMeterArea = QRectF (0, 0, tapeGaugeWidth, aiheight);
        altimeterArea = QRectF(AIMainArea.right(), 0, tapeGaugeWidth, aiheight);

        if (style == NO_OVERLAYS) {
            applyMargin(AIMainArea, margin, TOP|BOTTOM);
            applyMargin(altimeterArea, margin, TOP|BOTTOM|RIGHT);
            applyMargin(velocityMeterArea, margin, TOP|BOTTOM|LEFT);
            setMarginsForInlineLayout(margin, sensorsStatsArea, linkStatsArea, sysStatsArea, missionStatsArea);
        }

dongfang's avatar
dongfang committed
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
        qreal compassRelativeWidth = 0.75;
        qreal compassBottomMargin = 0.78;

        qreal compassSize = compassRelativeWidth  * AIMainArea.width();  // Diameter is this times the width.

        qreal compassCenterY;
        compassCenterY = AIMainArea.bottom() + compassSize / 4;

        if (height() - compassCenterY > AIMainArea.width()/2*compassBottomMargin)
            compassCenterY = height()-AIMainArea.width()/2*compassBottomMargin;

        // TODO: This is bad style...
        compassCenterY = (compassCenterY * 2 + AIMainArea.bottom() + compassSize / 4) / 3;

        compassArea = QRectF(AIMainArea.x()+(1-compassRelativeWidth)/2*AIMainArea.width(),
                             compassCenterY-compassSize/2,
                             compassSize,
                             compassSize);

        if (height()-compassCenterY < compassSize/2) {
            compassHalfSpan = acos((compassCenterY-height())*2/compassSize) * 180/M_PI + COMPASS_DISK_RESOLUTION;
            if (compassHalfSpan > 180) compassHalfSpan = 180;
        }

        compassAIIntrusion = compassSize/2 + AIMainArea.bottom() - compassCenterY;
        if (compassAIIntrusion<0) compassAIIntrusion = 0;

1308 1309
        break;
    }
dongfang's avatar
dongfang committed
1310 1311 1312 1313
    case COMPASS_SEPARATED: {
        // A layout for containers higher than their width.
        tapeGaugeWidth = tapesGaugeWidthFor(width(), width());

1314 1315
        qreal aiheight = width() - tapeGaugeWidth*2;
        qreal panelsHeight = 0;
dongfang's avatar
dongfang committed
1316

1317 1318
        AIMainArea = QRectF(
                    tapeGaugeWidth,
dongfang's avatar
dongfang committed
1319
                    0,
1320
                    width()-tapeGaugeWidth*2,
dongfang's avatar
dongfang committed
1321 1322
                    aiheight);

1323 1324 1325 1326 1327 1328 1329
        AIPaintArea = style == OVERLAY_HSI ?
                    QRectF(
                    0,
                    0,
                    width(),
                    height() - panelsHeight) : AIMainArea;

dongfang's avatar
dongfang committed
1330
        velocityMeterArea = QRectF (0, 0, tapeGaugeWidth, aiheight);
1331
        altimeterArea = QRectF(AIMainArea.right(), 0, tapeGaugeWidth, aiheight);
dongfang's avatar
dongfang committed
1332

1333 1334
        QPoint compassCenter = QPoint(width()/2, AIMainArea.bottom()+width()/2);
        qreal compassDiam = width() * 0.8;
dongfang's avatar
dongfang committed
1335
        compassArea = QRectF(compassCenter.x()-compassDiam/2, compassCenter.y()-compassDiam/2, compassDiam, compassDiam);
dongfang's avatar
dongfang committed
1336 1337 1338
        break;
    }
    }
1339

dongfang's avatar
dongfang committed
1340
    bool hadClip = painter.hasClipping();
dongfang's avatar
dongfang committed
1341

dongfang's avatar
dongfang committed
1342
    painter.setClipping(true);
1343
    painter.setClipRect(AIPaintArea);
1344

1345
    drawAIGlobalFeatures(painter, AIMainArea, AIPaintArea);
dongfang's avatar
dongfang committed
1346
    drawAIAttitudeScales(painter, AIMainArea, compassAIIntrusion);
1347
    drawAIAirframeFixedFeatures(painter, AIMainArea);
1348

1349
    drawAICompassDisk(painter, compassArea, compassHalfSpan);
1350

dongfang's avatar
dongfang committed
1351
    painter.setClipping(hadClip);
1352

1353
    drawAltimeter(painter, altimeterArea);
1354

1355
    drawVelocityMeter(painter, velocityMeterArea);
1356

dongfang's avatar
dongfang committed
1357
    painter.end();
1358
}