AreaData.cc 13.9 KB
Newer Older
1
#include "AreaData.h"
2

3 4
#include "geometry/MeasurementArea.h"
#include "geometry/SafeArea.h"
5
#include "geometry/snake.h"
6

7
#include "JsonHelper.h"
8
#include "QGCApplication.h"
9 10
#include "QGCLoggingCategory.h"
#include "QGCQGeoCoordinate.h"
11

12
QGC_LOGGING_CATEGORY(AreaDataLog, "AreaDataLog")
13

14
const char *originKey = "Origin";
15
const char *areaListKey = "AreaList";
16

17
AreaData::AreaData(QObject *parent) : QObject(parent) {}
18

19
AreaData::~AreaData() {}
20

21
AreaData::AreaData(const AreaData &other, QObject *parent)
22
    : QObject(parent), _showErrorMessages(true) {
23
  *this = other;
24 25
}

26
AreaData &AreaData::operator=(const AreaData &other) {
27 28 29 30 31 32 33
  this->clear();

  // Clone elements.
  for (int i = 0; i < other._areaList.count(); ++i) {
    auto obj = other._areaList[i];
    auto area = qobject_cast<const GeoArea *>(obj);
    this->insert(area->clone(this));
34
  }
35 36 37

  _origin = other._origin;

38
  return *this;
39 40
}

41
bool AreaData::insert(GeoArea *areaData) {
42 43 44
  if (areaData != nullptr) {
    if (Q_LIKELY(!this->_areaList.contains(areaData))) {
      _areaList.append(areaData);
45
      emit areaListChanged();
46 47 48 49 50 51 52

      auto *measurementArea = qobject_cast<MeasurementArea *>(areaData);
      if (measurementArea != nullptr) {
        connect(measurementArea, &MeasurementArea::centerChanged, this,
                &AreaData::_updateOrigin);
        _setOrigin(measurementArea->center());
      }
53
      return true;
54
    }
55 56
  }

57
  return false;
58 59
}

60 61 62 63
void AreaData::remove(GeoArea *areaData) {
  int index = _areaList.indexOf(areaData);
  if (index >= 0) {
    QObject *obj = _areaList.removeAt(index);
64

65 66 67 68 69 70
    auto *measurementArea = qobject_cast<MeasurementArea *>(areaData);
    if (measurementArea != nullptr) {
      disconnect(measurementArea, &MeasurementArea::centerChanged, this,
                 &AreaData::_updateOrigin);
      _setOrigin(QGeoCoordinate());
    }
71

72
    if (obj->parent() == nullptr || obj->parent() == this) {
73
      obj->deleteLater();
74 75
    }

76 77
    emit areaListChanged();
  }
78 79
}

80 81
void AreaData::clear() {
  if (_areaList.count() > 0) {
82 83
    while (_areaList.count() > 0) {
      remove(_areaList.value<GeoArea *>(0));
84 85 86
    }
    emit areaListChanged();
  }
87
  _errorString.clear();
88 89
}

90
QmlObjectListModel *AreaData::areaList() { return &_areaList; }
91

92
const QmlObjectListModel *AreaData::areaList() const { return &_areaList; }
93

94
QGeoCoordinate AreaData::origin() const { return _origin; }
95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
bool AreaData::isCorrect() {
  if (!initialized()) {
    qCWarning(AreaDataLog) << "isCorrect(): not initialized";
    return false;
  }

  // Check if areas are correct
  if (!_areasCorrect()) {
    return false;
  }

  // Check if areas where added.
  MeasurementArea *measurementArea = nullptr;
  SafeArea *safeArea = nullptr;
  if (!_getAreas(&measurementArea, &safeArea)) {
    return false;
  }
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
  // Check if measurement area is covered by safe area.
  if (!_origin.isValid()) {
    qCWarning(AreaDataLog) << "isCorrect(): origin invalid";
    return false;
  }
  const auto &origin = this->origin();
  snake::FPolygon safeAreaENU;
  snake::areaToEnu(origin, safeArea->pathModel(), safeAreaENU);
  snake::FPolygon measurementAreaENU;
  snake::areaToEnu(origin, measurementArea->pathModel(), measurementAreaENU);
  //  qDebug() << "origin" << origin;
  //  std::stringstream ss;
  //  ss << "measurementAreaENU: " << bg::wkt(measurementAreaENU) << std::endl;
  //  ss << "safeAreaENU: " << bg::wkt(safeAreaENU) << std::endl;
  //  qDebug() << ss.str().c_str();
  if (!bg::covered_by(measurementAreaENU, safeAreaENU)) {
    _processError(tr("Measurement Area not inside Safe Area. Please adjust "
131
                     "the Measurement Area.\n"));
132 133
    return false;
  }
134

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

bool AreaData::initialize(const QGeoCoordinate &bottomLeft,
                          const QGeoCoordinate &topRight) {
  // bottomLeft and topRight define the bounding box.
  if (bottomLeft.isValid() && topRight.isValid() && bottomLeft != topRight) {
    auto *measurementArea = getGeoArea<MeasurementArea *>(_areaList);
    auto *safeArea = getGeoArea<SafeArea *>(_areaList);

    if (safeArea == nullptr) {
146 147 148
      safeArea = new SafeArea(this);
      if (!insert(safeArea)) {
        safeArea->deleteLater();
149 150 151 152 153
        qCCritical(AreaDataLog)
            << "initialize(): safeArea == nullptr, but insert() failed.";
        return false;
      }
    }
154

155
    if (measurementArea == nullptr) {
156 157 158
      measurementArea = new MeasurementArea(this);
      if (!insert(measurementArea)) {
        measurementArea->deleteLater();
159 160 161 162 163
        qCCritical(AreaDataLog) << "initialize(): measurementArea == nullptr, "
                                   "but insert() failed.";
        return false;
      }
    }
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
    // Fit safe area to bounding box.
    safeArea->clear();
    safeArea->appendVertex(bottomLeft);
    safeArea->appendVertex(
        QGeoCoordinate(topRight.latitude(), bottomLeft.longitude()));
    safeArea->appendVertex(topRight);
    safeArea->appendVertex(
        QGeoCoordinate(bottomLeft.latitude(), topRight.longitude()));

    // Put measurement area inside safeArea;
    measurementArea->clear();
    measurementArea->appendVertex(QGeoCoordinate(
        0.8 * bottomLeft.latitude() + 0.2 * topRight.latitude(),
        0.8 * bottomLeft.longitude() + 0.2 * topRight.longitude()));
    measurementArea->appendVertex(QGeoCoordinate(
        0.2 * bottomLeft.latitude() + 0.8 * topRight.latitude(),
        0.8 * bottomLeft.longitude() + 0.2 * topRight.longitude()));
    measurementArea->appendVertex(QGeoCoordinate(
        0.2 * bottomLeft.latitude() + 0.8 * topRight.latitude(),
        0.2 * bottomLeft.longitude() + 0.8 * topRight.longitude()));
    measurementArea->appendVertex(QGeoCoordinate(
        0.8 * bottomLeft.latitude() + 0.2 * topRight.latitude(),
        0.2 * bottomLeft.longitude() + 0.8 * topRight.longitude()));
188 189 190 191 192 193 194 195

    // Set depot
    safeArea->setDepot(QGeoCoordinate(
        safeArea->vertexCoordinate(0).latitude() * 0.5 +
            measurementArea->vertexCoordinate(0).latitude() * 0.5,
        safeArea->vertexCoordinate(0).longitude() * 0.5 +
            measurementArea->vertexCoordinate(0).longitude() * 0.5));

196 197 198 199 200 201 202 203
    return true;
  } else {
    qCWarning(AreaDataLog)
        << "initialize(): bounding box invaldid (bottomLeft, topRight) "
        << bottomLeft << "," << topRight;
    return false;
  }
}
204

205 206 207 208 209 210
bool AreaData::initialized() {
  auto measurementArea = getGeoArea<MeasurementArea *>(_areaList);
  auto safeArea = getGeoArea<SafeArea *>(_areaList);
  return measurementArea != nullptr && safeArea != nullptr &&
         measurementArea->count() >= 3 && safeArea->count() >= 3;
}
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

void AreaData::intersection() {
  if (initialized() && _areasCorrect()) {
    MeasurementArea *measurementArea = nullptr;
    SafeArea *safeArea = nullptr;
    if (_getAreas(&measurementArea, &safeArea)) {

      // convert to ENU
      const auto origin = this->origin();
      snake::FPolygon safeAreaENU;
      snake::areaToEnu(origin, safeArea->pathModel(), safeAreaENU);
      snake::FPolygon measurementAreaENU;
      snake::areaToEnu(origin, measurementArea->pathModel(),
                       measurementAreaENU);

      // do intersection
      std::deque<snake::FPolygon> outputENU;
      boost::geometry::intersection(measurementAreaENU, safeAreaENU, outputENU);

      if (outputENU.size() < 1 || outputENU[0].outer().size() < 4) {
        _processError(
            "Intersection did't deliver any result. Measurement Area and "
            "Safe Area must touch each other.");
        return;
      }

      if (outputENU[0].inners().size() > 0 || outputENU.size() > 1) {
        _processError(
            "Hint: Only simple polygons can be displayed. If Intersection"
            "produces polygons with holes or multi polygons, only "
            "partial information can be displayed.");
      }

      // Shrink the result if safeAreaENU doesn't cover it.
      auto large = std::move(outputENU[0]);
      snake::FPolygon small;
      while (!bg::covered_by(large, safeAreaENU)) {
        snake::offsetPolygon(large, small, -0.1);
        large = std::move(small);
        qDebug() << "intersection(): shrink";
      }

      // Convert.
      measurementArea->clear();
      for (auto it = large.outer().begin(); it != large.outer().end() - 1;
           ++it) {
        QGeoCoordinate c;
        snake::fromENU(origin, *it, c);
        measurementArea->appendVertex(c);
      }
    }
  }
263 264
}

265 266 267 268 269 270
MeasurementArea *AreaData::measurementArea() {
  return getGeoArea<MeasurementArea *>(_areaList);
}

SafeArea *AreaData::safeArea() { return getGeoArea<SafeArea *>(_areaList); }

271
bool AreaData::operator==(const AreaData &other) const {
272 273 274 275 276 277 278 279 280 281
  if (_areaList.count() == other._areaList.count()) {
    for (int i = 0; i < _areaList.count(); ++i) {
      if (_areaList[i] != other._areaList[i]) {
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
282 283 284 285 286
}
bool AreaData::operator!=(const AreaData &other) const {
  return !(*this == other);
}

287 288 289 290
bool AreaData::load(const QJsonObject &obj, QString &errorString) {
  bool returnValue = true;

  // load areaList.
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  if (obj.contains(areaListKey) && obj[areaListKey].isArray()) {

    this->clear();

    // iterate over json array
    for (const auto valueRef : obj[areaListKey].toArray()) {
      const auto jsonArea = valueRef.toObject();

      // check if area type key is present
      if (jsonArea.contains(GeoArea::areaTypeKey) &&
          jsonArea[GeoArea::areaTypeKey].isString()) {

        // load MeasurementArea
        if (jsonArea[GeoArea::areaTypeKey].toString() ==
            MeasurementArea::name) {

          auto area = getGeoArea<MeasurementArea *>(_areaList);

          if (area == nullptr) {

            auto area = new MeasurementArea(this);
            QString e;
            if (area->loadFromJson(jsonArea, e)) {
              this->insert(area);
315 316
            } else {
              returnValue = false;
317 318 319
              errorString.append(e);
              errorString.append("\n");
              area->deleteLater();
320
            }
321 322 323 324
          } else {
            returnValue = false;
            errorString.append(
                tr("Multiple Measurement Areas detected. Area was ignored."));
325
          }
326 327 328 329 330 331 332 333 334 335 336
        }
        // load SafeArea
        else if (jsonArea[GeoArea::areaTypeKey].toString() == SafeArea::name) {

          auto area = getGeoArea<SafeArea *>(_areaList);
          if (area == nullptr) {

            auto area = new SafeArea(this);
            QString e;
            if (area->loadFromJson(jsonArea, e)) {
              this->insert(area);
337 338
            } else {
              returnValue = false;
339 340 341
              errorString.append(e);
              errorString.append("\n");
              area->deleteLater();
342
            }
343
          } else {
344
            returnValue = false;
345 346
            errorString.append(
                tr("Multiple Safe Areas detected. Area was ignored."));
347 348
          }
        }
349
        // unknown area
350 351
        else {
          returnValue = false;
352 353
          errorString.append(tr("Unknown area type: ") +
                             jsonArea[GeoArea::areaTypeKey].toString());
354
        }
355 356 357 358 359
      } else {
        // GeoArea::areaTypeKey missing
        returnValue = false;
        errorString.append(
            "Area type key missing, not able to determine area type.\n");
360 361
      }
    }
362
  } else {
363
    // AreaList missing
364 365
    returnValue = false;
    errorString.append("Not able to load areas.\n");
366 367 368
  }

  // load origin
369 370
  if (obj.contains(originKey) && obj[originKey].isObject()) {
    QGeoCoordinate origin;
371
    QString e;
372 373
    if (JsonHelper::loadGeoCoordinate(obj[originKey], false, origin, e)) {
      _origin = origin;
374 375 376 377
    }
  }

  return returnValue;
378 379
}

380 381 382 383
bool AreaData::save(QJsonObject &obj) {
  QJsonObject temp;

  QJsonValue jsonOrigin;
384
  JsonHelper::saveGeoCoordinate(_origin, false, jsonOrigin);
385
  temp[originKey] = jsonOrigin;
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

  QJsonArray jsonAreaList;
  for (int i = 0; i < _areaList.count(); ++i) {
    auto qobj = _areaList[i];
    auto area = qobject_cast<GeoArea *>(qobj);
    QJsonObject jsonArea;
    if (area->saveToJson(jsonArea)) {
      jsonAreaList.append(jsonArea);
    } else {
      qDebug(AreaDataLog) << "save(): not able to save area: "
                          << area->objectName();
      _processError(tr("Not able to save area: ") + area->objectName());
      return false;
    }
  }
  temp[areaListKey] = jsonAreaList;

  obj = std::move(temp);
404 405 406
  return true;
}

407
void AreaData::_setOrigin(const QGeoCoordinate &origin) {
408 409 410 411 412
  if (this->_origin != origin) {
    this->_origin = origin;
    emit originChanged();
  }
}
413

414 415 416 417 418 419
void AreaData::_processError(const QString &str) {
  this->_errorString = str;
  emit error();
  if (_showErrorMessages) {
    qgcApp()->informationMessageBoxOnMainThread(tr("Area Editor"),
                                                this->errorString());
420
  }
421
}
422

423 424 425 426 427 428 429
bool AreaData::_areasCorrect() {
  // Check if areas are correct.
  for (int i = 0; i < _areaList.count(); ++i) {
    auto *area = _areaList.value<GeoArea *>(0);
    if (!area->isCorrect()) {
      _processError(area->errorString());
      return false;
430 431 432
    }
  }

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
  return true;
}

bool AreaData::_getAreas(MeasurementArea **measurementArea,
                         SafeArea **safeArea) {
  *measurementArea = getGeoArea<MeasurementArea *>(_areaList);
  if (*measurementArea == nullptr) {
    _processError(
        tr("Measurement Area missing. Please define a measurement area."));
    return false;
  }
  *safeArea = getGeoArea<SafeArea *>(_areaList);
  if (*safeArea == nullptr) {
    _processError(tr("Safe Area missing. Please define a safe area."));
    return false;
  }

  return true;
451
}
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

void AreaData::setShowErrorMessages(bool showErrorMessages) {
  if (showErrorMessages != _showErrorMessages) {
    _showErrorMessages = showErrorMessages;
    emit showErrorMessagesChanged();
  }
}

void AreaData::_updateOrigin() {
  auto *measurementArea = getGeoArea<MeasurementArea *>(_areaList);
  if (measurementArea != nullptr) {
    _setOrigin(measurementArea->center());
  }
}

bool AreaData::showErrorMessages() const { return _showErrorMessages; }

QString AreaData::errorString() const { return _errorString; }