MeasurementComplexItem.cc 39.7 KB
Newer Older
1
#include "MeasurementComplexItem.h"
2

3
#include "AreaData.h"
4 5
#include "CircularGenerator.h"
#include "LinearGenerator.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
6
#include "NemoInterface.h"
7
#include "RoutingThread.h"
8 9 10 11
#include "geometry/GenericCircle.h"
#include "geometry/MeasurementArea.h"
#include "geometry/SafeArea.h"
#include "geometry/clipper/clipper.hpp"
12
#include "geometry/geometry.h"
13
#include "nemo_interface/MeasurementTile.h"
14

15 16
// QGC
#include "JsonHelper.h"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
17
#include "PlanMasterController.h"
18 19 20 21 22 23 24
#include "QGCApplication.h"
#include "QGCLoggingCategory.h"

// boost
#include <boost/units/io.hpp>
#include <boost/units/systems/si.hpp>

Valentin Platzgummer's avatar
Valentin Platzgummer committed
25
QGC_LOGGING_CATEGORY(MeasurementComplexItemLog, "MeasurementComplexItemLog")
26 27 28 29 30 31

template <typename T>
constexpr typename std::underlying_type<T>::type integral(T value) {
  return static_cast<typename std::underlying_type<T>::type>(value);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
32 33 34 35
const char *MeasurementComplexItem::settingsGroup = "MeasurementComplexItem";
const char *MeasurementComplexItem::jsonComplexItemTypeValue =
    "MeasurementComplexItem";
const QString MeasurementComplexItem::name(tr("Measurement"));
36 37

namespace {
38
const char *variantIndexKey = "VariantIndex";
39 40 41
const char *altitudeKey = "Altitude";
const char *areaDataKey = "AreaData";
const char *variantNamesKey = "VariantNames";
42 43
const char *generatorArrayKey = "GeneratorArray";
const char *variantArrayKey = "VariantArray";
44
const char *generatorIndexKey = "GeneratorIndex";
45
} // namespace
Valentin Platzgummer's avatar
Valentin Platzgummer committed
46 47 48 49

MeasurementComplexItem::MeasurementComplexItem(
    PlanMasterController *masterController, bool flyView,
    const QString &kmlOrShpFile, QObject *parent)
50
    : ComplexMissionItem(masterController, flyView, parent), _sequenceNumber(0),
51
      _followTerrain(false), _state(STATE::IDLE),
52
      _metaDataMap(FactMetaData::createMapFromJsonFile(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
53 54
          QStringLiteral(":/json/MeasurementComplexItem.SettingsGroup.json"),
          this)),
55
      _altitude(settingsGroup, _metaDataMap[altitudeKey]),
56
      _variantIndex(settingsGroup, _metaDataMap[variantIndexKey]),
57
      _pAreaData(new AreaData(this)), _pEditorData(new AreaData(this)),
58
      _pCurrentData(_pAreaData), _holdProgress(false), _pGenerator(nullptr),
59
      _pWorker(new RoutingThread(this)) {
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  // Setup altitude.
  _altitude.setRawValue(qgcApp()
                            ->toolbox()
                            ->settingsManager()
                            ->appSettings()
                            ->defaultMissionItemAltitude()
                            ->rawValue());
  connect(&_altitude, &SettingsFact::rawValueChanged, [this] {
    emit this->minAMSLAltitudeChanged(this->_altitude.rawValue().toDouble());
  });
  connect(&_altitude, &SettingsFact::rawValueChanged, [this] {
    emit this->maxAMSLAltitudeChanged(this->_altitude.rawValue().toDouble());
  });
  connect(&_altitude, &SettingsFact::rawValueChanged, [this] {
    emit this->amslEntryAltChanged(this->_altitude.rawValue().toDouble());
  });
  connect(&_altitude, &SettingsFact::rawValueChanged, [this] {
    emit this->amslExitAltChanged(this->_altitude.rawValue().toDouble());
  });
  connect(&_altitude, &SettingsFact::rawValueChanged, this,
          &MeasurementComplexItem::_onAltitudeChanged);

83
  Q_UNUSED(kmlOrShpFile)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
84
  _editorQml = "qrc:/qml/MeasurementItemEditor.qml";
85 86

  // Connect facts.
87 88
  connect(&this->_variantIndex, &Fact::rawValueChanged, this,
          &MeasurementComplexItem::_changeVariantIndex);
89 90

  // Connect worker.
91
  connect(this->_pWorker, &RoutingThread::result, this,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
92 93
          &MeasurementComplexItem::_storeRoutingData);

94
  // Connect coordinate and exitCoordinate.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
95 96 97 98 99 100 101 102
  connect(this, &MeasurementComplexItem::routeChanged,
          [this] { emit this->coordinateChanged(this->coordinate()); });
  connect(this, &MeasurementComplexItem::routeChanged,
          [this] { emit this->exitCoordinateChanged(this->exitCoordinate()); });
  connect(this, &MeasurementComplexItem::routeChanged, [this] {
    emit this->exitCoordinateSameAsEntryChanged(
        this->exitCoordinateSameAsEntry());
  });
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117
  // Connect isIncomplete.
  connect(this, &MeasurementComplexItem::idleChanged, [this] {
    if (this->idle()) {
      if (this->route().size() > 0 && this->_isIncomplete == true) {
        this->_isIncomplete = false;
        emit this->isIncompleteChanged();
      }
    } else {
      if (this->_isIncomplete == false) {
        this->_isIncomplete = true;
        emit this->isIncompleteChanged();
      }
    }
  });
118 119

  // Connect readyForSave
120 121 122
  connect(this, &MeasurementComplexItem::idleChanged, this,
          &MeasurementComplexItem::readyForSaveStateChanged);

123 124 125 126
  // Connect flightPathSegments
  connect(this, &MeasurementComplexItem::routeChanged, this,
          &MeasurementComplexItem::_updateFlightpathSegments);

127 128 129 130
  // Connect complexDistance.
  connect(this, &MeasurementComplexItem::routeChanged,
          [this] { emit this->complexDistanceChanged(); });

131
  resetGenerators();
132
  startEditing();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
133 134 135 136

  // connect to nemo interface
  connect(pNemoInterface, &NemoInterface::progressChanged, this,
          &MeasurementComplexItem::_onNewProgress);
137 138
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
139
MeasurementComplexItem::~MeasurementComplexItem() {}
140

Valentin Platzgummer's avatar
Valentin Platzgummer committed
141
void MeasurementComplexItem::reverseRoute() { _reverseRoute(); }
142

Valentin Platzgummer's avatar
Valentin Platzgummer committed
143
const AreaData *MeasurementComplexItem::areaData() const {
144
  return this->_pCurrentData;
145 146
}

147
AreaData *MeasurementComplexItem::areaData() { return this->_pCurrentData; }
148

Valentin Platzgummer's avatar
Valentin Platzgummer committed
149 150
QVariantList MeasurementComplexItem::route() { return _route; }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
151 152 153
QStringList MeasurementComplexItem::variantNames() const {
  return _variantNames;
}
154

Valentin Platzgummer's avatar
Valentin Platzgummer committed
155 156
bool MeasurementComplexItem::load(const QJsonObject &complexObject,
                                  int sequenceNumber, QString &errorString) {
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  // 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;
  }

173 174 175 176 177 178 179 180 181
  {
    QList<JsonHelper::KeyValidateInfo> keyInfoList = {
        {VisualMissionItem::jsonTypeKey, QJsonValue::String, true},
        {ComplexMissionItem::jsonComplexItemTypeKey, QJsonValue::String, true},
    };

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

183 184 185 186 187 188 189 190 191 192 193 194
    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;
    }
195 196 197
  }

  setSequenceNumber(sequenceNumber);
198 199
  startEditing();

200 201 202 203
  // load variant index
  if (complexObject.contains(variantIndexKey) &&
      complexObject[variantIndexKey].isDouble()) {
    _variantIndex.setRawValue(complexObject[variantIndexKey].toInt());
204 205 206
  }

  // load altitude
207 208 209 210 211
  if (complexObject.contains(altitudeKey) &&
      complexObject[altitudeKey].isDouble()) {
    _altitude.setRawValue(complexObject[altitudeKey].toDouble());
  } else {
    errorString.append(tr("No altitude found in file.\n"));
212 213
    abortEditing();
    return false;
214 215 216 217 218 219 220
  }

  // load AreaData.
  if (complexObject.contains(areaDataKey) &&
      complexObject[areaDataKey].isObject()) {
    QString e;
    if (_pCurrentData->load(complexObject[areaDataKey].toObject(), e)) {
221
      if (!_pCurrentData->isCorrect(false /*don't show gui message*/)) {
222
        errorString.append(_pCurrentData->errorString());
223 224 225
        abortEditing();
        return false;
      }
226

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    } else {
      // this is critical, proceeding is not
      // reasonable.
      errorString.append(e);
      abortEditing();
      return false;
    }
  } else {
    // this is critical, if no area data present, proceeding is not reasonable.
    errorString.append(tr("No area data found in file. Abort loading.\n"));
    abortEditing();
    return false;
  }

  // load Generators.
242 243
  if (complexObject.contains(generatorArrayKey) &&
      complexObject[generatorArrayKey].isArray()) {
244 245 246 247

    QVector<PtrGenerator> generatorList;
    QObject parent;

248
    for (const auto valueRef : complexObject[generatorArrayKey].toArray()) {
249 250 251 252 253 254 255
      const auto jsonGen = valueRef.toObject();

      if (jsonGen.contains(routing::GeneratorBase::typeKey) &&
          jsonGen[routing::GeneratorBase::typeKey].isString()) {
        QString e;

        // create generator
256
        auto gen = pGeneratorFactory->create(jsonGen, e, &parent /*parent*/);
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

        if (gen != nullptr) {
          // remove generators of same type and insert this generator.
          for (int i = 0; i < _generatorList.size();) {
            auto otherGen = generator(i);
            if (gen->type() == otherGen->type()) {
              removeGenerator(i);
            } else {
              ++i;
            }
          }
          gen->setData(this->_pAreaData);
          generatorList.append(gen);
        } else {
          // error loading generator.
          errorString.append(
              tr("Error loading generator of type ") +
              jsonGen[routing::GeneratorBase::typeKey].toString() + ".\n");
275
          if (!pGeneratorFactory->registered(
276 277 278 279 280 281 282 283 284 285
                  jsonGen[routing::GeneratorBase::typeKey].toString())) {
            errorString.append(tr("This type is unknown.\n"));
            qCritical()
                << "MeasurementComplexItem::load(): generator of type :"
                << jsonGen[routing::GeneratorBase::typeKey]
                << " not registered with the GeneratorFactory. This can either "
                   "mean that the file contains a invalid entry or "
                   "that the generator was not registered. In the latter case "
                   "use the REGISTER_GENERATOR() for registration";
          }
286 287
          abortEditing();
          return false;
288 289 290
        }

      } else {
291 292 293
        errorString.append(tr("Can not determine type of generator.\n"));
        abortEditing();
        return false;
294 295 296 297 298
      }

      // insert generators
      for (const auto gen : generatorList) {
        gen->setParent(this);
299
        addGenerator(gen);
300 301 302 303 304
      }
    }
  } else {
    errorString.append(
        tr("No generators found in file. Leaving generators unchanged.\n"));
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    abortEditing();
    return false;
  }

  // load generator index
  bool indexLoaded = false;
  if (complexObject.contains(generatorIndexKey) &&
      complexObject[generatorIndexKey].isDouble()) {
    int index = complexObject[generatorIndexKey].toDouble();
    if (index >= 0 && index < _generatorList.size()) {
      indexLoaded = true;
      switchToGenerator(index);
    }
  }
  if (!indexLoaded) {
    switchToGenerator(0);
321 322 323
  }

  // load Route Variants
324 325
  bool variantsSuccess = true;
  QVector<Variant> variantVector;
326 327
  if (complexObject.contains(variantArrayKey) &&
      complexObject[variantArrayKey].isArray()) {
328 329

    // load variants to variantVector for further processing.
330
    for (const auto valueRef : complexObject[variantArrayKey].toArray()) {
331
      if (valueRef.isArray()) {
332
        const auto jsonVariant = valueRef.toArray();
333 334
        Variant variant;
        QString e;
335
        if (JsonHelper::loadGeoCoordinateArray(jsonVariant, false, variant,
336 337 338 339
                                               e)) {
          if (variant.size() > 0) {
            variantVector.append(std::move(variant));
          } else {
340 341 342
            qCDebug(MeasurementComplexItemLog)
                << "Empty route variant skipped.\n"
                << valueRef.type();
343 344
          }
        } else {
345 346 347
          qCDebug(MeasurementComplexItemLog)
              << "Error loading route variant: " << e;
          variantsSuccess = false;
348 349 350 351
        }
      } else {
        qCDebug(MeasurementComplexItemLog)
            << "json variant is not an array but of type: " << valueRef.type();
352
        variantsSuccess = false;
353 354 355
      }
    }

356 357 358 359 360 361 362 363 364 365
    // Check if variantVector and variants are non empty
    if (variantVector.size() == 0) {
      variantsSuccess = false;
    }
    for (const auto &var : variantVector) {
      if (var.size() == 0) {
        variantsSuccess = false;
      }
    }

366
    // Check if variants are covered by safe area.
367
    if (variantsSuccess) {
368 369 370 371
      auto safeAreaArray = _pCurrentData->safeAreaArray();

      if (safeAreaArray.size() > 0 && safeAreaArray.at(0) != nullptr) {
        auto safeArea = safeAreaArray[0];
372 373
        QGeoCoordinate origin =
            safeArea->pathModel().value<QGCQGeoCoordinate *>(0)->coordinate();
374 375
        geometry::FPolygon safeAreaENU;
        geometry::areaToEnu(origin, safeArea->coordinateList(), safeAreaENU);
376
        for (const auto &variant : variantVector) {
377
          geometry::FLineString varENU;
378
          for (const auto &vertex : variant) {
379 380
            geometry::FPoint vertexENU;
            geometry::toENU(origin, vertex.value<QGeoCoordinate>(), vertexENU);
381 382 383 384 385 386 387 388 389 390 391 392
            varENU.push_back(vertexENU);
          }

          if (!bg::covered_by(varENU, safeAreaENU)) {
            variantsSuccess = false;
            break;
          }
        }
      } else {
        variantsSuccess = false;
      }
    }
393
  } else {
394
    variantsSuccess = false;
395
  }
396

397
  if (variantsSuccess) {
398
    _variantVector.swap(variantVector);
399 400 401 402 403 404 405

    // load variant names
    bool variantNamesLoaded = true;
    if (complexObject.contains(variantNamesKey) &&
        complexObject[variantNamesKey].isArray()) {
      QStringList variantNames;

406
      for (const auto &name : complexObject[variantNamesKey].toArray()) {
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
        if (name.isString()) {
          variantNames.append(name.toString());
        } else {
          variantNamesLoaded = false;
          break;
        }
      }

      if (variantNames.size() != _variantVector.size()) {
        variantNamesLoaded = false;
      }

      if (variantNamesLoaded) {
        _variantNames.swap(variantNames);
        emit variantNamesChanged();
      }
    } else {
      qCWarning(MeasurementComplexItemLog)
          << "Not able to load variant names. variantNamesKey missing or wrong "
             "type";
      if (complexObject.contains(variantNamesKey)) {
        qCWarning(MeasurementComplexItemLog)
            << "variantNamesKey type: "
            << complexObject[variantNamesKey].type();
      }
    }

    // create std. variant names if loading failed
    if (!variantNamesLoaded) {
      qCWarning(MeasurementComplexItemLog) << "Creating std. variant names.";
      this->_variantNames.clear();
      for (std::size_t i = 1; i <= std::size_t(this->_variantVector.size());
           ++i) {
        this->_variantNames.append(QString::number(i));
      }
      emit variantNamesChanged();
    }

445 446
    stopEditing(
        false /*doUpdate*/); // does noting if editing was already stopped
447 448 449 450

    _changeVariantIndex();
  } else {
    stopEditing(); // stop editing and trigger update
451
  }
452

453
  return true;
454 455
}

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
double
MeasurementComplexItem::greatestDistanceTo(const QGeoCoordinate &other) const {
  double d = -1 * std::numeric_limits<double>::infinity();
  if (other.isValid()) {
    if (this->_route.size() > 0) {
      std::for_each(this->_route.cbegin(), this->_route.cend(),
                    [&d, &other](const QVariant &variant) {
                      auto vertex = variant.value<QGeoCoordinate>();
                      d = std::max(d, vertex.distanceTo(other));
                    });
    }
  } else {
    qCDebug(MeasurementComplexItemLog)
        << "greatestDistanceTo(): invalid QGeoCoordinate: " << other;
  }
  return d;
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
474 475 476 477 478 479 480 481
bool MeasurementComplexItem::dirty() const { return _dirty; }

bool MeasurementComplexItem::isSimpleItem() const { return false; }

bool MeasurementComplexItem::isStandaloneCoordinate() const { return false; }

QString MeasurementComplexItem::mapVisualQML() const {
  return QStringLiteral("MeasurementItemMapVisual.qml");
482 483
}

484
void MeasurementComplexItem::save(QJsonArray &planItems) {
485
  if (idle()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
486
    QJsonObject saveObject;
487

Valentin Platzgummer's avatar
Valentin Platzgummer committed
488 489 490 491 492
    saveObject[JsonHelper::jsonVersionKey] = 1;
    saveObject[VisualMissionItem::jsonTypeKey] =
        VisualMissionItem::jsonTypeComplexItemValue;
    saveObject[ComplexMissionItem::jsonComplexItemTypeKey] =
        jsonComplexItemTypeValue;
493

494
    // Variant and altitude.
495
    saveObject[variantIndexKey] = double(_variantIndex.rawValue().toUInt());
496
    saveObject[altitudeKey] = double(_altitude.rawValue().toUInt());
497

498
    // Variant names.
499
    QJsonArray jsonVariantNames;
500 501 502
    for (auto const &name : _variantNames) {
      jsonVariantNames.append(name);
    }
503
    saveObject[variantNamesKey] = jsonVariantNames;
504 505

    // AreaData.
506 507 508 509 510 511
    QJsonObject jsonAreaData;
    if (!_pAreaData->save(jsonAreaData)) {
      qCDebug(MeasurementComplexItemLog)
          << "save(): not able to save area data";
      return;
    }
512
    saveObject[areaDataKey] = jsonAreaData;
513 514

    // Generators.
515 516 517
    QJsonArray generatorArray;
    for (int i = 0; i < _generatorList.size(); ++i) {
      auto const gen = _generatorList[i];
518 519
      QJsonObject obj;
      if (!gen->save(obj)) {
520
        qCDebug(MeasurementComplexItemLog)
521
            << "save(): not able to save generator with name: " << gen->name();
522 523
        return;
      } else {
524
        generatorArray.append(obj);
525 526
      }
    }
527
    saveObject[generatorArrayKey] = generatorArray;
528

529
    // generator index
530
    saveObject[generatorIndexKey] = generatorIndex();
531

532
    // Route Variants
533
    QJsonArray variantsArray;
534 535
    for (auto const &route : _variantVector) {
      QJsonValue variant;
536
      if (route.size() > 0) {
537
        JsonHelper::saveGeoCoordinateArray(route, false, variant);
538
      } else {
539
        JsonHelper::saveGeoCoordinateArray(_route, false, variant);
540 541 542
      }
      variantsArray.append(variant);
    }
543
    saveObject[variantArrayKey] = variantsArray;
544

Valentin Platzgummer's avatar
Valentin Platzgummer committed
545
    planItems.append(saveObject);
546 547
  } else {
    qCDebug(MeasurementComplexItemLog) << "save(): called while not idle.";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
548
  }
549 550
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
double MeasurementComplexItem::amslEntryAlt() const {
  return _altitude.rawValue().toDouble() +
         this->_masterController->missionController()
             ->plannedHomePosition()
             .altitude();
}

double MeasurementComplexItem::amslExitAlt() const { return amslEntryAlt(); }

double MeasurementComplexItem::minAMSLAltitude() const {
  return amslEntryAlt();
}

double MeasurementComplexItem::maxAMSLAltitude() const {
  return amslEntryAlt();
}

568 569 570 571 572 573 574 575 576 577 578 579
QString MeasurementComplexItem::commandDescription() const {
  return QStringLiteral("Measurement");
}

QString MeasurementComplexItem::commandName() const {
  return QStringLiteral("Measurement");
}

QString MeasurementComplexItem::abbreviation() const {
  return QStringLiteral("M");
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
580 581 582 583 584 585 586
bool MeasurementComplexItem::specifiesCoordinate() const {
  return _route.count() > 0;
}

bool MeasurementComplexItem::specifiesAltitudeOnly() const { return false; }

QGeoCoordinate MeasurementComplexItem::coordinate() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
587 588
  return this->_route.size() > 0 ? _route.first().value<QGeoCoordinate>()
                                 : QGeoCoordinate();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
589 590 591
}

QGeoCoordinate MeasurementComplexItem::exitCoordinate() const {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
592 593
  return this->_route.size() > 0 ? _route.last().value<QGeoCoordinate>()
                                 : QGeoCoordinate();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
}

int MeasurementComplexItem::sequenceNumber() const { return _sequenceNumber; }

double MeasurementComplexItem::specifiedFlightSpeed() {
  return std::numeric_limits<double>::quiet_NaN();
}

double MeasurementComplexItem::specifiedGimbalYaw() {
  return std::numeric_limits<double>::quiet_NaN();
}

double MeasurementComplexItem::specifiedGimbalPitch() {
  return std::numeric_limits<double>::quiet_NaN();
}

void MeasurementComplexItem::appendMissionItems(QList<MissionItem *> &items,
                                                QObject *missionItemParent) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
612

613
  if (idle()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
    qCDebug(MeasurementComplexItemLog) << "appendMissionItems()";

    int seqNum = this->_sequenceNumber;

    MAV_FRAME mavFrame =
        followTerrain() ? MAV_FRAME_GLOBAL : MAV_FRAME_GLOBAL_RELATIVE_ALT;

    for (const auto &variant : this->_route) {
      auto vertex = variant.value<QGeoCoordinate>();
      MissionItem *item = new MissionItem(
          seqNum++, MAV_CMD_NAV_WAYPOINT, mavFrame,
          0,   // hold time
          0.0, // No acceptance radius specified
          0.0, // Pass through waypoint
          std::numeric_limits<double>::quiet_NaN(), // Yaw unchanged
          vertex.latitude(), vertex.longitude(), vertex.altitude(),
          true,  // autoContinue
          false, // isCurrentItem
          missionItemParent);
      items.append(item);
    }
  } else {
    qCDebug(MeasurementComplexItemLog)
        << "appendMissionItems(): called while not ready().";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
638 639 640 641 642 643
  }
}

void MeasurementComplexItem::setMissionFlightStatus(
    const MissionController::MissionFlightStatus_t &missionFlightStatus) {
  ComplexMissionItem::setMissionFlightStatus(missionFlightStatus);
644 645
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
646
void MeasurementComplexItem::applyNewAltitude(double newAltitude) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
647
  this->_altitude.setRawValue(newAltitude);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
648 649 650 651 652
}

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

bool MeasurementComplexItem::_setGenerator(PtrGenerator newG) {
653 654
  if (this->_pGenerator != newG) {
    if (this->_pGenerator != nullptr) {
655
      disconnect(this->_pGenerator, &routing::GeneratorBase::generatorChanged,
Valentin Platzgummer's avatar
Valentin Platzgummer committed
656
                 this, &MeasurementComplexItem::_updateRoute);
657 658 659
    }

    this->_pGenerator = newG;
660 661 662 663 664 665

    if (this->_pGenerator != nullptr) {
      connect(this->_pGenerator, &routing::GeneratorBase::generatorChanged,
              this, &MeasurementComplexItem::_updateRoute);
    }

666 667
    emit generatorChanged();

Valentin Platzgummer's avatar
Valentin Platzgummer committed
668 669 670 671
    if (!editing()) {
      this->_setState(STATE::IDLE);
      _updateRoute();
    }
672 673 674 675 676 677 678

    return true;
  } else {
    return false;
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
679
void MeasurementComplexItem::_setState(MeasurementComplexItem::STATE state) {
680 681 682
  if (this->_state != state) {
    auto oldState = this->_state;
    this->_state = state;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
683

684 685 686
    if (_calculating(oldState) != _calculating(state)) {
      emit calculatingChanged();
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
687 688 689 690

    if (_editing(oldState) != _editing(state)) {
      emit editingChanged();
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
691

692 693
    if (_idle(oldState) != _idle(state)) {
      emit idleChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
694
    }
695 696 697
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
698
bool MeasurementComplexItem::_calculating(MeasurementComplexItem::STATE state) {
699 700 701
  return state == STATE::ROUTING;
}

702 703 704 705
bool MeasurementComplexItem::_editing(MeasurementComplexItem::STATE state) {
  return state == STATE::EDITING;
}

706
bool MeasurementComplexItem::_idle(MeasurementComplexItem::STATE state) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
707 708 709
  return state == STATE::IDLE;
}

710
void MeasurementComplexItem::_updateFlightpathSegments() {
711 712
  bool hasCollisionOld = _cTerrainCollisionSegments > 0;
  _cTerrainCollisionSegments = 0;
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737

  _flightPathSegments.beginReset();
  _flightPathSegments.clearAndDeleteContents();

  if (_route.size() > 2) {
    bool ok = false;
    double alt = _altitude.rawValue().toDouble(&ok) +
                 _masterController->missionController()
                     ->plannedHomePosition()
                     .altitude();
    if (ok) {
      auto prev = _route.cbegin();
      for (auto next = _route.cbegin() + 1; next != _route.end(); ++next) {
        auto v1 = prev->value<QGeoCoordinate>();
        auto v2 = next->value<QGeoCoordinate>();
        _appendFlightPathSegment(v1, alt, v2, alt);
        prev = next;
      }
    } else {
      qCCritical(MeasurementComplexItemLog) << "_altitude fact not ok.";
    }
  }

  _flightPathSegments.endReset();

738 739 740 741 742
  // Terrain collsision.
  bool hasCollision = _cTerrainCollisionSegments > 0;
  if (hasCollisionOld != hasCollision) {
    emit terrainCollisionChanged(hasCollision);
  }
743 744 745 746 747
  auto measurementAreaArray = _pAreaData->measurementAreaArray();
  for (auto area : measurementAreaArray) {
    if (area != nullptr) {
      area->setShowAltColor(hasCollision);
    }
748 749 750 751
  }

  _masterController->missionController()->recalcTerrainProfile();
}
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

void MeasurementComplexItem::_onAltitudeChanged() {
  // Apply altitude to variants and route.
  auto alt = _altitude.rawValue().toDouble();
  for (auto &var : _variantVector) {

    Variant *pVar;
    if (var.size() > 0) {
      pVar = &var;
    } else {
      pVar = &_route;
    }

    for (auto &qVariant : *pVar) {
      auto vertex = qVariant.value<QGeoCoordinate>();
      vertex.setAltitude(alt);
      qVariant = QVariant::fromValue(vertex);
    }
  }

  if (_route.size() > 0) {
    emit routeChanged();
  }
}
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793

bool MeasurementComplexItem::holdProgress() const { return _holdProgress; }

void MeasurementComplexItem::setHoldProgress(bool holdProgress) {
  if (_holdProgress != holdProgress) {
    _holdProgress = holdProgress;
    emit holdProgressChanged();

    if (_holdProgress) {
      disconnect(pNemoInterface, &NemoInterface::progressChanged, this,
                 &MeasurementComplexItem::_onNewProgress);
    } else {
      connect(pNemoInterface, &NemoInterface::progressChanged, this,
              &MeasurementComplexItem::_onNewProgress);
      _onNewProgress(pNemoInterface->getProgress());
    }
  }
}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
794 795
void MeasurementComplexItem::_setAreaData(
    MeasurementComplexItem::PtrAreaData data) {
796 797
  if (_pCurrentData != data) {
    _pCurrentData = data;
798 799 800 801
    emit areaDataChanged();
  }
}

802 803 804 805
void MeasurementComplexItem::_updateRoute() {
  if (!editing()) {
    // Reset data.
    this->_route.clear();
806
    emit routeChanged();
807 808 809 810 811 812
    this->_variantVector.clear();
    this->_variantNames.clear();
    emit variantNamesChanged();

    if (this->_pAreaData->isCorrect()) {

813 814 815 816 817 818 819 820 821 822 823 824 825 826
      auto measurmentAreaArray = _pAreaData->measurementAreaArray();
      bool measurementComplete = true;
      for (const auto &area : measurmentAreaArray) {
        if (!area->measurementCompleted()) {
          measurementComplete = false;
        }
      }

      if (measurementComplete) {
        qCDebug(MeasurementComplexItemLog)
            << "_updateWorker(): measurement complete!";
        return;
      }

827 828 829 830
      // Prepare data.
      auto origin = this->_pAreaData->origin();
      origin.setAltitude(0);
      if (!origin.isValid()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
831
        qCDebug(MeasurementComplexItemLog)
832 833
            << "_updateWorker(): origin invalid." << origin;
        return;
834 835
      }

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
      // Convert safe area.
      auto serviceArea =
          getGeoArea<const SafeArea *>(*this->_pAreaData->areaList());
      auto geoSafeArea = serviceArea->coordinateList();
      if (!(geoSafeArea.size() >= 3)) {
        qCDebug(MeasurementComplexItemLog)
            << "_updateWorker(): safe area invalid." << geoSafeArea;
        return;
      }
      for (auto &v : geoSafeArea) {
        if (v.isValid()) {
          v.setAltitude(0);
        } else {
          qCDebug(MeasurementComplexItemLog)
              << "_updateWorker(): safe area contains invalid coordinate."
              << geoSafeArea;
          return;
        }
      }
855

856 857 858 859
      // Routing par.
      RoutingParameter par;
      par.numSolutions = 5;
      auto &safeAreaENU = par.safeArea;
860
      geometry::areaToEnu(origin, geoSafeArea, safeAreaENU);
861 862 863

      // Create generator.
      if (this->_pGenerator != nullptr) {
864
        routing::GeneratorBase::Work g; // Transect generator.
865 866 867 868 869 870 871 872 873 874
        if (this->_pGenerator->get(g)) {
          // Start/Restart routing worker.
          this->_pWorker->route(par, g);
          _setState(STATE::ROUTING);
          return;
        } else {
          qCDebug(MeasurementComplexItemLog)
              << "_updateWorker(): generator creation failed.";
          return;
        }
875
      } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
876
        qCDebug(MeasurementComplexItemLog)
877 878 879 880
            << "_updateWorker(): pGenerator == nullptr, number of registered "
               "generators: "
            << this->_generatorList.size();
        return;
881 882
      }
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
883
      qCDebug(MeasurementComplexItemLog)
884
          << "_updateWorker(): area data invalid.";
885
      return;
886 887 888 889
    }
  }
}

890
void MeasurementComplexItem::_changeVariantIndex() {
891
  if (idle()) {
892
    auto variant = this->_variantIndex.rawValue().toUInt();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
893

894
    // Find old variant. Old variant corresponts with empty list.
Valentin Platzgummer's avatar
Valentin Platzgummer committed
895 896 897 898 899 900 901
    std::size_t old_variant = std::numeric_limits<std::size_t>::max();
    for (std::size_t i = 0; i < std::size_t(this->_variantVector.size()); ++i) {
      const auto &variantCoordinates = this->_variantVector.at(i);
      if (variantCoordinates.isEmpty()) {
        old_variant = i;
        break;
      }
902 903
    }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
904 905 906 907 908 909 910
    // Swap route.
    if (variant != old_variant) {
      // Swap in new variant.
      if (variant < std::size_t(this->_variantVector.size())) {
        if (old_variant != std::numeric_limits<std::size_t>::max()) {
          // this->_route containes a route, swap it back to
          // this->_solutionVector
911 912
          auto &oldRoute = this->_variantVector[old_variant];
          oldRoute.swap(this->_route);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
913
        }
914 915
        auto &newRoute = this->_variantVector[variant];
        this->_route.swap(newRoute);
916
        emit routeChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
917 918 919 920
      } else { // error
        qCDebug(MeasurementComplexItemLog)
            << "Variant out of bounds (variant =" << variant << ").";
        qCDebug(MeasurementComplexItemLog) << "Resetting variant to zero.";
921

922 923 924 925 926
        disconnect(&this->_variantIndex, &Fact::rawValueChanged, this,
                   &MeasurementComplexItem::_changeVariantIndex);
        this->_variantIndex.setCookedValue(QVariant(0));
        connect(&this->_variantIndex, &Fact::rawValueChanged, this,
                &MeasurementComplexItem::_changeVariantIndex);
927

Valentin Platzgummer's avatar
Valentin Platzgummer committed
928
        if (this->_variantVector.size() > 0) {
929
          this->_changeVariantIndex();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
930
        }
931 932 933 934 935
      }
    }
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
936
void MeasurementComplexItem::_reverseRoute() {
937
  if (idle()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
938 939 940 941
    if (this->_route.size() > 0) {
      auto &t = this->_route;
      std::reverse(t.begin(), t.end());
    }
942
    emit routeChanged();
943 944 945
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
void MeasurementComplexItem::_syncTiles() {
  auto areaArray = _pAreaData->measurementAreaArray();
  bool clear = false;
  if (areaArray.size() > 0) {

    // create tile ptr array
    TilePtrArray tilePtrArray;
    auto *pMeasurementArea = areaArray[0];
    auto pTiles = pMeasurementArea->tiles();
    for (int i = 0; i < pTiles->count(); ++i) {
      auto *tile = pTiles->value<MeasurementTile *>(i);
      Q_ASSERT(tile != nullptr);
      tilePtrArray.push_back(tile);
    }

    if (tilePtrArray.size() > 0) {
962 963 964
      (void)pNemoInterface->clearTiles();
      (void)pNemoInterface->addTiles(tilePtrArray);
      return;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
965 966 967 968 969 970 971 972
    } else {
      clear = true;
    }
  } else {
    clear = true;
  }

  if (clear) {
973
    (void)pNemoInterface->clearTiles();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
974 975 976 977 978 979 980 981 982 983 984 985
  }
}

void MeasurementComplexItem::_onNewProgress(const ProgressArray &array) {
  auto areaArray = this->_pAreaData->measurementAreaArray();
  if (areaArray.size() > 0) {
    for (auto &area : areaArray) {
      area->updateProgress(array);
    }
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
986
ComplexMissionItem::ReadyForSaveState
Valentin Platzgummer's avatar
Valentin Platzgummer committed
987
MeasurementComplexItem::readyForSaveState() const {
988
  if (idle()) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
989
    return ReadyForSaveState::ReadyForSave;
990
  } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
991
    return ReadyForSaveState::NotReadyForSaveData;
992 993 994
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
995 996 997 998
bool MeasurementComplexItem::exitCoordinateSameAsEntry() const {
  return this->_route.size() > 0 ? this->_route.first() == this->_route.last()
                                 : false;
}
999

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1000 1001 1002 1003 1004 1005
void MeasurementComplexItem::setDirty(bool dirty) {
  if (this->_dirty != dirty) {
    this->_dirty = dirty;
    emit dirtyChanged(this->_dirty);
  }
}
1006

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
void MeasurementComplexItem::setCoordinate(const QGeoCoordinate &coordinate) {
  Q_UNUSED(coordinate);
}

void MeasurementComplexItem::setSequenceNumber(int sequenceNumber) {
  if (this->_sequenceNumber != sequenceNumber) {
    this->_sequenceNumber = sequenceNumber;
    emit sequenceNumberChanged(this->_sequenceNumber);
  }
}

QString MeasurementComplexItem::patternName() const { return name; }

1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
double MeasurementComplexItem::complexDistance() const {
  double d = 0;
  if (this->_route.size() > 1) {
    auto vertex = _route.first().value<QGeoCoordinate>();
    std::for_each(this->_route.cbegin() + 1, this->_route.cend(),
                  [&vertex, &d](const QVariant &variant) {
                    auto otherVertex = variant.value<QGeoCoordinate>();
                    d += vertex.distanceTo(otherVertex);
                    vertex = otherVertex;
                  });
  }
  return d;
}

int MeasurementComplexItem::lastSequenceNumber() const {
  return _sequenceNumber + std::max(0, this->_route.size() - 1);
}

1038
bool MeasurementComplexItem::addGenerator(routing::GeneratorBase *g) {
1039

1040
  if (g == nullptr) {
1041
    qCDebug(MeasurementComplexItemLog) << "addGenerator(): empty generator.";
1042
    Q_ASSERT(g != nullptr);
1043 1044 1045
    return false;
  }

1046 1047 1048 1049 1050 1051 1052
  for (const auto &otherGenerator : _generatorList) {
    if (otherGenerator->name() == g->name()) {
      qCDebug(MeasurementComplexItemLog)
          << "addGenerator(): generator with name " << g->name()
          << " already added.";
      Q_ASSERT(otherGenerator->name() == g->name());
      return false;
1053
    }
1054
  }
1055

1056 1057 1058
  this->_generatorList.push_back(g);
  if (this->_generatorList.size() == 1) {
    _setGenerator(g);
1059
  }
1060 1061 1062

  emit generatorListChanged();
  return true;
1063 1064
}

1065
bool MeasurementComplexItem::removeGenerator(const QString &name) {
1066 1067 1068 1069 1070
  return removeGenerator(generatorIndex(name));
}

bool MeasurementComplexItem::removeGenerator(int index) {
  if (index >= 0 && index < this->_generatorList.size()) {
1071 1072 1073 1074
    // Is this the current generator?
    const auto &g = this->_generatorList.at(index);
    if (g == this->_pGenerator) {
      if (index > 0) {
1075
        _setGenerator(this->_generatorList.at(index - 1));
1076 1077
      } else if (index + 1 < _generatorList.size()) {
        _setGenerator(this->_generatorList.at(index + 1));
1078
      } else {
1079
        _setGenerator(nullptr);
1080 1081 1082
      }
    }

1083
    auto gen = this->_generatorList.takeAt(index);
1084

1085 1086 1087 1088
    // Should the generator be deleted?
    if (gen->parent() == this || gen->parent() == nullptr) {
      gen->deleteLater();
    }
1089

1090 1091
    emit generatorListChanged();
    return true;
1092
  } else {
1093 1094 1095 1096
    qCDebug(MeasurementComplexItemLog) << "removeGenerator(): index (" << index
                                       << ") out"
                                          "of bounds ( "
                                       << this->_generatorList.size() << " ).";
1097 1098 1099 1100
    return false;
  }
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1101
bool MeasurementComplexItem::switchToGenerator(const QString &name) {
1102
  return switchToGenerator(generatorIndex(name));
1103 1104
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1105
bool MeasurementComplexItem::switchToGenerator(int index) {
1106
  if (index >= 0 && index < _generatorList.size()) {
1107
    _setGenerator(this->_generatorList.at(index));
1108 1109
    return true;
  } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1110
    qCDebug(MeasurementComplexItemLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1111
        << "switchToGenerator(): index (" << index
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1112 1113
        << ") out"
           "of bounds ( "
1114
        << this->_generatorList.size() << " ).";
1115 1116 1117 1118
    return false;
  }
}

1119 1120 1121 1122
void MeasurementComplexItem::resetGenerators() {
  while (_generatorList.size() > 0) {
    removeGenerator(0);
  }
1123

1124 1125
  auto lg =
      pGeneratorFactory->create(routing::LinearGenerator::typeString, this);
1126 1127 1128
  lg->setData(this->_pAreaData);
  addGenerator(lg);

1129 1130
  auto cg =
      pGeneratorFactory->create(routing::CircularGenerator::typeString, this);
1131 1132 1133 1134 1135 1136 1137
  cg->setData(this->_pAreaData);
  addGenerator(cg);
}

QList<MeasurementComplexItem::PtrGenerator>
MeasurementComplexItem::generatorList() const {
  return _generatorList;
1138 1139
}

1140
QStringList MeasurementComplexItem::generatorNameList() const {
1141 1142 1143 1144 1145
  QStringList list;
  for (const auto gen : _generatorList) {
    list.append(gen->name());
  }
  return list;
1146 1147
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1148 1149 1150
routing::GeneratorBase *MeasurementComplexItem::generator() {
  return _pGenerator;
}
1151

1152 1153 1154 1155 1156 1157
const routing::GeneratorBase *MeasurementComplexItem::generator() const {
  return _pGenerator;
}

const routing::GeneratorBase *
MeasurementComplexItem::generator(int index) const {
1158
  if (index >= 0 && index < _generatorList.size()) {
1159 1160 1161 1162 1163 1164 1165
    return _generatorList[index];
  } else {
    return nullptr;
  }
}

routing::GeneratorBase *MeasurementComplexItem::generator(int index) {
1166
  if (index >= 0 && index < _generatorList.size()) {
1167 1168 1169 1170 1171 1172 1173
    return _generatorList[index];
  } else {
    return nullptr;
  }
}

int MeasurementComplexItem::generatorIndex() const {
1174 1175 1176
  return this->_generatorList.indexOf(this->_pGenerator);
}

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
int MeasurementComplexItem::generatorIndex(const QString &name) {
  int index = -1;
  for (int i = 0; i < _generatorList.size(); ++i) {
    const auto gen = _generatorList[i];
    if (gen->name() == name) {
      index = i;
      break;
    }
  }
  return index;
}

1189 1190
void MeasurementComplexItem::startEditing() {
  if (!editing()) {
1191 1192
    *_pEditorData = *_pAreaData;
    _setAreaData(_pEditorData);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1193
    _setState(STATE::EDITING);
1194 1195 1196
  }
}

1197
bool MeasurementComplexItem::stopEditing(bool doUpdate) {
1198
  if (editing()) {
1199
    bool isDifferent = *_pEditorData != *_pAreaData;
1200 1201
    bool correct = _pEditorData->isCorrect();
    if (correct) {
1202
      *_pAreaData = *_pEditorData;
1203
    }
1204
    _setAreaData(_pAreaData);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1205
    _setState(STATE::IDLE);
1206 1207 1208
    bool updated = false;
    if (doUpdate && correct && isDifferent) {
      updated = true;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1209
      _updateRoute();
1210
    }
1211

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1212 1213 1214 1215
    if (correct && isDifferent) {
      _syncTiles();
    }

1216
    return updated;
1217
  }
1218
  return false;
1219 1220
}

1221 1222 1223
void MeasurementComplexItem::abortEditing() {
  if (editing()) {
    _setAreaData(_pAreaData);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1224
    _syncTiles();
1225 1226 1227 1228
    _setState(STATE::IDLE);
  }
}

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
void MeasurementComplexItem::reset() {
  if (editing()) {
    *_pEditorData = *_pAreaData;
  }
}

bool MeasurementComplexItem::initialize(const QGeoCoordinate &bottomLeft,
                                        const QGeoCoordinate &topRight) {
  bool r1 = _pAreaData->initialize(bottomLeft, topRight);
  bool r2 = _pEditorData->initialize(bottomLeft, topRight);

  return r1 && r2;
}

bool MeasurementComplexItem::initialized() {
  return _pCurrentData->initialized();
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1247
void MeasurementComplexItem::_storeRoutingData(
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1248
    MeasurementComplexItem::PtrRoutingData pRoute) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1249 1250
  if (this->_state == STATE::ROUTING) {
    // Store solutions.
1251
    auto ori = this->_pAreaData->origin();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1252 1253
    ori.setAltitude(0);
    QVector<Variant> variantVector;
1254
    const std::size_t nSolutions = pRoute->solutionVector.size();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1255 1256 1257 1258 1259 1260 1261

    for (std::size_t j = 0; j < nSolutions; ++j) {
      Variant var;
      const auto &solution = pRoute->solutionVector.at(j);
      if (solution.size() > 0) {
        const auto &route = solution.at(0);
        const auto &path = route.path;
1262 1263 1264 1265 1266

        // Convert to geo coordinates.

        for (const auto &vertex : path) {
          QGeoCoordinate c;
1267
          geometry::fromENU(ori, vertex, c);
1268
          var.append(QVariant::fromValue(c));
1269 1270
        }
      } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1271
        qCDebug(MeasurementComplexItemLog)
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1272
            << "_setTransects(): solution.size() == 0";
1273 1274
      }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1275 1276 1277
      if (var.size() > 0) {
        variantVector.push_back(std::move(var));
      }
1278 1279
    }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1280 1281 1282 1283
    // Assign routes if no error occured.
    if (variantVector.size() > 0) {
      // Swap first route to _route.
      this->_variantVector.swap(variantVector);
1284

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1285 1286 1287 1288 1289 1290 1291
      // Add route variant names.
      this->_variantNames.clear();
      for (std::size_t i = 1; i <= std::size_t(this->_variantVector.size());
           ++i) {
        this->_variantNames.append(QString::number(i));
      }
      emit variantNamesChanged();
1292

1293
      // Set variant to 0.
1294 1295 1296 1297 1298
      disconnect(&this->_variantIndex, &Fact::rawValueChanged, this,
                 &MeasurementComplexItem::_changeVariantIndex);
      this->_variantIndex.setCookedValue(QVariant(0));
      connect(&this->_variantIndex, &Fact::rawValueChanged, this,
              &MeasurementComplexItem::_changeVariantIndex);
1299

1300
      // Select first variant as route.
1301
      this->_route.swap(this->_variantVector.first());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1302
      emit routeChanged();
1303 1304

      this->_setState(STATE::IDLE);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1305 1306 1307 1308 1309
    } else {
      qCDebug(MeasurementComplexItemLog)
          << "_setTransects(): failed, variantVector empty.";
      this->_setState(STATE::IDLE);
    }
1310 1311 1312
  }
}

1313
Fact *MeasurementComplexItem::variantIndex() { return &_variantIndex; }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
1314 1315

Fact *MeasurementComplexItem::altitude() { return &this->_altitude; }
1316

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1317
bool MeasurementComplexItem::calculating() const {
1318 1319 1320
  return this->_calculating(this->_state);
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1321 1322
bool MeasurementComplexItem::editing() const { return _editing(this->_state); }

1323
bool MeasurementComplexItem::idle() const { return _idle(this->_state); }
1324

Valentin Platzgummer's avatar
Valentin Platzgummer committed
1325
bool MeasurementComplexItem::followTerrain() const { return _followTerrain; }