CircularSurveyComplexItem.cc 27.3 KB
Newer Older
1
#include "CircularSurveyComplexItem.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
2 3
#include "JsonHelper.h"
#include "QGCApplication.h"
4
#include <chrono>
5

6

Valentin Platzgummer's avatar
Valentin Platzgummer committed
7
const char* CircularSurveyComplexItem::settingsGroup =              "CircularSurvey";
8 9
const char* CircularSurveyComplexItem::deltaRName =                 "DeltaR";
const char* CircularSurveyComplexItem::deltaAlphaName =             "DeltaAlpha";
10
const char* CircularSurveyComplexItem::transectMinLengthName =      "TransectMinLength";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
11
const char* CircularSurveyComplexItem::fixedDirectionName =         "FixedDirection";
12
const char* CircularSurveyComplexItem::reverseName =                "Reverse";
13
const char* CircularSurveyComplexItem::maxWaypointsName =           "MaxWaypoints";
14

15

Valentin Platzgummer's avatar
Valentin Platzgummer committed
16 17 18
const char* CircularSurveyComplexItem::jsonComplexItemTypeValue     =   "circularSurvey";
const char* CircularSurveyComplexItem::jsonDeltaRKey                =   "deltaR";
const char* CircularSurveyComplexItem::jsonDeltaAlphaKey            =   "deltaAlpha";
19
const char* CircularSurveyComplexItem::jsonTransectMinLengthKey     =   "transectMinLength";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
20
const char* CircularSurveyComplexItem::jsonfixedDirectionKey        =   "fixedDirection";
21
const char* CircularSurveyComplexItem::jsonReverseKey               =   "reverse";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
22 23 24 25
const char* CircularSurveyComplexItem::jsonReferencePointLatKey     =   "referencePointLat";
const char* CircularSurveyComplexItem::jsonReferencePointLongKey    =   "referencePointLong";
const char* CircularSurveyComplexItem::jsonReferencePointAltKey     =   "referencePointAlt";

26
CircularSurveyComplexItem::CircularSurveyComplexItem(Vehicle *vehicle, bool flyView, const QString &kmlOrShpFile, QObject *parent)
27
    :   TransectStyleComplexItem    (vehicle, flyView, settingsGroup, parent)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
28
    ,   _referencePoint             (QGeoCoordinate(0, 0,0))
29 30 31
    ,   _metaDataMap                (FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/CircularSurvey.SettingsGroup.json"), this))
    ,   _deltaR                     (settingsGroup, _metaDataMap[deltaRName])
    ,   _deltaAlpha                 (settingsGroup, _metaDataMap[deltaAlphaName])
32
    ,   _transectMinLength          (settingsGroup, _metaDataMap[transectMinLengthName])
Valentin Platzgummer's avatar
Valentin Platzgummer committed
33
    ,   _fixedDirection             (settingsGroup, _metaDataMap[fixedDirectionName])
34
    ,   _reverse                    (settingsGroup, _metaDataMap[reverseName])
35
    ,   _maxWaypoints               (settingsGroup, _metaDataMap[maxWaypointsName])
36
    ,   _isInitialized              (false)
37
    ,   _reverseOnly                (false)
38
{
39
    Q_UNUSED(kmlOrShpFile)
40
    _editorQml = "qrc:/qml/CircularSurveyItemEditor.qml";
41 42 43
    connect(&_deltaR,               &Fact::valueChanged, this, &CircularSurveyComplexItem::_triggerSlowRecalc);
    connect(&_deltaAlpha,           &Fact::valueChanged, this, &CircularSurveyComplexItem::_triggerSlowRecalc);
    connect(&_transectMinLength,    &Fact::valueChanged, this, &CircularSurveyComplexItem::_triggerSlowRecalc);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
44
    connect(&_fixedDirection,       &Fact::valueChanged, this, &CircularSurveyComplexItem::_triggerSlowRecalc);
45
    connect(&_maxWaypoints,         &Fact::valueChanged, this, &CircularSurveyComplexItem::_triggerSlowRecalc);
46
    connect(&_reverse,              &Fact::valueChanged, this, &CircularSurveyComplexItem::_reverseTransects);
47
    connect(this,                   &CircularSurveyComplexItem::refPointChanged, this, &CircularSurveyComplexItem::_triggerSlowRecalc);
48
    //connect(&_cameraCalc.distanceToSurface(), &Fact::rawValueChanged, this->)
49

50 51
}

52 53 54 55 56
void CircularSurveyComplexItem::resetReference()
{
    setRefPoint(_surveyAreaPolygon.center());
}

57 58 59 60 61
void CircularSurveyComplexItem::comprehensiveUpdate()
{
    _triggerSlowRecalc();
}

62
void CircularSurveyComplexItem::setRefPoint(const QGeoCoordinate &refPt)
63
{
64 65
    if (refPt != _referencePoint){
        _referencePoint = refPt;
66

67 68 69 70
        emit refPointChanged();
    }
}

71
void CircularSurveyComplexItem::setIsInitialized(bool isInitialized)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
72
{
73 74
    if (isInitialized != _isInitialized) {
        _isInitialized = isInitialized;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
75

76
        emit isInitializedChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
77 78 79
    }
}

80 81 82
QGeoCoordinate CircularSurveyComplexItem::refPoint() const
{
    return _referencePoint;
83 84
}

85 86 87 88 89 90 91 92 93 94
Fact *CircularSurveyComplexItem::deltaR()
{
    return &_deltaR;
}

Fact *CircularSurveyComplexItem::deltaAlpha()
{
    return &_deltaAlpha;
}

95
bool CircularSurveyComplexItem::isInitialized()
Valentin Platzgummer's avatar
Valentin Platzgummer committed
96
{
97
    return _isInitialized;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
98 99
}

100 101
bool CircularSurveyComplexItem::load(const QJsonObject &complexObject, int sequenceNumber, QString &errorString)
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    // We need to pull version first to determine what validation/conversion needs to be performed
    QList<JsonHelper::KeyValidateInfo> versionKeyInfoList = {
        { JsonHelper::jsonVersionKey, QJsonValue::Double, true },
    };
    if (!JsonHelper::validateKeys(complexObject, versionKeyInfoList, errorString)) {
        return false;
    }

    int version = complexObject[JsonHelper::jsonVersionKey].toInt();
    if (version != 1) {
        errorString = tr("Survey items do not support version %1").arg(version);
        return false;
    }

    QList<JsonHelper::KeyValidateInfo> keyInfoList = {
        { VisualMissionItem::jsonTypeKey,               QJsonValue::String, true },
        { ComplexMissionItem::jsonComplexItemTypeKey,   QJsonValue::String, true },
        { jsonDeltaRKey,                                QJsonValue::Double, true },
        { jsonDeltaAlphaKey,                            QJsonValue::Double, true },
121
        { jsonTransectMinLengthKey,                     QJsonValue::Double, true },
Valentin Platzgummer's avatar
Valentin Platzgummer committed
122
        { jsonfixedDirectionKey,                        QJsonValue::Bool,   true },
123
        { jsonReverseKey,                               QJsonValue::Bool,   true },
Valentin Platzgummer's avatar
Valentin Platzgummer committed
124
        { jsonReferencePointLatKey,                     QJsonValue::Double, true },
125
        { jsonReferencePointLongKey,                    QJsonValue::Double, true },
Valentin Platzgummer's avatar
Valentin Platzgummer committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
        { jsonReferencePointAltKey,                     QJsonValue::Double, true },
    };

    if (!JsonHelper::validateKeys(complexObject, keyInfoList, errorString)) {
        return false;
    }

    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);
        return false;
    }

    _ignoreRecalc = true;

    setSequenceNumber(sequenceNumber);

    if (!_surveyAreaPolygon.loadFromJson(complexObject, true /* required */, errorString)) {
        _surveyAreaPolygon.clear();
        return false;
    }

    if (!_load(complexObject, errorString)) {
        _ignoreRecalc = false;
        return false;
    }

    _deltaR.setRawValue             (complexObject[jsonDeltaRKey].toDouble());
    _deltaAlpha.setRawValue         (complexObject[jsonDeltaAlphaKey].toDouble());
156
    _transectMinLength.setRawValue  (complexObject[jsonTransectMinLengthKey].toDouble());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
157 158 159
    _referencePoint.setLongitude    (complexObject[jsonReferencePointLongKey].toDouble());
    _referencePoint.setLatitude     (complexObject[jsonReferencePointLatKey].toDouble());
    _referencePoint.setAltitude     (complexObject[jsonReferencePointAltKey].toDouble());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
160
    _fixedDirection.setRawValue     (complexObject[jsonfixedDirectionKey].toBool());
161
    _reverse.setRawValue            (complexObject[jsonReverseKey].toBool());
162
    setIsInitialized(true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
163 164 165 166 167 168 169 170 171 172

    _ignoreRecalc = false;

    _recalcComplexDistance();
    if (_cameraShots == 0) {
        // Shot count was possibly not available from plan file
        _recalcCameraShots();
    }

    return true;
173 174 175 176
}

void CircularSurveyComplexItem::save(QJsonArray &planItems)
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
177 178 179 180 181 182 183
    QJsonObject saveObject;

    _save(saveObject);

    saveObject[JsonHelper::jsonVersionKey] =                    1;
    saveObject[VisualMissionItem::jsonTypeKey] =                VisualMissionItem::jsonTypeComplexItemValue;
    saveObject[ComplexMissionItem::jsonComplexItemTypeKey] =    jsonComplexItemTypeValue;
184

Valentin Platzgummer's avatar
Valentin Platzgummer committed
185
    saveObject[jsonDeltaRKey]               = _deltaR.rawValue().toDouble();
186
    saveObject[jsonDeltaAlphaKey]           = _deltaAlpha.rawValue().toDouble();    
187
    saveObject[jsonTransectMinLengthKey]    = _transectMinLength.rawValue().toDouble();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
188
    saveObject[jsonfixedDirectionKey]       = _fixedDirection.rawValue().toBool();
189
    saveObject[jsonReverseKey]              = _reverse.rawValue().toBool();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
190 191 192 193 194 195 196 197
    saveObject[jsonReferencePointLongKey]   = _referencePoint.longitude();
    saveObject[jsonReferencePointLatKey]    = _referencePoint.latitude();
    saveObject[jsonReferencePointAltKey]    = _referencePoint.altitude();

    // Polygon shape
    _surveyAreaPolygon.saveToJson(saveObject);

    planItems.append(saveObject);
198 199 200 201
}

void CircularSurveyComplexItem::appendMissionItems(QList<MissionItem *> &items, QObject *missionItemParent)
{
202
    if (_transectsDirty)
203
        return;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
204 205 206 207 208 209 210 211 212 213 214 215
    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);
    }
}

void CircularSurveyComplexItem::_appendLoadedMissionItems(QList<MissionItem*>& items, QObject* missionItemParent)
{
    //qCDebug(SurveyComplexItemLog) << "_appendLoadedMissionItems";
216
    if (_transectsDirty)
217
        return;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
218 219 220 221 222 223 224
    int seqNum = _sequenceNumber;

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
227
void CircularSurveyComplexItem::_buildAndAppendMissionItems(QList<MissionItem*>& items, QObject* missionItemParent)
228
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
229 230 231 232 233
    // original code: SurveyComplexItem::_buildAndAppendMissionItems()
    //qCDebug(SurveyComplexItemLog) << "_buildAndAppendMissionItems";

    // Now build the mission items from the transect points

234
    if (_transectsDirty)
235 236
        return;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
237 238 239
    MissionItem* item;
    int seqNum =                    _sequenceNumber;

240 241
    MAV_FRAME mavFrame = followTerrain() || !_cameraCalc.distanceToSurfaceRelative()
            ? MAV_FRAME_GLOBAL : MAV_FRAME_GLOBAL_RELATIVE_ALT;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
242

243
    for (const QList<TransectStyleComplexItem::CoordInfo_t>& transect : _transects) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
        //bool transectEntry = true;

        for (const CoordInfo_t& transectCoordInfo: transect) {
            item = new MissionItem(seqNum++,
                                   MAV_CMD_NAV_WAYPOINT,
                                   mavFrame,
                                   0,                                           // Hold time (delay for hover and capture to settle vehicle before image is taken)
                                   0.0,                                         // No acceptance radius specified
                                   0.0,                                         // Pass through waypoint
                                   std::numeric_limits<double>::quiet_NaN(),    // Yaw unchanged
                                   transectCoordInfo.coord.latitude(),
                                   transectCoordInfo.coord.longitude(),
                                   transectCoordInfo.coord.altitude(),
                                   true,                                        // autoContinue
                                   false,                                       // isCurrentItem
                                   missionItemParent);
            items.append(item);
        }
    }
}
264

Valentin Platzgummer's avatar
Valentin Platzgummer committed
265 266 267 268 269
void CircularSurveyComplexItem::applyNewAltitude(double newAltitude)
{
    _cameraCalc.valueSetIsDistance()->setRawValue(true);
    _cameraCalc.distanceToSurface()->setRawValue(newAltitude);
    _cameraCalc.setDistanceToSurfaceRelative(true);
270 271 272 273 274 275 276 277 278
}

double CircularSurveyComplexItem::timeBetweenShots()
{
    return 1;
}

bool CircularSurveyComplexItem::readyForSave() const
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
279
    return TransectStyleComplexItem::readyForSave();
280 281 282 283 284 285
}

double CircularSurveyComplexItem::additionalTimeDelay() const
{
    return 0;
}
286
void CircularSurveyComplexItem::_rebuildTransectsPhase1(void){
287
    if (_doFastRecalc){
288 289 290
        _rebuildTransectsFast();
    } else {
        _rebuildTransectsSlow();
291
        _doFastRecalc = true;
292 293
    }
}
294

295
void CircularSurveyComplexItem::_rebuildTransectsFast()
296
{
297 298 299 300
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
    using namespace PlanimetryCalculus;

301
    _transects.clear();
302

Valentin Platzgummer's avatar
Valentin Platzgummer committed
303 304
    QPolygonF surveyPolygon;
    toCartesianList(_surveyAreaPolygon.coordinateList(), _referencePoint, surveyPolygon);
305
    if (!_rebuildTransectsInputCheck(surveyPolygon))
306 307 308 309 310 311 312 313 314
        return;

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

315 316
    QVector<QVector<QPointF>> transectPath;
    if(!_generateTransectPath(transectPath, surveyPolygon))
317 318
        return;

319
    /// optimize path to snake or zig-zag pattern
Valentin Platzgummer's avatar
Valentin Platzgummer committed
320
    bool fixedDirectionBool = _fixedDirection.rawValue().toBool();
321 322
    QVector<QPointF> currentSection = transectPath.takeFirst();
    if ( currentSection.isEmpty() )
323 324
        return;

325 326 327 328 329 330 331
    QVector<QPointF> optiPath; // optimized path
    while( !transectPath.empty() ) {
        optiPath.append(currentSection);
        QPointF endVertex = currentSection.last();
        double minDist = std::numeric_limits<double>::infinity();
        int index = 0;
        bool reversePath = false;
332

333 334 335 336 337 338 339 340
        // iterate over all paths in fullPath and assign the one with the shortest distance to endVertex to currentSection
        for (int i = 0; i < transectPath.size(); i++) {
            auto iteratorPath = transectPath[i];
            double dist = PlanimetryCalculus::distance(endVertex, iteratorPath.first());
            if ( dist < minDist ) {
                minDist = dist;
                index = i;
                reversePath = false;
341
            }
342 343 344 345 346
            dist = PlanimetryCalculus::distance(endVertex, iteratorPath.last());
            if (dist < minDist) {
                minDist = dist;
                index = i;
                reversePath = true;
347 348
            }
        }
349
        currentSection = transectPath.takeAt(index);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
350
        if (reversePath && !fixedDirectionBool) {
351
            PolygonCalculus::reversePath(currentSection);
352 353 354
        }
    }

355
    optiPath.append(currentSection); // append last section
356

357 358
    if (optiPath.size() > _maxWaypoints.rawValue().toInt())
        return;
359 360


361
    _rebuildTransectsToGeo(optiPath, _referencePoint);
362
    _transectsDirty = true;
363 364 365 366 367 368 369
}


void CircularSurveyComplexItem::_rebuildTransectsSlow()
{
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    using namespace PlanimetryCalculus;

    if (_reverseOnly) { // reverse transects and return
        _reverseOnly = false;

        QList<QList<CoordInfo_t>>  transectsReverse;
        transectsReverse.reserve(_transects.size());
        for (auto list : _transects) {
            QList<CoordInfo_t> listReverse;
            for (auto coordinate : list)
                    listReverse.prepend(coordinate);

            transectsReverse.prepend(listReverse);
        }
        _transects = transectsReverse;

        return;
    }
388

389
    _transects.clear();
390

Valentin Platzgummer's avatar
Valentin Platzgummer committed
391 392
    QPolygonF surveyPolygon;
    toCartesianList(_surveyAreaPolygon.coordinateList(), _referencePoint, surveyPolygon);
393 394
    if (!_rebuildTransectsInputCheck(surveyPolygon))
        return;
395

396
    // If the transects are getting rebuilt then any previously loaded mission items are now invalid.
397 398 399 400 401 402
    if (_loadedMissionItemsParent) {
        _loadedMissionItems.clear();
        _loadedMissionItemsParent->deleteLater();
        _loadedMissionItemsParent = nullptr;
    }

403 404
    QVector<QVector<QPointF>> transectPath;
    if(!_generateTransectPath(transectPath, surveyPolygon))
405 406
        return;

407
    // optimize path to snake or zig-zag pattern
Valentin Platzgummer's avatar
Valentin Platzgummer committed
408
    const bool fixedDirectionBool = _fixedDirection.rawValue().toBool();
409 410 411 412 413 414 415
    QVector<QPointF> currentSection = transectPath.takeFirst(); if ( currentSection.isEmpty() ) return;
    QVector<QPointF> optimizedPath(currentSection);
    bool reversePath = true; // controlls if currentSection gets reversed, has nothing todo with _reverseOnly
    while( !transectPath.empty() ) {
        QPointF endVertex = currentSection.last();
        double minDist = std::numeric_limits<double>::infinity();
        int index = 0;
416

417 418 419 420 421 422
        // iterate over all paths in fullPath and assign the one with the shortest distance to endVertex to currentSection
        QVector<QPointF> connectorPath;
        for (int i = 0; i < transectPath.size(); i++) {
            QVector<QPointF> iteratorPath = transectPath[i];
            QVector<QPointF> tempConnectorPath;
            bool retVal;
423

Valentin Platzgummer's avatar
Valentin Platzgummer committed
424
            if (reversePath  && !fixedDirectionBool) {
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
                 retVal = PolygonCalculus::shortestPath(surveyPolygon, endVertex, iteratorPath.last(), tempConnectorPath);
            } else {
                 retVal = PolygonCalculus::shortestPath(surveyPolygon, endVertex, iteratorPath.first(), tempConnectorPath);
            }

            if (!retVal)
                qWarning("CircularSurveyComplexItem::_rebuildTransectsPhase1: internal error; false shortestPath");

            double dist = 0;
            for (int i = 0; i < tempConnectorPath.size()-1; ++i)
                dist += PlanimetryCalculus::distance(tempConnectorPath[i], tempConnectorPath[i+1]);

            if (dist < minDist) {
                minDist = dist;
                index = i;
                connectorPath = tempConnectorPath;
            }
        }
        currentSection = transectPath.takeAt(index);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
444
        if (reversePath && !fixedDirectionBool) {
445 446 447 448 449
            PolygonCalculus::reversePath(currentSection);
        }

        reversePath ^= true; // toggle

450 451 452 453
        connectorPath.pop_front();
        connectorPath.pop_back();
        if (connectorPath.size() > 0)
            optimizedPath.append(connectorPath);
454 455 456
        optimizedPath.append(currentSection);
    }
    if (optimizedPath.size() > _maxWaypoints.rawValue().toInt())
457
        return;
458 459

    _rebuildTransectsToGeo(optimizedPath, _referencePoint);
460 461 462 463

    _transectsDirty      = false;
    //_triggerSlowRecalcTimer.stop(); // stop any pending slow recalculations
    return;
464 465 466 467
}

void CircularSurveyComplexItem::_triggerSlowRecalc()
{
468
    _doFastRecalc = false;
469 470 471 472 473 474
    _rebuildTransects();
}

void CircularSurveyComplexItem::_recalcComplexDistance()
{
    _complexDistance = 0;
475
    if (_transectsDirty)
476
        return;
477 478 479 480 481
    for (int i=0; i<_visualTransectPoints.count() - 1; i++) {
        _complexDistance += _visualTransectPoints[i].value<QGeoCoordinate>().distanceTo(_visualTransectPoints[i+1].value<QGeoCoordinate>());
    }
    emit complexDistanceChanged();
}
482

483 484 485 486 487 488 489 490 491
// no cameraShots in Circular Survey, add if desired
void CircularSurveyComplexItem::_recalcCameraShots()
{
    _cameraShots = 0;
}

void CircularSurveyComplexItem::_reverseTransects()
{
    _reverseOnly = true;
492
    _triggerSlowRecalc();
493 494 495 496 497 498
}

bool CircularSurveyComplexItem::_shortestPath(const QGeoCoordinate &start, const QGeoCoordinate &destination, QVector<QGeoCoordinate> &shortestPath)
{
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
499 500 501 502 503
    QPolygonF polygon2D;
    toCartesianList(this->surveyAreaPolygon()->coordinateList(), /*origin*/ start, polygon2D);
    QPointF start2D(0,0);
    QPointF end2D;
    toCartesian(destination, start, end2D);
504 505
    QVector<QPointF> path2D;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
506
    bool retVal = PolygonCalculus::shortestPath(polygon2D, start2D, end2D, path2D);
507
    if (retVal)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
508
        toGeoList(path2D, /*origin*/ start, shortestPath);
509 510 511 512 513 514 515 516 517

    return  retVal;
}

bool CircularSurveyComplexItem::_generateTransectPath(QVector<QVector<QPointF> > &transectPath, const QPolygonF &surveyPolygon)
{
    using namespace PlanimetryCalculus;
    QVector<double> distances;
    for (const QPointF &p : surveyPolygon) distances.append(norm(p));
518

519
    // fetch input data
520 521 522 523 524
    double dalpha   = _deltaAlpha.rawValue().toDouble()/180.0*M_PI; // angle discretisation of circles
    double dr       = _deltaR.rawValue().toDouble(); // distance between circles
    double lmin     = _transectMinLength.rawValue().toDouble(); // minimal transect length
    double r_min    = dr; // minimal circle radius
    double r_max    = (*std::max_element(distances.begin(), distances.end())); // maximal circle radius
525
    unsigned int maxWaypoints = _maxWaypoints.rawValue().toUInt();
526 527 528

    QPointF origin(0, 0);
    IntersectType type;
529
    bool originInside = true;
530 531 532 533 534
    if (!contains(surveyPolygon, origin, type)) {
        QVector<double> angles;
        for (const QPointF &p : surveyPolygon) angles.append(truncateAngle(angle(p)));

        // determine r_min by successive approximation
535 536
        double r = r_min;
        while ( r < r_max) {
537 538
            Circle circle(r, origin);

539
            if (intersects(circle, surveyPolygon)) {
540 541 542 543
                r_min = r;
                break;
            }

544
            r += dr;
545
        }
546
        originInside = false;
547 548
    }

549 550
    double r = r_min;

551
    unsigned int waypointCounter = 0;
552 553
    while (r < r_max) {
        Circle circle(r, origin);
554 555 556
        QVector<QPointFVector> intersectPoints;
        QVector<IntersectType> typeList;
        QVector<QPair<int, int>> neighbourList;
557 558 559 560
        if (intersects(circle, surveyPolygon, intersectPoints, neighbourList, typeList)) {

            // intersection Points between circle and polygon, entering polygon
            // when walking in counterclockwise direction along circle
561
            QVector<QPointF> entryPoints;
562 563
            // intersection Points between circle and polygon, leaving polygon
            // when walking in counterclockwise direction along circle
564
            QVector<QPointF> exitPoints;
565 566
            // determine entryPoints and exit Points
            for (int j = 0; j < intersectPoints.size(); j++) {
567
                QVector<QPointF> intersects = intersectPoints[j]; // one pt = tangent, two pt = sekant
568 569 570 571

                QPointF p1 = surveyPolygon[neighbourList[j].first];
                QPointF p2 = surveyPolygon[neighbourList[j].second];
                QLineF intersetLine(p1, p2);
572 573
                double lineAngle = angle(intersetLine);

574
                for (QPointF ipt : intersects) {
575 576 577 578 579
                    double circleTangentAngle = angle(ipt)+M_PI_2;
                    if (   !qFuzzyIsNull(truncateAngle(lineAngle - circleTangentAngle))
                        && !qFuzzyIsNull(truncateAngle(lineAngle - circleTangentAngle - M_PI) ))
                        {
                        if (truncateAngle(circleTangentAngle - lineAngle)  > M_PI) {
580 581 582
                            entryPoints.append(ipt);
                        } else {
                            exitPoints.append(ipt);
583
                        }
584 585
                    }
                }
586
            }
587

588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
            // sort
            std::sort(entryPoints.begin(), entryPoints.end(), [](QPointF p1, QPointF p2) {
               return angle(p1) < angle(p2);
            });
            std::sort(exitPoints.begin(), exitPoints.end(), [](QPointF p1, QPointF p2) {
               return angle(p1) < angle(p2);
            });

            // match entry and exit points
            int offset = 0;
            double minAngle = std::numeric_limits<double>::infinity();
            for (int k = 0; k < exitPoints.size(); k++) {
                QPointF pt = exitPoints[k];
                double alpha = truncateAngle(angle(pt) - angle(entryPoints[0]));
                if (minAngle > alpha) {
                    minAngle = alpha;
                    offset = k;
605
                }
606
            }
607

608
            // generate circle sectors
609 610 611
            for (int k = 0; k < entryPoints.size(); k++) {
                double alpha1 = angle(entryPoints[k]);
                double alpha2 = angle(exitPoints[(k+offset) % entryPoints.size()]);
612
                double dAlpha = truncateAngle(alpha2-alpha1);
613
                int numNodes = int(ceil(dAlpha/dalpha)) + 1;
614

615
                QVector<QPointF> sectorPath = circle.approximateSektor(numNodes, alpha1, alpha2);
616
                // use shortestPath() here if necessary, could be a problem if dr >>
617 618 619
                if (sectorPath.size() > 0) {
                    waypointCounter += uint(sectorPath.size());
                    if (waypointCounter > maxWaypoints )
620
                        return false;
621
                    transectPath.append(sectorPath);
622
                }
623
            }
624
        } else if (originInside) {
625
            // circle fully inside polygon
626
            int numNodes = int(ceil(2*M_PI/dalpha)) + 1;
627
            QVector<QPointF> sectorPath = circle.approximateSektor(numNodes, 0, 2*M_PI);
628
            // use shortestPath() here if necessary, could be a problem if dr >>
629 630
            waypointCounter += uint(sectorPath.size());
            if (waypointCounter > maxWaypoints )
631
                return false;
632
            transectPath.append(sectorPath);
633
        }
634 635 636 637
        r += dr;
     }

    if (transectPath.size() == 0)
638
        return false;;
639

640
    // remove short transects
641 642
    for (int i = 0; i < transectPath.size(); i++) {
        auto transect = transectPath[i];
643 644 645 646 647 648
        double len = 0;
        for (int j = 0; j < transect.size()-1; ++j) {
            len += PlanimetryCalculus::distance(transect[j], transect[j+1]);
        }

        if (len < lmin)
649
            transectPath.removeAt(i--);
650
    }
651
    if (transectPath.size() == 0)
652
        return false;
653

654 655
    return true;
}
656

657 658 659 660 661
bool CircularSurveyComplexItem::_rebuildTransectsInputCheck(QPolygonF &poly)
{
    // rebuild not necessary?
    if (!_isInitialized)
        return false;
662

663 664 665
    // check if input is valid
    if ( _surveyAreaPolygon.count() < 3)
        return false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
666

667 668 669
    // some more checks
    if (!PolygonCalculus::isSimplePolygon(poly))
        return false;
670

671 672 673
    // even more checks
    if (!PolygonCalculus::hasClockwiseWinding(poly))
        PolygonCalculus::reversePath(poly);
674

675 676 677 678 679 680 681
    // check if input is valid
    if (   _deltaAlpha.rawValue() > _deltaAlpha.rawMax()
           && _deltaAlpha.rawValue() < _deltaAlpha.rawMin())
        return false;
    if (   _deltaR.rawValue() > _deltaR.rawMax()
           && _deltaR.rawValue() < _deltaR.rawMin())
        return false;
682

683 684
    return true;
}
685

686 687 688
void CircularSurveyComplexItem::_rebuildTransectsToGeo(const QVector<QPointF> &path, const QGeoCoordinate &reference)
{
    using namespace GeoUtilities;
689

Valentin Platzgummer's avatar
Valentin Platzgummer committed
690 691
    QVector<QGeoCoordinate> geoPath;
    toGeoList(path, reference, geoPath);
692
    QList<CoordInfo_t> transectList;
693
    transectList.reserve(path.size());
694 695 696
    for ( const QGeoCoordinate &coordinate : geoPath) {
        CoordInfo_t coordinfo = {coordinate, CoordTypeInterior};
        transectList.append(coordinfo);
697
    }
698
    _transects.append(transectList);
699
}
700

701

702 703 704
Fact *CircularSurveyComplexItem::transectMinLength()
{
    return &_transectMinLength;
705 706
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
707
Fact *CircularSurveyComplexItem::fixedDirection()
708
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
709
    return &_fixedDirection;
710 711
}

712 713 714 715 716
Fact *CircularSurveyComplexItem::reverse()
{
    return &_reverse;
}

717 718 719 720 721
Fact *CircularSurveyComplexItem::maxWaypoints()
{
    return &_maxWaypoints;
}

722 723 724



725 726 727 728 729 730 731 732 733 734 735
/*!
    \class CircularSurveyComplexItem
    \inmodule Wima

    \brief The \c CircularSurveyComplexItem class provides a survey mission item with circular transects around a point of interest.

    CircularSurveyComplexItem class provides a survey mission item with circular transects around a point of interest. Within the
    \c Wima module it's used to scan a defined area with constant angle (circular transects) to the base station (point of interest).

    \sa WimaArea
*/
736 737