MeasurementArea.cc 13.8 KB
Newer Older
1
#include "MeasurementArea.h"
2
#include "QtConcurrentRun"
3
#include "nemo_interface/SnakeTile.h"
4 5 6 7 8 9 10 11 12 13
#include "snake.h"

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

#include "QGCLoggingCategory.h"

#ifndef SNAKE_MAX_TILES
#define SNAKE_MAX_TILES 1000
#endif

14
QGC_LOGGING_CATEGORY(MeasurementAreaLog, "MeasurementAreaLog")
15 16 17 18 19 20 21 22 23 24 25

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[i];
    const auto *tile = qobject_cast<const SnakeTile *>(obj);
    if (tile != nullptr) {
26
      this->tiles.append(tile->clone(this));
27
    } else {
28
      qCWarning(MeasurementAreaLog) << "TileData::operator=: nullptr";
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    }
  }
  this->tileCenterPoints = other.tileCenterPoints;
  return *this;
}

bool TileData::operator==(const TileData &other) const {
  if (this->tileCenterPoints == other.tileCenterPoints &&
      this->tiles.count() == other.tiles.count()) {
    for (int i = 0; i < other.tiles.count(); ++i) {
      if (this->tiles[i] != other.tiles[i]) {
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
}

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

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;
  }
}

66
const char *MeasurementArea::settingsGroup = "MeasurementArea";
67
const char *MeasurementArea::tileHeightKey = "TileHeight";
68
const char *MeasurementArea::tileWidthName = "TileWidth";
69 70 71
const char *MeasurementArea::minTileAreaKey = "MinTileAreaPercent";
const char *MeasurementArea::showTilesKey = "ShowTiles";
const char *MeasurementArea::name = "Measurement Area";
72

73 74
MeasurementArea::MeasurementArea(QObject *parent)
    : GeoArea(parent),
75
      _metaDataMap(FactMetaData::createMapFromJsonFile(
76
          QStringLiteral(":/json/MeasurementArea.SettingsGroup.json"),
77
          this /* QObject parent */)),
78
      _tileHeight(SettingsFact(settingsGroup, _metaDataMap[tileHeightKey],
79 80 81 82
                               this /* QObject parent */)),
      _tileWidth(SettingsFact(settingsGroup, _metaDataMap[tileWidthName],
                              this /* QObject parent */)),
      _minTileAreaPercent(SettingsFact(settingsGroup,
83
                                       _metaDataMap[minTileAreaKey],
84
                                       this /* QObject parent */)),
85
      _showTiles(SettingsFact(settingsGroup, _metaDataMap[showTilesKey],
86 87 88 89 90
                              this /* QObject parent */)),
      _state(STATE::IDLE) {
  init();
}

91 92
MeasurementArea::MeasurementArea(const MeasurementArea &other, QObject *parent)
    : GeoArea(other, parent),
93
      _metaDataMap(FactMetaData::createMapFromJsonFile(
94
          QStringLiteral(":/json/MeasurementArea.SettingsGroup.json"),
95
          this /* QObject parent */)),
96
      _tileHeight(SettingsFact(settingsGroup, _metaDataMap[tileHeightKey],
97 98 99 100
                               this /* QObject parent */)),
      _tileWidth(SettingsFact(settingsGroup, _metaDataMap[tileWidthName],
                              this /* QObject parent */)),
      _minTileAreaPercent(SettingsFact(settingsGroup,
101
                                       _metaDataMap[minTileAreaKey],
102
                                       this /* QObject parent */)),
103
      _showTiles(SettingsFact(settingsGroup, _metaDataMap[showTilesKey],
104 105
                              this /* QObject parent */)),
      _state(STATE::IDLE) {
106 107 108
  init();
  disableUpdate();

109 110 111 112 113
  _tileHeight = other._tileHeight;
  _tileWidth = other._tileWidth;
  _minTileAreaPercent = other._minTileAreaPercent;
  _showTiles = other._showTiles;

114 115 116 117 118 119 120 121
  if (other.ready()) {
    _progress = other._progress;
    _tileData = other._tileData;
    enableUpdate();
  } else {
    enableUpdate();
    doUpdate();
  }
122 123
}

124 125
MeasurementArea &MeasurementArea::operator=(const MeasurementArea &other) {
  GeoArea::operator=(other);
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

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

  if (other.ready()) {
    _progress = other._progress;
    _tileData = other._tileData;
    enableUpdate();
  } else {
    enableUpdate();
    doUpdate();
  }
141 142 143
  return *this;
}

144
MeasurementArea::~MeasurementArea() {}
145

146 147
QString MeasurementArea::mapVisualQML() const {
  return QStringLiteral("MeasurementAreaMapVisual.qml");
148
  // return QStringLiteral("");
149 150
}

151 152
QString MeasurementArea::editorQML() const {
  return QStringLiteral("MeasurementAreaEditor.qml");
153 154
}

155 156 157
MeasurementArea *MeasurementArea::clone(QObject *parent) const {
  return new MeasurementArea(*this, parent);
}
158

159
Fact *MeasurementArea::tileHeight() { return &_tileHeight; }
160

161
Fact *MeasurementArea::tileWidth() { return &_tileWidth; }
162

163
Fact *MeasurementArea::minTileArea() { return &_minTileAreaPercent; }
164

165
Fact *MeasurementArea::showTiles() { return &_showTiles; }
166

167
QmlObjectListModel *MeasurementArea::tiles() { return &this->_tileData.tiles; }
168

169
const QVector<int> &MeasurementArea::progress() const {
170 171 172
  return this->_progress;
}

173 174 175
QVector<int> MeasurementArea::progressQml() const { return this->_progress; }

const QmlObjectListModel *MeasurementArea::tiles() const {
176 177 178
  return &this->_tileData.tiles;
}

179
const QVariantList &MeasurementArea::tileCenterPoints() const {
180 181 182
  return this->_tileData.tileCenterPoints;
}

183
const TileData &MeasurementArea::tileData() const { return this->_tileData; }
184

185
int MeasurementArea::maxTiles() const { return SNAKE_MAX_TILES; }
186

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

189 190 191 192 193 194 195
const char *MeasurementArea::getTileWidthName() { return tileWidthName; }

void MeasurementArea::setTileWidthName(const char *value) {
  tileWidthName = value;
}

bool MeasurementArea::saveToJson(QJsonObject &json) {
196
  if (ready()) {
197 198 199 200 201 202 203 204 205 206 207
    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();
      json[areaTypeKey] = name;
      return true;
    } else {
      qCDebug(MeasurementAreaLog)
          << "saveToJson(): error inside GeoArea::saveToJson().";
    }
208
  } else {
209
    qCDebug(MeasurementAreaLog) << "saveToJson(): not ready().";
210
  }
211
  return false;
212 213
}

214 215 216
bool MeasurementArea::loadFromJson(const QJsonObject &json,
                                   QString &errorString) {
  if (this->GeoArea::loadFromJson(json, errorString)) {
217 218 219
    disableUpdate();
    bool retVal = true;

220
    if (!json.contains(tileHeightKey) || !json[tileHeightKey].isDouble()) {
221 222 223
      errorString.append(tr("Could not load tile height!\n"));
      retVal = false;
    } else {
224
      _tileHeight.setRawValue(json[tileHeightKey].toDouble());
225 226 227 228 229 230 231 232 233
    }

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

234
    if (!json.contains(minTileAreaKey) || !json[minTileAreaKey].isDouble()) {
235 236 237
      errorString.append(tr("Could not load minimal tile area!\n"));
      retVal = false;
    } else {
238
      _minTileAreaPercent.setRawValue(json[minTileAreaKey].toDouble());
239 240
    }

241
    if (!json.contains(showTilesKey) || !json[showTilesKey].isBool()) {
242 243 244
      errorString.append(tr("Could not load show tiles !\n"));
      retVal = false;
    } else {
245
      _showTiles.setRawValue(json[showTilesKey].toBool());
246 247 248 249 250 251 252 253 254 255 256
    }

    enableUpdate();
    doUpdate();

    return retVal;
  } else {
    return false;
  }
}

257 258 259 260 261 262 263 264 265 266 267 268
bool MeasurementArea::isCorrect() {
  if (GeoArea::isCorrect()) {
    if (ready()) {
      return true;
    } else {
      setErrorString(
          tr("Measurement Area tile calculation in progess. Please wait."));
    }
  }
  return false;
}

269
bool MeasurementArea::setProgress(const QVector<int> &p) {
270 271 272 273 274 275 276 277 278 279 280
  if (ready()) {
    if (p.size() == this->tiles()->count() && this->_progress != p) {
      this->_progress = p;
      emit progressChanged();
      emit progressAccepted();
      return true;
    }
  }
  return false;
}
//!
281 282
//! \brief MeasurementArea::doUpdate
//! \pre MeasurementArea::deferUpdate must be called first, don't call
283
//! this function directly!
284
void MeasurementArea::doUpdate() {
285 286 287 288 289 290 291 292 293 294 295 296 297
  using namespace snake;
  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.
    if (long(std::ceil(estNumTiles.value())) <= SNAKE_MAX_TILES &&
298
        this->GeoArea::isCorrect()) {
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
      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();
      auto future = QtConcurrent::run([polygon, th, height, width, minArea] {
        auto start = std::chrono::high_resolution_clock::now();

        DataPtr pData(new TileData());
        // Convert to ENU system.
        QGeoCoordinate origin = polygon.first();
        FPolygon polygonENU;
        areaToEnu(origin, polygon, polygonENU);
        std::vector<FPolygon> tilesENU;
        BoundingBox bbox;
        std::string errorString;
        // Generate tiles.
        if (snake::tiles(polygonENU, height, width, minArea, tilesENU, bbox,
                         errorString)) {
          // Convert to geo system.
          for (const auto &t : tilesENU) {
            auto geoTile = new SnakeTile(pData.get());
            for (const auto &v : t.outer()) {
              QGeoCoordinate geoVertex;
              fromENU(origin, v, geoVertex);
              geoTile->push_back(geoVertex);
            }
            pData->tiles.append(geoTile);
            // Calculate center.
            snake::FPoint center;
            snake::polygonCenter(t, center);
            QGeoCoordinate geoCenter;
            fromENU(origin, center, geoCenter);
            pData->tileCenterPoints.append(QVariant::fromValue(geoCenter));
          }
        }
        pData->moveToThread(th);

341
        qCDebug(MeasurementAreaLog)
342 343 344 345 346 347 348 349 350 351 352 353
            << "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);
    }
  }
354
  qCDebug(MeasurementAreaLog)
355 356 357 358 359 360 361
      << "doUpdate(): execution time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
}

362
void MeasurementArea::deferUpdate() {
363
  if (this->_state == STATE::IDLE || this->_state == STATE::DEFERED) {
364
    qCDebug(MeasurementAreaLog) << "defereUpdate(): defer update.";
365 366 367 368 369 370 371 372 373
    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::UPDATEING) {
374
    qCDebug(MeasurementAreaLog) << "defereUpdate(): restart.";
375 376 377 378
    setState(STATE::RESTARTING);
  }
}

379
void MeasurementArea::storeTiles() {
380 381 382
  auto start = std::chrono::high_resolution_clock::now();

  if (this->_state == STATE::UPDATEING) {
383
    qCDebug(MeasurementAreaLog) << "storeTiles(): update.";
384 385 386 387 388 389 390 391

    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::RESTARTING) {
392
    qCDebug(MeasurementAreaLog) << "storeTiles(): restart.";
393 394
    doUpdate();
  } else if (this->_state == STATE::STOP) {
395
    qCDebug(MeasurementAreaLog) << "storeTiles(): stop.";
396
  }
397
  qCDebug(MeasurementAreaLog)
398 399 400 401 402 403 404
      << "storeTiles() execution time: "
      << std::chrono::duration_cast<std::chrono::milliseconds>(
             std::chrono::high_resolution_clock::now() - start)
             .count()
      << " ms";
}

405
void MeasurementArea::disableUpdate() {
406 407 408 409
  setState(STATE::IDLE);
  this->_timer.stop();
}

410
void MeasurementArea::enableUpdate() {
411 412 413 414 415
  if (this->_state == STATE::STOP) {
    setState(STATE::IDLE);
  }
}

416
void MeasurementArea::init() {
417
  this->setObjectName(name);
418
  connect(&this->_tileHeight, &Fact::rawValueChanged, this,
419
          &MeasurementArea::deferUpdate);
420
  connect(&this->_tileWidth, &Fact::rawValueChanged, this,
421
          &MeasurementArea::deferUpdate);
422
  connect(&this->_minTileAreaPercent, &Fact::rawValueChanged, this,
423 424
          &MeasurementArea::deferUpdate);
  connect(this, &GeoArea::pathChanged, this, &MeasurementArea::deferUpdate);
425
  this->_timer.setSingleShot(true);
426
  connect(&this->_timer, &QTimer::timeout, this, &MeasurementArea::doUpdate);
427 428
  connect(&this->_watcher,
          &QFutureWatcher<std::unique_ptr<QmlObjectListModel>>::finished, this,
429
          &MeasurementArea::storeTiles);
430 431
}

432
void MeasurementArea::setState(MeasurementArea::STATE s) {
433 434 435 436 437 438 439 440
  if (this->_state != s) {
    auto oldState = this->_state;
    this->_state = s;
    if (s == STATE::IDLE || oldState == STATE::IDLE) {
      emit readyChanged();
    }
  }
}