WimaMeasurementArea.cc 12.1 KB
Newer Older
1
#include "WimaMeasurementArea.h"
2
#include "QtConcurrentRun"
Valentin Platzgummer's avatar
Valentin Platzgummer committed
3 4 5 6
#include "SnakeTile.h"
#include "snake.h"

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

8 9
#include "QGCLoggingCategory.h"

10 11 12 13
#ifndef SNAKE_MAX_TILES
#define SNAKE_MAX_TILES 1000
#endif

14 15
QGC_LOGGING_CATEGORY(WimaMeasurementAreaLog, "WimaMeasurementAreaLog")

16 17 18 19 20 21 22 23 24 25 26 27
TileData::TileData() : tiles(this) {}

TileData::~TileData() { tiles.clearAndDeleteContents(); }

TileData &TileData::operator=(const TileData &other) {
  this->tiles.clearAndDeleteContents();
  for (std::size_t i = 0; i < std::size_t(other.tiles.count()); ++i) {
    const auto *obj = other.tiles.get(i);
    const auto *tile = qobject_cast<const SnakeTile *>(obj);
    if (tile != nullptr) {
      this->tiles.append(new SnakeTile(*tile, this));
    } else {
28
      qCWarning(WimaMeasurementAreaLog) << "TileData::operator=: nullptr";
29 30 31 32 33 34
    }
  }
  this->tileCenterPoints = other.tileCenterPoints;
  return *this;
}

35 36 37 38 39 40 41 42 43
bool TileData::operator==(const TileData &other) const {
  return this->tiles == other.tiles &&
         this->tileCenterPoints == other.tileCenterPoints;
}

bool TileData::operator!=(const TileData &other) const {
  return !this->operator==(other);
}

44 45 46 47 48 49 50 51 52 53 54 55 56
void TileData::clear() {
  this->tiles.clearAndDeleteContents();
  this->tileCenterPoints.clear();
}

size_t TileData::size() const {
  if (tiles.count() == tileCenterPoints.size()) {
    return tiles.count();
  } else {
    return 0;
  }
}

57
const char *WimaMeasurementArea::settingsGroup = "MeasurementArea";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
58 59 60 61
const char *WimaMeasurementArea::tileHeightName = "TileHeight";
const char *WimaMeasurementArea::tileWidthName = "TileWidth";
const char *WimaMeasurementArea::minTileAreaName = "MinTileArea";
const char *WimaMeasurementArea::showTilesName = "ShowTiles";
62
const char *WimaMeasurementArea::WimaMeasurementAreaName = "Measurement Area";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
63

64 65
void tileDeleter(QmlObjectListModel *tiles) { tiles->clearAndDeleteContents(); }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
66
WimaMeasurementArea::WimaMeasurementArea(QObject *parent)
67 68 69 70
    : WimaArea(parent),
      _metaDataMap(FactMetaData::createMapFromJsonFile(
          QStringLiteral(":/json/WimaMeasurementArea.SettingsGroup.json"),
          this /* QObject parent */)),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
71 72 73 74 75 76 77 78
      _tileHeight(SettingsFact(settingsGroup, _metaDataMap[tileHeightName],
                               this /* QObject parent */)),
      _tileWidth(SettingsFact(settingsGroup, _metaDataMap[tileWidthName],
                              this /* QObject parent */)),
      _minTileArea(SettingsFact(settingsGroup, _metaDataMap[minTileAreaName],
                                this /* QObject parent */)),
      _showTiles(SettingsFact(settingsGroup, _metaDataMap[showTilesName],
                              this /* QObject parent */)),
79
      _state(STATE::IDLE) {
80
  init();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
81 82
}

83 84 85 86 87 88
WimaMeasurementArea::WimaMeasurementArea(const WimaMeasurementArea &other,
                                         QObject *parent)
    : WimaArea(other, parent),
      _metaDataMap(FactMetaData::createMapFromJsonFile(
          QStringLiteral(":/json/WimaMeasurementArea.SettingsGroup.json"),
          this /* QObject parent */)),
Valentin Platzgummer's avatar
Valentin Platzgummer committed
89 90 91 92 93 94 95 96
      _tileHeight(SettingsFact(settingsGroup, _metaDataMap[tileHeightName],
                               this /* QObject parent */)),
      _tileWidth(SettingsFact(settingsGroup, _metaDataMap[tileWidthName],
                              this /* QObject parent */)),
      _minTileArea(SettingsFact(settingsGroup, _metaDataMap[minTileAreaName],
                                this /* QObject parent */)),
      _showTiles(SettingsFact(settingsGroup, _metaDataMap[showTilesName],
                              this /* QObject parent */)),
97
      _state(STATE::IDLE) {
98
  init();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
99 100
}

101 102 103 104 105
/*!
 * \overload operator=()
 *
 * Calls the inherited operator WimaArea::operator=().
 */
106 107 108 109 110 111
WimaMeasurementArea &WimaMeasurementArea::
operator=(const WimaMeasurementArea &other) {
  WimaArea::operator=(other);
  return *this;
}

112
WimaMeasurementArea::~WimaMeasurementArea() {}
Valentin Platzgummer's avatar
Valentin Platzgummer committed
113

114
QString WimaMeasurementArea::mapVisualQML() const {
115
  return QStringLiteral("WimaMeasurementAreaMapVisual.qml");
116
}
117

118
QString WimaMeasurementArea::editorQML() const {
119
  return QStringLiteral("WimaMeasurementAreaEditor.qml");
120 121
}

122 123
Fact *WimaMeasurementArea::tileHeight() { return &_tileHeight; }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
124 125 126 127 128 129
Fact *WimaMeasurementArea::tileWidth() { return &_tileWidth; }

Fact *WimaMeasurementArea::minTileArea() { return &_minTileArea; }

Fact *WimaMeasurementArea::showTiles() { return &_showTiles; }

130 131 132
QmlObjectListModel *WimaMeasurementArea::tiles() {
  return &this->_tileData.tiles;
}
133

134 135 136 137 138 139 140
const QVector<int> &WimaMeasurementArea::progress() const {
  return this->_progress;
}

QVector<int> WimaMeasurementArea::progressQml() const {
  return this->_progress;
}
141

142
const QmlObjectListModel *WimaMeasurementArea::tiles() const {
143 144 145 146 147 148 149 150 151
  return &this->_tileData.tiles;
}

const QVariantList &WimaMeasurementArea::tileCenterPoints() const {
  return this->_tileData.tileCenterPoints;
}

const TileData &WimaMeasurementArea::tileData() const {
  return this->_tileData;
152 153 154
}

int WimaMeasurementArea::maxTiles() const { return SNAKE_MAX_TILES; }
155

156
bool WimaMeasurementArea::ready() const { return this->_state == STATE::IDLE; }
157

158 159
void WimaMeasurementArea::saveToJson(QJsonObject &json) {
  this->WimaArea::saveToJson(json);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
160 161 162 163
  json[tileHeightName] = _tileHeight.rawValue().toDouble();
  json[tileWidthName] = _tileWidth.rawValue().toDouble();
  json[minTileAreaName] = _minTileArea.rawValue().toDouble();
  json[showTilesName] = _showTiles.rawValue().toBool();
164
  json[areaTypeName] = WimaMeasurementAreaName;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
165 166
}

167 168 169 170 171
bool WimaMeasurementArea::loadFromJson(const QJsonObject &json,
                                       QString &errorString) {
  if (this->WimaArea::loadFromJson(json, errorString)) {
    bool retVal = true;

Valentin Platzgummer's avatar
Valentin Platzgummer committed
172 173
    if (json.contains(tileHeightName) && json[tileHeightName].isDouble()) {
      _tileHeight.setRawValue(json[tileHeightName].toDouble());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
174
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
175
      errorString.append(tr("Could not load tile height!\n"));
176
      retVal = false;
Valentin Platzgummer's avatar
Valentin Platzgummer committed
177 178
    }

Valentin Platzgummer's avatar
Valentin Platzgummer committed
179
    if (json.contains(tileWidthName) && json[tileWidthName].isDouble()) {
180
      _tileWidth.setRawValue(json[tileWidthName].toDouble());
181
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
182
      errorString.append(tr("Could not load tile width!\n"));
183 184
      retVal = false;
    }
185

Valentin Platzgummer's avatar
Valentin Platzgummer committed
186
    if (json.contains(minTileAreaName) && json[minTileAreaName].isDouble()) {
187
      _minTileArea.setRawValue(json[minTileAreaName].toDouble());
188
    } else {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
189
      errorString.append(tr("Could not load minimal tile area!\n"));
190
      retVal = false;
191
    }
192

Valentin Platzgummer's avatar
Valentin Platzgummer committed
193
    if (json.contains(showTilesName) && json[showTilesName].isBool()) {
194
      _showTiles.setRawValue(json[showTilesName].toBool());
Valentin Platzgummer's avatar
Valentin Platzgummer committed
195 196 197 198
    } else {
      errorString.append(tr("Could not load show tiles !\n"));
      retVal = false;
    }
199 200 201 202
    return retVal;
  } else {
    return false;
  }
203
}
204 205

bool WimaMeasurementArea::setProgress(const QVector<int> &p) {
Valentin Platzgummer's avatar
Valentin Platzgummer committed
206
  if (ready()) {
207 208 209
    if (p.size() == this->tiles()->count() && this->_progress != p) {
      this->_progress = p;
      emit progressChanged();
Valentin Platzgummer's avatar
Valentin Platzgummer committed
210
      emit progressAccepted();
211 212 213 214 215
      return true;
    }
  }
  return false;
}
216 217
//!
//! \brief WimaMeasurementArea::doUpdate
218 219
//! \pre WimaMeasurementArea::deferUpdate must be called first, don't call
//! this function directly!
Valentin Platzgummer's avatar
Valentin Platzgummer committed
220 221 222
void WimaMeasurementArea::doUpdate() {
  using namespace snake;
  using namespace boost::units;
223

Valentin Platzgummer's avatar
Valentin Platzgummer committed
224
  auto start = std::chrono::high_resolution_clock::now();
225

226 227 228 229 230
  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;
231
  if (this->_state != STATE::UPDATE &&
232 233
      long(std::ceil(estNumTiles.value())) <= SNAKE_MAX_TILES &&
      this->count() >= 3 && this->isSimplePolygon()) {
234
    setState(STATE::UPDATE);
235 236 237
    auto polygon = this->coordinateList();
    for (auto &v : polygon) {
      v.setAltitude(0);
238 239
    }
    const auto minArea =
Valentin Platzgummer's avatar
Valentin Platzgummer committed
240
        this->_minTileArea.rawValue().toDouble() * si::meter * si::meter;
241 242 243
    auto *th = this->thread();
    auto future = QtConcurrent::run([polygon, th, height, width, minArea] {
      auto start = std::chrono::high_resolution_clock::now();
244

245 246
      DataPtr pData(new TileData());
      // Convert to ENU system.
247
      QGeoCoordinate origin = polygon.first();
248
      FPolygon polygonENU;
249
      areaToEnu(origin, polygon, polygonENU);
250
      std::vector<FPolygon> tilesENU;
251 252
      BoundingBox bbox;
      std::string errorString;
253
      // Generate tiles.
254 255
      if (snake::tiles(polygonENU, height, width, minArea, tilesENU, bbox,
                       errorString)) {
256
        // Convert to geo system.
257
        for (const auto &t : tilesENU) {
258
          auto geoTile = new SnakeTile(pData.get());
259 260 261 262 263
          for (const auto &v : t.outer()) {
            QGeoCoordinate geoVertex;
            fromENU(origin, v, geoVertex);
            geoTile->push_back(geoVertex);
          }
264 265
          pData->tiles.append(geoTile);
          // Calculate center.
266
          snake::FPoint center;
267 268 269 270
          snake::polygonCenter(t, center);
          QGeoCoordinate geoCenter;
          fromENU(origin, center, geoCenter);
          pData->tileCenterPoints.append(QVariant::fromValue(geoCenter));
Valentin Platzgummer's avatar
Valentin Platzgummer committed
271 272
        }
      }
273
      pData->moveToThread(th);
274 275 276 277 278 279 280 281

      qCDebug(WimaMeasurementAreaLog)
          << "doUpdate(): update time: "
          << std::chrono::duration_cast<std::chrono::milliseconds>(
                 std::chrono::high_resolution_clock::now() - start)
                 .count()
          << " ms";

282
      return pData;
283 284 285
    }); // QtConcurrent::run()

    this->_watcher.setFuture(future);
286
  }
287 288 289 290 291 292 293

  qCDebug(WimaMeasurementAreaLog)
      << "doUpdate(): execution time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
Valentin Platzgummer's avatar
Valentin Platzgummer committed
294 295
}

Valentin Platzgummer's avatar
Valentin Platzgummer committed
296
void WimaMeasurementArea::deferUpdate() {
297 298 299 300 301 302 303 304 305 306 307
  if (this->_state == STATE::IDLE || this->_state == STATE::DEFERED) {
    if (this->_state == STATE::IDLE) {
      this->_progress.clear();
      this->_tileData.clear();
      emit this->progressChanged();
      emit this->tilesChanged();
    }
    this->setState(STATE::DEFERED);
    this->_timer.start(100);
  } else if (this->_state == STATE::UPDATE) {
    setState(STATE::RESTART);
308
  }
Valentin Platzgummer's avatar
Valentin Platzgummer committed
309 310
}

311 312
void WimaMeasurementArea::storeTiles() {
  auto start = std::chrono::high_resolution_clock::now();
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

  if (this->_state == STATE::UPDATE) {

    qCDebug(WimaMeasurementAreaLog) << "storeTiles(): update.";

    this->_tileData = *this->_watcher.result();
    // This is expensive. Drawing tiles is expensive too.
    this->_progress = QVector<int>(this->_tileData.tiles.count(), 0);
    this->progressChanged();
    emit this->tilesChanged();
    setState(STATE::IDLE);
  } else if (this->_state == STATE::RESTART) {
    qCDebug(WimaMeasurementAreaLog) << "storeTiles(): restart.";

    doUpdate();
  }
  qCDebug(WimaMeasurementAreaLog)
      << "storeTiles() execution time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
335 336
}

337 338
void WimaMeasurementArea::init() {
  this->setObjectName(WimaMeasurementAreaName);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
339 340 341 342 343 344 345 346 347 348 349
  connect(&this->_tileHeight, &Fact::rawValueChanged, this,
          &WimaMeasurementArea::deferUpdate);
  connect(&this->_tileWidth, &Fact::rawValueChanged, this,
          &WimaMeasurementArea::deferUpdate);
  connect(&this->_minTileArea, &Fact::rawValueChanged, this,
          &WimaMeasurementArea::deferUpdate);
  connect(this, &WimaArea::pathChanged, this,
          &WimaMeasurementArea::deferUpdate);
  this->_timer.setSingleShot(true);
  connect(&this->_timer, &QTimer::timeout, this,
          &WimaMeasurementArea::doUpdate);
350 351 352
  connect(&this->_watcher,
          &QFutureWatcher<std::unique_ptr<QmlObjectListModel>>::finished, this,
          &WimaMeasurementArea::storeTiles);
Valentin Platzgummer's avatar
Valentin Platzgummer committed
353 354
}

355 356 357 358 359 360 361 362 363 364
void WimaMeasurementArea::setState(WimaMeasurementArea::STATE s) {
  if (this->_state != s) {
    auto oldState = this->_state;
    this->_state = s;
    if (s == STATE::IDLE || oldState == STATE::IDLE) {
      emit readyChanged();
    }
  }
}

365 366
/*!
 * \class WimaMeasurementArea
367 368
 * \brief Class defining the area inside which the actual drone measurements
 * are performed.
369 370 371
 *
 * \sa WimaArea, WimaController, WimaPlaner
 */