CircularSurveyComplexItem.cc 29.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";
11
const char* CircularSurveyComplexItem::isSnakePathName =            "IsSnakePath";
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";
20
const char* CircularSurveyComplexItem::jsonIsSnakePathKey           =   "isSnakePath";
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])
33 34
    ,   _isSnakePath                (settingsGroup, _metaDataMap[isSnakePathName])    
    ,   _reverse                    (settingsGroup, _metaDataMap[reverseName])
35
    ,   _maxWaypoints               (settingsGroup, _metaDataMap[maxWaypointsName])
36
    ,   _isInitialized              (false)
37 38
    ,   _reverseOnly                (false)
    ,   _referencePointBeingChanged (false)
39
    ,   _updateCounter              (0)
40
{
41
    Q_UNUSED(kmlOrShpFile)
42
    _editorQml = "qrc:/qml/CircularSurveyItemEditor.qml";
43 44 45
    connect(&_deltaR,               &Fact::valueChanged, this, &CircularSurveyComplexItem::_rebuildTransects);
    connect(&_deltaAlpha,           &Fact::valueChanged, this, &CircularSurveyComplexItem::_rebuildTransects);
    connect(&_transectMinLength,    &Fact::valueChanged, this, &CircularSurveyComplexItem::_rebuildTransects);
46
    connect(&_isSnakePath,          &Fact::valueChanged, this, &CircularSurveyComplexItem::_rebuildTransects);
47
    connect(&_maxWaypoints,         &Fact::valueChanged, this, &CircularSurveyComplexItem::_rebuildTransects);
48
    connect(&_reverse,              &Fact::valueChanged, this, &CircularSurveyComplexItem::_reverseTransects);
49
    connect(this,                   &CircularSurveyComplexItem::refPointChanged, this, &CircularSurveyComplexItem::_rebuildTransects);
50
    //connect(&_cameraCalc.distanceToSurface(), &Fact::rawValueChanged, this->)
51

52 53
}

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

59 60 61 62 63
void CircularSurveyComplexItem::setReferencePointBeingChanged(bool changeing)
{
    _referencePointBeingChanged = changeing;
}

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

69 70 71 72
        emit refPointChanged();
    }
}

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

78
        emit isInitializedChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
79 80 81
    }
}

82 83 84
QGeoCoordinate CircularSurveyComplexItem::refPoint() const
{
    return _referencePoint;
85 86
}

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

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

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

102 103 104 105 106
bool CircularSurveyComplexItem::referencePointBeingChanged()
{
    return _referencePointBeingChanged;
}

107 108
bool CircularSurveyComplexItem::load(const QJsonObject &complexObject, int sequenceNumber, QString &errorString)
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    // 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 },
128
        { jsonTransectMinLengthKey,                     QJsonValue::Double, true },
129
        { jsonIsSnakePathKey,                           QJsonValue::Bool,   true },
130
        { jsonReverseKey,                               QJsonValue::Bool,   true },
Valentin Platzgummer's avatar
Valentin Platzgummer committed
131
        { jsonReferencePointLatKey,                     QJsonValue::Double, true },
132
        { jsonReferencePointLongKey,                    QJsonValue::Double, true },
Valentin Platzgummer's avatar
Valentin Platzgummer committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
        { 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());
163
    _transectMinLength.setRawValue  (complexObject[jsonTransectMinLengthKey].toDouble());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
164 165 166
    _referencePoint.setLongitude    (complexObject[jsonReferencePointLongKey].toDouble());
    _referencePoint.setLatitude     (complexObject[jsonReferencePointLatKey].toDouble());
    _referencePoint.setAltitude     (complexObject[jsonReferencePointAltKey].toDouble());
167
    _isSnakePath.setRawValue        (complexObject[jsonIsSnakePathKey].toBool());
168
    _reverse.setRawValue            (complexObject[jsonReverseKey].toBool());
169
    setIsInitialized(true);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
170 171 172 173 174 175 176 177 178 179

    _ignoreRecalc = false;

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

    return true;
180 181 182 183
}

void CircularSurveyComplexItem::save(QJsonArray &planItems)
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
184 185 186 187 188 189 190
    QJsonObject saveObject;

    _save(saveObject);

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
192
    saveObject[jsonDeltaRKey]               = _deltaR.rawValue().toDouble();
193
    saveObject[jsonDeltaAlphaKey]           = _deltaAlpha.rawValue().toDouble();    
194
    saveObject[jsonTransectMinLengthKey]    = _transectMinLength.rawValue().toDouble();
195
    saveObject[jsonIsSnakePathKey]          = _isSnakePath.rawValue().toBool();
196
    saveObject[jsonReverseKey]              = _reverse.rawValue().toBool();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
197 198 199 200 201 202 203 204
    saveObject[jsonReferencePointLongKey]   = _referencePoint.longitude();
    saveObject[jsonReferencePointLatKey]    = _referencePoint.latitude();
    saveObject[jsonReferencePointAltKey]    = _referencePoint.altitude();

    // Polygon shape
    _surveyAreaPolygon.saveToJson(saveObject);

    planItems.append(saveObject);
205 206 207 208
}

void CircularSurveyComplexItem::appendMissionItems(QList<MissionItem *> &items, QObject *missionItemParent)
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
209 210 211 212 213 214 215 216 217 218 219 220
    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";
221

Valentin Platzgummer's avatar
Valentin Platzgummer committed
222 223 224 225 226 227 228
    int seqNum = _sequenceNumber;

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

Valentin Platzgummer's avatar
Valentin Platzgummer committed
231
void CircularSurveyComplexItem::_buildAndAppendMissionItems(QList<MissionItem*>& items, QObject* missionItemParent)
232
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
233 234 235 236 237 238 239 240 241
    // original code: SurveyComplexItem::_buildAndAppendMissionItems()
    //qCDebug(SurveyComplexItemLog) << "_buildAndAppendMissionItems";

    // Now build the mission items from the transect points

    MissionItem* item;
    int seqNum =                    _sequenceNumber;
    // bool imagesEverywhere =         _cameraTriggerInTurnAroundFact.rawValue().toBool();
    // bool addTriggerAtBeginning =    !hoverAndCaptureEnabled() && imagesEverywhere;
242
    //bool firstOverallPoint =        true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

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

    for (const QList<TransectStyleComplexItem::CoordInfo_t>& transect: _transects) {
        //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);
            // implement capture if desired
//            if (hoverAndCaptureEnabled()) {
//                item = new MissionItem(seqNum++,
//                                       MAV_CMD_IMAGE_START_CAPTURE,
//                                       MAV_FRAME_MISSION,
//                                       0,                                   // Reserved (Set to 0)
//                                       0,                                   // Interval (none)
//                                       1,                                   // Take 1 photo
//                                       qQNaN(), qQNaN(), qQNaN(), qQNaN(),  // param 4-7 reserved
//                                       true,                                // autoContinue
//                                       false,                               // isCurrentItem
//                                       missionItemParent);
//                items.append(item);
//            }

//            if (firstOverallPoint && addTriggerAtBeginning) {
//                // Start triggering
//                addTriggerAtBeginning = false;
//                item = new MissionItem(seqNum++,
//                                       MAV_CMD_DO_SET_CAM_TRIGG_DIST,
//                                       MAV_FRAME_MISSION,
//                                       triggerDistance(),   // 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);
//            }
294
            //firstOverallPoint = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

//            // Possibly add trigger start/stop to survey area entrance/exit
//            if (triggerCamera() && !hoverAndCaptureEnabled() && transectCoordInfo.coordType == TransectStyleComplexItem::CoordTypeSurveyEdge) {
//                if (transectEntry) {
//                    // Start of transect, always start triggering. We do this even if we are taking images everywhere.
//                    // This allows a restart of the mission in mid-air without losing images from the entire mission.
//                    // At most you may lose part of a transect.
//                    item = new MissionItem(seqNum++,
//                                           MAV_CMD_DO_SET_CAM_TRIGG_DIST,
//                                           MAV_FRAME_MISSION,
//                                           triggerDistance(),   // 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);
//                    transectEntry = false;
//                } else if (!imagesEverywhere && !transectEntry){
//                    // End of transect, 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);
//                }
//            }
        }
    }

    // implemetn photo capture if desired
//    if (triggerCamera() && !hoverAndCaptureEnabled() && imagesEverywhere) {
//        // Stop triggering
//        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);
//    }
}
348

Valentin Platzgummer's avatar
Valentin Platzgummer committed
349 350 351 352 353
void CircularSurveyComplexItem::applyNewAltitude(double newAltitude)
{
    _cameraCalc.valueSetIsDistance()->setRawValue(true);
    _cameraCalc.distanceToSurface()->setRawValue(newAltitude);
    _cameraCalc.setDistanceToSurfaceRelative(true);
354 355 356 357 358 359 360 361 362
}

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

bool CircularSurveyComplexItem::readyForSave() const
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
363
    return TransectStyleComplexItem::readyForSave();
364 365 366 367 368 369 370 371 372
}

double CircularSurveyComplexItem::additionalTimeDelay() const
{
    return 0;
}

void CircularSurveyComplexItem::_rebuildTransectsPhase1()
{
373 374 375 376
    using namespace GeoUtilities;
    using namespace PolygonCalculus;
    using namespace PlanimetryCalculus;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
377
    // rebuild not necessary?
378
    if (!_isInitialized || _referencePointBeingChanged)
379 380 381
        return;

    _updateCounter++;
382
    unsigned int waypointCounter = 0;
383

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

391

392 393 394
    // check if input is valid
    if ( _surveyAreaPolygon.count() < 3) {
        _transects.clear();
395
        return;
396
    }
397

398 399
    // reverse transects and return
    if (_reverseOnly) {
400
        _reverseOnly = false;
401

402 403 404
        if (_transects.size() > 1) {
            QList<QList<CoordInfo_t>>  transectsReverse;
            transectsReverse.reserve(_transects.size());
405

406 407 408 409
            for (auto list : _transects) {
                QList<CoordInfo_t> listReverse;
                for (auto coordinate : list)
                        listReverse.prepend(coordinate);
410

411 412 413
                transectsReverse.prepend(listReverse);
            }
            _transects = transectsReverse;
414

415 416
            return;
        }
417 418
    }

419
    _transects.clear();
420 421
    QPolygonF surveyPolygon = toQPolygonF(toCartesian2D(_surveyAreaPolygon.coordinateList(), _referencePoint));

422 423 424 425 426 427 428 429 430 431
    // some more checks
    if (!PolygonCalculus::isSimplePolygon(surveyPolygon)) {
        _transects.clear();
        return;
    }

    // even more checks
    if (!PolygonCalculus::hasClockwiseWinding(surveyPolygon))
        PolygonCalculus::reversePath(surveyPolygon);

432
    QVector<double> distances;
433 434
    for (const QPointF &p : surveyPolygon) distances.append(norm(p));

435 436 437 438 439 440 441 442 443
    // check if input is valid
    if (   _deltaAlpha.rawValue() > _deltaAlpha.rawMax()
           && _deltaAlpha.rawValue() < _deltaAlpha.rawMin())
        return;
    if (   _deltaR.rawValue() > _deltaR.rawMax()
           && _deltaR.rawValue() < _deltaR.rawMin())
        return;


444
    // fetch input data
Valentin Platzgummer's avatar
Valentin Platzgummer committed
445 446 447 448 449
    double dalpha   = _deltaAlpha.rawValue().toDouble()/180.0*M_PI; // radiants
    double dr       = _deltaR.rawValue().toDouble(); // meter
    double lmin     = _transectMinLength.rawValue().toDouble();
    double r_min    = dr; // meter
    double r_max    = (*std::max_element(distances.begin(), distances.end())); // meter
450
    unsigned int maxWaypoints = _maxWaypoints.rawValue().toUInt();
451 452 453

    QPointF origin(0, 0);
    IntersectType type;
454
    bool originInside = true;
455 456 457 458 459
    if (!contains(surveyPolygon, origin, type)) {
        QVector<double> angles;
        for (const QPointF &p : surveyPolygon) angles.append(truncateAngle(angle(p)));

        // determine r_min by successive approximation
460 461
        double r = r_min;
        while ( r < r_max) {
462 463
            Circle circle(r, origin);

464
            if (intersects(circle, surveyPolygon)) {
465 466 467 468
                r_min = r;
                break;
            }

469
            r += dr;
470
        }
471
        originInside = false;
472 473
    }

474

475
    // generate transects
476
    QVector<QVector<QPointF>> transectPath;
477 478 479 480
    double r = r_min;

    while (r < r_max) {
        Circle circle(r, origin);
481 482 483
        QVector<QPointFVector> intersectPoints;
        QVector<IntersectType> typeList;
        QVector<QPair<int, int>> neighbourList;
484 485 486 487 488 489 490 491 492 493
        if (intersects(circle, surveyPolygon, intersectPoints, neighbourList, typeList)) {

            // intersection Points between circle and polygon, entering polygon
            // when walking in counterclockwise direction along circle
            QPointFList entryPoints;
            // intersection Points between circle and polygon, leaving polygon
            // when walking in counterclockwise direction along circle
            QPointFList exitPoints;
            // determine entryPoints and exit Points
            for (int j = 0; j < intersectPoints.size(); j++) {
494
                QVector<QPointF> intersects = intersectPoints[j]; // one pt = tangent, two pt = sekant
495 496 497 498

                QPointF p1 = surveyPolygon[neighbourList[j].first];
                QPointF p2 = surveyPolygon[neighbourList[j].second];
                QLineF intersetLine(p1, p2);
499 500 501 502 503 504 505
                double lineAngle = angle(intersetLine);

//                int n = 16;
//                for (int i = -n; i <= n; i++) {
//                    double alpha = 2*M_PI*double(i)/double(n);
//                    qDebug() << i << " " << alpha << " " << truncateAngle(alpha);
//                }
506 507

                for (QPointF ipt : intersects) {
508
                    double circleTangentAngle = angle(ipt)+M_PI_2;
509 510
                    // compare line angle and circle tangent at intersection point
                    // to determine between exit and entry point
511 512 513 514 515 516 517 518
//                    qDebug() << "lineAngle" << lineAngle*180/M_PI;
//                    qDebug() << "circleTangentAngle" << circleTangentAngle*180/M_PI;
//                    qDebug() << "!qFuzzyIsNull(truncateAngle(lineAngle - circleTangentAngle): " << !qFuzzyIsNull(truncateAngle(lineAngle - circleTangentAngle));
//                    qDebug() << "!qFuzzyIsNull(truncateAngle(lineAngle - circleTangentAngle - M_PI): " << !qFuzzyIsNull(truncateAngle(lineAngle - circleTangentAngle - M_PI));
                    if (   !qFuzzyIsNull(truncateAngle(lineAngle - circleTangentAngle))
                        && !qFuzzyIsNull(truncateAngle(lineAngle - circleTangentAngle - M_PI) ))
                        {
                        if (truncateAngle(circleTangentAngle - lineAngle)  > M_PI) {
519 520 521
                            entryPoints.append(ipt);
                        } else {
                            exitPoints.append(ipt);
522
                        }
523 524
                    }
                }
525
            }
526

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
            // 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;
544
                }
545
            }
546

547
            // generate circle sectors
548 549 550
            for (int k = 0; k < entryPoints.size(); k++) {
                double alpha1 = angle(entryPoints[k]);
                double alpha2 = angle(exitPoints[(k+offset) % entryPoints.size()]);
551
                double dAlpha = truncateAngle(alpha2-alpha1);
552
                int numNodes = int(ceil(dAlpha/dalpha)) + 1;
553 554 555 556
//                qDebug() << "alpha1" << alpha1;
//                qDebug() << "alpha2" << alpha2;
//                qDebug() << "dAlpha" << dAlpha;
//                qDebug() << "numNodes" << numNodes;
557

558
                QVector<QPointF> sectorPath = circle.approximateSektor(numNodes, alpha1, alpha2);
559
                // use shortestPath() here if necessary, could be a problem if dr >>
560 561 562 563
                if (sectorPath.size() > 0) {
                    waypointCounter += uint(sectorPath.size());
                    if (waypointCounter > maxWaypoints )
                        return;
564
                    transectPath.append(sectorPath);
565
                }
566
            }
567
        } else if (originInside) {
568 569
            // circle fully inside polygon            
            int numNodes = int(ceil(2*M_PI/dalpha)) + 1;
570
            QVector<QPointF> sectorPath = circle.approximateSektor(numNodes, 0, 2*M_PI);
571
            // use shortestPath() here if necessary, could be a problem if dr >>
572 573 574
            waypointCounter += uint(sectorPath.size());
            if (waypointCounter > maxWaypoints )
                return;
575
            transectPath.append(sectorPath);
576
        }
577 578 579 580
        r += dr;
     }

    if (transectPath.size() == 0)
581
        return;
582

583
    // remove short transects
584 585
    for (int i = 0; i < transectPath.size(); i++) {
        auto transect = transectPath[i];
586 587 588 589 590 591
        double len = 0;
        for (int j = 0; j < transect.size()-1; ++j) {
            len += PlanimetryCalculus::distance(transect[j], transect[j+1]);
        }

        if (len < lmin)
592
            transectPath.removeAt(i--);
593
    }
594
    if (transectPath.size() == 0)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
595
        return;
596

597 598
    // optimize path to snake or zig-zag pattern
    bool isSnakePattern = _isSnakePath.rawValue().toBool();
599
    QVector<QPointF> currentSection = transectPath.takeFirst();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
600 601
    if ( currentSection.isEmpty() )
        return;
602
    QVector<QPointF> optiPath; // optimized path
603
    while( !transectPath.empty() ) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
604 605 606 607 608 609 610
        optiPath.append(currentSection);
        QPointF endVertex = currentSection.last();
        double minDist = std::numeric_limits<double>::infinity();
        int index = 0;
        bool reversePath = false;

        // iterate over all paths in fullPath and assign the one with the shortest distance to endVertex to currentSection
611 612
        for (int i = 0; i < transectPath.size(); i++) {
            auto iteratorPath = transectPath[i];
Valentin Platzgummer's avatar
Valentin Platzgummer committed
613 614 615 616
            double dist = PlanimetryCalculus::distance(endVertex, iteratorPath.first());
            if ( dist < minDist ) {
                minDist = dist;
                index = i;
617
                reversePath = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
618 619 620 621 622 623 624 625
            }
            dist = PlanimetryCalculus::distance(endVertex, iteratorPath.last());
            if (dist < minDist) {
                minDist = dist;
                index = i;
                reversePath = true;
            }
        }
626
        currentSection = transectPath.takeAt(index);
627
        if (reversePath && isSnakePattern) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
628 629 630 631 632
            PolygonCalculus::reversePath(currentSection);
        }
    }

    optiPath.append(currentSection); // append last section
633

634 635 636
    if (optiPath.size() > _maxWaypoints.rawValue().toInt())
        return;

637 638

    // convert to CoordInfo_t
639 640 641
    if (_reverse.rawValue().toBool())
        PolygonCalculus::reversePath(optiPath);

642
    QVector<QGeoCoordinate> geoPath = toGeo(optiPath, _referencePoint);
643
    QList<CoordInfo_t> transectList;
644
    transectList.reserve(optiPath.size());
645 646 647
    for ( const QGeoCoordinate &coordinate : geoPath) {
        CoordInfo_t coordinfo = {coordinate, CoordTypeInterior};
        transectList.append(coordinfo);
648
    }
649
    _transects.append(transectList);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
650

651
    qDebug() << "CircularSurveyComplexItem::_rebuildTransectsPhase1(): calls: " << _updateCounter;
652

653 654 655 656
}

void CircularSurveyComplexItem::_recalcComplexDistance()
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
657 658 659 660 661
    _complexDistance = 0;
    for (int i=0; i<_visualTransectPoints.count() - 1; i++) {
        _complexDistance += _visualTransectPoints[i].value<QGeoCoordinate>().distanceTo(_visualTransectPoints[i+1].value<QGeoCoordinate>());
    }
    emit complexDistanceChanged();
662 663
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
664
// no cameraShots in Circular Survey, add if desired
665 666
void CircularSurveyComplexItem::_recalcCameraShots()
{
Valentin Platzgummer's avatar
Valentin Platzgummer committed
667
    _cameraShots = 0;
668 669
}

670 671 672 673 674 675 676
void CircularSurveyComplexItem::_reverseTransects()
{
    _reverseOnly = true;
    _rebuildTransects();
}


677

678 679 680
Fact *CircularSurveyComplexItem::transectMinLength()
{
    return &_transectMinLength;
681 682
}

683 684 685 686 687
Fact *CircularSurveyComplexItem::isSnakePath()
{
    return &_isSnakePath;
}

688 689 690 691 692
Fact *CircularSurveyComplexItem::reverse()
{
    return &_reverse;
}

693 694 695 696 697
Fact *CircularSurveyComplexItem::maxWaypoints()
{
    return &_maxWaypoints;
}

698 699 700



701 702 703 704 705 706 707 708 709 710 711
/*!
    \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
*/
712 713