QGCMapWidget.cc 31.7 KB
Newer Older
1
#include <QInputDialog>
lm's avatar
lm committed
2
#include "QGCMapWidget.h"
LM's avatar
LM committed
3
#include "QGCMapToolBar.h"
lm's avatar
lm committed
4
#include "UASInterface.h"
5
#include "HomePositionManager.h"
6
#include "MAV2DIcon.h"
7
#include "Waypoint2DIcon.h"
8
#include "UASWaypointManager.h"
Don Gagne's avatar
Don Gagne committed
9
#include "QGCMessageBox.h"
10
#include "MultiVehicleManager.h"
lm's avatar
lm committed
11 12

QGCMapWidget::QGCMapWidget(QWidget *parent) :
13 14
    mapcontrol::OPMapWidget(parent),
    firingWaypointChange(NULL),
15
    maxUpdateInterval(2.1f), // 2 seconds
16 17 18
    followUAVEnabled(false),
    trailType(mapcontrol::UAVTrailType::ByTimeElapsed),
    trailInterval(2.0f),
19
    followUAVID(0),
20
    mapInitialized(false),
21
    mapPositionInitialized(false),
22
    homeAltitude(0),
23
    zoomBlocked(false),
24
    _uas(NULL)
lm's avatar
lm committed
25
{
26 27
    currWPManager = MultiVehicleManager::instance()->activeWaypointManager();
    
28
    waypointLines.insert(0, new QGraphicsItemGroup(map));
29
    
30
    connect(currWPManager, SIGNAL(waypointEditableListChanged(int)), this, SLOT(updateWaypointList(int)));
31
    connect(currWPManager, SIGNAL(waypointEditableChanged(int, MissionItem*)), this, SLOT(updateWaypoint(int,MissionItem*)));
32
    
33 34
    connect(this, SIGNAL(waypointCreated(MissionItem*)), currWPManager, SLOT(addWaypointEditable(MissionItem*)));
    connect(this, SIGNAL(waypointChanged(MissionItem*)), currWPManager, SLOT(notifyOfChangeEditable(MissionItem*)));
35
    
36
    offlineMode = true;
37
    // Widget is inactive until shown
38
    defaultGuidedAlt = -1;
39
    loadSettings(false);
40

41 42 43 44
    //handy for debugging:
    //this->SetShowTileGridLines(true);

    //default appears to be Google Hybrid, and is broken currently
45
#if defined MAP_DEFAULT_TYPE_BING
46
    this->SetMapType(MapType::BingHybrid);
47 48 49 50 51
#elif defined MAP_DEFAULT_TYPE_GOOGLE
    this->SetMapType(MapType::GoogleHybrid);
#else
    this->SetMapType(MapType::OpenStreetMap);
#endif
52

53 54
    this->setContextMenuPolicy(Qt::ActionsContextMenu);

55
    // Go to options
56 57 58 59 60 61 62 63
    QAction *guidedaction = new QAction(this);
    guidedaction->setText("Go To Here (Guided Mode)");
    connect(guidedaction,SIGNAL(triggered()),this,SLOT(guidedActionTriggered()));
    this->addAction(guidedaction);
    guidedaction = new QAction(this);
    guidedaction->setText("Go To Here Alt (Guided Mode)");
    connect(guidedaction,SIGNAL(triggered()),this,SLOT(guidedAltActionTriggered()));
    this->addAction(guidedaction);
64
    
65 66 67 68 69
    // Set home location option
    QAction *sethomeaction = new QAction(this);
    sethomeaction->setText("Set Home Location Here");
    connect(sethomeaction,SIGNAL(triggered()),this,SLOT(setHomeActionTriggered()));
    this->addAction(sethomeaction);
70 71 72
}
void QGCMapWidget::guidedActionTriggered()
{
73
    if (!_uas)
74
    {
Don Gagne's avatar
Don Gagne committed
75
        QGCMessageBox::information(tr("Error"), tr("Please connect first"));
76 77
        return;
    }
78 79 80 81 82 83 84 85 86 87
    if (currWPManager)
    {
        if (defaultGuidedAlt == -1)
        {
            if (!guidedAltActionTriggered())
            {
                return;
            }
        }
        // Create new waypoint and send it to the WPManager to send out.
88
        internals::PointLatLng pos = map->FromLocalToLatLng(contextMousePressPos.x(), contextMousePressPos.y());
89
        qDebug() << "Guided action requested. Lat:" << pos.Lat() << "Lon:" << pos.Lng();
90
        MissionItem wp;
91 92 93 94 95 96 97 98
        wp.setLatitude(pos.Lat());
        wp.setLongitude(pos.Lng());
        wp.setAltitude(defaultGuidedAlt);
        currWPManager->goToWaypoint(&wp);
    }
}
bool QGCMapWidget::guidedAltActionTriggered()
{
99
    if (!_uas)
100
    {
Don Gagne's avatar
Don Gagne committed
101
        QGCMessageBox::information(tr("Error"), tr("Please connect first"));
102 103
        return false;
    }
104 105 106 107 108 109 110 111 112 113 114 115
    bool ok = false;
    int tmpalt = QInputDialog::getInt(this,"Altitude","Enter default altitude (in meters) of destination point for guided mode",100,0,30000,1,&ok);
    if (!ok)
    {
        //Use has chosen cancel. Do not send the waypoint
        return false;
    }
    defaultGuidedAlt = tmpalt;
    guidedActionTriggered();
    return true;
}

116 117 118 119 120
/**
 * @brief QGCMapWidget::setHomeActionTriggered
 */
bool QGCMapWidget::setHomeActionTriggered()
{
121
    if (!_uas)
122
    {
Don Gagne's avatar
Don Gagne committed
123
        QGCMessageBox::information(tr("Error"), tr("Please connect first"));
124 125
        return false;
    }
126
    HomePositionManager *uasManager = HomePositionManager::instance();
127 128 129 130
    if (!uasManager) { return false; }

    // Enter an altitude
    bool ok = false;
131
    double alt = QInputDialog::getDouble(this,"Home Altitude","Enter altitude (in meters) of new home location",0.0,0.0,30000.0,2,&ok);
132 133 134
    if (!ok) return false; //Use has chosen cancel. Do not send the waypoint

    // Create new waypoint and send it to the WPManager to send out.
135 136
    internals::PointLatLng pos = map->FromLocalToLatLng(contextMousePressPos.x(), contextMousePressPos.y());
    qDebug("Set home location sent. Lat: %f, Lon: %f, Alt: %f.", pos.Lat(), pos.Lng(), alt);
137 138 139 140 141 142 143 144

    bool success = uasManager->setHomePositionAndNotify(pos.Lat(),pos.Lng(), alt);

    qDebug() << ((success)? "Set new home location." : "Failed to set new home location.");

    return success;
}

145 146
void QGCMapWidget::mousePressEvent(QMouseEvent *event)
{
147 148 149 150 151 152 153

    // Store right-click event presses separate for context menu
    // TODO add check if click was on map, or popup box.
    if (event->button() == Qt::RightButton) {
        contextMousePressPos = event->pos();
    }

154 155 156 157 158 159 160
    mapcontrol::OPMapWidget::mousePressEvent(event);
}

void QGCMapWidget::mouseReleaseEvent(QMouseEvent *event)
{
    mousePressPos = event->pos();
    mapcontrol::OPMapWidget::mouseReleaseEvent(event);
161 162 163

    // If the mouse is released, we can't be dragging
    if (firingWaypointChange) {
164
        firingWaypointChange->setChanged();
165 166
        firingWaypointChange = NULL;
    }
167 168 169 170 171 172
}

QGCMapWidget::~QGCMapWidget()
{
    SetShowHome(false);	// doing this appears to stop the map lib crashing on exit
    SetShowUAV(false);	//   "          "
173
    storeSettings();
174 175 176 177
}

void QGCMapWidget::showEvent(QShowEvent* event)
{
178
    // Disable OP's standard UAV, we have more than one
LM's avatar
LM committed
179 180
    SetShowUAV(false);

181 182 183
    // Pass on to parent widget
    OPMapWidget::showEvent(event);

184
    // Connect map updates to the adapter slots
185
    connect(this, SIGNAL(WPValuesChanged(WayPointItem*)), this, SLOT(handleMapWaypointEdit(WayPointItem*)), Qt::UniqueConnection);
186

187 188 189
    connect(MultiVehicleManager::instance(), &MultiVehicleManager::vehicleAdded, this, &QGCMapWidget::_vehicleAdded);
    connect(MultiVehicleManager::instance(), &MultiVehicleManager::activeVehicleChanged, this, &QGCMapWidget::_activeVehicleChanged);
    
190
    connect(HomePositionManager::instance(), SIGNAL(homePositionChanged(double,double,double)), this, SLOT(updateHomePosition(double,double,double)), Qt::UniqueConnection);
191 192 193
    
    foreach (Vehicle* vehicle, MultiVehicleManager::instance()->vehicles()) {
        _vehicleAdded(vehicle);
lm's avatar
lm committed
194
    }
lm's avatar
lm committed
195

196 197 198
    if (!mapInitialized)
    {
        internals::PointLatLng pos_lat_lon = internals::PointLatLng(0, 0);
lm's avatar
lm committed
199

200 201
        SetMouseWheelZoomType(internals::MouseWheelZoomType::MousePositionWithoutCenter);	    // set how the mouse wheel zoom functions
        SetFollowMouse(true);				    // we want a contiuous mouse position reading
lm's avatar
lm committed
202

203
        SetShowHome(true);					    // display the HOME position on the map
204 205
        Home->SetSafeArea(0);                         // set radius (meters)
        Home->SetShowSafeArea(false);                                         // show the safe area
206
        Home->SetCoord(pos_lat_lon);             // set the HOME position
lm's avatar
lm committed
207

208 209
        setFrameStyle(QFrame::NoFrame);      // no border frame
        setBackgroundBrush(QBrush(Qt::black)); // tile background
lm's avatar
lm committed
210

211
        if (!MultiVehicleManager::instance()->activeVehicle()) {
212 213 214 215
            SetCurrentPosition(pos_lat_lon);         // set the map position to default
        }

        // Set home
216
        updateHomePosition(HomePositionManager::instance()->getHomeLatitude(), HomePositionManager::instance()->getHomeLongitude(), HomePositionManager::instance()->getHomeAltitude());
217

218
        // Set currently selected system
219
        _activeVehicleChanged(MultiVehicleManager::instance()->activeVehicle());
220
        setFocus();
221

222 223 224
        // Start timer
        connect(&updateTimer, SIGNAL(timeout()), this, SLOT(updateGlobalPosition()));
        mapInitialized = true;
225
        //QTimer::singleShot(800, this, SLOT(loadSettings()));
226
    }
227
    updateTimer.start(maxUpdateInterval*1000);
228
    // Update all UAV positions
229
    updateGlobalPosition();
lm's avatar
lm committed
230 231
}

232
void QGCMapWidget::hideEvent(QHideEvent* event)
lm's avatar
lm committed
233
{
234
    updateTimer.stop();
235 236
    storeSettings();
    OPMapWidget::hideEvent(event);
lm's avatar
lm committed
237
}
lm's avatar
lm committed
238

239 240 241 242 243 244 245
void QGCMapWidget::wheelEvent ( QWheelEvent * event )
{
    if (!zoomBlocked) {
        OPMapWidget::wheelEvent(event);
    }
}

246 247 248 249
/**
 * @param changePosition Load also the last position from settings and update the map position.
 */
void QGCMapWidget::loadSettings(bool changePosition)
250 251 252 253 254 255 256 257
{
    // Atlantic Ocean near Africa, coordinate origin
    double lastZoom = 1;
    double lastLat = 0;
    double lastLon = 0;

    QSettings settings;
    settings.beginGroup("QGC_MAPWIDGET");
258 259 260 261 262 263 264 265
    if (changePosition)
    {
        lastLat = settings.value("LAST_LATITUDE", lastLat).toDouble();
        lastLon = settings.value("LAST_LONGITUDE", lastLon).toDouble();
        lastZoom = settings.value("LAST_ZOOM", lastZoom).toDouble();
    }
    trailType = static_cast<mapcontrol::UAVTrailType::Types>(settings.value("TRAIL_TYPE", trailType).toInt());
    trailInterval = settings.value("TRAIL_INTERVAL", trailInterval).toFloat();
266 267
    settings.endGroup();

268 269
#if 0
    // FIXME: NYI
270 271 272 273 274
    // SET CORRECT MENU CHECKBOXES
    // Set the correct trail interval
    if (trailType == mapcontrol::UAVTrailType::ByDistance)
    {
        // XXX
275
        qDebug() << "WARNING: Settings loading for trail type (ByDistance) not implemented";
276 277 278 279
    }
    else if (trailType == mapcontrol::UAVTrailType::ByTimeElapsed)
    {
        // XXX
280
        qDebug() << "WARNING: Settings loading for trail type (ByTimeElapsed) not implemented";
281
    }
282
#endif
283

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    // SET TRAIL TYPE
    foreach (mapcontrol::UAVItem* uav, GetUAVS())
    {
        // Set the correct trail type
        uav->SetTrailType(trailType);
        // Set the correct trail interval
        if (trailType == mapcontrol::UAVTrailType::ByDistance)
        {
            uav->SetTrailDistance(trailInterval);
        }
        else if (trailType == mapcontrol::UAVTrailType::ByTimeElapsed)
        {
            uav->SetTrailTime(trailInterval);
        }
    }

300 301 302
    // SET INITIAL POSITION AND ZOOM
    internals::PointLatLng pos_lat_lon = internals::PointLatLng(lastLat, lastLon);
    SetCurrentPosition(pos_lat_lon);        // set the map position
303
    SetZoom(lastZoom); // set map zoom level
304 305 306 307 308 309 310 311 312 313
}

void QGCMapWidget::storeSettings()
{
    QSettings settings;
    settings.beginGroup("QGC_MAPWIDGET");
    internals::PointLatLng pos = CurrentPosition();
    settings.setValue("LAST_LATITUDE", pos.Lat());
    settings.setValue("LAST_LONGITUDE", pos.Lng());
    settings.setValue("LAST_ZOOM", ZoomReal());
314 315
    settings.setValue("TRAIL_TYPE", static_cast<int>(trailType));
    settings.setValue("TRAIL_INTERVAL", trailInterval);
316 317 318 319 320
    settings.endGroup();
}

void QGCMapWidget::mouseDoubleClickEvent(QMouseEvent* event)
{
321 322
    // If a waypoint manager is available
    if (currWPManager)
323
    {
324 325
        // Create new waypoint
        internals::PointLatLng pos = map->FromLocalToLatLng(event->pos().x(), event->pos().y());
326
        MissionItem* wp = currWPManager->createWaypoint();
327 328 329 330
        wp->setLatitude(pos.Lat());
        wp->setLongitude(pos.Lng());
        wp->setFrame((MAV_FRAME)currWPManager->getFrameRecommendation());
        wp->setAltitude(currWPManager->getAltitudeRecommendation());
331
    }
332

lm's avatar
lm committed
333
    OPMapWidget::mouseDoubleClickEvent(event);
334 335 336
}


lm's avatar
lm committed
337 338
/**
 *
339
 * @param uas the UAS/MAV to monitor/display with the map widget
lm's avatar
lm committed
340
 */
341
void QGCMapWidget::_vehicleAdded(Vehicle* vehicle)
lm's avatar
lm committed
342
{
343 344
    UAS* uas = vehicle->uas();
    
345 346 347
    connect(uas, SIGNAL(globalPositionChanged(UASInterface*,double,double,double,double,quint64)),
            this, SLOT(updateGlobalPosition(UASInterface*,double,double,double,double,quint64)), Qt::UniqueConnection);
    connect(uas, SIGNAL(systemSpecsChanged(int)), this, SLOT(updateSystemSpecs(int)), Qt::UniqueConnection);
348 349 350 351 352 353 354 355
    if (!waypointLines.value(uas->getUASID(), NULL)) {
        waypointLines.insert(uas->getUASID(), new QGraphicsItemGroup(map));
    } else {
        foreach (QGraphicsItem* item, waypointLines.value(uas->getUASID())->childItems())
        {
            delete item;
        }
    }
lm's avatar
lm committed
356 357
}

358
void QGCMapWidget::_activeVehicleChanged(Vehicle* vehicle)
359
{
360
    _uas = NULL;
361 362

    // Disconnect old MAV manager
363 364
    if (currWPManager)
    {
365
        // Disconnect the waypoint manager / data storage from the UI
366
        disconnect(currWPManager, SIGNAL(waypointEditableListChanged(int)), this, SLOT(updateWaypointList(int)));
367 368 369
        disconnect(currWPManager, SIGNAL(waypointEditableChanged(int, MissionItem*)), this, SLOT(updateWaypoint(int,MissionItem*)));
        disconnect(this, SIGNAL(waypointCreated(MissionItem*)), currWPManager, SLOT(addWaypointEditable(MissionItem*)));
        disconnect(this, SIGNAL(waypointChanged(MissionItem*)), currWPManager, SLOT(notifyOfChangeEditable(MissionItem*)));
370 371
    }

372 373
    // Attach the new waypoint manager if a new UAS was selected. Otherwise, indicate
    // that no such manager exists.
374
    if (vehicle)
375
    {
376 377 378
        _uas = vehicle->uas();
        
        currWPManager = _uas->getWaypointManager();
379

380 381 382
        updateSelectedSystem(vehicle->id());
        followUAVID = vehicle->id();
        updateWaypointList(vehicle->id());
383

384
        // Connect the waypoint manager / data storage to the UI
385
        connect(currWPManager, SIGNAL(waypointEditableListChanged(int)), this, SLOT(updateWaypointList(int)), Qt::UniqueConnection);
386 387 388
        connect(currWPManager, SIGNAL(waypointEditableChanged(int, MissionItem*)), this, SLOT(updateWaypoint(int,MissionItem*)), Qt::UniqueConnection);
        connect(this, SIGNAL(waypointCreated(MissionItem*)), currWPManager, SLOT(addWaypointEditable(MissionItem*)), Qt::UniqueConnection);
        connect(this, SIGNAL(waypointChanged(MissionItem*)), currWPManager, SLOT(notifyOfChangeEditable(MissionItem*)), Qt::UniqueConnection);
389 390

        if (!mapPositionInitialized) {
391
            internals::PointLatLng pos_lat_lon = internals::PointLatLng(_uas->getLatitude(), _uas->getLongitude());
392 393 394 395 396 397 398
            SetCurrentPosition(pos_lat_lon);

            // Zoom in
            SetZoom(13);

            mapPositionInitialized = true;
        }
399 400 401 402 403
    }
    else
    {
        currWPManager = NULL;
    }
404 405
}

lm's avatar
lm committed
406 407 408 409 410 411 412 413 414
/**
 * Updates the global position of one MAV and append the last movement to the trail
 *
 * @param uas The unmanned air system
 * @param lat Latitude in WGS84 ellipsoid
 * @param lon Longitutde in WGS84 ellipsoid
 * @param alt Altitude over mean sea level
 * @param usec Timestamp of the position message in milliseconds FIXME will move to microseconds
 */
415
void QGCMapWidget::updateGlobalPosition(UASInterface* uas, double lat, double lon, double altAMSL, double altWGS84, quint64 usec)
lm's avatar
lm committed
416 417
{
    Q_UNUSED(usec);
418
    Q_UNUSED(altAMSL);
lm's avatar
lm committed
419

420 421
    // Immediate update
    if (maxUpdateInterval == 0)
422
    {
423 424 425 426 427 428 429 430 431
        // Get reference to graphic UAV item
        mapcontrol::UAVItem* uav = GetUAV(uas->getUASID());
        // Check if reference is valid, else create a new one
        if (uav == NULL)
        {
            MAV2DIcon* newUAV = new MAV2DIcon(map, this, uas);
            newUAV->setParentItem(map);
            UAVS.insert(uas->getUASID(), newUAV);
            uav = GetUAV(uas->getUASID());
432 433 434 435 436 437 438 439 440 441 442
            // Set the correct trail type
            uav->SetTrailType(trailType);
            // Set the correct trail interval
            if (trailType == mapcontrol::UAVTrailType::ByDistance)
            {
                uav->SetTrailDistance(trailInterval);
            }
            else if (trailType == mapcontrol::UAVTrailType::ByTimeElapsed)
            {
                uav->SetTrailTime(trailInterval);
            }
443 444 445 446
        }

        // Set new lat/lon position of UAV icon
        internals::PointLatLng pos_lat_lon = internals::PointLatLng(lat, lon);
447
        uav->SetUAVPos(pos_lat_lon, altWGS84);
448 449
        // Follow status
        if (followUAVEnabled && uas->getUASID() == followUAVID) SetCurrentPosition(pos_lat_lon);
450 451
        // Convert from radians to degrees and apply
        uav->SetUAVHeading((uas->getYaw()/M_PI)*180.0f);
452
    }
453
}
lm's avatar
lm committed
454

455 456 457 458 459
/**
 * Pulls in the positions of all UAVs from the UAS manager
 */
void QGCMapWidget::updateGlobalPosition()
{
460
    foreach (Vehicle* vehicle, MultiVehicleManager::instance()->vehicles())
461
    {
462 463
        UAS* system = vehicle->uas();
        
464 465 466 467 468 469
        // Get reference to graphic UAV item
        mapcontrol::UAVItem* uav = GetUAV(system->getUASID());
        // Check if reference is valid, else create a new one
        if (uav == NULL)
        {
            MAV2DIcon* newUAV = new MAV2DIcon(map, this, system);
470 471
            AddUAV(system->getUASID(), newUAV);
            uav = newUAV;
LM's avatar
LM committed
472 473 474
            uav->SetTrailTime(1);
            uav->SetTrailDistance(5);
            uav->SetTrailType(mapcontrol::UAVTrailType::ByTimeElapsed);
475 476 477 478
        }

        // Set new lat/lon position of UAV icon
        internals::PointLatLng pos_lat_lon = internals::PointLatLng(system->getLatitude(), system->getLongitude());
479
        uav->SetUAVPos(pos_lat_lon, system->getAltitudeAMSL());
480 481
        // Follow status
        if (followUAVEnabled && system->getUASID() == followUAVID) SetCurrentPosition(pos_lat_lon);
482 483 484
        // Convert from radians to degrees and apply
        uav->SetUAVHeading((system->getYaw()/M_PI)*180.0f);
    }
485 486
}

487 488
void QGCMapWidget::updateLocalPosition()
{
489
    foreach (Vehicle* vehicle, MultiVehicleManager::instance()->vehicles())
490
    {
491 492
        UAS* system = vehicle->uas();
        
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
        // Get reference to graphic UAV item
        mapcontrol::UAVItem* uav = GetUAV(system->getUASID());
        // Check if reference is valid, else create a new one
        if (uav == NULL)
        {
            MAV2DIcon* newUAV = new MAV2DIcon(map, this, system);
            AddUAV(system->getUASID(), newUAV);
            uav = newUAV;
            uav->SetTrailTime(1);
            uav->SetTrailDistance(5);
            uav->SetTrailType(mapcontrol::UAVTrailType::ByTimeElapsed);
        }

        // Set new lat/lon position of UAV icon
        internals::PointLatLng pos_lat_lon = internals::PointLatLng(system->getLatitude(), system->getLongitude());
508
        uav->SetUAVPos(pos_lat_lon, system->getAltitudeAMSL());
509 510 511 512 513 514 515 516 517
        // Follow status
        if (followUAVEnabled && system->getUASID() == followUAVID) SetCurrentPosition(pos_lat_lon);
        // Convert from radians to degrees and apply
        uav->SetUAVHeading((system->getYaw()/M_PI)*180.0f);
    }
}

void QGCMapWidget::updateLocalPositionEstimates()
{
518
    updateLocalPosition();
519 520
}

521 522 523 524 525 526 527 528 529

void QGCMapWidget::updateSystemSpecs(int uas)
{
    foreach (mapcontrol::UAVItem* p, UAVS.values())
    {
        MAV2DIcon* icon = dynamic_cast<MAV2DIcon*>(p);
        if (icon && icon->getUASId() == uas)
        {
            // Set new airframe
530
            icon->setAirframe(MultiVehicleManager::instance()->getVehicleById(uas)->uas()->getAirframe());
531 532 533 534 535 536
            icon->drawIcon();
        }
    }
}

/**
537
 * Does not update the system type or configuration, only the selected status
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
 */
void QGCMapWidget::updateSelectedSystem(int uas)
{
    foreach (mapcontrol::UAVItem* p, UAVS.values())
    {
        MAV2DIcon* icon = dynamic_cast<MAV2DIcon*>(p);
        if (icon)
        {
            // Set as selected if ids match
            icon->setSelectedUAS((icon->getUASId() == uas));
        }
    }
}


553 554 555 556 557 558
// MAP NAVIGATION
void QGCMapWidget::showGoToDialog()
{
    bool ok;
    QString text = QInputDialog::getText(this, tr("Please enter coordinates"),
                                         tr("Coordinates (Lat,Lon):"), QLineEdit::Normal,
559
                                         QString("%1,%2").arg(CurrentPosition().Lat(), 0, 'g', 6).arg(CurrentPosition().Lng(), 0, 'g', 6), &ok);
560 561
    if (ok && !text.isEmpty())
    {
562
        QStringList split = text.split(",");
563 564
        if (split.length() == 2)
        {
565 566 567 568 569 570
            bool convert;
            double latitude = split.first().toDouble(&convert);
            ok &= convert;
            double longitude = split.last().toDouble(&convert);
            ok &= convert;

571 572
            if (ok)
            {
573 574 575 576 577 578 579 580 581 582
                internals::PointLatLng pos_lat_lon = internals::PointLatLng(latitude, longitude);
                SetCurrentPosition(pos_lat_lon);        // set the map position
            }
        }
    }
}


void QGCMapWidget::updateHomePosition(double latitude, double longitude, double altitude)
{
583
    qDebug() << "HOME SET TO: " << latitude << longitude << altitude;
584 585
    Home->SetCoord(internals::PointLatLng(latitude, longitude));
    Home->SetAltitude(altitude);
586
    homeAltitude = altitude;
587
    SetShowHome(true);                      // display the HOME position on the map
588
    Home->RefreshPos();
589 590
}

591 592 593
void QGCMapWidget::goHome()
{
    SetCurrentPosition(Home->Coord());
594
    SetZoom(17);
595 596
}

597 598 599 600 601 602 603 604 605 606
/**
 * Limits the update rate on the specified interval. Set to zero (0) to run at maximum
 * telemetry speed. Recommended rate is 2 s.
 */
void QGCMapWidget::setUpdateRateLimit(float seconds)
{
    maxUpdateInterval = seconds;
    updateTimer.start(maxUpdateInterval*1000);
}

607 608 609 610 611 612
void QGCMapWidget::cacheVisibleRegion()
{
    internals::RectLatLng rect = map->SelectedArea();

    if (rect.IsEmpty())
    {
Don Gagne's avatar
Don Gagne committed
613 614
        QGCMessageBox::information(tr("Cannot cache tiles for offline use"),
                                   tr("Please select an area first by holding down SHIFT or ALT and selecting the area with the left mouse button."));
615
    }
616 617 618 619 620 621
    else
    {
        RipMap();
        // Set empty area = unselect area
        map->SetSelectedArea(internals::RectLatLng());
    }
622 623
}

624

625 626 627 628 629
// WAYPOINT MAP INTERACTION FUNCTIONS

void QGCMapWidget::handleMapWaypointEdit(mapcontrol::WayPointItem* waypoint)
{
    // Block circle updates
630
    MissionItem* wp = iconsToWaypoints.value(waypoint, NULL);
631 632 633 634 635

    // Delete UI element if wp doesn't exist
    if (!wp)
        WPDelete(waypoint);

636 637
    // Update WP values
    internals::PointLatLng pos = waypoint->Coord();
638 639 640

    // Block waypoint signals
    wp->blockSignals(true);
641 642
    wp->setLatitude(pos.Lat());
    wp->setLongitude(pos.Lng());
643
    wp->blockSignals(false);
644

645

646 647 648
//    internals::PointLatLng coord = waypoint->Coord();
//    QString coord_str = " " + QString::number(coord.Lat(), 'f', 6) + "   " + QString::number(coord.Lng(), 'f', 6);
//    qDebug() << "MAP WP COORD (MAP):" << coord_str << __FILE__ << __LINE__;
Don Gagne's avatar
Don Gagne committed
649
//    QString wp_str = QString::number(wp->getLatitude(), 'f', 6) + "   " + QString::number(wp->longitude(), 'f', 6);
650
//    qDebug() << "MAP WP COORD (WP):" << wp_str << __FILE__ << __LINE__;
651

652 653 654 655 656 657 658
    // Protect from vicious double update cycle
    if (firingWaypointChange == wp) {
        return;
    }
    // Not in cycle, block now from entering it
    firingWaypointChange = wp;

659
    emit waypointChanged(wp);
660
}
661 662

// WAYPOINT UPDATE FUNCTIONS
663 664

/**
665 666
 * This function is called if a a single waypoint is updated and
 * also if the whole list changes.
667
 */
668
void QGCMapWidget::updateWaypoint(int uas, MissionItem* wp)
669
{
670
    //qDebug() << __FILE__ << __LINE__ << "UPDATING WP FUNCTION CALLED";
671
    // Source of the event was in this widget, do nothing
672 673 674
    if (firingWaypointChange == wp) {
        return;
    }
675 676
    // Currently only accept waypoint updates from the UAS in focus
    // this has to be changed to accept read-only updates from other systems as well.
677
    UASInterface* uasInstance = MultiVehicleManager::instance()->getVehicleById(uas)->uas();
678
    if (currWPManager)
lm's avatar
lm committed
679
    {
680
        // Only accept waypoints in global coordinate frame
Don Gagne's avatar
Don Gagne committed
681
        if (((wp->frame() == MAV_FRAME_GLOBAL) || (wp->frame() == MAV_FRAME_GLOBAL_RELATIVE_ALT)) && wp->isNavigationType())
lm's avatar
lm committed
682
        {
683 684 685 686 687
            // We're good, this is a global waypoint

            // Get the index of this waypoint
            // note the call to getGlobalFrameAndNavTypeIndexOf()
            // as we're only handling global waypoints
688
            int wpindex = currWPManager->getGlobalFrameAndNavTypeIndexOf(wp);
689
            // If not found, return (this should never happen, but helps safety)
690
            if (wpindex < 0) return;
691 692 693
            // Mark this wp as currently edited
            firingWaypointChange = wp;

694 695
            qDebug() << "UPDATING WAYPOINT" << wpindex << "IN 2D MAP";

696
            // Check if wp exists yet in map
lm's avatar
lm committed
697 698
            if (!waypointsToIcons.contains(wp))
            {
699
                // Create icon for new WP
700 701 702
                QColor wpColor(Qt::red);
                if (uasInstance) wpColor = uasInstance->getColor();
                Waypoint2DIcon* icon = new Waypoint2DIcon(map, this, wp, wpColor, wpindex);
703 704 705 706 707 708
                ConnectWP(icon);
                icon->setParentItem(map);
                // Update maps to allow inverse data association
                waypointsToIcons.insert(wp, icon);
                iconsToWaypoints.insert(icon, wp);

lm's avatar
lm committed
709 710 711 712
                // Add line element if this is NOT the first waypoint
                if (wpindex > 0)
                {
                    // Get predecessor of this WP
713 714
                    QList<MissionItem* > wps = currWPManager->getGlobalFrameAndNavTypeWaypointList();
                    MissionItem* wp1 = wps.at(wpindex-1);
lm's avatar
lm committed
715 716 717 718
                    mapcontrol::WayPointItem* prevIcon = waypointsToIcons.value(wp1, NULL);
                    // If we got a valid graphics item, continue
                    if (prevIcon)
                    {
719
                        mapcontrol::WaypointLineItem* line = new mapcontrol::WaypointLineItem(prevIcon, icon, wpColor, map);
lm's avatar
lm committed
720
                        line->setParentItem(map);
lm's avatar
lm committed
721 722 723 724
                        QGraphicsItemGroup* group = waypointLines.value(uas, NULL);
                        if (group)
                        {
                            group->addToGroup(line);
lm's avatar
lm committed
725
                            group->setParentItem(map);
lm's avatar
lm committed
726 727 728
                        }
                    }
                }
lm's avatar
lm committed
729 730 731
            }
            else
            {
732
                // MissionItem exists, block it's signals and update it
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
                mapcontrol::WayPointItem* icon = waypointsToIcons.value(wp);
                // Make sure we don't die on a null pointer
                // this should never happen, just a precaution
                if (!icon) return;
                // Block outgoing signals to prevent an infinite signal loop
                // should not happen, just a precaution
                this->blockSignals(true);
                // Update the WP
                Waypoint2DIcon* wpicon = dynamic_cast<Waypoint2DIcon*>(icon);
                if (wpicon)
                {
                    // Let icon read out values directly from waypoint
                    icon->SetNumber(wpindex);
                    wpicon->updateWaypoint();
                }
                else
                {
750
                    // Use safe standard interfaces for non MissionItem-class based wps
Don Gagne's avatar
Don Gagne committed
751 752
                    icon->SetCoord(internals::PointLatLng(wp->latitude(), wp->longitude()));
                    icon->SetAltitude(wp->altitude());
Don Gagne's avatar
Don Gagne committed
753
                    icon->SetHeading(wp->yawRadians());
754
                    icon->SetNumber(wpindex);
755
                }
756 757 758
                // Re-enable signals again
                this->blockSignals(false);
            }
759

760
            firingWaypointChange = NULL;
761

lm's avatar
lm committed
762 763 764
        }
        else
        {
765 766 767 768
            // Check if the index of this waypoint is larger than the global
            // waypoint list. This implies that the coordinate frame of this
            // waypoint was changed and the list containing only global
            // waypoints was shortened. Thus update the whole list
769
            if (waypointsToIcons.count() > currWPManager->getGlobalFrameAndNavTypeCount())
lm's avatar
lm committed
770
            {
771
                updateWaypointList(uas);
772 773
            }
        }
774
    }
775 776 777 778 779 780 781 782 783
}

/**
 * Update the whole list of waypoints. This is e.g. necessary if the list order changed.
 * The UAS manager will emit the appropriate signal whenever updating the list
 * is necessary.
 */
void QGCMapWidget::updateWaypointList(int uas)
{
784
    qDebug() << "UPDATE WP LIST IN 2D MAP CALLED FOR UAS" << uas;
785 786
    // Currently only accept waypoint updates from the UAS in focus
    // this has to be changed to accept read-only updates from other systems as well.
787
    UASInterface* uasInstance = MultiVehicleManager::instance()->getVehicleById(uas)->uas();
788
    if (currWPManager)
lm's avatar
lm committed
789
    {
790 791
        // ORDER MATTERS HERE!
        // TWO LOOPS ARE NEEDED - INFINITY LOOP ELSE
792

793 794
        qDebug() << "DELETING NOW OLD WPS";

795 796 797 798 799 800 801 802 803 804
        // Delete connecting waypoint lines
        QGraphicsItemGroup* group = waypointLines.value(uas, NULL);
        if (group)
        {
            foreach (QGraphicsItem* item, group->childItems())
            {
                delete item;
            }
        }

805 806
        // Delete first all old waypoints
        // this is suboptimal (quadratic, but wps should stay in the sub-100 range anyway)
807 808
        QList<MissionItem* > wps = currWPManager->getGlobalFrameAndNavTypeWaypointList();
        foreach (MissionItem* wp, waypointsToIcons.keys())
809
        {
810 811
            if (!wps.contains(wp))
            {
lm's avatar
lm committed
812 813
                // Get icon to work on
                mapcontrol::WayPointItem* icon = waypointsToIcons.value(wp);
814 815 816 817
                waypointsToIcons.remove(wp);
                iconsToWaypoints.remove(icon);
                WPDelete(icon);
            }
818 819
        }

820
        // Update all existing waypoints
821
        foreach (MissionItem* wp, waypointsToIcons.keys())
822 823 824 825
        {
            // Update remaining waypoints
            updateWaypoint(uas, wp);
        }
826

827
        // Update all potentially new waypoints
828
        foreach (MissionItem* wp, wps)
829
        {
Don Gagne's avatar
Don Gagne committed
830
            qDebug() << "UPDATING NEW WP" << wp->sequenceNumber();
831 832 833
            // Update / add only if new
            if (!waypointsToIcons.contains(wp)) updateWaypoint(uas, wp);
        }
lm's avatar
lm committed
834 835 836

        // Add line element if this is NOT the first waypoint
        mapcontrol::WayPointItem* prevIcon = NULL;
837
        foreach (MissionItem* wp, wps)
lm's avatar
lm committed
838 839 840 841 842 843 844
        {
            mapcontrol::WayPointItem* currIcon = waypointsToIcons.value(wp, NULL);
            // Do not work on first waypoint, but only increment counter
            // do not continue if icon is invalid
            if (prevIcon && currIcon)
            {
                // If we got a valid graphics item, continue
845 846 847
                QColor wpColor(Qt::red);
                if (uasInstance) wpColor = uasInstance->getColor();
                mapcontrol::WaypointLineItem* line = new mapcontrol::WaypointLineItem(prevIcon, currIcon, wpColor, map);
lm's avatar
lm committed
848
                line->setParentItem(map);
lm's avatar
lm committed
849 850 851 852
                QGraphicsItemGroup* group = waypointLines.value(uas, NULL);
                if (group)
                {
                    group->addToGroup(line);
lm's avatar
lm committed
853
                    group->setParentItem(map);
lm's avatar
lm committed
854 855 856 857
                }
            }
            prevIcon = currIcon;
        }
858
    }
lm's avatar
lm committed
859
}
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902


//// ADAPTER / HELPER FUNCTIONS
//float QGCMapWidget::metersToPixels(double meters)
//{
//    return meters/map->Projection()->GetGroundResolution(map->ZoomTotal(),coord.Lat());
//}

//double QGCMapWidget::headingP1P2(internals::PointLatLng p1, internals::PointLatLng p2)
//{
//    double lat1 = p1.Lat() * deg_to_rad;
//    double lon1 = p2.Lng() * deg_to_rad;

//    double lat2 = p2.Lat() * deg_to_rad;
//    double lon2 = p2.Lng() * deg_to_rad;

//    double delta_lon = lon2 - lon1;

//    double y = sin(delta_lon) * cos(lat2);
//    double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(delta_lon);
//    double heading = atan2(y, x) * rad_to_deg;

//    heading += 360;
//    while (heading < 0) bear += 360;
//    while (heading >= 360) bear -= 360;

//    return heading;
//}

//internals::PointLatLng QGCMapWidget::targetLatLon(internals::PointLatLng source, double heading, double dist)
//{
//    double lat1 = source.Lat() * deg_to_rad;
//    double lon1 = source.Lng() * deg_to_rad;

//    heading *= deg_to_rad;

//    double ad = dist / earth_mean_radius;

//    double lat2 = asin(sin(lat1) * cos(ad) + cos(lat1) * sin(ad) * cos(heading));
//    double lon2 = lon1 + atan2(sin(bear) * sin(ad) * cos(lat1), cos(ad) - sin(lat1) * sin(lat2));

//    return internals::PointLatLng(lat2 * rad_to_deg, lon2 * rad_to_deg);
//}