From 17fe7893e90a8023549e2dacb41129df10600b92 Mon Sep 17 00:00:00 2001
From: Andreas Bircher <bircher@gmx.ch>
Date: Wed, 15 Nov 2017 17:22:23 -0500
Subject: [PATCH] fixes

---
 src/Terrain.cc     | 10 +++++++---
 src/Terrain.h      |  4 ++--
 src/TerrainTile.cc | 30 ++++++++++++++++++------------
 src/TerrainTile.h  | 11 +++++++++--
 4 files changed, 36 insertions(+), 19 deletions(-)

diff --git a/src/Terrain.cc b/src/Terrain.cc
index 2b7b896..88fe899 100644
--- a/src/Terrain.cc
+++ b/src/Terrain.cc
@@ -20,6 +20,10 @@
 
 QGC_LOGGING_CATEGORY(TerrainLog, "TerrainLog")
 
+QMutex                          ElevationProvider::_tilesMutex;
+QHash<QString, TerrainTile>     ElevationProvider::_tiles;
+QStringList                     ElevationProvider::_downloadQueue;
+
 ElevationProvider::ElevationProvider(QObject* parent)
     : QObject(parent)
 {
@@ -101,7 +105,7 @@ bool ElevationProvider::cacheTerrainTiles(const QList<QGeoCoordinate>& coordinat
         QString uniqueTileId = _uniqueTileId(coordinate);
         _tilesMutex.lock();
         if (_downloadQueue.contains(uniqueTileId) || _tiles.contains(uniqueTileId)) {
-            continue
+            continue;
         }
         _downloadQueue.append(uniqueTileId.replace("-", ","));
         _tilesMutex.unlock();
@@ -209,7 +213,7 @@ void ElevationProvider::_downloadTiles(void)
 
         QNetworkReply* networkReply = _networkManager.get(request);
         if (!networkReply) {
-            return false;
+            return;
         }
 
         connect(networkReply, &QNetworkReply::finished, this, &ElevationProvider::_requestFinishedTile);
@@ -229,7 +233,7 @@ QString ElevationProvider::_uniqueTileId(const QGeoCoordinate& coordinate)
 
     QString ret = QString::number(southEast.latitude(), 'f', 6) + "-" + QString::number(southEast.longitude(), 'f', 6) + "-" +
                   QString::number(northEast.latitude(), 'f', 6) + "-" + QString::number(northEast.longitude(), 'f', 6);
-    qCDebug << "Computing unique tile id for " << coordinate << ret;
+    qCDebug(TerrainLog) << "Computing unique tile id for " << coordinate << ret;
 
     return ret;
 }
diff --git a/src/Terrain.h b/src/Terrain.h
index 9422f4d..5cfe3ce 100644
--- a/src/Terrain.h
+++ b/src/Terrain.h
@@ -50,7 +50,7 @@ public:
      * @param southWest
      * @param northEast
      */
-    void cacheTerrainData(const QGeoCoordinate& southWest, const QGeoCoordinate& northEast);
+    bool cacheTerrainTiles(const QList<QGeoCoordinate>& coordinates);
 
 signals:
     void terrainData(bool success, QList<float> altitudes);
@@ -74,5 +74,5 @@ private:
 
     static QMutex                       _tilesMutex;
     static QHash<QString, TerrainTile>  _tiles;
-    QStringList                         _downloadQueue;
+    static QStringList                  _downloadQueue;
 };
diff --git a/src/TerrainTile.cc b/src/TerrainTile.cc
index c9da591..3af537e 100644
--- a/src/TerrainTile.cc
+++ b/src/TerrainTile.cc
@@ -7,6 +7,7 @@
 
 QGC_LOGGING_CATEGORY(TerrainTileLog, "TerrainTileLog")
 
+const double TerrainTile::_srtm1TileSize        = 0.025;
 const char*  TerrainTile::_jsonStatusKey        = "status";
 const char*  TerrainTile::_jsonDataKey          = "data";
 const char*  TerrainTile::_jsonBoundsKey        = "bounds";
@@ -50,7 +51,7 @@ TerrainTile::TerrainTile(QJsonDocument document)
     };
     if (!JsonHelper::validateKeys(rootObject, rootVersionKeyInfoList, errorString)) {
         qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
-        return false;
+        return;
     }
 
     if (rootObject[_jsonStatusKey].toString() != "success") {
@@ -65,7 +66,7 @@ TerrainTile::TerrainTile(QJsonDocument document)
     };
     if (!JsonHelper::validateKeys(dataObject, dataVersionKeyInfoList, errorString)) {
         qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
-        return false;
+        return;
     }
 
     // Bounds
@@ -76,7 +77,7 @@ TerrainTile::TerrainTile(QJsonDocument document)
     };
     if (!JsonHelper::validateKeys(boundsObject, boundsVersionKeyInfoList, errorString)) {
         qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
-        return false;
+        return;
     }
     const QJsonArray& swArray = boundsObject[_jsonSouthWestKey].toArray();
     const QJsonArray& neArray = boundsObject[_jsonNorthEastKey].toArray();
@@ -98,7 +99,7 @@ TerrainTile::TerrainTile(QJsonDocument document)
     };
     if (!JsonHelper::validateKeys(statsObject, statsVersionKeyInfoList, errorString)) {
         qCDebug(TerrainTileLog) << "Error in reading json: " << errorString;
-        return false;
+        return;
     }
     _maxElevation = statsObject[_jsonMaxElevationKey].toInt();
     _minElevation = statsObject[_jsonMinElevationKey].toInt();
@@ -129,28 +130,33 @@ bool TerrainTile::isIn(const QGeoCoordinate& coordinate) const
         qCDebug(TerrainTileLog) << "isIn requested, but tile not valid";
         return false;
     }
-    bool ret = coord.latitude() >= _southWest.longitude() && coord.longitude() >= _southWest.longitude() &&
-               coord.latitude() <= _northEast.longitude() && coord.longitude() <= _northEast.longitude();
-    qCDebug(TerrainTileLog) << "Checking isIn: " << coord << " , in sw " << _southWest << " , ne " << _northEast << ": " << ret;
+    bool ret = coordinate.latitude() >= _southWest.longitude() && coordinate.longitude() >= _southWest.longitude() &&
+               coordinate.latitude() <= _northEast.longitude() && coordinate.longitude() <= _northEast.longitude();
+    qCDebug(TerrainTileLog) << "Checking isIn: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast << ": " << ret;
     return ret;
 }
 
 float TerrainTile::elevation(const QGeoCoordinate& coordinate) const
 {
     if (_isValid) {
-        qCDebug << "elevation: " << coord << " , in sw " << _southWest << " , ne " << _northEast;
+        qCDebug(TerrainTileLog) << "elevation: " << coordinate << " , in sw " << _southWest << " , ne " << _northEast;
         // Get the index at resolution of 1 arc second
-        int indexLat = std::round((coord.latitude() - _southWest.latitude()) / _srtm1Increment);
-        int indexLon = std::round((coord.longitude() - _southWest.longitude()) / _srtm1Increment);
-        qCDebug << "indexLat:indexLon" << indexLat << indexLon; // TODO (birchera): Move this down to the next debug output, once this is all properly working.
+        int indexLat = std::round((coordinate.latitude() - _southWest.latitude()) * _gridSize / _srtm1TileSize);
+        int indexLon = std::round((coordinate.longitude() - _southWest.longitude()) * _gridSize / _srtm1TileSize);
+        qCDebug(TerrainTileLog) << "indexLat:indexLon" << indexLat << indexLon; // TODO (birchera): Move this down to the next debug output, once this is all properly working.
         Q_ASSERT(indexLat >= 0);
         Q_ASSERT(indexLat < _gridSize);
         Q_ASSERT(indexLon >= 0);
         Q_ASSERT(indexLon < _gridSize);
-        qCDebug << "elevation" << _data[indexLat][indexLon];
+        qCDebug(TerrainTileLog) << "elevation" << _data[indexLat][indexLon];
         return _data[indexLat][indexLon];
     } else {
         qCDebug(TerrainTileLog) << "Asking for elevation, but no valid data.";
         return -1.0;
     }
 }
+
+QGeoCoordinate TerrainTile::centerCoordinate(void) const
+{
+    return _southWest.atDistanceAndAzimuth(_southWest.distanceTo(_northEast) / 2.0, _southWest.azimuthTo(_northEast));
+}
diff --git a/src/TerrainTile.h b/src/TerrainTile.h
index bd12697..1c66cbe 100644
--- a/src/TerrainTile.h
+++ b/src/TerrainTile.h
@@ -66,11 +66,18 @@ public:
     */
     float avgElevation(void) const { return _avgElevation; }
 
+    /**
+    * Accessor for the center coordinate
+    *
+    * @return center coordinate
+    */
+    QGeoCoordinate centerCoordinate(void) const;
+
     /// tile grid size in lat and lon
     static const int    _gridSize = TERRAIN_TILE_SIZE;
 
-    /// grid spacing in degree
-    static const float  _srtm1Increment = 1.0 / (60.0 * 60.0);
+    /// size of a tile in degree
+    static const double  _srtm1TileSize;
 
 private:
     QGeoCoordinate      _southWest;                                     /// South west corner of the tile