CorridorScanComplexItem.cc 14.9 KB
Newer Older
1 2
/****************************************************************************
 *
Gus Grubba's avatar
Gus Grubba committed
3
 * (c) 2009-2020 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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"
19
#include "PlanMasterController.h"
20 21 22 23 24

#include <QPolygonF>

QGC_LOGGING_CATEGORY(CorridorScanComplexItemLog, "CorridorScanComplexItemLog")

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

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

31 32
CorridorScanComplexItem::CorridorScanComplexItem(PlanMasterController* masterController, bool flyView, const QString& kmlFile, QObject* parent)
    : TransectStyleComplexItem  (masterController, flyView, settingsGroup, parent)
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
    connect(&_corridorPolyline,     &QGCMapPolyline::dirtyChanged,  this, &CorridorScanComplexItem::_polylineDirtyChanged);
51

52 53
    connect(&_corridorPolyline,     &QGCMapPolyline::pathChanged,   this, &CorridorScanComplexItem::_rebuildCorridorPolygon);
    connect(&_corridorWidthFact,    &Fact::valueChanged,            this, &CorridorScanComplexItem::_rebuildCorridorPolygon);
54

DonLakeFlyer's avatar
DonLakeFlyer committed
55 56
    connect(&_corridorPolyline,     &QGCMapPolyline::isValidChanged,this, &CorridorScanComplexItem::readyForSaveStateChanged);

57 58 59 60 61
    if (!kmlFile.isEmpty()) {
        _corridorPolyline.loadKMLFile(kmlFile);
        _corridorPolyline.setDirty(false);
    }
    setDirty(false);
62 63
}

64
void CorridorScanComplexItem::save(QJsonArray&  planItems)
65 66 67
{
    QJsonObject saveObject;

Don Gagne's avatar
Don Gagne committed
68
    TransectStyleComplexItem::_save(saveObject);
69 70

    saveObject[JsonHelper::jsonVersionKey] =                    2;
71 72
    saveObject[VisualMissionItem::jsonTypeKey] =                VisualMissionItem::jsonTypeComplexItemValue;
    saveObject[ComplexMissionItem::jsonComplexItemTypeKey] =    jsonComplexItemTypeValue;
73
    saveObject[corridorWidthName] =                             _corridorWidthFact.rawValue().toDouble();
74
    saveObject[_jsonEntryPointKey] =                            _entryPoint;
75 76 77

    _corridorPolyline.saveToJson(saveObject);

78
    planItems.append(saveObject);
79 80 81 82
}

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

86 87 88 89
    QList<JsonHelper::KeyValidateInfo> keyInfoList = {
        { JsonHelper::jsonVersionKey,                   QJsonValue::Double, true },
        { VisualMissionItem::jsonTypeKey,               QJsonValue::String, true },
        { ComplexMissionItem::jsonComplexItemTypeKey,   QJsonValue::String, true },
90
        { corridorWidthName,                            QJsonValue::Double, true },
91
        { _jsonEntryPointKey,                           QJsonValue::Double, true },
92 93 94
        { QGCMapPolyline::jsonPolylineKey,              QJsonValue::Array,  true },
    };
    if (!JsonHelper::validateKeys(complexObject, keyInfoList, errorString)) {
95
        _ignoreRecalc = false;
96 97 98
        return false;
    }

DonLakeFlyer's avatar
DonLakeFlyer committed
99
    if (!_corridorPolyline.loadFromJson(complexObject, true, errorString)) {
100
        _ignoreRecalc = false;
DonLakeFlyer's avatar
DonLakeFlyer committed
101 102
        return false;
    }
103 104 105 106 107

    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);
108
        _ignoreRecalc = false;
109 110 111 112
        return false;
    }

    int version = complexObject[JsonHelper::jsonVersionKey].toInt();
113
    if (version != 2) {
114
        errorString = tr("%1 complex item version %2 not supported").arg(jsonComplexItemTypeValue).arg(version);
115
        _ignoreRecalc = false;
116 117 118 119 120
        return false;
    }

    setSequenceNumber(sequenceNumber);

Don Gagne's avatar
Don Gagne committed
121
    if (!_load(complexObject, false /* forPresets */, errorString)) {
122
        _ignoreRecalc = false;
123 124 125
        return false;
    }

126 127
    _corridorWidthFact.setRawValue      (complexObject[corridorWidthName].toDouble());

128
    _entryPoint = complexObject[_jsonEntryPointKey].toInt();
129

130 131
    _ignoreRecalc = false;

132 133 134 135 136 137
    _recalcComplexDistance();
    if (_cameraShots == 0) {
        // Shot count was possibly not available from plan file
        _recalcCameraShots();
    }

138 139 140 141 142 143 144 145
    return true;
}

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

146
int CorridorScanComplexItem::_calcTransectCount(void) const
147 148
{
    double fullWidth = _corridorWidthFact.rawValue().toDouble();
149
    return fullWidth > 0.0 ? qCeil(fullWidth / _calcTransectSpacing()) : 1;
150 151
}

152 153
void CorridorScanComplexItem::applyNewAltitude(double newAltitude)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
154 155 156
    _cameraCalc.valueSetIsDistance()->setRawValue(true);
    _cameraCalc.distanceToSurface()->setRawValue(newAltitude);
    _cameraCalc.setDistanceToSurfaceRelative(true);
157 158 159 160 161 162 163 164 165 166 167
}

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

void CorridorScanComplexItem::rotateEntryPoint(void)
{
168 169 170
    _entryPoint++;
    if (_entryPoint > 3) {
        _entryPoint = 0;
171
    }
172

173
    _rebuildTransects();
174 175 176 177 178
}

void CorridorScanComplexItem::_rebuildCorridorPolygon(void)
{
    if (_corridorPolyline.count() < 2) {
179
        _surveyAreaPolygon.clear();
180 181 182 183 184 185 186 187
        return;
    }

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

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

188
    _surveyAreaPolygon.clear();
DonLakeFlyer's avatar
DonLakeFlyer committed
189 190

    QList<QGeoCoordinate> rgCoord;
191
    for (const QGeoCoordinate& vertex: firstSideVertices) {
DonLakeFlyer's avatar
DonLakeFlyer committed
192
        rgCoord.append(vertex);
193 194
    }
    for (int i=secondSideVertices.count() - 1; i >= 0; i--) {
DonLakeFlyer's avatar
DonLakeFlyer committed
195
        rgCoord.append(secondSideVertices[i]);
196
    }
DonLakeFlyer's avatar
DonLakeFlyer committed
197
    _surveyAreaPolygon.appendVertices(rgCoord);
198 199
}

200
void CorridorScanComplexItem::_rebuildTransectsPhase1(void)
201
{
202 203 204 205 206 207 208 209
    if (_ignoreRecalc) {
        return;
    }

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

213
    _transects.clear();
214
    _transectsPathHeightInfo.clear();
215

216
    double transectSpacing = _calcTransectSpacing();
217 218
    double fullWidth = _corridorWidthFact.rawValue().toDouble();
    double halfWidth = fullWidth / 2.0;
219
    int transectCount = _calcTransectCount();
220 221
    double normalizedTransectPosition = transectSpacing / 2.0;

222 223
    if (_corridorPolyline.count() >= 2) {
        // First build up the transects all going the same direction
224
        //qDebug() << "_rebuildTransectsPhase1";
225
        for (int i=0; i<transectCount; i++) {
226
            //qDebug() << "start transect";
227 228 229 230 231 232 233 234 235
            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;
            }

236 237 238 239 240 241 242
            // Turn transect into CoordInfo transect
            QList<TransectStyleComplexItem::CoordInfo_t> transect;
            QList<QGeoCoordinate> transectCoords = _corridorPolyline.offsetPolyline(offsetDistance);
            for (int j=1; j<transectCoords.count() - 1; j++) {
                TransectStyleComplexItem::CoordInfo_t coordInfo = { transectCoords[j], CoordTypeInterior };
                transect.append(coordInfo);
            }
243
            TransectStyleComplexItem::CoordInfo_t coordInfo = { transectCoords.first(), CoordTypeSurveyEntry };
244
            transect.prepend(coordInfo);
245
            coordInfo = { transectCoords.last(), CoordTypeSurveyExit };
246 247 248
            transect.append(coordInfo);

            // Extend the transect ends for turnaround
249
            if (_hasTurnaround()) {
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                 QGeoCoordinate turnaroundCoord;
                 double turnAroundDistance = _turnAroundDistanceFact.rawValue().toDouble();

                 double azimuth = transectCoords[0].azimuthTo(transectCoords[1]);
                 turnaroundCoord = transectCoords[0].atDistanceAndAzimuth(-turnAroundDistance, azimuth);
                 turnaroundCoord.setAltitude(qQNaN());
                 TransectStyleComplexItem::CoordInfo_t coordInfo = { turnaroundCoord, CoordTypeTurnaround };
                 transect.prepend(coordInfo);

                 azimuth = transectCoords.last().azimuthTo(transectCoords[transectCoords.count() - 2]);
                 turnaroundCoord = transectCoords.last().atDistanceAndAzimuth(-turnAroundDistance, azimuth);
                 turnaroundCoord.setAltitude(qQNaN());
                 coordInfo = { turnaroundCoord, CoordTypeTurnaround };
                 transect.append(coordInfo);
            }

#if 0
            qDebug() << "transect debug";
268
            for (const TransectStyleComplexItem::CoordInfo_t& coordInfo: transect) {
269
                qDebug() << coordInfo.coordType;
270
            }
271
#endif
272

273
            _transects.append(transect);
274
            normalizedTransectPosition += transectSpacing;
275 276
        }

277 278 279 280 281 282 283 284 285 286 287
        // 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;
288
            reverseVertices = false;
289 290 291 292 293 294 295 296 297 298 299
            break;
        case 1:
            reverseTransects = true;
            reverseVertices = false;
            break;
        case 2:
            reverseTransects = false;
            reverseVertices = true;
            break;
        case 3:
            reverseTransects = true;
300
            reverseVertices = true;
301
            break;
302
        }
303
        if (reverseTransects) {
304
            QList<QList<TransectStyleComplexItem::CoordInfo_t>> reversedTransects;
305
            for (const QList<TransectStyleComplexItem::CoordInfo_t>& transect: _transects) {
306 307
                reversedTransects.prepend(transect);
            }
308
            _transects = reversedTransects;
309 310
        }
        if (reverseVertices) {
311 312
            for (int i=0; i<_transects.count(); i++) {
                QList<TransectStyleComplexItem::CoordInfo_t> reversedVertices;
313
                for (const TransectStyleComplexItem::CoordInfo_t& vertex: _transects[i]) {
314 315
                    reversedVertices.prepend(vertex);
                }
316
                _transects[i] = reversedVertices;
317
            }
318 319
        }

320
        // Adjust to lawnmower pattern
321
        reverseVertices = false;
322
        for (int i=0; i<_transects.count(); i++) {
323
            // We must reverse the vertices for every other transect in order to make a lawnmower pattern
324
            QList<TransectStyleComplexItem::CoordInfo_t> transectVertices = _transects[i];
325 326
            if (reverseVertices) {
                reverseVertices = false;
327
                QList<TransectStyleComplexItem::CoordInfo_t> reversedVertices;
328 329 330 331 332 333 334
                for (int j=transectVertices.count()-1; j>=0; j--) {
                    reversedVertices.append(transectVertices[j]);
                }
                transectVertices = reversedVertices;
            } else {
                reverseVertices = true;
            }
335
            _transects[i] = transectVertices;
336
        }
337
    }
338
}
339

340
void CorridorScanComplexItem::_recalcComplexDistance(void)
341
{
342
    _complexDistance = 0;
343
    for (int i=0; i<_visualTransectPoints.count() - 1; i++) {
344
        _complexDistance += _visualTransectPoints[i].value<QGeoCoordinate>().distanceTo(_visualTransectPoints[i+1].value<QGeoCoordinate>());
345
    }
346 347
    emit complexDistanceChanged();
}
348

349 350
void CorridorScanComplexItem::_recalcCameraShots(void)
{
351 352 353
    double triggerDistance = _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble();
    if (triggerDistance == 0) {
        _cameraShots = 0;
354
    } else {
355 356 357 358
        if (_cameraTriggerInTurnAroundFact.rawValue().toBool()) {
            _cameraShots = qCeil(_complexDistance / triggerDistance);
        } else {
            int singleTransectImageCount = qCeil(_corridorPolyline.length() / triggerDistance);
359
            _cameraShots = singleTransectImageCount * _calcTransectCount();
360
        }
361 362 363 364
    }
    emit cameraShotsChanged();
}

DonLakeFlyer's avatar
DonLakeFlyer committed
365
CorridorScanComplexItem::ReadyForSaveState CorridorScanComplexItem::readyForSaveState(void) const
366
{
DonLakeFlyer's avatar
DonLakeFlyer committed
367
    return TransectStyleComplexItem::readyForSaveState();
368
}
369 370 371

double CorridorScanComplexItem::timeBetweenShots(void)
{
372
    return _cruiseSpeed == 0 ? 0 : _cameraCalc.adjustedFootprintFrontal()->rawValue().toDouble() / _cruiseSpeed;
373
}
374

375
double CorridorScanComplexItem::_calcTransectSpacing(void) const
376 377 378 379 380 381 382 383 384 385 386
{
    double transectSpacing = _cameraCalc.adjustedFootprintSide()->rawValue().toDouble();
    if (transectSpacing < 0.5) {
        // We can't let spacing get too small otherwise we will end up with too many transects.
        // So we limit to 0.5 meter spacing as min and set to huge value which will cause a single
        // transect to be added.
        transectSpacing = 100000;
    }

    return transectSpacing;
}