MeasurementArea.cc 22.6 KB
Newer Older
1
#include "MeasurementArea.h"
2
#include "HashFunctions.h"
3
#include "geometry.h"
4 5
#include "nemo_interface/MeasurementTile.h"

6
#include <ctime>
7

8 9 10 11
#include "QtConcurrentRun"
#include <QJsonArray>
#include <QQmlEngine>

12 13
#include <boost/units/systems/si.hpp>

14
#include "JsonHelper.h"
15
#include "QGCLoggingCategory.h"
16
#include "QmlObjectListHelper.h"
17

18 19
#ifndef MAX_TILES
#define MAX_TILES 1000
20 21
#endif

22 23
QString randomId();

24 25 26 27 28 29 30 31
using namespace geometry;
namespace trans = bg::strategy::transform;

// Aux function
bool getTiles(const FPolygon &area, Length tileHeight, Length tileWidth,
              Area minTileArea, std::vector<FPolygon> &tiles,
              BoundingBox &bbox);

32
QGC_LOGGING_CATEGORY(MeasurementAreaLog, "MeasurementAreaLog")
33

34 35 36 37
namespace {
const char *tileArrayKey = "TileArray";
} // namespace

38
const char *MeasurementArea::settingsGroup = "MeasurementArea";
39 40 41 42
const char *tileHeightKey = "TileHeight";
const char *tileWidthName = "TileWidth";
const char *minTileAreaKey = "MinTileAreaPercent";
const char *showTilesKey = "ShowTiles";
43
const char *tileKey = "Tiles";
44
const char *toManyTilesKey = "ToManyTiles";
45
const char *MeasurementArea::nameString = "Measurement Area";
46

47 48
MeasurementArea::MeasurementArea(QObject *parent)
    : GeoArea(parent),
49
      _metaDataMap(FactMetaData::createMapFromJsonFile(
50
          QStringLiteral(":/json/MeasurementArea.SettingsGroup.json"),
51
          this /* QObject parent */)),
52
      _tileHeight(SettingsFact(settingsGroup, _metaDataMap[tileHeightKey],
53 54 55 56
                               this /* QObject parent */)),
      _tileWidth(SettingsFact(settingsGroup, _metaDataMap[tileWidthName],
                              this /* QObject parent */)),
      _minTileAreaPercent(SettingsFact(settingsGroup,
57
                                       _metaDataMap[minTileAreaKey],
58
                                       this /* QObject parent */)),
59
      _showTiles(SettingsFact(settingsGroup, _metaDataMap[showTilesKey],
60
                              this /* QObject parent */)),
61 62
      _toManyTiles(false), _tiles(new QmlObjectListModel()),
      _state(STATE::IDLE) {
63 64 65
  init();
}

66 67
MeasurementArea::MeasurementArea(const MeasurementArea &other, QObject *parent)
    : GeoArea(other, parent),
68
      _metaDataMap(FactMetaData::createMapFromJsonFile(
69
          QStringLiteral(":/json/MeasurementArea.SettingsGroup.json"),
70
          this /* QObject parent */)),
71
      _tileHeight(SettingsFact(settingsGroup, _metaDataMap[tileHeightKey],
72 73 74 75
                               this /* QObject parent */)),
      _tileWidth(SettingsFact(settingsGroup, _metaDataMap[tileWidthName],
                              this /* QObject parent */)),
      _minTileAreaPercent(SettingsFact(settingsGroup,
76
                                       _metaDataMap[minTileAreaKey],
77
                                       this /* QObject parent */)),
78
      _showTiles(SettingsFact(settingsGroup, _metaDataMap[showTilesKey],
79
                              this /* QObject parent */)),
80 81
      _toManyTiles(other._toManyTiles), _tiles(new QmlObjectListModel()),
      _state(STATE::IDLE) {
82 83 84
  init();
  disableUpdate();

85 86 87 88 89
  _tileHeight = other._tileHeight;
  _tileWidth = other._tileWidth;
  _minTileAreaPercent = other._minTileAreaPercent;
  _showTiles = other._showTiles;

90
  if (other.ready()) {
91 92 93 94 95
    for (int i = 0; i < other._tiles->count(); ++i) {
      _tiles->append(
          qobject_cast<const MeasurementTile *>(other._tiles->operator[](i))
              ->clone(_tiles.get()));
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
96
    _indexMap = other._indexMap;
97 98 99 100 101
    enableUpdate();
  } else {
    enableUpdate();
    doUpdate();
  }
102 103
}

104 105
MeasurementArea &MeasurementArea::operator=(const MeasurementArea &other) {
  GeoArea::operator=(other);
106 107 108 109 110 111 112 113

  disableUpdate();
  _tileHeight = other._tileHeight;
  _tileWidth = other._tileWidth;
  _minTileAreaPercent = other._minTileAreaPercent;
  _showTiles = other._showTiles;

  if (other.ready()) {
114 115 116 117 118 119
    _tiles->clearAndDeleteContents();
    for (int i = 0; i < other._tiles->count(); ++i) {
      _tiles->append(
          qobject_cast<const MeasurementTile *>(other._tiles->operator[](i))
              ->clone(_tiles.get()));
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
120
    _indexMap = other._indexMap;
121
    _toManyTiles = other._toManyTiles;
122 123 124 125 126
    enableUpdate();
  } else {
    enableUpdate();
    doUpdate();
  }
127 128 129
  return *this;
}

130
MeasurementArea::~MeasurementArea() { _tiles->clearAndDeleteContents(); }
131

132 133
QString MeasurementArea::mapVisualQML() const {
  return QStringLiteral("MeasurementAreaMapVisual.qml");
134
  // return QStringLiteral("");
135 136
}

137 138
QString MeasurementArea::editorQML() const {
  return QStringLiteral("MeasurementAreaEditor.qml");
139 140
}

141 142 143
MeasurementArea *MeasurementArea::clone(QObject *parent) const {
  return new MeasurementArea(*this, parent);
}
144

145
Fact *MeasurementArea::tileHeight() { return &_tileHeight; }
146

147
Fact *MeasurementArea::tileWidth() { return &_tileWidth; }
148

149
Fact *MeasurementArea::minTileArea() { return &_minTileAreaPercent; }
150

151
Fact *MeasurementArea::showTiles() { return &_showTiles; }
152

153
QmlObjectListModel *MeasurementArea::tiles() { return _tiles.get(); }
154 155

const QmlObjectListModel *MeasurementArea::tiles() const {
156
  return _tiles.get();
157 158
}

159
int MeasurementArea::maxTiles() const { return MAX_TILES; }
160

161
bool MeasurementArea::ready() const { return this->_state == STATE::IDLE; }
162

163 164
bool MeasurementArea::measurementCompleted() const {
  if (ready()) {
165 166 167
    for (int i = 0; i < _tiles->count(); ++i) {
      const auto tile = qobject_cast<const MeasurementTile *>(_tiles->get(i));
      if (!qFuzzyCompare(tile->progress(), 100)) {
168 169 170 171 172 173 174 175 176
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
}

177
bool MeasurementArea::saveToJson(QJsonObject &json) {
178
  if (ready()) {
179 180 181 182 183
    if (this->GeoArea::saveToJson(json)) {
      json[tileHeightKey] = _tileHeight.rawValue().toDouble();
      json[tileWidthName] = _tileWidth.rawValue().toDouble();
      json[minTileAreaKey] = _minTileAreaPercent.rawValue().toDouble();
      json[showTilesKey] = _showTiles.rawValue().toBool();
184
      json[areaTypeKey] = nameString;
185
      json[toManyTilesKey] = _toManyTiles;
186 187

      // save tiles
188 189 190 191 192 193 194 195
      QJsonArray jsonTileArray;
      for (int i = 0; i < _tiles->count(); ++i) {
        auto tile = qobject_cast<MeasurementTile *>(_tiles->get(i));
        QJsonObject jsonTile;
        tile->saveToJson(jsonTile);
        jsonTileArray.append(jsonTile);
      }
      json[tileArrayKey] = std::move(jsonTileArray);
196

197 198 199 200 201
      return true;
    } else {
      qCDebug(MeasurementAreaLog)
          << "saveToJson(): error inside GeoArea::saveToJson().";
    }
202
  } else {
203
    qCDebug(MeasurementAreaLog) << "saveToJson(): not ready().";
204
  }
205
  return false;
206 207
}

208 209 210
bool MeasurementArea::loadFromJson(const QJsonObject &json,
                                   QString &errorString) {
  if (this->GeoArea::loadFromJson(json, errorString)) {
211 212 213
    disableUpdate();
    bool retVal = true;

214
    // load parameters necessary for tile calculation.
215
    if (!json.contains(tileHeightKey) || !json[tileHeightKey].isDouble()) {
216 217 218
      errorString.append(tr("Could not load tile height!\n"));
      retVal = false;
    } else {
219
      _tileHeight.setRawValue(json[tileHeightKey].toDouble());
220 221 222 223 224 225 226 227 228
    }

    if (!json.contains(tileWidthName) || !json[tileWidthName].isDouble()) {
      errorString.append(tr("Could not load tile width!\n"));
      retVal = false;
    } else {
      _tileWidth.setRawValue(json[tileWidthName].toDouble());
    }

229
    if (!json.contains(minTileAreaKey) || !json[minTileAreaKey].isDouble()) {
230 231 232
      errorString.append(tr("Could not load minimal tile area!\n"));
      retVal = false;
    } else {
233
      _minTileAreaPercent.setRawValue(json[minTileAreaKey].toDouble());
234 235
    }

236 237
    // load less important parameters
    if (json.contains(showTilesKey) || !json[showTilesKey].isBool()) {
238
      _showTiles.setRawValue(json[showTilesKey].toBool());
239 240
    }

241
    // load tiles
242
    bool tileError = false;
243 244
    if (json.contains(tileArrayKey) && json[tileArrayKey].isArray()) {

245
      QString e;
246 247 248
      _tiles->clearAndDeleteContents();

      for (auto &&jsonTile : json[tileArrayKey].toArray()) {
249

250 251 252 253
        auto tile = new MeasurementTile(this);

        if (tile->loadFromJson(jsonTile.toObject(), e)) {
          _tiles->append(tile);
254
        } else {
255 256 257
          tile->deleteLater();
          qCWarning(MeasurementAreaLog) << e;
          tileError = true;
258 259 260
          break;
        }
      }
261
    }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
262

263 264 265 266 267 268 269 270 271
    if (json.contains(toManyTilesKey) && json[toManyTilesKey].isBool()) {
      _toManyTiles = json[toManyTilesKey].toBool();
    } else {
      tileError = true;
    }

    if (!tileError) {
      this->_indexMap.clear();
      for (int i = 0; i < _tiles->count(); ++i) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
272

273 274 275 276 277 278 279 280 281 282 283 284
        auto tile = qobject_cast<MeasurementTile *>(_tiles->get(i));
        auto it = _indexMap.find(tile->id());

        // find unique id
        if (it != _indexMap.end()) {
          auto newId = MeasurementTile::randomId();
          constexpr long counterMax = 1e6;
          unsigned long counter = 0;
          for (; counter <= counterMax; ++counter) {
            it = _indexMap.find(newId);
            if (it == _indexMap.end()) {
              break;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
285
            } else {
286
              newId = MeasurementTile::randomId();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
287 288 289
            }
          }

290 291 292 293 294 295 296 297
          if (counter != counterMax) {
            tile->setId(newId);
            tile->setProgress(0.0);
          } else {
            qCritical() << "MeasurementArea::storeTiles(): not able to find "
                           "unique id!";
            continue;
          }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
298
        }
299 300

        _indexMap.insert(std::make_pair(tile->id(), i));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
301
      }
302
    } else {
303 304 305 306 307 308 309
      qCWarning(MeasurementAreaLog)
          << "Not able to load tiles. tileArrayKey missing or wrong type.";
      if (json.contains(tileArrayKey)) {
        qCWarning(MeasurementAreaLog)
            << "tile array type: " << json[tileArrayKey].type();
      }
      tileError = true;
310 311 312
    }

    // do update if error occurred.
313
    enableUpdate();
314
    if (tileError) {
315 316
      doUpdate();
    }
317 318 319 320 321 322 323

    return retVal;
  } else {
    return false;
  }
}

324 325 326 327
bool MeasurementArea::isCorrect() {
  if (GeoArea::isCorrect()) {
    if (ready()) {
      return true;
328 329 330 331 332
    } else if (_toManyTiles) {
      setErrorString(
          tr("Calculation would yield to many tiles, please adjust the tile "
             "parameters to reduce the number of tiles."));
    } else
333 334 335
      setErrorString(
          tr("Measurement Area tile calculation in progess. Please wait."));
  }
336

337 338 339
  return false;
}

340
void MeasurementArea::updateProgress(const ProgressArray &array) {
341
  if (ready() && array.size() > 0) {
342
    bool anyChanges = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
343 344 345 346 347 348 349
    for (const auto &lp : array) {
      auto it = _indexMap.find(lp.id());
      if (it != _indexMap.end()) {
        int tileIndex = it->second;
        auto *tile = _tiles->value<MeasurementTile *>(tileIndex);
        if (!qFuzzyCompare(lp.progress(), tile->progress())) {
          tile->setProgress(lp.progress());
350 351 352 353 354 355
          anyChanges = true;
        }
      }
    }

    if (anyChanges) {
356 357 358 359
      emit progressChanged();
    }
  }
}
360 361 362

void MeasurementArea::randomProgress() {
  if (ready()) {
363

364
    std::srand(std::time(nullptr));
365

Valentin Platzgummer's avatar
Valentin Platzgummer committed
366 367
    ProgressArray progressArray;

368 369 370 371 372 373
    for (int i = 0; i < _tiles->count(); ++i) {

      auto tile = _tiles->value<MeasurementTile *>(i);
      Q_ASSERT(tile != nullptr);

      auto p = tile->progress();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
374
      p += std::rand() % 125;
375 376 377
      if (p > 100) {
        p = 100;
      }
378

Valentin Platzgummer's avatar
Valentin Platzgummer committed
379
      progressArray.append(LabeledProgress(p, tile->id()));
380 381
    }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
382
    updateProgress(progressArray);
383 384 385 386 387
  }
}

void MeasurementArea::resetProgress() {
  if (ready()) {
388 389 390 391 392 393 394 395 396 397 398
    bool anyChanges = false;

    for (int i = 0; i < _tiles->count(); ++i) {

      auto tile = _tiles->value<MeasurementTile *>(i);
      Q_ASSERT(tile != nullptr);

      if (!qFuzzyCompare(tile->progress(), 0)) {
        tile->setProgress(0);
        anyChanges = true;
      }
399 400
    }

401 402 403
    if (anyChanges) {
      emit progressChanged();
    }
404 405
  }
}
406

407
//!
408 409
//! \brief MeasurementArea::doUpdate
//! \pre MeasurementArea::deferUpdate must be called first, don't call
410
//! this function directly!
411
void MeasurementArea::doUpdate() {
412
  using namespace geometry;
413 414 415 416 417 418 419 420 421 422 423
  using namespace boost::units;

  auto start = std::chrono::high_resolution_clock::now();

  if (this->_state != STATE::UPDATEING && this->_state != STATE::STOP) {
    const auto height = this->_tileHeight.rawValue().toDouble() * si::meter;
    const auto width = this->_tileWidth.rawValue().toDouble() * si::meter;
    const auto tileArea = width * height;
    const auto totalArea = this->area() * si::meter * si::meter;
    const auto estNumTiles = totalArea / tileArea;
    // Check some conditions.
424 425 426 427
    if (long(std::ceil(estNumTiles.value())) >= MAX_TILES) {
      _toManyTiles = true;
    } else if (this->GeoArea::isCorrect()) {
      _toManyTiles = false;
428 429 430 431 432 433 434 435 436
      setState(STATE::UPDATEING);

      auto polygon = this->coordinateList();
      for (auto &v : polygon) {
        v.setAltitude(0);
      }
      const auto minArea =
          this->_minTileAreaPercent.rawValue().toDouble() / 100 * tileArea;
      auto *th = this->thread();
437

438 439 440
      auto future = QtConcurrent::run([polygon, th, height, width, minArea] {
        auto start = std::chrono::high_resolution_clock::now();

441
        TilePtr pData(new QmlObjectListModel());
442 443 444 445 446 447 448
        // Convert to ENU system.
        QGeoCoordinate origin = polygon.first();
        FPolygon polygonENU;
        areaToEnu(origin, polygon, polygonENU);
        std::vector<FPolygon> tilesENU;
        BoundingBox bbox;
        // Generate tiles.
449
        if (getTiles(polygonENU, height, width, minArea, tilesENU, bbox)) {
450 451
          // Convert to geo system.
          for (const auto &t : tilesENU) {
452
            auto geoTile = new MeasurementTile(pData.get());
453 454 455 456 457
            for (const auto &v : t.outer()) {
              QGeoCoordinate geoVertex;
              fromENU(origin, v, geoVertex);
              geoTile->push_back(geoVertex);
            }
458
            pData->append(geoTile);
459 460 461 462
          }
        }
        pData->moveToThread(th);

463
        qCDebug(MeasurementAreaLog)
464 465 466 467 468 469 470 471 472 473 474 475
            << "doUpdate(): update time: "
            << std::chrono::duration_cast<std::chrono::milliseconds>(
                   std::chrono::high_resolution_clock::now() - start)
                   .count()
            << " ms";

        return pData;
      }); // QtConcurrent::run()

      this->_watcher.setFuture(future);
    }
  }
476
  qCDebug(MeasurementAreaLog)
477 478 479 480 481 482 483
      << "doUpdate(): execution time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
}

484
void MeasurementArea::deferUpdate() {
485
  if (this->_state == STATE::IDLE || this->_state == STATE::DEFERED) {
486
    qCDebug(MeasurementAreaLog) << "defereUpdate(): defer update.";
487
    if (this->_state == STATE::IDLE) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
488
      this->_indexMap.clear();
489 490 491
      this->_tiles->clearAndDeleteContents();
      emit tilesChanged();
      emit progressChanged();
492 493 494 495
    }
    this->setState(STATE::DEFERED);
    this->_timer.start(100);
  } else if (this->_state == STATE::UPDATEING) {
496
    qCDebug(MeasurementAreaLog) << "defereUpdate(): restart.";
497 498 499 500
    setState(STATE::RESTARTING);
  }
}

501
void MeasurementArea::storeTiles() {
502 503 504
  auto start = std::chrono::high_resolution_clock::now();

  if (this->_state == STATE::UPDATEING) {
505
    qCDebug(MeasurementAreaLog) << "storeTiles(): update.";
506

507 508 509 510 511 512 513
    _tiles->clearAndDeleteContents();
    this->_tiles = this->_watcher.result();
    this->_watcher.result().reset();
    QQmlEngine::setObjectOwnership(this->_tiles.get(),
                                   QQmlEngine::CppOwnership);

    // update tileMap
Valentin Platzgummer's avatar
Valentin Platzgummer committed
514
    this->_indexMap.clear();
515 516 517
    for (int i = 0; i < _tiles->count(); ++i) {

      auto tile = qobject_cast<MeasurementTile *>(_tiles->get(i));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
518
      auto it = _indexMap.find(tile->id());
519 520

      // find unique id
Valentin Platzgummer's avatar
Valentin Platzgummer committed
521
      if (it != _indexMap.end()) {
522
        auto newId = MeasurementTile::randomId();
523 524 525
        constexpr long counterMax = 1e6;
        unsigned long counter = 0;
        for (; counter <= counterMax; ++counter) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
526 527
          it = _indexMap.find(newId);
          if (it == _indexMap.end()) {
528 529
            break;
          } else {
530
            newId = MeasurementTile::randomId();
531 532 533 534 535 536 537 538 539 540 541 542 543
          }
        }

        if (counter != counterMax) {
          tile->setId(newId);
          tile->setProgress(0.0);
        } else {
          qCritical()
              << "MeasurementArea::storeTiles(): not able to find unique id!";
          continue;
        }
      }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
544
      _indexMap.insert(std::make_pair(tile->id(), i));
545 546
    }

547 548
    // This is expensive. Drawing tiles is expensive too.
    emit this->tilesChanged();
549
    emit progressChanged();
550 551
    setState(STATE::IDLE);
  } else if (this->_state == STATE::RESTARTING) {
552
    qCDebug(MeasurementAreaLog) << "storeTiles(): restart.";
553 554
    doUpdate();
  } else if (this->_state == STATE::STOP) {
555
    qCDebug(MeasurementAreaLog) << "storeTiles(): stop.";
556
  }
557
  qCDebug(MeasurementAreaLog)
558 559 560 561 562 563 564
      << "storeTiles() execution time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
}

565
void MeasurementArea::disableUpdate() {
566
  setState(STATE::STOP);
567 568 569
  this->_timer.stop();
}

570
void MeasurementArea::enableUpdate() {
571 572 573 574 575
  if (this->_state == STATE::STOP) {
    setState(STATE::IDLE);
  }
}

576
void MeasurementArea::init() {
577
  this->setObjectName(nameString);
578 579 580

  QQmlEngine::setObjectOwnership(this->_tiles.get(), QQmlEngine::CppOwnership);

581
  connect(&this->_tileHeight, &Fact::rawValueChanged, this,
582
          &MeasurementArea::deferUpdate);
583
  connect(&this->_tileWidth, &Fact::rawValueChanged, this,
584
          &MeasurementArea::deferUpdate);
585
  connect(&this->_minTileAreaPercent, &Fact::rawValueChanged, this,
586 587
          &MeasurementArea::deferUpdate);
  connect(this, &GeoArea::pathChanged, this, &MeasurementArea::deferUpdate);
588
  this->_timer.setSingleShot(true);
589
  connect(&this->_timer, &QTimer::timeout, this, &MeasurementArea::doUpdate);
590 591
  connect(&this->_watcher,
          &QFutureWatcher<std::unique_ptr<QmlObjectListModel>>::finished, this,
592
          &MeasurementArea::storeTiles);
593 594
}

595
void MeasurementArea::setState(MeasurementArea::STATE s) {
596 597 598 599 600 601 602 603
  if (this->_state != s) {
    auto oldState = this->_state;
    this->_state = s;
    if (s == STATE::IDLE || oldState == STATE::IDLE) {
      emit readyChanged();
    }
  }
}
604

605 606 607
void MeasurementArea::updateIds(const QList<TileDiff> &array) {
  for (const auto &diff : array) {

Valentin Platzgummer's avatar
Valentin Platzgummer committed
608 609 610 611 612 613 614 615 616 617 618 619 620 621
    auto it = _indexMap.find(diff.oldTile.id());

    if (it != _indexMap.end()) {
      int tileIndex = it->second;
      auto *tile = _tiles->value<MeasurementTile *>(tileIndex);
      if (diff.oldTile.coordinateList() == tile->coordinateList()) {
        // Change id and update _tileMap.
        const auto newId = diff.newTile.id();
        tile->setId(newId);
        _indexMap.erase(it);
        auto ret = _indexMap.insert(std::make_pair(newId, tileIndex));
        Q_ASSERT(ret.second == true /*insert success?*/);
        Q_UNUSED(ret);
      }
622 623 624 625
    }
  }
}

626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
bool getTiles(const FPolygon &area, Length tileHeight, Length tileWidth,
              Area minTileArea, std::vector<FPolygon> &tiles,
              BoundingBox &bbox) {
  if (area.outer().empty() || area.outer().size() < 4) {
    qCDebug(MeasurementAreaLog) << "Area has to few vertices.";
    return false;
  }

  if (tileWidth <= 0 * bu::si::meter || tileHeight <= 0 * bu::si::meter ||
      minTileArea < 0 * bu::si::meter * bu::si::meter) {
    std::stringstream ss;
    ss << "Parameters tileWidth (" << tileWidth << "), tileHeight ("
       << tileHeight << "), minTileArea (" << minTileArea
       << ") must be positive.";
    qCDebug(MeasurementAreaLog) << ss.str().c_str();
    return false;
  }

  if (bbox.corners.outer().size() != 5) {
    bbox.corners.clear();
    minimalBoundingBox(area, bbox);
  }

  if (bbox.corners.outer().size() < 5)
    return false;
  double bboxWidth = bbox.width;
  double bboxHeight = bbox.height;
  FPoint origin = bbox.corners.outer()[0];

  // cout << "Origin: " << origin[0] << " " << origin[1] << endl;
  // Transform _mArea polygon to bounding box coordinate system.
  trans::rotate_transformer<boost::geometry::degree, double, 2, 2> rotate(
      bbox.angle * 180 / M_PI);
  trans::translate_transformer<double, 2, 2> translate(-origin.get<0>(),
                                                       -origin.get<1>());
  FPolygon translated_polygon;
  FPolygon rotated_polygon;
  boost::geometry::transform(area, translated_polygon, translate);
  boost::geometry::transform(translated_polygon, rotated_polygon, rotate);
  bg::correct(rotated_polygon);
  // cout << bg::wkt<BoostPolygon2D>(rotated_polygon) << endl;

  size_t iMax = ceil(bboxWidth / tileWidth.value());
  size_t jMax = ceil(bboxHeight / tileHeight.value());

  if (iMax < 1 || jMax < 1) {
    std::stringstream ss;
    ss << "Tile width (" << tileWidth << ") or tile height (" << tileHeight
       << ") to large for measurement area.";
    qCDebug(MeasurementAreaLog) << ss.str().c_str();
    return false;
  }

  trans::rotate_transformer<boost::geometry::degree, double, 2, 2> rotate_back(
      -bbox.angle * 180 / M_PI);
  trans::translate_transformer<double, 2, 2> translate_back(origin.get<0>(),
                                                            origin.get<1>());
  for (size_t i = 0; i < iMax; ++i) {
    double x_min = tileWidth.value() * i;
    double x_max = x_min + tileWidth.value();
    for (size_t j = 0; j < jMax; ++j) {
      double y_min = tileHeight.value() * j;
      double y_max = y_min + tileHeight.value();

      FPolygon tile_unclipped;
      tile_unclipped.outer().push_back(FPoint{x_min, y_min});
      tile_unclipped.outer().push_back(FPoint{x_min, y_max});
      tile_unclipped.outer().push_back(FPoint{x_max, y_max});
      tile_unclipped.outer().push_back(FPoint{x_max, y_min});
      tile_unclipped.outer().push_back(FPoint{x_min, y_min});

      std::deque<FPolygon> boost_tiles;
      if (!boost::geometry::intersection(tile_unclipped, rotated_polygon,
                                         boost_tiles))
        continue;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
702
      for (FPolygon &t : boost_tiles) {
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
        if (bg::area(t) > minTileArea.value()) {
          // Transform boost_tile to world coordinate system.
          FPolygon rotated_tile;
          FPolygon translated_tile;
          boost::geometry::transform(t, rotated_tile, rotate_back);
          boost::geometry::transform(rotated_tile, translated_tile,
                                     translate_back);

          // Store tile and calculate center point.
          tiles.push_back(translated_tile);
        }
      }
    }
  }

  if (tiles.size() < 1) {
    std::stringstream ss;
    ss << "No tiles calculated. Is the minTileArea (" << minTileArea
       << ") parameter large enough?";
    qCDebug(MeasurementAreaLog) << ss.str().c_str();
    return false;
  }

  return true;
}
728 729 730 731 732 733 734 735 736 737 738

QString randomId() {
  std::srand(std::time(nullptr));
  std::int64_t r = 0;

  for (int i = 0; i < 10; ++i) {
    r ^= std::rand();
  }

  return QString::number(r);
}