HDDisplay.cc 27.3 KB
Newer Older
pixhawk's avatar
pixhawk committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/*=====================================================================

PIXHAWK Micro Air Vehicle Flying Robotics Toolkit

(c) 2009, 2010 PIXHAWK PROJECT  <http://pixhawk.ethz.ch>

This file is part of the PIXHAWK project

    PIXHAWK is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    PIXHAWK is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PIXHAWK. If not, see <http://www.gnu.org/licenses/>.

======================================================================*/

/**
 * @file
 *   @brief Implementation of Head Down Display (HDD)
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include <QFile>
#include <QGLWidget>
pixhawk's avatar
pixhawk committed
34
#include <QStringList>
35 36
#include <QGraphicsTextItem>
#include <QMouseEvent>
pixhawk's avatar
pixhawk committed
37 38 39
#include "UASManager.h"
#include "HDDisplay.h"
#include "ui_HDDisplay.h"
40
#include "MG.h"
41
#include "QGC.h"
42 43 44
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
pixhawk's avatar
pixhawk committed
45 46
#include <QDebug>

pixhawk's avatar
pixhawk committed
47
HDDisplay::HDDisplay(QStringList* plotList, QWidget *parent) :
48
        QGraphicsView(parent),
pixhawk's avatar
pixhawk committed
49 50 51 52 53 54
        uas(NULL),
        values(QMap<QString, float>()),
        valuesDot(QMap<QString, float>()),
        valuesMean(QMap<QString, float>()),
        valuesCount(QMap<QString, int>()),
        lastUpdate(QMap<QString, quint64>()),
pixhawk's avatar
pixhawk committed
55 56 57 58
        minValues(),
        maxValues(),
        goodRanges(),
        critRanges(),
pixhawk's avatar
pixhawk committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
        xCenterOffset(0.0f),
        yCenterOffset(0.0f),
        vwidth(80.0f),
        vheight(80.0f),
        backgroundColor(QColor(0, 0, 0)),
        defaultColor(QColor(70, 200, 70)),
        setPointColor(QColor(200, 20, 200)),
        warningColor(Qt::yellow),
        criticalColor(Qt::red),
        infoColor(QColor(20, 200, 20)),
        fuelColor(criticalColor),
        warningBlinkRate(5),
        refreshTimer(new QTimer(this)),
        hardwareAcceleration(true),
        strongStrokeWidth(1.5f),
        normalStrokeWidth(1.0f),
        fineStrokeWidth(0.5f),
pixhawk's avatar
pixhawk committed
76
        acceptList(plotList),
77
        lastPaintTime(0),
pixhawk's avatar
pixhawk committed
78 79 80 81
        m_ui(new Ui::HDDisplay)
{
    //m_ui->setupUi(this);

82 83 84 85 86 87
        // Check if acceptlist exists
    if (!acceptList)
    {
        acceptList = new QStringList();
    }

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
//    setBackgroundBrush(QBrush(backgroundColor));
//    setDragMode(QGraphicsView::ScrollHandDrag);
//    setCacheMode(QGraphicsView::CacheBackground);
//    // FIXME Handle full update with care - ressource intensive
//    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
//
//    setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
//
//    //Set-up the scene
//    QGraphicsScene* Scene = new QGraphicsScene(this);
//    setScene(Scene);
//
//    //Populate the scene
//    for(int x = 0; x < 1000; x = x + 25) {
//        for(int y = 0; y < 1000; y = y + 25) {
//
//            if(x % 100 == 0 && y % 100 == 0) {
//                Scene->addRect(x, y, 2, 2);
//
//                QString pointString;
//                QTextStream stream(&pointString);
//                stream << "(" << x << "," << y << ")";
//                QGraphicsTextItem* item = Scene->addText(pointString);
//                item->setPos(x, y);
//            } else {
//                Scene->addRect(x, y, 1, 1);
//            }
//        }
//    }
//
//    //Set-up the view
//    setSceneRect(0, 0, 1000, 1000);
//    setCenter(QPointF(500.0, 500.0)); //A modified version of centerOn(), handles special cases
//    setCursor(Qt::OpenHandCursor);


124 125
    this->setMinimumHeight(125);
    this->setMinimumWidth(100);
pixhawk's avatar
pixhawk committed
126 127

    // Refresh timer
128
    refreshTimer->setInterval(180); //
129
    connect(refreshTimer, SIGNAL(timeout()), this, SLOT(triggerUpdate()));
pixhawk's avatar
pixhawk committed
130 131 132 133 134 135 136 137
    //connect(refreshTimer, SIGNAL(timeout()), this, SLOT(paintGL()));

    fontDatabase = QFontDatabase();
    const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app
    const QString fontFamilyName = "Bitstream Vera Sans";
    if(!QFile::exists(fontFileName)) qDebug() << "ERROR! font file: " << fontFileName << " DOES NOT EXIST!";

    fontDatabase.addApplicationFont(fontFileName);
138
    font = fontDatabase.font(fontFamilyName, "Roman", qMax(5, (int)(10*scalingFactor*1.2f+0.5f)));
pixhawk's avatar
pixhawk committed
139 140 141
    if (font.family() != fontFamilyName) qDebug() << "ERROR! Font not loaded: " << fontFamilyName;

    // Connect with UAS
pixhawk's avatar
pixhawk committed
142
    connect(UASManager::instance(), SIGNAL(activeUASSet(UASInterface*)), this, SLOT(setActiveUAS(UASInterface*)));
pixhawk's avatar
pixhawk committed
143
    //start();
144 145

    this->setVisible(false);
pixhawk's avatar
pixhawk committed
146 147 148 149 150 151 152
}

HDDisplay::~HDDisplay()
{
    delete m_ui;
}

153 154
void HDDisplay::enableGLRendering(bool enable)
{
155
    Q_UNUSED(enable)
156 157
}

158 159 160
void HDDisplay::triggerUpdate()
{
    // Only repaint the regions necessary
161
    update(this->geometry());
162 163
}

pixhawk's avatar
pixhawk committed
164 165
void HDDisplay::paintEvent(QPaintEvent * event)
{
166
    Q_UNUSED(event);
167
    static quint64 interval = 0;
lm's avatar
lm committed
168
    //qDebug() << "INTERVAL:" << MG::TIME::getGroundTimeNow() - interval << __FILE__ << __LINE__;
169
    interval = MG::TIME::getGroundTimeNow();
170
    renderOverlay();
171 172
}

173
void HDDisplay::renderOverlay()
174
{
175 176 177
#if (QGC_EVENTLOOP_DEBUG)
    qDebug() << "EVENTLOOP:" << __FILE__ << __LINE__;
#endif
178
    quint64 refreshInterval = 100;
179 180 181 182 183 184 185
    quint64 currTime = MG::TIME::getGroundTimeNow();
    if (currTime - lastPaintTime < refreshInterval)
    {
        // FIXME Need to find the source of the spurious paint events
        //return;
    }
    lastPaintTime = currTime;
pixhawk's avatar
pixhawk committed
186 187 188 189 190 191 192 193
    // Draw instruments
    // TESTING THIS SHOULD BE MOVED INTO A QGRAPHICSVIEW
    // Update scaling factor
    // adjust scaling to fit both horizontally and vertically
    scalingFactor = this->width()/vwidth;
    double scalingFactorH = this->height()/vheight;
    if (scalingFactorH < scalingFactor) scalingFactor = scalingFactorH;

194
    QPainter painter(viewport());
pixhawk's avatar
pixhawk committed
195 196
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::HighQualityAntialiasing, true);
197
    //painter.fillRect(QRect(0, 0, width(), height()), backgroundColor);
pixhawk's avatar
pixhawk committed
198 199
    const int columns = 3;
    const float spacing = 0.4f; // 40% of width
200
    const float gaugeWidth = vwidth / (((float)columns) + (((float)columns+1) * spacing + spacing * 0.5f));
pixhawk's avatar
pixhawk committed
201
    const QColor gaugeColor = QColor(200, 200, 200);
pixhawk's avatar
pixhawk committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215
    //drawSystemIndicator(10.0f-gaugeWidth/2.0f, 20.0f, 10.0f, 40.0f, 15.0f, &painter);
    //drawGauge(15.0f, 15.0f, gaugeWidth/2.0f, 0, 1.0f, "thrust", values.value("thrust", 0.0f), gaugeColor, &painter, qMakePair(0.45f, 0.8f), qMakePair(0.8f, 1.0f), true);
    //drawGauge(15.0f+gaugeWidth*1.7f, 15.0f, gaugeWidth/2.0f, 0, 10.0f, "altitude", values.value("altitude", 0.0f), gaugeColor, &painter, qMakePair(1.0f, 2.5f), qMakePair(0.0f, 0.5f), true);

    // Left spacing from border / other gauges, measured from left edge to center
    float leftSpacing = gaugeWidth * spacing;
    float xCoord = leftSpacing + gaugeWidth/2.0f;

    float topSpacing = leftSpacing;
    float yCoord = topSpacing + gaugeWidth/2.0f;

    for (int i = 0; i < acceptList->size(); ++i)
    {
        QString value = acceptList->at(i);
216
        drawGauge(xCoord, yCoord, gaugeWidth/2.0f, minValues.value(value, -1.0f), maxValues.value(value, 1.0f), value, values.value(value, minValues.value(value, 0.0f)), gaugeColor, &painter, goodRanges.value(value, qMakePair(0.0f, 0.5f)), critRanges.value(value, qMakePair(0.7f, 1.0f)), true);
pixhawk's avatar
pixhawk committed
217 218 219 220 221 222 223 224
        xCoord += gaugeWidth + leftSpacing;
        // Move one row down if necessary
        if (xCoord + gaugeWidth > vwidth)
        {
            yCoord += topSpacing + gaugeWidth;
            xCoord = leftSpacing + gaugeWidth/2.0f;
        }
    }
pixhawk's avatar
pixhawk committed
225 226 227 228 229 230 231 232
}

/**
 *
 * @param uas the UAS/MAV to monitor/display with the HUD
 */
void HDDisplay::setActiveUAS(UASInterface* uas)
{
pixhawk's avatar
pixhawk committed
233
    //qDebug() << "ATTEMPTING TO SET UAS";
pixhawk's avatar
pixhawk committed
234
    if (this->uas != NULL)
pixhawk's avatar
pixhawk committed
235 236
    {
        // Disconnect any previously connected active MAV
237
        disconnect(this->uas, SIGNAL(valueChanged(UASInterface*,QString,double,quint64)), this, SLOT(updateValue(UASInterface*,QString,double,quint64)));
pixhawk's avatar
pixhawk committed
238 239 240 241
    }

    // Now connect the new UAS

pixhawk's avatar
pixhawk committed
242
    //qDebug() << "UAS SET!" << "ID:" << uas->getUASID();
pixhawk's avatar
pixhawk committed
243 244
    // Setup communication
    connect(uas, SIGNAL(valueChanged(UASInterface*,QString,double,quint64)), this, SLOT(updateValue(UASInterface*,QString,double,quint64)));
pixhawk's avatar
pixhawk committed
245
    this->uas = uas;
pixhawk's avatar
pixhawk committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
}

/**
 * Rotate a polygon around a point
 *
 * @param p polygon to rotate
 * @param origin the rotation center
 * @param angle rotation angle, in radians
 * @return p Polygon p rotated by angle around the origin point
 */
void HDDisplay::rotatePolygonClockWiseRad(QPolygonF& p, float angle, QPointF origin)
{
    // Standard 2x2 rotation matrix, counter-clockwise
    //
    //   |  cos(phi)   sin(phi) |
    //   | -sin(phi)   cos(phi) |
    //
    for (int i = 0; i < p.size(); i++)
    {
        QPointF curr = p.at(i);

        const float x = curr.x();
        const float y = curr.y();

        curr.setX(((cos(angle) * (x-origin.x())) + (-sin(angle) * (y-origin.y()))) + origin.x());
        curr.setY(((sin(angle) * (x-origin.x())) + (cos(angle) * (y-origin.y()))) + origin.y());
        p.replace(i, curr);
    }
}

void HDDisplay::drawPolygon(QPolygonF refPolygon, QPainter* painter)
{
    // Scale coordinates
    QPolygonF draw(refPolygon.size());
    for (int i = 0; i < refPolygon.size(); i++)
    {
        QPointF curr;
        curr.setX(refToScreenX(refPolygon.at(i).x()));
        curr.setY(refToScreenY(refPolygon.at(i).y()));
        draw.replace(i, curr);
    }
    painter->drawPolygon(draw);
}

void HDDisplay::drawChangeRateStrip(float xRef, float yRef, float height, float minRate, float maxRate, float value, QPainter* painter)
{
    QBrush brush(defaultColor, Qt::NoBrush);
    painter->setBrush(brush);
    QPen rectPen(Qt::SolidLine);
    rectPen.setWidth(0);
    rectPen.setColor(defaultColor);
    painter->setPen(rectPen);

    float scaledValue = value;

    // Saturate value
    if (value > maxRate) scaledValue = maxRate;
    if (value < minRate) scaledValue = minRate;

    //           x (Origin: xRef, yRef)
    //           -
    //           |
    //           |
    //           |
    //           =
    //           |
    //   -0.005 >|
    //           |
    //           -

    const float width = height / 8.0f;
    const float lineWidth = 0.5f;

    // Indicator lines
    // Top horizontal line
    drawLine(xRef, yRef, xRef+width, yRef, lineWidth, defaultColor, painter);
    // Vertical main line
    drawLine(xRef+width/2.0f, yRef, xRef+width/2.0f, yRef+height, lineWidth, defaultColor, painter);
    // Zero mark
    drawLine(xRef, yRef+height/2.0f, xRef+width, yRef+height/2.0f, lineWidth, defaultColor, painter);
    // Horizontal bottom line
    drawLine(xRef, yRef+height, xRef+width, yRef+height, lineWidth, defaultColor, painter);

    // Text
    QString label;
    label.sprintf("< %06.2f", value);
    paintText(label, defaultColor, 3.0f, xRef+width/2.0f, yRef+height-((scaledValue - minRate)/(maxRate-minRate))*height - 1.6f, painter);
}

void HDDisplay::drawGauge(float xRef, float yRef, float radius, float min, float max, QString name, float value, const QColor& color, QPainter* painter, QPair<float, float> goodRange, QPair<float, float> criticalRange, bool solid)
{
    // Draw the circle
    QPen circlePen(Qt::SolidLine);

    // Rotate the whole gauge with this angle (in radians) for the zero position
    const float zeroRotation = 0.49f;

    // Scale the rotation so that the gauge does one revolution
    // per max. change
    const float rangeScale = ((2.0f * M_PI) / (max - min)) * 0.72f;

    const float nameHeight = radius / 2.5f;
    paintText(name.toUpper(), color, nameHeight*0.7f, xRef-radius, yRef-radius, painter);

    if (!solid)
    {
        circlePen.setStyle(Qt::DotLine);
    }
    circlePen.setWidth(refLineWidthToPen(radius/12.0f));
    circlePen.setColor(color);
    painter->setBrush(Qt::NoBrush);
    painter->setPen(circlePen);
358 359
    drawCircle(xRef, yRef+nameHeight, radius, 0.0f, color, painter);
    //drawCircle(xRef, yRef+nameHeight, radius, 0.0f, 170.0f, 1.0f, color, painter);
pixhawk's avatar
pixhawk committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

    QString label;
    label.sprintf("%05.1f", value);


    // Text
    // height
    const float textHeight = radius/2.0f;
    const float textX = xRef-radius/6.0f;
    const float textY = yRef+radius/2.0f;

    // Draw background rectangle
    // FIXME add background color for use in instrument panel
    QBrush brush(QColor(0, 0, 0), Qt::SolidPattern);
    painter->setBrush(brush);
    painter->setPen(Qt::NoPen);
    painter->drawRect(refToScreenX(xRef-radius/2.5f), refToScreenY(yRef+nameHeight+radius/4.0f), refToScreenX(radius+radius/2.0f), refToScreenY((radius - radius/4.0f)*1.2f));

    // Draw good value and crit. value markers
    if (goodRange.first != goodRange.second)
    {
        QRectF rectangle(refToScreenX(xRef-radius/2.0f), refToScreenY(yRef+nameHeight-radius/2.0f), refToScreenX(radius*2.0f), refToScreenX(radius*2.0f));
        painter->setPen(Qt::green);
        //int start = ((goodRange.first*rangeScale+zeroRotation)/M_PI)*180.0f * 16.0f;// + 16.0f * 60.0f;
        //int span  = start - ((goodRange.second*rangeScale+zeroRotation)/M_PI)*180.0f * 16.0f;
        //painter->drawArc(rectangle, start, span);
    }

    if (criticalRange.first != criticalRange.second)
    {
        QRectF rectangle(refToScreenX(xRef-radius/2.0f-3.0f), refToScreenY(yRef+nameHeight-radius/2.0f-3.0f), refToScreenX(radius*2.0f), refToScreenX(radius*2.0f));
        painter->setPen(Qt::yellow);
        //int start = ((criticalRange.first*rangeScale+zeroRotation)/M_PI)*180.0f * 16.0f - 180.0f*16.0f;// + 16.0f * 60.0f;
        //int span  = start - ((criticalRange.second*rangeScale+zeroRotation)/M_PI)*180.0f * 16.0f + 180.0f*16.0f;
        //painter->drawArc(rectangle, start, span);
    }

    // Draw the value
    //painter->setPen(textColor);
    paintText(label, color, textHeight, textX, textY+nameHeight, painter);
    //paintText(label, color, ((radius - radius/3.0f)*1.1f), xRef-radius/2.5f, yRef+radius/3.0f, painter);

    // Draw the needle

    const float maxWidth = radius / 6.0f;
    const float minWidth = maxWidth * 0.3f;

    QPolygonF p(6);

    p.replace(0, QPointF(xRef-maxWidth/2.0f, yRef+nameHeight+radius * 0.05f));
    p.replace(1, QPointF(xRef-minWidth/2.0f, yRef+nameHeight+radius * 0.9f));
    p.replace(2, QPointF(xRef+minWidth/2.0f, yRef+nameHeight+radius * 0.9f));
    p.replace(3, QPointF(xRef+maxWidth/2.0f, yRef+nameHeight+radius * 0.05f));
    p.replace(4, QPointF(xRef,               yRef+nameHeight+radius * 0.0f));
    p.replace(5, QPointF(xRef-maxWidth/2.0f, yRef+nameHeight+radius * 0.05f));


    rotatePolygonClockWiseRad(p, value*rangeScale+zeroRotation, QPointF(xRef, yRef+nameHeight));

    QBrush indexBrush;
    indexBrush.setColor(color);
    indexBrush.setStyle(Qt::SolidPattern);
    painter->setPen(Qt::NoPen);
    painter->setBrush(indexBrush);
    drawPolygon(p, painter);
}


void HDDisplay::drawSystemIndicator(float xRef, float yRef, int maxNum, float maxWidth, float maxHeight, QPainter* painter)
{
    if (values.size() > 0)
    {
        QString selectedKey = values.begin().key();
        //   | | | | | |
        //   | | | | | |
        //   x speed: 2.54

        // One column per value
        QMapIterator<QString, float> value(values);

        float x = xRef;
        float y = yRef;

        const float vspacing = 1.0f;
        float width = 1.5f;
        float height = 1.5f;
        const float hspacing = 0.6f;

        int i = 0;
pixhawk's avatar
pixhawk committed
449
        while (value.hasNext() && i < maxNum && x < maxWidth && y < maxHeight)
pixhawk's avatar
pixhawk committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
        {
            value.next();
            QBrush brush(Qt::SolidPattern);


            if (value.value() < 0.01f && value.value() > -0.01f)
            {
                brush.setColor(Qt::gray);
            }
            else if (value.value() > 0.01f)
            {
                brush.setColor(Qt::blue);
            }
            else
            {
                brush.setColor(Qt::yellow);
            }

            painter->setBrush(brush);
            painter->setPen(Qt::NoPen);

            // Draw current value colormap
            painter->drawRect(refToScreenX(x), refToScreenY(y), refToScreenX(width), refToScreenY(height));

            // Draw change rate colormap
            painter->drawRect(refToScreenX(x), refToScreenY(y+height+hspacing), refToScreenX(width), refToScreenY(height));

            // Draw mean value colormap
            painter->drawRect(refToScreenX(x), refToScreenY(y+2.0f*(height+hspacing)), refToScreenX(width), refToScreenY(height));

            // Add spacing
            x += width+vspacing;

            // Iterate
            i++;
        }

        // Draw detail label
        QString detail = "NO DATA AVAILABLE";

        if (values.contains(selectedKey))
        {
            detail = values.find(selectedKey).key();
            detail.append(": ");
            detail.append(QString::number(values.find(selectedKey).value()));
        }
        paintText(detail, QColor(255, 255, 255), 3.0f, xRef, yRef+3.0f*(height+hspacing)+1.0f, painter);
    }
}

void HDDisplay::drawChangeIndicatorGauge(float xRef, float yRef, float radius, float expectedMaxChange, float value, const QColor& color, QPainter* painter, bool solid)
{
    // Draw the circle
    QPen circlePen(Qt::SolidLine);
    if (!solid) circlePen.setStyle(Qt::DotLine);
    circlePen.setWidth(refLineWidthToPen(0.5f));
    circlePen.setColor(defaultColor);
    painter->setBrush(Qt::NoBrush);
    painter->setPen(circlePen);
509 510
    drawCircle(xRef, yRef, radius, 200.0f, color, painter);
    //drawCircle(xRef, yRef, radius, 200.0f, 170.0f, 1.0f, color, painter);
pixhawk's avatar
pixhawk committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

    QString label;
    label.sprintf("%05.1f", value);

    // Draw the value
    paintText(label, color, 4.5f, xRef-7.5f, yRef-2.0f, painter);

    // Draw the needle
    // Scale the rotation so that the gauge does one revolution
    // per max. change
    const float rangeScale = (2.0f * M_PI) / expectedMaxChange;
    const float maxWidth = radius / 10.0f;
    const float minWidth = maxWidth * 0.3f;

    QPolygonF p(6);

    p.replace(0, QPointF(xRef-maxWidth/2.0f, yRef-radius * 0.5f));
    p.replace(1, QPointF(xRef-minWidth/2.0f, yRef-radius * 0.9f));
    p.replace(2, QPointF(xRef+minWidth/2.0f, yRef-radius * 0.9f));
    p.replace(3, QPointF(xRef+maxWidth/2.0f, yRef-radius * 0.5f));
    p.replace(4, QPointF(xRef,               yRef-radius * 0.46f));
    p.replace(5, QPointF(xRef-maxWidth/2.0f, yRef-radius * 0.5f));

    rotatePolygonClockWiseRad(p, value*rangeScale, QPointF(xRef, yRef));

    QBrush indexBrush;
    indexBrush.setColor(defaultColor);
    indexBrush.setStyle(Qt::SolidPattern);
    painter->setPen(Qt::SolidLine);
    painter->setPen(defaultColor);
    painter->setBrush(indexBrush);
    drawPolygon(p, painter);
}

/**
 * Paint text on top of the image and OpenGL drawings
 *
 * @param text chars to write
 * @param color text color
 * @param fontSize text size in mm
 * @param refX position in reference units (mm of the real instrument). This is relative to the measurement unit position, NOT in pixels.
 * @param refY position in reference units (mm of the real instrument). This is relative to the measurement unit position, NOT in pixels.
 */
void HDDisplay::paintText(QString text, QColor color, float fontSize, float refX, float refY, QPainter* painter)
{
    QPen prevPen = painter->pen();
    float pPositionX = refToScreenX(refX) - (fontSize*scalingFactor*0.072f);
    float pPositionY = refToScreenY(refY) - (fontSize*scalingFactor*0.212f);

560 561 562 563
    QFont font("Bitstream Vera Sans");
    // Enforce minimum font size of 5 pixels
    int fSize = qMax(5, (int)(fontSize*scalingFactor*1.26f));
    font.setPixelSize(fSize);
pixhawk's avatar
pixhawk committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

    QFontMetrics metrics = QFontMetrics(font);
    int border = qMax(4, metrics.leading());
    QRect rect = metrics.boundingRect(0, 0, width() - 2*border, int(height()*0.125),
                                      Qt::AlignLeft | Qt::TextWordWrap, text);
    painter->setPen(color);
    painter->setFont(font);
    painter->setRenderHint(QPainter::TextAntialiasing);
    painter->drawText(pPositionX, pPositionY,
                      rect.width(), rect.height(),
                      Qt::AlignCenter | Qt::TextWordWrap, text);
    painter->setPen(prevPen);
}

float HDDisplay::refLineWidthToPen(float line)
{
    return line * 2.50f;
}

void HDDisplay::updateValue(UASInterface* uas, QString name, double value, quint64 msec)
{
585
    Q_UNUSED(uas);
586 587
    //if (this->uas == uas)
    //{
pixhawk's avatar
pixhawk committed
588 589 590 591 592 593 594 595
        // Update mean
        const float oldMean = valuesMean.value(name, 0.0f);
        const int meanCount = valuesCount.value(name, 0);
        valuesMean.insert(name, (oldMean * meanCount +  value) / (meanCount + 1));
        valuesCount.insert(name, meanCount + 1);
        valuesDot.insert(name, (value - values.value(name, 0.0f)) / ((msec - lastUpdate.value(name, 0))/1000.0f));
        values.insert(name, value);
        lastUpdate.insert(name, msec);
596
    //}
pixhawk's avatar
pixhawk committed
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
}

/**
 * @param y coordinate in pixels to be converted to reference mm units
 * @return the screen coordinate relative to the QGLWindow origin
 */
float HDDisplay::refToScreenX(float x)
{
    return (scalingFactor * x);
}

/**
 * @param x coordinate in pixels to be converted to reference mm units
 * @return the screen coordinate relative to the QGLWindow origin
 */
float HDDisplay::refToScreenY(float y)
{
    return (scalingFactor * y);
}

617 618 619 620 621 622 623 624 625 626
float HDDisplay::screenToRefX(float x)
{
    return x/scalingFactor;
}

float HDDisplay::screenToRefY(float y)
{
    return y/scalingFactor;
}

pixhawk's avatar
pixhawk committed
627 628 629 630 631 632 633 634 635
void HDDisplay::drawLine(float refX1, float refY1, float refX2, float refY2, float width, const QColor& color, QPainter* painter)
{
    QPen pen(Qt::SolidLine);
    pen.setWidth(refLineWidthToPen(width));
    pen.setColor(color);
    painter->setPen(pen);
    painter->drawLine(QPoint(refToScreenX(refX1), refToScreenY(refY1)), QPoint(refToScreenX(refX2), refToScreenY(refY2)));
}

636
void HDDisplay::drawEllipse(float refX, float refY, float radiusX, float radiusY, float lineWidth, const QColor& color, QPainter* painter)
pixhawk's avatar
pixhawk committed
637 638 639 640 641 642 643 644
{
    QPen pen(painter->pen().style());
    pen.setWidth(refLineWidthToPen(lineWidth));
    pen.setColor(color);
    painter->setPen(pen);
    painter->drawEllipse(QPointF(refToScreenX(refX), refToScreenY(refY)), refToScreenX(radiusX), refToScreenY(radiusY));
}

645
void HDDisplay::drawCircle(float refX, float refY, float radius, float lineWidth, const QColor& color, QPainter* painter)
pixhawk's avatar
pixhawk committed
646
{
647
    drawEllipse(refX, refY, radius, radius, lineWidth, color, painter);
pixhawk's avatar
pixhawk committed
648 649 650 651 652 653 654 655 656 657 658 659 660
}

void HDDisplay::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
661 662


663 664 665 666
void HDDisplay::showEvent(QShowEvent* event)
{
    // React only to internal (pre-display)
    // events
667
    Q_UNUSED(event)
668
    {
669 670 671 672 673 674 675 676 677 678 679
        refreshTimer->start(updateInterval);
    }
}

void HDDisplay::hideEvent(QHideEvent* event)
{
    // React only to internal (pre-display)
    // events
    Q_UNUSED(event)
    {
        refreshTimer->stop();
680 681
    }
}
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813


///**
//  * Sets the current centerpoint.  Also updates the scene's center point.
//  * Unlike centerOn, which has no way of getting the floating point center
//  * back, SetCenter() stores the center point.  It also handles the special
//  * sidebar case.  This function will claim the centerPoint to sceneRec ie.
//  * the centerPoint must be within the sceneRec.
//  */
////Set the current centerpoint in the
//void HDDisplay::setCenter(const QPointF& centerPoint) {
//    //Get the rectangle of the visible area in scene coords
//    QRectF visibleArea = mapToScene(rect()).boundingRect();
//
//    //Get the scene area
//    QRectF sceneBounds = sceneRect();
//
//    double boundX = visibleArea.width() / 2.0;
//    double boundY = visibleArea.height() / 2.0;
//    double boundWidth = sceneBounds.width() - 2.0 * boundX;
//    double boundHeight = sceneBounds.height() - 2.0 * boundY;
//
//    //The max boundary that the centerPoint can be to
//    QRectF bounds(boundX, boundY, boundWidth, boundHeight);
//
//    if(bounds.contains(centerPoint)) {
//        //We are within the bounds
//        currentCenterPoint = centerPoint;
//    } else {
//        //We need to clamp or use the center of the screen
//        if(visibleArea.contains(sceneBounds)) {
//            //Use the center of scene ie. we can see the whole scene
//            currentCenterPoint = sceneBounds.center();
//        } else {
//
//            currentCenterPoint = centerPoint;
//
//            //We need to clamp the center. The centerPoint is too large
//            if(centerPoint.x() > bounds.x() + bounds.width()) {
//                currentCenterPoint.setX(bounds.x() + bounds.width());
//            } else if(centerPoint.x() < bounds.x()) {
//                currentCenterPoint.setX(bounds.x());
//            }
//
//            if(centerPoint.y() > bounds.y() + bounds.height()) {
//                currentCenterPoint.setY(bounds.y() + bounds.height());
//            } else if(centerPoint.y() < bounds.y()) {
//                currentCenterPoint.setY(bounds.y());
//            }
//
//        }
//    }
//
//    //Update the scrollbars
//    centerOn(currentCenterPoint);
//}
//
///**
//  * Handles when the mouse button is pressed
//  */
//void HDDisplay::mousePressEvent(QMouseEvent* event) {
//    //For panning the view
//    lastPanPoint = event->pos();
//    setCursor(Qt::ClosedHandCursor);
//}
//
///**
//  * Handles when the mouse button is released
//  */
//void HDDisplay::mouseReleaseEvent(QMouseEvent* event) {
//    setCursor(Qt::OpenHandCursor);
//    lastPanPoint = QPoint();
//}
//
///**
//*Handles the mouse move event
//*/
//void HDDisplay::mouseMoveEvent(QMouseEvent* event) {
//    if(!lastPanPoint.isNull()) {
//        //Get how much we panned
//        QPointF delta = mapToScene(lastPanPoint) - mapToScene(event->pos());
//        lastPanPoint = event->pos();
//
//        //Update the center ie. do the pan
//        setCenter(getCenter() + delta);
//    }
//}
//
///**
//  * Zoom the view in and out.
//  */
//void HDDisplay::wheelEvent(QWheelEvent* event) {
//
//    //Get the position of the mouse before scaling, in scene coords
//    QPointF pointBeforeScale(mapToScene(event->pos()));
//
//    //Get the original screen centerpoint
//    QPointF screenCenter = getCenter(); //CurrentCenterPoint; //(visRect.center());
//
//    //Scale the view ie. do the zoom
//    double scaleFactor = 1.15; //How fast we zoom
//    if(event->delta() > 0) {
//        //Zoom in
//        scale(scaleFactor, scaleFactor);
//    } else {
//        //Zooming out
//        scale(1.0 / scaleFactor, 1.0 / scaleFactor);
//    }
//
//    //Get the position after scaling, in scene coords
//    QPointF pointAfterScale(mapToScene(event->pos()));
//
//    //Get the offset of how the screen moved
//    QPointF offset = pointBeforeScale - pointAfterScale;
//
//    //Adjust to the new center for correct zooming
//    QPointF newCenter = screenCenter + offset;
//    setCenter(newCenter);
//}
//
///**
//  * Need to update the center so there is no jolt in the
//  * interaction after resizing the widget.
//  */
//void HDDisplay::resizeEvent(QResizeEvent* event) {
//    //Get the rectangle of the visible area in scene coords
//    QRectF visibleArea = mapToScene(rect()).boundingRect();
//    setCenter(visibleArea.center());
//
//    //Call the subclass resize so the scrollbars are updated correctly
//    QGraphicsView::resizeEvent(event);
//}