CorridorScanComplexItem.cc 20.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "CorridorScanComplexItem.h"
#include "JsonHelper.h"
#include "MissionController.h"
#include "QGCGeo.h"
#include "QGroundControlQmlGlobal.h"
#include "QGCQGeoCoordinate.h"
#include "SettingsManager.h"
#include "AppSettings.h"
#include "QGCQGeoCoordinate.h"

#include <QPolygonF>

QGC_LOGGING_CATEGORY(CorridorScanComplexItemLog, "CorridorScanComplexItemLog")

24 25
const char* CorridorScanComplexItem::settingsGroup =            "CorridorScan";
const char* CorridorScanComplexItem::corridorWidthName =        "CorridorWidth";
26
const char* CorridorScanComplexItem::_jsonEntryPointKey =       "EntryPoint";
27

28
const char* CorridorScanComplexItem::jsonComplexItemTypeValue = "CorridorScan";
29 30

CorridorScanComplexItem::CorridorScanComplexItem(Vehicle* vehicle, QObject* parent)
31
    : TransectStyleComplexItem  (vehicle, settingsGroup, parent)
32
    , _ignoreRecalc             (false)
33 34 35
    , _entryPoint               (0)
    , _metaDataMap              (FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/CorridorScan.SettingsGroup.json"), this))
    , _corridorWidthFact        (settingsGroup, _metaDataMap[corridorWidthName])
36 37 38
{
    _editorQml = "qrc:/qml/CorridorScanEditor.qml";

DonLakeFlyer's avatar
DonLakeFlyer committed
39 40 41 42 43
    // We override the altitude to the mission default
    if (_cameraCalc.isManualCamera() || !_cameraCalc.valueSetIsDistance()->rawValue().toBool()) {
        _cameraCalc.distanceToSurface()->setRawValue(qgcApp()->toolbox()->settingsManager()->appSettings()->defaultMissionItemAltitude()->rawValue());
    }

44 45 46
    connect(&_corridorWidthFact,    &Fact::valueChanged,                                this, &CorridorScanComplexItem::_setDirty);
    connect(&_corridorPolyline,     &QGCMapPolyline::pathChanged,                       this, &CorridorScanComplexItem::_setDirty);

47 48
    connect(&_cameraCalc,           &CameraCalc::distanceToSurfaceRelativeChanged, this, &CorridorScanComplexItem::coordinateHasRelativeAltitudeChanged);
    connect(&_cameraCalc,           &CameraCalc::distanceToSurfaceRelativeChanged, this, &CorridorScanComplexItem::exitCoordinateHasRelativeAltitudeChanged);
49

50 51
    connect(&_corridorPolyline,     &QGCMapPolyline::dirtyChanged,  this, &CorridorScanComplexItem::_polylineDirtyChanged);
    connect(&_corridorPolyline,     &QGCMapPolyline::countChanged,  this, &CorridorScanComplexItem::_polylineCountChanged);
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

    connect(&_corridorPolyline,     &QGCMapPolyline::pathChanged,   this, &CorridorScanComplexItem::_rebuildCorridor);
    connect(&_corridorWidthFact,    &Fact::valueChanged,            this, &CorridorScanComplexItem::_rebuildCorridor);

    _rebuildCorridor();
}

void CorridorScanComplexItem::_polylineCountChanged(int count)
{
    Q_UNUSED(count);
    emit lastSequenceNumberChanged(lastSequenceNumber());
}

int CorridorScanComplexItem::lastSequenceNumber(void) const
{
67 68
    int itemCount = _transectPoints.count();    // Each transpect point represents a waypoint item

69
    if (_cameraTriggerInTurnAroundFact.rawValue().toBool()) {
70 71 72 73 74 75 76
        // Only one camera start and on camera stop
        itemCount += 2;
    } else {
        // Each transect will have a camera start and stop in it
        itemCount += _transectCount() * 2;
    }

77
    return _sequenceNumber + itemCount - 1;
78 79
}

80
void CorridorScanComplexItem::save(QJsonArray&  planItems)
81 82 83
{
    QJsonObject saveObject;

84 85 86
    _save(saveObject);

    saveObject[JsonHelper::jsonVersionKey] =                    2;
87 88
    saveObject[VisualMissionItem::jsonTypeKey] =                VisualMissionItem::jsonTypeComplexItemValue;
    saveObject[ComplexMissionItem::jsonComplexItemTypeKey] =    jsonComplexItemTypeValue;
89
    saveObject[corridorWidthName] =                             _corridorWidthFact.rawValue().toDouble();
90
    saveObject[_jsonEntryPointKey] =                            _entryPoint;
91 92 93 94 95 96 97

    QJsonObject cameraCalcObject;
    _cameraCalc.save(cameraCalcObject);
    saveObject[_jsonCameraCalcKey] = cameraCalcObject;

    _corridorPolyline.saveToJson(saveObject);

98
    planItems.append(saveObject);
99 100 101 102
}

bool CorridorScanComplexItem::load(const QJsonObject& complexObject, int sequenceNumber, QString& errorString)
{
103 104 105
    // We don't recalc while loading since all the information we need is specified in the file
    _ignoreRecalc = true;

106 107 108 109
    QList<JsonHelper::KeyValidateInfo> keyInfoList = {
        { JsonHelper::jsonVersionKey,                   QJsonValue::Double, true },
        { VisualMissionItem::jsonTypeKey,               QJsonValue::String, true },
        { ComplexMissionItem::jsonComplexItemTypeKey,   QJsonValue::String, true },
110
        { corridorWidthName,                            QJsonValue::Double, true },
111
        { _jsonEntryPointKey,                           QJsonValue::Double, true },
112 113 114
        { QGCMapPolyline::jsonPolylineKey,              QJsonValue::Array,  true },
    };
    if (!JsonHelper::validateKeys(complexObject, keyInfoList, errorString)) {
115
        _ignoreRecalc = false;
116 117 118
        return false;
    }

DonLakeFlyer's avatar
DonLakeFlyer committed
119
    if (!_corridorPolyline.loadFromJson(complexObject, true, errorString)) {
120
        _ignoreRecalc = false;
DonLakeFlyer's avatar
DonLakeFlyer committed
121 122
        return false;
    }
123 124 125 126 127

    QString itemType = complexObject[VisualMissionItem::jsonTypeKey].toString();
    QString complexType = complexObject[ComplexMissionItem::jsonComplexItemTypeKey].toString();
    if (itemType != VisualMissionItem::jsonTypeComplexItemValue || complexType != jsonComplexItemTypeValue) {
        errorString = tr("%1 does not support loading this complex mission item type: %2:%3").arg(qgcApp()->applicationName()).arg(itemType).arg(complexType);
128
        _ignoreRecalc = false;
129 130 131 132
        return false;
    }

    int version = complexObject[JsonHelper::jsonVersionKey].toInt();
133
    if (version != 2) {
134
        errorString = tr("%1 complex item version %2 not supported").arg(jsonComplexItemTypeValue).arg(version);
135
        _ignoreRecalc = false;
136 137 138 139 140
        return false;
    }

    setSequenceNumber(sequenceNumber);

141
    if (!_load(complexObject, errorString)) {
142
        _ignoreRecalc = false;
143 144 145
        return false;
    }

146 147
    _corridorWidthFact.setRawValue      (complexObject[corridorWidthName].toDouble());

148
    _entryPoint = complexObject[_jsonEntryPointKey].toInt();
149 150 151

    _rebuildCorridor();

152 153
    _ignoreRecalc = false;

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    return true;
}

bool CorridorScanComplexItem::specifiesCoordinate(void) const
{
    return _corridorPolyline.count() > 1;
}

int CorridorScanComplexItem::_transectCount(void) const
{
    double transectSpacing = _cameraCalc.adjustedFootprintSide()->rawValue().toDouble();
    double fullWidth = _corridorWidthFact.rawValue().toDouble();
    return fullWidth > 0.0 ? qCeil(fullWidth / transectSpacing) : 1;
}

169 170 171 172 173 174 175 176 177 178 179 180 181 182
void CorridorScanComplexItem::_appendLoadedMissionItems(QList<MissionItem*>& items, QObject* missionItemParent)
{
    qCDebug(CorridorScanComplexItemLog) << "_appendLoadedMissionItems";

    int seqNum = _sequenceNumber;

    foreach (const MissionItem* loadedMissionItem, _loadedMissionItems) {
        MissionItem* item = new MissionItem(*loadedMissionItem, missionItemParent);
        item->setSequenceNumber(seqNum++);
        items.append(item);
    }
}

void CorridorScanComplexItem::_buildAndAppendMissionItems(QList<MissionItem*>& items, QObject* missionItemParent)
183
{
184 185
    qCDebug(CorridorScanComplexItemLog) << "_buildAndAppendMissionItems";

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    // First adjust for terrain (this will set altitudes into _transectionPoints in all cases
    _adjustTransectPointsForTerrain();

    // Now build the mission items from the transect points

    MissionItem* item;
    int seqNum =                    _sequenceNumber;
    bool imagesEverywhere =         _cameraTriggerInTurnAroundFact.rawValue().toBool();
    bool addTriggerAtBeginning =    imagesEverywhere;
    bool firstPoint =               true;
    bool entryPoint =               true;

    MAV_FRAME mavFrame = followTerrain() || !_cameraCalc.distanceToSurfaceRelative() ? MAV_FRAME_GLOBAL : MAV_FRAME_GLOBAL_RELATIVE_ALT;

    foreach (const QVariant& transectPointVar, _transectPoints) {
        QGeoCoordinate transectPoint = transectPointVar.value<QGeoCoordinate>();

        item = new MissionItem(seqNum++,
                        MAV_CMD_NAV_WAYPOINT,
                        mavFrame,
                        0,                                          // No hold time
                        0.0,                                        // No acceptance radius specified
                        0.0,                                        // Pass through waypoint
                        std::numeric_limits<double>::quiet_NaN(),   // Yaw unchanged
                        transectPoint.latitude(),
                        transectPoint.longitude(),
                        qAbs(transectPoint.altitude()),             // qAbs since negative value indicates survey edge
                        true,                                       // autoContinue
                        false,                                      // isCurrentItem
                        missionItemParent);
        items.append(item);
217

218 219 220 221 222 223 224 225 226 227 228 229 230
        if (firstPoint && addTriggerAtBeginning) {
            // Start triggering
            addTriggerAtBeginning = false;
            item = new MissionItem(seqNum++,
                                   MAV_CMD_DO_SET_CAM_TRIGG_DIST,
                                   MAV_FRAME_MISSION,
                                   _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble(),   // trigger distance
                                   0,                                                               // shutter integration (ignore)
                                   1,                                                               // trigger immediately when starting
                                   0, 0, 0, 0,                                                      // param 4-7 unused
                                   true,                                                            // autoContinue
                                   false,                                                           // isCurrentItem
                                   missionItemParent);
231
            items.append(item);
232 233
        }
        firstPoint = false;
234

235 236 237
        if (transectPoint.altitude() < 0 && !imagesEverywhere) {
            if (entryPoint) {
                // Start triggering
238 239 240 241 242 243 244 245 246 247 248
                item = new MissionItem(seqNum++,
                                       MAV_CMD_DO_SET_CAM_TRIGG_DIST,
                                       MAV_FRAME_MISSION,
                                       _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble(),   // trigger distance
                                       0,                                                               // shutter integration (ignore)
                                       1,                                                               // trigger immediately when starting
                                       0, 0, 0, 0,                                                      // param 4-7 unused
                                       true,                                                            // autoContinue
                                       false,                                                           // isCurrentItem
                                       missionItemParent);
                items.append(item);
249 250 251 252 253 254 255 256 257 258 259 260 261
            } else {
                // Stop triggering
                item = new MissionItem(seqNum++,
                                                    MAV_CMD_DO_SET_CAM_TRIGG_DIST,
                                                    MAV_FRAME_MISSION,
                                                    0,           // stop triggering
                                                    0,           // shutter integration (ignore)
                                                    0,           // trigger immediately when starting
                                                    0, 0, 0, 0,  // param 4-7 unused
                                                    true,        // autoContinue
                                                    false,       // isCurrentItem
                                                    missionItemParent);
                items.append(item);
262
            }
263
            entryPoint = !entryPoint;
264
        }
265
    }
266 267

    if (imagesEverywhere) {
268
        // Stop triggering
269 270 271 272 273 274 275 276 277 278 279 280
        MissionItem* item = new MissionItem(seqNum++,
                                            MAV_CMD_DO_SET_CAM_TRIGG_DIST,
                                            MAV_FRAME_MISSION,
                                            0,           // stop triggering
                                            0,           // shutter integration (ignore)
                                            0,           // trigger immediately when starting
                                            0, 0, 0, 0,  // param 4-7 unused
                                            true,        // autoContinue
                                            false,       // isCurrentItem
                                            missionItemParent);
        items.append(item);
    }
281 282
}

283 284 285 286 287 288 289 290 291 292 293
void CorridorScanComplexItem::appendMissionItems(QList<MissionItem*>& items, QObject* missionItemParent)
{
    if (_loadedMissionItems.count()) {
        // We have mission items from the loaded plan, use those
        _appendLoadedMissionItems(items, missionItemParent);
    } else {
        // Build the mission items on the fly
        _buildAndAppendMissionItems(items, missionItemParent);
    }
}

294 295
void CorridorScanComplexItem::applyNewAltitude(double newAltitude)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
296 297 298
    _cameraCalc.valueSetIsDistance()->setRawValue(true);
    _cameraCalc.distanceToSurface()->setRawValue(newAltitude);
    _cameraCalc.setDistanceToSurfaceRelative(true);
299 300 301 302 303 304 305 306 307 308 309
}

void CorridorScanComplexItem::_polylineDirtyChanged(bool dirty)
{
    if (dirty) {
        setDirty(true);
    }
}

void CorridorScanComplexItem::rotateEntryPoint(void)
{
310 311 312
    _entryPoint++;
    if (_entryPoint > 3) {
        _entryPoint = 0;
313
    }
314 315

    _rebuildCorridor();
316 317 318 319 320
}

void CorridorScanComplexItem::_rebuildCorridorPolygon(void)
{
    if (_corridorPolyline.count() < 2) {
321
        _surveyAreaPolygon.clear();
322 323 324 325 326 327 328 329
        return;
    }

    double halfWidth = _corridorWidthFact.rawValue().toDouble() / 2.0;

    QList<QGeoCoordinate> firstSideVertices = _corridorPolyline.offsetPolyline(halfWidth);
    QList<QGeoCoordinate> secondSideVertices = _corridorPolyline.offsetPolyline(-halfWidth);

330
    _surveyAreaPolygon.clear();
331
    foreach (const QGeoCoordinate& vertex, firstSideVertices) {
332
        _surveyAreaPolygon.appendVertex(vertex);
333 334
    }
    for (int i=secondSideVertices.count() - 1; i >= 0; i--) {
335
        _surveyAreaPolygon.appendVertex(secondSideVertices[i]);
336 337 338
    }
}

339
void CorridorScanComplexItem::_rebuildTransectsPhase1(void)
340
{
341 342 343 344 345 346 347 348 349 350 351
    if (_ignoreRecalc) {
        return;
    }

    // If the transects are getting rebuilt then any previsouly loaded mission items are now invalid
    if (_loadedMissionItemsParent) {
        _loadedMissionItems.clear();
        _loadedMissionItemsParent->deleteLater();
        _loadedMissionItemsParent = NULL;
    }

352
    _transectPoints.clear();
353
    _transectsPathHeightInfo.clear();
354 355 356 357 358 359 360

    double transectSpacing = _cameraCalc.adjustedFootprintSide()->rawValue().toDouble();
    double fullWidth = _corridorWidthFact.rawValue().toDouble();
    double halfWidth = fullWidth / 2.0;
    int transectCount = _transectCount();
    double normalizedTransectPosition = transectSpacing / 2.0;

361 362 363 364 365 366 367 368 369 370 371 372 373 374
    if (_corridorPolyline.count() >= 2) {
        // First build up the transects all going the same direction
        QList<QList<QGeoCoordinate>> transects;
        for (int i=0; i<transectCount; i++) {
            double offsetDistance;
            if (transectCount == 1) {
                // Single transect is flown over scan line
                offsetDistance = 0;
            } else {
                // Convert from normalized to absolute transect offset distance
                offsetDistance = halfWidth - normalizedTransectPosition;
            }

            QList<QGeoCoordinate> transect = _corridorPolyline.offsetPolyline(offsetDistance);
375 376
            transect[0].setAltitude(_surveyEdgeIndicator);
            transect[1].setAltitude(_surveyEdgeIndicator);
377 378 379 380 381 382
            if (_hasTurnaround()) {
                QGeoCoordinate extensionCoord;

                // Extend the transect ends for turnaround
                double azimuth = transect[0].azimuthTo(transect[1]);
                extensionCoord = transect[0].atDistanceAndAzimuth(-_turnAroundDistanceFact.rawValue().toDouble(), azimuth);
DonLakeFlyer's avatar
DonLakeFlyer committed
383
                extensionCoord.setAltitude(qQNaN());
384 385 386
                transect.prepend(extensionCoord);
                azimuth = transect.last().azimuthTo(transect[transect.count() - 2]);
                extensionCoord = transect.last().atDistanceAndAzimuth(-_turnAroundDistanceFact.rawValue().toDouble(), azimuth);
DonLakeFlyer's avatar
DonLakeFlyer committed
387
                extensionCoord.setAltitude(qQNaN());
388 389 390 391 392
                transect.append(extensionCoord);
            }

            transects.append(transect);
            normalizedTransectPosition += transectSpacing;
393 394
        }

395 396 397 398 399 400 401 402 403 404 405
        // Now deal with fixing up the entry point:
        //  0: Leave alone
        //  1: Start at same end, opposite side of center
        //  2: Start at opposite end, same side
        //  3: Start at opposite end, opposite side

        bool reverseTransects = false;
        bool reverseVertices = false;
        switch (_entryPoint) {
        case 0:
            reverseTransects = false;
406
            reverseVertices = false;
407 408 409 410 411 412 413 414 415 416 417
            break;
        case 1:
            reverseTransects = true;
            reverseVertices = false;
            break;
        case 2:
            reverseTransects = false;
            reverseVertices = true;
            break;
        case 3:
            reverseTransects = true;
418
            reverseVertices = true;
419
            break;
420
        }
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        if (reverseTransects) {
            QList<QList<QGeoCoordinate>> reversedTransects;
            foreach (const QList<QGeoCoordinate>& transect, transects) {
                reversedTransects.prepend(transect);
            }
            transects = reversedTransects;
        }
        if (reverseVertices) {
            for (int i=0; i<transects.count(); i++) {
                QList<QGeoCoordinate> reversedVertices;
                foreach (const QGeoCoordinate& vertex, transects[i]) {
                    reversedVertices.prepend(vertex);
                }
                transects[i] = reversedVertices;
            }
436 437
        }

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
        // Convert the list of transects to grid points
        reverseVertices = false;
        for (int i=0; i<transects.count(); i++) {
            // We must reverse the vertices for every other transect in order to make a lawnmower pattern
            QList<QGeoCoordinate> transectVertices = transects[i];
            if (reverseVertices) {
                reverseVertices = false;
                QList<QGeoCoordinate> reversedVertices;
                for (int j=transectVertices.count()-1; j>=0; j--) {
                    reversedVertices.append(transectVertices[j]);
                }
                transectVertices = reversedVertices;
            } else {
                reverseVertices = true;
            }
            for (int i=0; i<transectVertices.count(); i++) {
                _transectPoints.append(QVariant::fromValue((transectVertices[i])));
            }

            normalizedTransectPosition += transectSpacing;
        }
459
    }
460 461

    _queryTransectsPathHeightInfo();
462
}
463

464 465
void CorridorScanComplexItem::_rebuildTransectsPhase2(void)
{
466 467 468 469 470 471
    // Calculate distance flown for complex item
    _complexDistance = 0;
    for (int i=0; i<_transectPoints.count() - 2; i++) {
        _complexDistance += _transectPoints[i].value<QGeoCoordinate>().distanceTo(_transectPoints[i+1].value<QGeoCoordinate>());
    }

472
    if (_cameraTriggerInTurnAroundFact.rawValue().toBool()) {
473
        _cameraShots = qCeil(_complexDistance / _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble());
474 475 476
    } else {
        int singleTransectImageCount = qCeil(_corridorPolyline.length() / _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble());
        _cameraShots = singleTransectImageCount * _transectCount();
477 478 479 480 481 482 483
    }

    _coordinate = _transectPoints.count() ? _transectPoints.first().value<QGeoCoordinate>() : QGeoCoordinate();
    _exitCoordinate = _transectPoints.count() ? _transectPoints.last().value<QGeoCoordinate>() : QGeoCoordinate();

    emit transectPointsChanged();
    emit cameraShotsChanged();
484
    emit complexDistanceChanged();
485 486 487 488 489 490 491
    emit coordinateChanged(_coordinate);
    emit exitCoordinateChanged(_exitCoordinate);
}

void CorridorScanComplexItem::_rebuildCorridor(void)
{
    _rebuildCorridorPolygon();
492 493
    _rebuildTransectsPhase1();
    _rebuildTransectsPhase2();
494
}
495 496 497 498 499

bool CorridorScanComplexItem::readyForSave(void) const
{
    return TransectStyleComplexItem::readyForSave();
}